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