]> gerrit.simantics Code Review - simantics/district.git/blob - org.simantics.district.network.ui/src/org/simantics/district/network/ui/table/ImportCSVHandler.java
Fixing UI related bugs in Dynamic Visualisations view
[simantics/district.git] / org.simantics.district.network.ui / src / org / simantics / district / network / ui / table / ImportCSVHandler.java
1 package org.simantics.district.network.ui.table;
2
3 import java.util.Collection;
4 import java.util.HashMap;
5 import java.util.Map;
6 import java.util.Set;
7
8 import javax.inject.Inject;
9 import javax.inject.Named;
10
11 import org.eclipse.e4.core.di.annotations.Execute;
12 import org.eclipse.e4.ui.model.application.ui.basic.MPart;
13 import org.eclipse.e4.ui.services.IServiceConstants;
14 import org.eclipse.e4.ui.workbench.modeling.EPartService;
15 import org.eclipse.jface.dialogs.Dialog;
16 import org.eclipse.jface.layout.GridDataFactory;
17 import org.eclipse.swt.SWT;
18 import org.eclipse.swt.events.ModifyEvent;
19 import org.eclipse.swt.events.ModifyListener;
20 import org.eclipse.swt.layout.GridData;
21 import org.eclipse.swt.layout.GridLayout;
22 import org.eclipse.swt.widgets.Combo;
23 import org.eclipse.swt.widgets.Composite;
24 import org.eclipse.swt.widgets.Control;
25 import org.eclipse.swt.widgets.Group;
26 import org.eclipse.swt.widgets.Label;
27 import org.eclipse.swt.widgets.Shell;
28 import org.eclipse.ui.dialogs.SelectionStatusDialog;
29 import org.geotools.geometry.DirectPosition2D;
30 import org.geotools.referencing.CRS;
31 import org.opengis.geometry.DirectPosition;
32 import org.opengis.referencing.crs.CoordinateReferenceSystem;
33 import org.opengis.referencing.operation.MathTransform;
34 import org.simantics.Simantics;
35 import org.simantics.db.ReadGraph;
36 import org.simantics.db.Resource;
37 import org.simantics.db.WriteGraph;
38 import org.simantics.db.common.request.IndexRoot;
39 import org.simantics.db.common.request.ReadRequest;
40 import org.simantics.db.common.request.WriteRequest;
41 import org.simantics.db.exception.DatabaseException;
42 import org.simantics.db.layer0.request.PossibleActiveModel;
43 import org.simantics.district.network.DistrictNetworkUtil;
44 import org.simantics.district.network.ui.function.Functions;
45 import org.simantics.modeling.ModelingResources;
46 import org.slf4j.Logger;
47 import org.slf4j.LoggerFactory;
48
49 public class ImportCSVHandler {
50
51     private static final Logger LOGGER = LoggerFactory.getLogger(ImportCSVHandler.class);
52
53         @Inject
54         EPartService partService;
55         
56         @Execute
57         public void execute(@Named(IServiceConstants.ACTIVE_SHELL) Shell s) {
58                 // here we can import based on the current CSV table data
59                 MPart activePart = partService.getActivePart();
60                 Object object = activePart.getObject();
61                 // this object is the part wrapped by e4part
62                 DistrictCSVTableView view = (DistrictCSVTableView) object;
63                 String[][] data = view.getCurrentData();
64
65                 SelectionDialog d = new SelectionDialog(s);
66                 
67                 if (d.open() == Dialog.CANCEL)
68                     return;
69                 
70                 String sourceEPSGCRS =  d.getSourceCRS();//"EPSG:3067";
71                 
72                 Resource targetDiagram = d.getTargetDiagram();
73                 Resource mappingType = d.getMappingType();
74
75                 try {
76                         MathTransform transform = null;
77                         boolean doTransform = false;
78                         // if sourceEPSGCRS is empty || null then ignore transformation
79                         if (sourceEPSGCRS != null && !sourceEPSGCRS.isEmpty()) {
80                                 CoordinateReferenceSystem sourceCRS = CRS.decode(sourceEPSGCRS);
81                                 CoordinateReferenceSystem targetCRS = CRS.decode("EPSG:4326");
82                                 transform = CRS.findMathTransform(sourceCRS, targetCRS, false);
83                                 doTransform = true;
84                         }
85                         
86                         final MathTransform finalTransform = transform;
87                         
88                         int x = xColumn(data);
89                         int y = yColumn(data);
90                         int z = zColumn(data);
91                         
92                         Simantics.getSession().asyncRequest(new WriteRequest() {
93                 
94                 @Override
95                 public void perform(WriteGraph graph) throws DatabaseException {
96                     for (int i = 1; i < data.length; i++) {
97                         try {
98                             String[] rows = data[i];
99                             String xCoords = rows[x];
100                             String yCoords = rows[y];
101                             double xCoord = Double.parseDouble(xCoords);
102                             double yCoord = Double.parseDouble(yCoords);
103                             DirectPosition2D targetPos = new DirectPosition2D();
104                             DirectPosition2D sourcePos = new DirectPosition2D(xCoord, yCoord);
105                             DirectPosition res = finalTransform.transform(sourcePos, targetPos);
106                             double[] coords = res.getCoordinate();
107                             flipAxes(coords);
108                             Resource vertex = DistrictNetworkUtil.createVertex(graph, targetDiagram, coords, z, mappingType);
109                         } catch (Exception e) {
110                             LOGGER.error("", e);
111                         }
112                     }
113                 }
114             });
115                 } catch (Exception e) {
116                         LOGGER.error("", e);
117                 }
118                 
119                 
120         }
121
122     private static void flipAxes(double[] coords) {
123         double tmp = coords[0];
124         coords[0] = coords[1];
125         coords[1] = tmp;
126     }
127
128         
129         private int zColumn(String[][] data) {
130                 return column("z", data);
131         }
132         
133         private int yColumn(String[][] data) {
134                 return column("y", data);
135         }
136
137         private int xColumn(String[][] data) {
138                 return column("x", data);
139         }
140
141         private int column(String expected, String[][] data) {
142                 String[] columns = data[0]; // first row should be headers
143                 for (int i = 0; i < columns.length; i++) {
144                         String col = columns[i];
145                         if (col.equals(expected)) {
146                                 return i;
147                         }
148                 }
149                 return -1;
150         }
151         
152         private static class SelectionDialog extends SelectionStatusDialog {
153
154         private Map<String, Resource> diagrams = new HashMap<>();
155         private Map<String, Resource> vertexMappings = new HashMap<>();
156
157         private Composite composite;
158         private Combo networkDiagramSelectionCombo;
159         private Combo sourceCRSCombo;
160         private Combo vertexMappingCombo;
161         private String sourceCRS;
162         private Resource diagram;
163         private Resource mapping;
164
165         public SelectionDialog(Shell parent) {
166             super(parent);
167         }
168
169         public Resource getMappingType() {
170             return mapping;
171         }
172
173         public Resource getTargetDiagram() {
174             return diagram;
175         }
176
177         public String getSourceCRS() {
178             return "EPSG:" + sourceCRS;
179         }
180
181         @Override
182         protected Control createDialogArea(Composite parent) {
183             composite = (Composite) super.createDialogArea(parent);
184             createMappingsGroup(composite);
185             computeContent();
186             return composite;
187         }
188         
189         private void computeContent() {
190             Simantics.getSession().asyncRequest(new ReadRequest() {
191                 
192                 @Override
193                 public void run(ReadGraph graph) throws DatabaseException {
194                     
195                     Resource indexRoot = graph.sync(new IndexRoot(graph.sync(new PossibleActiveModel(Simantics.getProjectResource()))));
196                     vertexMappings = Functions.getVertexMappings(graph, indexRoot);
197                     
198                     Collection<Resource> diagramss = Functions.getDistrictDiagrams(graph);
199                     ModelingResources MOD = ModelingResources.getInstance(graph);
200                     Resource projectResource = Simantics.getProjectResource();
201                     String projectURI = graph.getURI(projectResource);
202                     for (Resource diagram : diagramss) {
203                         Resource composite = graph.getSingleObject(diagram, MOD.DiagramToComposite);
204                         String compositeURI = graph.getURI(composite);
205                         String path = compositeURI.replace(projectURI, "");
206                         diagrams.put(path, diagram);
207                     }
208                     
209                     composite.getDisplay().asyncExec(() -> {
210                         
211                         vertexMappingCombo.setItems(vertexMappings.keySet().toArray(new String[vertexMappings.size()]));
212                         
213                         networkDiagramSelectionCombo.setItems(diagrams.keySet().toArray(new String[diagrams.size()]));
214                         if (diagrams.size() > 0) {
215                             networkDiagramSelectionCombo.select(0);
216                         }
217                         Set<String> codes = CRS.getSupportedCodes("EPSG");
218                         sourceCRSCombo.setItems(codes.toArray(new String[codes.size()]));
219                         sourceCRSCombo.addModifyListener(new ModifyListener() {
220                             
221                             @Override
222                             public void modifyText(ModifyEvent e) {
223                                 String currentText = sourceCRSCombo.getText();
224                                 if (codes.contains(currentText)) {
225                                     // Select this
226                                     String[] items = sourceCRSCombo.getItems();
227                                     int i;
228                                     for (i = 0; i < items.length; i++) {
229                                         String item = items[i];
230                                         if (currentText.equals(item)) {
231                                             break;
232                                         }
233                                     }
234                                     if (i != 0) {
235                                         sourceCRSCombo.select(i);
236                                     } else {
237                                         System.err.println("Should not happen");
238                                     }
239                                 }
240                             }
241                         });
242                     });
243                 }
244             });
245         }
246
247         private void createMappingsGroup(Composite parent) {
248             Group group= new Group(parent, SWT.NONE);
249             group.setFont(parent.getFont());
250             group.setText("Select Diagram & CRS");
251             GridDataFactory.fillDefaults().grab(true, false).applyTo(group);
252             group.setLayout(new GridLayout(1, false));
253             
254             Composite cmposite = new Composite(group, SWT.NONE);
255             cmposite.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false));
256             cmposite.setLayout(new GridLayout(2, false));
257             
258             Label vertexMappingLabel = new Label(cmposite, SWT.NONE);
259             vertexMappingLabel.setText("Select Vertex Mapping");
260
261             vertexMappingCombo = new Combo(cmposite, SWT.READ_ONLY | SWT.BORDER);
262             GridDataFactory.fillDefaults().grab(true, false).applyTo(vertexMappingCombo);
263             
264             Label selectNetworkDiagramLabel = new Label(cmposite, SWT.NONE);
265             selectNetworkDiagramLabel.setText("Select Network Diagram");
266
267             networkDiagramSelectionCombo = new Combo(cmposite, SWT.READ_ONLY | SWT.BORDER);
268             GridDataFactory.fillDefaults().grab(true, false).applyTo(networkDiagramSelectionCombo);
269             
270             Label label = new Label(cmposite, SWT.NONE);
271             label.setText("Select Source Coordinate Reference System");
272             
273             sourceCRSCombo = new Combo(cmposite, SWT.NONE);
274             sourceCRSCombo.setToolTipText("Select the coordinate reference system that is used in the source material for possible transformation to target coordinate reference system (EPSG:4326)");
275             
276             GridDataFactory.fillDefaults().grab(true, false).applyTo(sourceCRSCombo);
277         }
278         
279         @Override
280         protected void computeResult() {
281             mapping = vertexMappings.get(vertexMappingCombo.getItem(vertexMappingCombo.getSelectionIndex()));
282             diagram = diagrams.get(networkDiagramSelectionCombo.getItem(networkDiagramSelectionCombo.getSelectionIndex()));
283             sourceCRS = sourceCRSCombo.getItem(sourceCRSCombo.getSelectionIndex());
284         }
285         }
286 }