]> gerrit.simantics Code Review - simantics/platform.git/blob - bundles/org.simantics.annotation.ui/src/org/simantics/annotation/ui/wizard/AnnotationTypeExportPage.java
Migrated source code from Simantics SVN
[simantics/platform.git] / bundles / org.simantics.annotation.ui / src / org / simantics / annotation / ui / wizard / AnnotationTypeExportPage.java
1 /*******************************************************************************\r
2  * Copyright (c) 2012 Association for Decentralized Information Management in\r
3  * Industry THTH ry.\r
4  * All rights reserved. This program and the accompanying materials\r
5  * are made available under the terms of the Eclipse Public License v1.0\r
6  * which accompanies this distribution, and is available at\r
7  * http://www.eclipse.org/legal/epl-v10.html\r
8  *\r
9  * Contributors:\r
10  *     VTT Technical Research Centre of Finland - initial API and implementation\r
11  *******************************************************************************/\r
12 package org.simantics.annotation.ui.wizard;\r
13 \r
14 import java.io.File;\r
15 import java.util.ArrayList;\r
16 import java.util.Collections;\r
17 import java.util.HashSet;\r
18 import java.util.List;\r
19 import java.util.Map;\r
20 import java.util.Set;\r
21 import java.util.TreeMap;\r
22 \r
23 import org.eclipse.jface.layout.GridDataFactory;\r
24 import org.eclipse.jface.wizard.WizardPage;\r
25 import org.eclipse.swt.SWT;\r
26 import org.eclipse.swt.custom.CCombo;\r
27 import org.eclipse.swt.events.ModifyEvent;\r
28 import org.eclipse.swt.events.ModifyListener;\r
29 import org.eclipse.swt.events.SelectionAdapter;\r
30 import org.eclipse.swt.events.SelectionEvent;\r
31 import org.eclipse.swt.layout.GridData;\r
32 import org.eclipse.swt.layout.GridLayout;\r
33 import org.eclipse.swt.widgets.Button;\r
34 import org.eclipse.swt.widgets.Composite;\r
35 import org.eclipse.swt.widgets.FileDialog;\r
36 import org.eclipse.swt.widgets.Label;\r
37 import org.simantics.NameLabelMode;\r
38 import org.simantics.NameLabelUtil;\r
39 import org.simantics.annotation.ontology.AnnotationResource;\r
40 import org.simantics.databoard.Bindings;\r
41 import org.simantics.db.ReadGraph;\r
42 import org.simantics.db.Resource;\r
43 import org.simantics.db.common.NamedResource;\r
44 import org.simantics.db.common.request.PossibleIndexRoot;\r
45 import org.simantics.db.common.request.UniqueRead;\r
46 import org.simantics.db.exception.DatabaseException;\r
47 import org.simantics.db.layer0.SelectionHints;\r
48 import org.simantics.db.layer0.adapter.Instances;\r
49 import org.simantics.db.layer0.variable.Variable;\r
50 import org.simantics.db.layer0.variable.Variables;\r
51 import org.simantics.layer0.Layer0;\r
52 import org.simantics.utils.strings.AlphanumComparator;\r
53 import org.simantics.utils.ui.ISelectionUtils;\r
54 \r
55 /**\r
56  * @author Tuukka Lehtonen\r
57  * @author Teemu Mätäsniemi\r
58  */\r
59 public class AnnotationTypeExportPage extends WizardPage {\r
60 \r
61     ExportPlan          exportModel;\r
62     CCombo              model;\r
63     CCombo              exportLocation;\r
64 \r
65     List<NamedResource> models = Collections.emptyList();\r
66     private Button      overwrite;\r
67 \r
68     protected AnnotationTypeExportPage(ExportPlan model) {\r
69         super("Export Annotation Type", "Define Export Location", null);\r
70         this.exportModel = model;\r
71     }\r
72 \r
73     @Override\r
74     public void createControl(Composite parent) {\r
75         Composite container = new Composite(parent, SWT.NONE);\r
76         {\r
77             GridLayout layout = new GridLayout();\r
78             layout.horizontalSpacing = 20;\r
79             layout.verticalSpacing = 10;\r
80             layout.numColumns = 3;\r
81             container.setLayout(layout);\r
82         }\r
83 \r
84         new Label(container, SWT.NONE).setText("Exported &annotation type:");\r
85         model = new CCombo(container, SWT.BORDER);\r
86         {\r
87             model.setEditable(false);\r
88             model.setText("");\r
89             model.setToolTipText("Selects the annotation type to export.");\r
90             GridDataFactory.fillDefaults().grab(true, false).span(2, 1).applyTo(model);\r
91             model.addModifyListener(new ModifyListener(){\r
92                 @Override\r
93                 public void modifyText(ModifyEvent e) {\r
94                     validatePage();\r
95                 }\r
96             });\r
97         }\r
98 \r
99         new Label(container, SWT.NONE).setText("&Target file:");\r
100         exportLocation = new CCombo(container, SWT.BORDER);\r
101         {\r
102             exportLocation.setText("");\r
103             GridDataFactory.fillDefaults().grab(true, false).span(1, 1).applyTo(exportLocation);\r
104             exportLocation.addModifyListener(new ModifyListener(){\r
105                 @Override\r
106                 public void modifyText(ModifyEvent e) {\r
107                     validatePage();\r
108                 }\r
109             });\r
110         }\r
111         Button browseFileButton = new Button(container, SWT.PUSH);\r
112         {\r
113             browseFileButton.setText("Browse...");\r
114             browseFileButton.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false));\r
115             browseFileButton.addSelectionListener(new SelectionAdapter() {\r
116                 @Override\r
117                 public void widgetSelected(SelectionEvent e) {\r
118                     FileDialog dialog = new FileDialog(getShell(), SWT.SAVE);\r
119                     dialog.setText("Choose Export Target File");\r
120                     String loc = exportLocation.getText();\r
121                     dialog.setFilterPath(loc);\r
122                     dialog.setFilterExtensions(new String[] { "*.annotationType" });\r
123                     dialog.setFilterNames(new String[] { "Annotation Type (*.annotationType)" });\r
124                     dialog.setOverwrite(false);\r
125                     String file = dialog.open();\r
126                     if (file == null)\r
127                         return;\r
128                     exportLocation.setText(file);\r
129                     validatePage();\r
130                 }\r
131             });\r
132         }\r
133 \r
134         Label horizRule = new Label(container, SWT.BORDER);\r
135         GridDataFactory.fillDefaults().hint(SWT.DEFAULT, 0).grab(true, false).span(3, 1).applyTo(horizRule);\r
136 \r
137         overwrite = new Button(container, SWT.CHECK);\r
138         overwrite.setText("&Overwrite existing files without warning");\r
139         overwrite.setSelection(exportModel.overwrite);\r
140         GridDataFactory.fillDefaults().grab(true, false).span(3, 1).applyTo(overwrite);\r
141         overwrite.addSelectionListener(new SelectionAdapter() {\r
142             @Override\r
143             public void widgetSelected(SelectionEvent e) {\r
144                 validatePage();\r
145             }\r
146         });\r
147 \r
148         try {\r
149             initializeData();\r
150         } catch (DatabaseException e) {\r
151             e.printStackTrace();\r
152         }\r
153 \r
154         setControl(container);\r
155         validatePage();\r
156     }\r
157 \r
158     private void initializeData() throws DatabaseException {\r
159         final List<Resource> resources = ISelectionUtils.getPossibleKeys(exportModel.selection, SelectionHints.KEY_MAIN, Resource.class);\r
160 \r
161         models = exportModel.sessionContext.getSession().syncRequest(new UniqueRead<List<NamedResource>>() {\r
162             AnnotationResource ANNO;\r
163             Layer0 L0;\r
164             NameLabelMode mode;\r
165 \r
166             @Override\r
167             public List<NamedResource> perform(ReadGraph graph) throws DatabaseException {\r
168                 ANNO = AnnotationResource.getInstance(graph);\r
169                 L0 = Layer0.getInstance(exportModel.sessionContext.getSession());\r
170                 mode = NameLabelMode.NAME; //NameLabelUtil.getNameLabelMode(graph);\r
171 \r
172                 Map<String, NamedResource> result = new TreeMap<String, NamedResource>(AlphanumComparator.CASE_INSENSITIVE_COMPARATOR);\r
173                 for (Resource r : resources)\r
174                     process(graph, r, result);\r
175 \r
176                 if (result.isEmpty()) {\r
177                     // Look for all annotation types in the index roots contained by the selected resources.\r
178                     Set<Resource> visited = new HashSet<Resource>();\r
179                     Instances types = graph.adapt(ANNO.AnnotationType, Instances.class);\r
180                     for (Resource r : resources) {\r
181                         Resource indexRoot = graph.syncRequest(new PossibleIndexRoot(r));\r
182                         if (indexRoot == null || !visited.add(indexRoot))\r
183                             continue;\r
184                         for (Resource at : types.find(graph, indexRoot)) {\r
185                             Resource atRoot = graph.syncRequest(new PossibleIndexRoot(at));\r
186                             if (indexRoot.equals(atRoot))\r
187                                 process(graph, at, result);\r
188                         }\r
189                     }\r
190                 }\r
191 \r
192                 return new ArrayList<NamedResource>( result.values() );\r
193             }\r
194 \r
195             private NamedResource process(ReadGraph graph, Resource r, Map<String, NamedResource> result) throws DatabaseException {\r
196                 NamedResource nr = process(graph, r);\r
197                 if (nr != null)\r
198                     result.put(nr.getName(), nr);\r
199                 return nr;\r
200             }\r
201 \r
202             private NamedResource process(ReadGraph graph, Resource r) throws DatabaseException {\r
203                 if (!graph.isInstanceOf(r, ANNO.AnnotationType))\r
204                     return null;\r
205                 Resource property = graph.getPossibleObject(r, L0.HasRange_Inverse);\r
206                 String name = pathName(graph, r, property != null ? property : r);\r
207                 return new NamedResource(name, r);\r
208             }\r
209 \r
210             private String pathName(ReadGraph graph, Resource r, Resource namedEntity) throws DatabaseException {\r
211                 String name = graph.getRelatedValue(namedEntity, L0.HasName, Bindings.STRING);\r
212 \r
213                 Resource indexRoot = graph.syncRequest(new PossibleIndexRoot(r));\r
214                 if (indexRoot == null)\r
215                     return name;\r
216                 Variable rootV = Variables.getPossibleVariable(graph, indexRoot);\r
217                 Variable v = Variables.getPossibleVariable(graph, r);\r
218                 if (v == null || rootV == null)\r
219                     return name;\r
220 \r
221                 List<Variable> path = Variables.getPath(graph, rootV, v);\r
222                 path.add(0, rootV);\r
223                 StringBuilder sb = new StringBuilder();\r
224                 for (Variable p : path) {\r
225                     String segmentName = NameLabelUtil.modalName(graph, p, mode);\r
226                     sb.append(segmentName).append(" / ");\r
227                 }\r
228                 sb.append(name);\r
229                 return sb.toString();\r
230             }\r
231         });\r
232 \r
233         if (!models.isEmpty())\r
234             exportModel.model = models.get(0);\r
235 \r
236         // Populate combo boxes\r
237         int i = 0;\r
238         for (NamedResource m : models) {\r
239             model.add(m.getName());\r
240             model.setData(String.valueOf(i), m);\r
241             if (m.equals(exportModel.model))\r
242                 model.select(i);\r
243             ++i;\r
244         }\r
245 \r
246         for (String path : exportModel.recentLocations) {\r
247             exportLocation.add(path);\r
248         }\r
249         if (exportLocation.getItemCount() > 0)\r
250             exportLocation.select(0);\r
251     }\r
252 \r
253     void validatePage() {\r
254         if (exportModel.model == null) {\r
255             setMessage("Select model to export from.");\r
256             setErrorMessage(null);\r
257             setPageComplete(false);\r
258             return;\r
259         }\r
260 \r
261         String exportLoc = exportLocation.getText();\r
262         if (exportLoc.isEmpty()) {\r
263             setMessage("Select target file.");\r
264             setErrorMessage(null);\r
265             setPageComplete(false);\r
266             return;\r
267         }\r
268         if (!exportLoc.endsWith(".annotationType"))\r
269             exportLoc += exportLoc.endsWith(".") ? "annotationType" : ".annotationType";\r
270         File file = new File(exportLoc);\r
271         if (file.isDirectory()) {\r
272             setErrorMessage("The target is a directory.");\r
273             setPageComplete(false);\r
274             return;\r
275         }\r
276         File parent = file.getParentFile();\r
277         if (parent == null || !parent.isDirectory()) {\r
278             setErrorMessage("The target directory does not exist.");\r
279             setPageComplete(false);\r
280             return;\r
281         }\r
282         exportModel.exportLocation = file;\r
283         exportModel.overwrite = overwrite.getSelection();\r
284 \r
285         setErrorMessage(null);\r
286         setMessage("Export annotation type to " + exportLoc + ".");\r
287         setPageComplete(true);\r
288     }\r
289 \r
290 }\r