Statistics
| Revision:

svn-gvsig-desktop / tags / v1_1_Build_1013 / extensions / extGeoreferencing / src / org / gvsig / georeferencing / utils / GeoPointPersistence.java @ 13521

History | View | Annotate | Download (31.3 KB)

1 5791 nacho
/* gvSIG. Sistema de Informaci?n Geogr?fica de la Generalitat Valenciana
2
 *
3
 * Copyright (C) 2006 IVER T.I. and Generalitat Valenciana.
4
 *
5
 * This program is free software; you can redistribute it and/or
6
 * modify it under the terms of the GNU General Public License
7
 * as published by the Free Software Foundation; either version 2
8
 * of the License, or (at your option) any later version.
9
 *
10
 * This program is distributed in the hope that it will be useful,
11
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13
 * GNU General Public License for more details.
14
 *
15
 * You should have received a copy of the GNU General Public License
16
 * along with this program; if not, write to the Free Software
17
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307,USA.
18
 */
19 5217 nacho
package org.gvsig.georeferencing.utils;
20
import java.awt.Dimension;
21
import java.awt.geom.Point2D;
22
import java.awt.geom.Rectangle2D;
23
import java.io.BufferedOutputStream;
24 5328 nacho
import java.io.BufferedReader;
25
import java.io.BufferedWriter;
26 5217 nacho
import java.io.File;
27 5328 nacho
import java.io.FileInputStream;
28
import java.io.FileNotFoundException;
29 5217 nacho
import java.io.FileOutputStream;
30
import java.io.IOException;
31 5328 nacho
import java.io.InputStreamReader;
32 5217 nacho
import java.io.OutputStream;
33
import java.io.OutputStreamWriter;
34
import java.io.StringWriter;
35
import java.util.ArrayList;
36
37
import javax.xml.parsers.DocumentBuilder;
38
import javax.xml.parsers.DocumentBuilderFactory;
39
import javax.xml.parsers.ParserConfigurationException;
40
41
import org.apache.crimson.jaxp.DocumentBuilderFactoryImpl;
42
import org.apache.xml.serialize.OutputFormat;
43
import org.apache.xml.serialize.XMLSerializer;
44 5982 nacho
import org.cresques.io.data.RasterMetaFileTags;
45 5241 nacho
import org.gvsig.georeferencing.GeoreferencingToolsModule;
46 5818 nacho
import org.gvsig.georeferencing.gui.dialog.GeoreferencingDialog;
47
import org.gvsig.georeferencing.gui.panels.ZoomControlPanel;
48 5217 nacho
import org.w3c.dom.Document;
49
import org.w3c.dom.Element;
50
import org.w3c.dom.Node;
51
import org.w3c.dom.NodeList;
52
import org.xml.sax.SAXException;
53
54
import com.iver.andami.PluginServices;
55
import com.iver.cit.gvsig.fmap.DriverException;
56
import com.iver.cit.gvsig.fmap.ViewPort;
57 7703 luisw2
import com.iver.cit.gvsig.fmap.crs.CRSFactory;
58 5241 nacho
import com.iver.cit.gvsig.fmap.layers.FLyrGeoRaster;
59
import com.iver.cit.gvsig.fmap.layers.FLyrPoints;
60
import com.iver.cit.gvsig.fmap.layers.GeoPoint;
61
import com.iver.cit.gvsig.fmap.layers.IPersistence;
62 8765 jjdelcerro
import com.iver.cit.gvsig.project.documents.view.gui.View;
63 5217 nacho
64
/**
65 6641 caballero
 * Clase que controla la persistencia de la capa de puntos.
66 5217 nacho
 * @author Nacho Brodin (brodin_ign@gva.es)
67
 */
68 5241 nacho
public class GeoPointPersistence implements IPersistence{
69 5217 nacho
        //**********************Vars**********************************
70
        private ArrayList                 geoPointList = null;
71
        private Document                 xmlDoc = null;
72
        private Element                 generalTag = null;
73
        private FLyrPoints                 lyrPoints = null;
74
        private double[]                lastViewPort = null;
75
        //**********************End Vars******************************
76 6641 caballero
77 5217 nacho
        //**********************Methods*******************************
78
        /**
79
         * Constructor
80
         */
81
        public GeoPointPersistence(){}
82 6641 caballero
83 5217 nacho
        /**
84
         * Constructor
85
         * @param geoPointList        Lista de geopuntos
86
         */
87
        public GeoPointPersistence(FLyrPoints lyrPoints){
88
                this.geoPointList = lyrPoints.getListPoint();
89
                this.lyrPoints = lyrPoints;
90
        }
91 6641 caballero
92 5217 nacho
        /**
93
         * Carga la lista de puntos desde un fichero
94
         * @param file        Nombre del fichero
95
         * @return        Array con la lista de puntos
96
         */
97
        public void loadPointList(String file){
98
                try {
99
                DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
100
                DocumentBuilder db = dbf.newDocumentBuilder();
101
                File f = new File(file);
102
                Document doc = db.parse(f);
103 6641 caballero
104 5352 nacho
                if(doc.getDocumentElement().getTagName().equals(RasterMetaFileTags.MAIN_TAG)){
105
                        NodeList nodeListMain = doc.getDocumentElement().getChildNodes();
106
                        for(int j=0;j<nodeListMain.getLength();j++){
107
                                Node nodeMain = nodeListMain.item(j);
108
                                if(nodeMain.getNodeName().equals(RasterMetaFileTags.GEOPOINTS)){
109 6641 caballero
110 5352 nacho
                                        NodeList nodeListGeoPoints = nodeMain.getChildNodes();
111
                                    lyrPoints.clear();
112
                                    for(int i=0;i<nodeListGeoPoints.getLength();i++){
113
                                            Node node = nodeListGeoPoints.item(i);
114
                                            if(node.getNodeName().equals(RasterMetaFileTags.POINTS_LYR)){
115
                                                    NodeList nl = node.getChildNodes();
116 6641 caballero
                                                    lastViewPort = processFlyrGeoRasterNodeValue(nl);
117 5352 nacho
                                            }
118
                                            if(node.getNodeName().equals(RasterMetaFileTags.GEOPOINT)){
119
                                                    NodeList nl = node.getChildNodes();
120 6641 caballero
                                                    processGeoPointNodeValue(nl);
121 5352 nacho
                                            }
122
                                    }
123
                                    this.geoPointList = lyrPoints.getListPoint();
124 6641 caballero
125 5217 nacho
                                }
126
                        }
127
                }
128 6641 caballero
129 5217 nacho
            } catch (ParserConfigurationException e) {
130
                    return;
131
            } catch (SAXException e1) {
132
                    return;
133
            } catch (IOException e1) {
134
                    return;
135
            }
136
        }
137 6641 caballero
138 5217 nacho
        /**
139
         * Crea el XML con la lista de puntos y la salva a disco
140
         * @param file
141
         */
142
        public void savePointList(String file){
143
                this.geoPointList = lyrPoints.getListPoint();
144
                try {
145
                        DocumentBuilderFactory dbFactory = DocumentBuilderFactoryImpl.newInstance();
146
                    DocumentBuilder docBuilder = dbFactory.newDocumentBuilder();
147
                    xmlDoc = docBuilder.newDocument();
148
                } catch(Exception e) {
149
                      System.out.println(e);
150
                }
151 6641 caballero
152 5352 nacho
                generalTag = xmlDoc.createElement(RasterMetaFileTags.GEOPOINTS);
153 5217 nacho
                xmlDoc.appendChild(generalTag);
154 6641 caballero
155 5217 nacho
                createXMLFLyrGeoRasterNode(lyrPoints.getLyrGeoRaster());
156 6641 caballero
157 5217 nacho
                for(int i=0;i<geoPointList.size();i++)
158
                        createXMLGeoPointNode((GeoPoint)(geoPointList.get(i)), i);
159 6641 caballero
160 5217 nacho
                XML2File(Document2Text(), file);
161 6641 caballero
        }
162
163 5217 nacho
        /**
164 5818 nacho
         * Crea la lista de puntos a partir de un fichero CSV
165
         * @param file
166
         */
167
        public void loadCSVPointList(String file){
168
                try{
169
                        BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
170
                        String line = in.readLine();
171
                        int nPoint = 0;
172
                        while(line != null){
173
                                if(nPoint == 0){
174
                                        if(!line.equals("\"Pt\",\"X\",\"Y\",\"X'\",\"Y'\",\"ErrX\",\"ErrY\",\"RMS\""))
175
                                                return;
176
                                }else{
177
                                        double x = 0D, y = 0D, xx = 0D, yy = 0D;
178
                                        String[] tokens = line.split(",");
179
                                    for(int tok=0; tok<tokens.length;tok++){
180
                                            try{
181
                                                    if(tok == 1)
182 6641 caballero
                                                            x = Double.parseDouble(tokens[tok]);
183 5818 nacho
                                                    if(tok == 2)
184
                                                            y = Double.parseDouble(tokens[tok]);
185
                                                    if(tok == 3)
186
                                                            xx = Double.parseDouble(tokens[tok]);
187
                                                    if(tok == 4)
188
                                                            yy = Double.parseDouble(tokens[tok]);
189
                                            }catch(NumberFormatException ex){
190
                                                    return;
191
                                            }
192
                                    }
193
                                        int pos = nPoint - 1;
194 6641 caballero
195 5818 nacho
                                        if(x == 0 && y == 0 && xx == 0 && yy == 0){
196
                                                line = in.readLine();
197
                                                continue;
198
                                        }
199 6641 caballero
200 5818 nacho
                                        lyrPoints.getPointManager().newEmptyPoint();
201
                                    Point2D p = new Point2D.Double();
202
                                        p.setLocation(x, y);
203
                                        Point2D m = new Point2D.Double();
204
                                        m.setLocation(xx, yy);
205 6641 caballero
206 5818 nacho
                                        Point2D leftCenter = new Point2D.Double();
207
                                        leftCenter.setLocation(lyrPoints.getLyrGeoRaster().img2World(p));
208
                                        Point2D rightCenter = new Point2D.Double();
209
                                        rightCenter.setLocation(m);
210 6641 caballero
211 5818 nacho
                                        View theView = null;
212
                                        ViewPort viewPort = null;
213
                                try{
214 6880 cesar
                                        theView = (View) PluginServices.getMDIManager().getActiveWindow();
215 5818 nacho
                                        viewPort = theView.getMapControl().getMapContext().getViewPort();
216
                                }catch(ClassCastException exc){
217
                                        return ;
218
                                }
219
                                        ViewPort leftViewPort = viewPort.cloneViewPort();
220
                                        leftViewPort.setImageSize(new java.awt.Dimension(ZoomControlPanel.WIDTH_MINIMG, ZoomControlPanel.HEIGHT_MINIMG));
221
                                        ViewPort rightViewPort = viewPort.cloneViewPort();
222
                                        rightViewPort.setImageSize(new java.awt.Dimension(ZoomControlPanel.WIDTH_MINIMG, ZoomControlPanel.HEIGHT_MINIMG));
223
                                        leftViewPort = lyrPoints.getPointManager().getDialog().getZoomControlLeft().getCanvas().initViewPort(viewPort, leftCenter, leftViewPort, 1);
224
                                        rightViewPort = lyrPoints.getPointManager().getDialog().getZoomControlLeft().getCanvas().initViewPort(viewPort, rightCenter, rightViewPort, 1);
225 6641 caballero
226 5818 nacho
                                        GeoreferencingToolsModule.setEnabled(true);
227 6641 caballero
228 5818 nacho
                                        lyrPoints.setPointActive(pos, true);
229
                                        lyrPoints.setLeftCenterPoint(pos,leftCenter);
230
                                        lyrPoints.setRightCenterPoint(pos, rightCenter);
231
                                        lyrPoints.setMiniExtent(pos, lyrPoints.getLyrGeoRaster().img2World(p), leftViewPort, false);
232
                                        lyrPoints.setMiniExtent(pos, m, rightViewPort, true);
233
                                        lyrPoints.getPointManager().updateData(pos + 1, p, m, lyrPoints.getPointManager().getDialog(), null);
234
                                        lyrPoints.setZoomLeft(pos, 1);
235
                                        lyrPoints.setZoomRight(pos, 1);
236
                                        if(lyrPoints.getCountPoints() > 0){
237
                                                GeoreferencingDialog grd = lyrPoints.getPointManager().getDialog();
238
                                                grd.getConectorPanel().getDataPointsTabPanel().getSelectPointsPanel().getTableControlerPanel().setNItems(lyrPoints.getCountPoints());
239
                                                grd.getConectorPanel().getDataPointsTabPanel().getTablePointsPanel().getTableControlerPanel().setNItems(lyrPoints.getCountPoints());
240
                                                lyrPoints.getPointManager().selectPoint(0, grd);
241
                                        }
242
                                }
243
                                nPoint++;
244
                                line = in.readLine();
245
                        }
246
                        in.close();
247
                }catch(FileNotFoundException ex){
248
                        //No salvamos el csv
249
                }catch(IOException ex){
250
                        //No salvamos el csv
251
                }
252
        }
253 6641 caballero
254 5818 nacho
        /**
255 5217 nacho
         * Crea el fichero Ascii con la lista de puntos y la salva a disco
256
         * @param file
257
         */
258 5818 nacho
        public void saveCSVPointList(String file){
259 5217 nacho
                this.geoPointList = lyrPoints.getListPoint();
260 5447 nacho
                try{
261
                        BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file)));
262
                        if(lyrPoints.getLyrGeoRaster().getGeoDialog().isErrorCSV())
263
                                out.write("\"Pt\",\"X\",\"Y\",\"X'\",\"Y'\",\"ErrX\",\"ErrY\",\"RMS\"\n");
264
                        else
265
                                out.write("\"Pt\",\"X\",\"Y\",\"X'\",\"Y'\"\n");
266 6641 caballero
267 5447 nacho
                        for(int i=0;i<geoPointList.size();i++){
268
                                GeoPoint geoPoint =  (GeoPoint)geoPointList.get(i);
269
                                String point = (i+1)+","+
270
                                                                geoPoint.pixelPoint.getX()+","+
271
                                                                geoPoint.pixelPoint.getY()+","+
272
                                                                geoPoint.mapPoint.getX()+","+
273
                                                                geoPoint.mapPoint.getY();
274 5460 nacho
                                double[][] err = lyrPoints.getLyrGeoRaster().getGeoDialog().getErrors();
275 5447 nacho
                                String error = "";
276 5460 nacho
                                try{
277
                                        error = err[i][0]+","+err[i][1]+","+err[i][2];
278
                                        if(lyrPoints.getLyrGeoRaster().getGeoDialog().isErrorCSV())
279
                                                out.write(point+","+error+"\n");
280
                                        else
281
                                                out.write(point+"\n");
282
                                }catch(ArrayIndexOutOfBoundsException ex){
283 5447 nacho
                                        out.write(point+"\n");
284 5460 nacho
                                }
285 6641 caballero
                        }
286 5447 nacho
                        out.close();
287
                }catch(FileNotFoundException ex){
288
                        //No salvamos el csv
289
                }catch(IOException ex){
290
                        //No salvamos el csv
291
                }
292 6641 caballero
        }
293 5217 nacho
        //****************************************************
294 6641 caballero
295 5217 nacho
        /**
296 6641 caballero
         * Aplica una transformaci?n al extent dependiendo de si el extent de la imagen
297 5217 nacho
         * original ha cambiado o no. Si la capa FLyrGeoRaster cargada tiene un extent
298 6641 caballero
         * distinto al que se ha salvado en el fichero de puntos esto significa que el
299 5217 nacho
         * extent de la miniimagen que tiene los puntos relativos a las coordenadas de la
300 6641 caballero
         * imagen en pixels ha de sufrir un desplazamiento. Este cambio puede producirse
301
         * cuando el usuario carga un proyecto con una capa a georreferenciar y la desplaza de
302 5550 nacho
         * sitio con las herramientas. Posteriormente puede cargar los puntos del fichero .rmf
303 6641 caballero
         * @param imgExtent Extent de la imagen
304 5217 nacho
         * @param miniExtent ViewPor del miniextent a transformar
305 6641 caballero
         * @return ViewPort        ViewPort del miniextent transformado
306 5217 nacho
         */
307
        private ViewPort transformMiniExtent(Rectangle2D imgExtent, ViewPort miniExtent){
308
                if(        lastViewPort[0] != imgExtent.getMinX() ||
309
                        lastViewPort[1] != imgExtent.getMinY() ||
310
                        lastViewPort[2] != imgExtent.getWidth() ||
311
                        lastViewPort[3] != imgExtent.getHeight()){
312
                        Rectangle2D r = new Rectangle2D.Double();
313 6641 caballero
                        r.setRect(         miniExtent.getExtent().getMinX() - (lastViewPort[0] - imgExtent.getMinX()),
314 5217 nacho
                                                miniExtent.getExtent().getMinY() - (lastViewPort[1] - imgExtent.getMinY()),
315
                                                miniExtent.getExtent().getWidth(),
316
                                                miniExtent.getExtent().getHeight());
317
                        miniExtent.setExtent(r);
318
                }
319
                return miniExtent;
320
        }
321 6641 caballero
322 5217 nacho
        /**
323 6641 caballero
         * Aplica una transformaci?n al centro del extent dependiendo de si el extent de la imagen
324
         * original ha cambiado o no.
325 5217 nacho
         */
326
        private Point2D transformCenter(Rectangle2D imgExtent, Point2D center){
327
                if(        lastViewPort[0] != imgExtent.getMinX() ||
328
                        lastViewPort[1] != imgExtent.getMinY() ||
329
                        lastViewPort[2] != imgExtent.getWidth() ||
330
                        lastViewPort[3] != imgExtent.getHeight()){
331
                        Point2D c = new Point2D.Double();
332 6641 caballero
                        c.setLocation(center.getX() - (lastViewPort[0] - imgExtent.getMinX()),
333 5217 nacho
                                                  center.getY() - (lastViewPort[1] - imgExtent.getMinY()));
334
                        return c;
335
                }
336
                return center;
337
        }
338 6641 caballero
339 5217 nacho
        /**
340
         * Obtiene el valor del extent de la imagen obtenido desde un nodo
341
         * XML. A partir de este valor obtenido crea un punto en la capa.
342
         */
343
        private double[] processFlyrGeoRasterNodeValue(NodeList nl){
344
                double[] res = null;
345
                for(int j=0;j<nl.getLength();j++){
346
                        Node geoNode = nl.item(j);
347 5352 nacho
                        if(geoNode.getNodeName().equals(RasterMetaFileTags.POINTS_VP)){
348 5550 nacho
                                res = new double[7];
349 5217 nacho
                                NodeList vpChildNodes = geoNode.getChildNodes();
350
                                for(int i=0;i<vpChildNodes.getLength();i++){
351
                                        Node vpNode = vpChildNodes.item(i);
352 5352 nacho
                                        if(vpNode.getNodeName().equals(RasterMetaFileTags.POINTS_BBOX)){
353 5217 nacho
                                                NodeList extentChildNodes = vpNode.getChildNodes();
354
                                                for(int k=0;k<extentChildNodes.getLength();k++){
355
                                                        Node extentNode = extentChildNodes.item(k);
356 5352 nacho
                                                        if(extentNode.getNodeName().equals(RasterMetaFileTags.POINTS_PX))
357 5217 nacho
                                                                res[0] = Double.valueOf(extentNode.getFirstChild().getNodeValue()).doubleValue();
358 5352 nacho
                                                        if(extentNode.getNodeName().equals(RasterMetaFileTags.POINTS_PY))
359 5217 nacho
                                                                res[1] = Double.valueOf(extentNode.getFirstChild().getNodeValue()).doubleValue();
360 5352 nacho
                                                        if(extentNode.getNodeName().equals(RasterMetaFileTags.POINTS_W))
361 5217 nacho
                                                                res[2] = Double.valueOf(extentNode.getFirstChild().getNodeValue()).doubleValue();
362 5352 nacho
                                                        if(extentNode.getNodeName().equals(RasterMetaFileTags.POINTS_H))
363 5217 nacho
                                                                res[3] = Double.valueOf(extentNode.getFirstChild().getNodeValue()).doubleValue();
364
                                                }
365
                                        }
366 5392 nacho
                                        if(vpNode.getNodeName().equals(RasterMetaFileTags.POINTS_DIM)){
367
                                                NodeList dimChildNodes = vpNode.getChildNodes();
368
                                                for(int k=0; k<dimChildNodes.getLength();k++){
369
                                                        Node dimNode = dimChildNodes.item(k);
370
                                                        if(dimNode.getNodeName().equals(RasterMetaFileTags.WIDTH))
371
                                                                res[4] = Double.valueOf(dimNode.getFirstChild().getNodeValue()).doubleValue();
372
                                                        if(dimNode.getNodeName().equals(RasterMetaFileTags.HEIGHT))
373
                                                                res[5] = Double.valueOf(dimNode.getFirstChild().getNodeValue()).doubleValue();
374
                                                }
375
                                                lyrPoints.getLyrGeoRaster().setImageDimension(res[4], res[5]);
376
                                        }
377 5217 nacho
                                }
378
                        }
379
                }
380
                return res;
381
        }
382 6641 caballero
383 5217 nacho
        /**
384
         * Obtiene el valor de un punto georeferenciado obtenido desde un nodo
385
         * XML. A partir de este valor obtenido crea un punto en la capa.
386
         */
387
        private void processGeoPointNodeValue(NodeList nl){
388
                Point2D leftCenter = null, rightCenter = null;
389
                ViewPort leftViewPort = null, rightViewPort = null;
390 5550 nacho
                double zoomLeft = 1, zoomRight = 1;
391 5217 nacho
                double pX = 0D, pY = 0D, mX = 0D, mY = 0D;
392
                boolean active = false;
393
                for(int j=0;j<nl.getLength();j++){
394
                        Node geoNode = nl.item(j);
395 5352 nacho
                        if(geoNode.getNodeName().equals(RasterMetaFileTags.GEOPOINT_PX))
396 5217 nacho
                                pX = Double.valueOf(geoNode.getFirstChild().getNodeValue()).doubleValue();
397 5352 nacho
                        if(geoNode.getNodeName().equals(RasterMetaFileTags.GEOPOINT_PY))
398 5217 nacho
                                pY = Double.valueOf(geoNode.getFirstChild().getNodeValue()).doubleValue();
399 5352 nacho
                        if(geoNode.getNodeName().equals(RasterMetaFileTags.GEOPOINT_MAPX))
400 5217 nacho
                                mX = Double.valueOf(geoNode.getFirstChild().getNodeValue()).doubleValue();
401 5352 nacho
                        if(geoNode.getNodeName().equals(RasterMetaFileTags.GEOPOINT_MAPY))
402 5217 nacho
                                mY = Double.valueOf(geoNode.getFirstChild().getNodeValue()).doubleValue();
403 5352 nacho
                        if(geoNode.getNodeName().equals(RasterMetaFileTags.GEOPOINT_ACTIVE))
404 5217 nacho
                                active =  Boolean.valueOf(geoNode.getFirstChild().getNodeValue()).booleanValue();
405 5352 nacho
                        if(geoNode.getNodeName().equals(RasterMetaFileTags.GEOPOINT_LCENTER))
406 5217 nacho
                                leftCenter = processCenterPoint(geoNode.getChildNodes());
407 5352 nacho
                        if(geoNode.getNodeName().equals(RasterMetaFileTags.GEOPOINT_RCENTER))
408 5217 nacho
                                rightCenter = processCenterPoint(geoNode.getChildNodes());
409 5550 nacho
                        if(geoNode.getNodeName().equals(RasterMetaFileTags.GEOPOINT_LVP)){
410
                                Object[] obj = processViewPort(geoNode.getChildNodes());
411
                                leftViewPort = (ViewPort)obj[0];
412
                                zoomLeft = ((Double)obj[1]).doubleValue();
413
                        }
414
                        if(geoNode.getNodeName().equals(RasterMetaFileTags.GEOPOINT_RVP)){
415
                                Object[] obj = processViewPort(geoNode.getChildNodes());
416
                                rightViewPort = (ViewPort)obj[0];
417
                                zoomRight = ((Double)obj[1]).doubleValue();
418
                        }
419 5217 nacho
                }
420 6641 caballero
421 5217 nacho
                Point2D p = new Point2D.Double();
422
                p.setLocation(pX, pY);
423
                Point2D m = new Point2D.Double();
424
                m.setLocation(mX, mY);
425 6641 caballero
426 5217 nacho
                lyrPoints.getPointManager().newEmptyPoint();
427 5241 nacho
                GeoreferencingToolsModule.setEnabled(true);
428 6641 caballero
429 5217 nacho
                int pos = lyrPoints.getCountPoints() -1;
430
                try{
431
                        leftViewPort = transformMiniExtent(lyrPoints.getLyrGeoRaster().getFullExtent(), leftViewPort);
432
                        leftCenter = transformCenter(lyrPoints.getLyrGeoRaster().getFullExtent(), leftCenter);
433
                }catch(DriverException ex){}
434
                lyrPoints.setPointActive(pos, active);
435
                lyrPoints.setLeftCenterPoint(pos,leftCenter);
436
                lyrPoints.setRightCenterPoint(pos, rightCenter);
437 5743 nacho
                lyrPoints.setMiniExtent(pos, lyrPoints.getLyrGeoRaster().img2World(p), leftViewPort, false);
438
                lyrPoints.setMiniExtent(pos, m, rightViewPort, true);
439
                lyrPoints.getPointManager().updateData(pos + 1, p, m, lyrPoints.getPointManager().getDialog(), null);
440 5550 nacho
                lyrPoints.setZoomLeft(pos, zoomLeft);
441
                lyrPoints.setZoomRight(pos, zoomRight);
442 5217 nacho
                if(lyrPoints.getCountPoints() > 0){
443
                        GeoreferencingDialog grd = lyrPoints.getPointManager().getDialog();
444
                        grd.getConectorPanel().getDataPointsTabPanel().
445
                                getSelectPointsPanel().getTableControlerPanel().setNItems(lyrPoints.getCountPoints());
446
                        grd.getConectorPanel().getDataPointsTabPanel().
447
                                getTablePointsPanel().getTableControlerPanel().setNItems(lyrPoints.getCountPoints());
448
                        lyrPoints.getPointManager().selectPoint(0, grd);
449
                }
450
                //lyrPoints.addPoint(p, m);
451
        }
452 6641 caballero
453 5217 nacho
        /**
454
         * Procesa un nodo correspondiente a un extent
455
         * @param nodeList Lista de nodos
456
         * @return Rectangle2D
457
         */
458
        private Rectangle2D processExtent(NodeList nodeList){
459
                Rectangle2D r = new Rectangle2D.Double();
460
                double x = 0D, y = 0D, width = 0D, height = 0D;
461
                for(int j=0;j<nodeList.getLength();j++){
462
                        Node node = nodeList.item(j);
463 5352 nacho
                        if(node.getNodeName().equals(RasterMetaFileTags.POINTS_PX))
464 5217 nacho
                                x = Double.valueOf(node.getFirstChild().getNodeValue()).doubleValue();
465 5352 nacho
                        if(node.getNodeName().equals(RasterMetaFileTags.POINTS_PY))
466 5217 nacho
                                y = Double.valueOf(node.getFirstChild().getNodeValue()).doubleValue();
467 5352 nacho
                        if(node.getNodeName().equals(RasterMetaFileTags.POINTS_W))
468 5217 nacho
                                width = Double.valueOf(node.getFirstChild().getNodeValue()).doubleValue();
469 5352 nacho
                        if(node.getNodeName().equals(RasterMetaFileTags.POINTS_H))
470 5217 nacho
                                height = Double.valueOf(node.getFirstChild().getNodeValue()).doubleValue();
471
                }
472
                r.setRect(x, y, width, height);
473
                return r;
474
        }
475 6641 caballero
476 5217 nacho
        /**
477
         * Procesa un nodo correspondiente a la dimension de un viewPort
478
         * @param nodeList Lista de nodos
479
         * @return Rectangle2D
480
         */
481
        private Dimension processImageSize(NodeList nodeList){
482
                Dimension d = new Dimension();
483
                double x = 0D, y = 0D;
484
                for(int j=0;j<nodeList.getLength();j++){
485
                        Node node = nodeList.item(j);
486 5352 nacho
                        if(node.getNodeName().equals(RasterMetaFileTags.WIDTH))
487 5217 nacho
                                x = Double.valueOf(node.getFirstChild().getNodeValue()).doubleValue();
488 5352 nacho
                        if(node.getNodeName().equals(RasterMetaFileTags.HEIGHT))
489 5217 nacho
                                y = Double.valueOf(node.getFirstChild().getNodeValue()).doubleValue();
490
                }
491
                d.setSize(x, y);
492
                return d;
493
        }
494 6641 caballero
495 5217 nacho
        /**
496
         * Procesa el nodo correspondiente a un viewport de una mini imagen
497
         * @param nodeList Lista de nodos
498
         * @return ViewPort obtenido
499
         */
500 5550 nacho
        private Object[] processViewPort(NodeList nodeList){
501
                Object[] obj = new Object[2];
502 5217 nacho
                ViewPort vp = new ViewPort(null);
503 5550 nacho
                Double zoom =  new Double(1);
504 5217 nacho
                for(int j=0;j<nodeList.getLength();j++){
505
                        Node node = nodeList.item(j);
506 5352 nacho
                        if(node.getNodeName().equals(RasterMetaFileTags.POINTS_PROJ))
507 7703 luisw2
                                vp.setProjection(CRSFactory.getCRS(node.getFirstChild().getNodeValue()));
508 5352 nacho
                        if(node.getNodeName().equals(RasterMetaFileTags.POINTS_BBOX))
509 5217 nacho
                                vp.setExtent(processExtent(node.getChildNodes()));
510 5352 nacho
                        if(node.getNodeName().equals(RasterMetaFileTags.POINTS_DIM))
511 5217 nacho
                                vp.setImageSize(processImageSize(node.getChildNodes()));
512 5550 nacho
                        if(node.getNodeName().equals(RasterMetaFileTags.POINTS_ZOOM))
513
                                zoom = new Double(node.getFirstChild().getNodeValue());
514 5217 nacho
                }
515 5550 nacho
                obj[0] = vp;
516
                obj[1] = zoom;
517 6641 caballero
                vp.refreshExtent();
518 5550 nacho
                return obj;
519 5217 nacho
        }
520 6641 caballero
521 5217 nacho
        /**
522
         * Procesa un node correspondiente a un punto central de una
523
         * mini imagen
524
         * @param nodeList Lista de elementos del nodo centro
525
         * @return Punto obtenido
526
         */
527
        private Point2D processCenterPoint(NodeList nodeList){
528
                Point2D p = new Point2D.Double();
529
                double x = 0D, y = 0D;
530
                for(int j=0;j<nodeList.getLength();j++){
531
                        Node node = nodeList.item(j);
532 5352 nacho
                        if(node.getNodeName().equals(RasterMetaFileTags.POSX))
533 5217 nacho
                                x = Double.valueOf(node.getFirstChild().getNodeValue()).doubleValue();
534 5352 nacho
                        if(node.getNodeName().equals(RasterMetaFileTags.POSY))
535 5217 nacho
                                y = Double.valueOf(node.getFirstChild().getNodeValue()).doubleValue();
536
                }
537
                p.setLocation(x, y);
538
                return p;
539
        }
540
541
        //****************************************************
542 6641 caballero
543 5217 nacho
        /**
544
         * Crea un elemento simple xml de la forma <elem>texNode</elem>
545
         * a?adiendoselo al elemento padre pasado por par?metro
546
         * @param parent Elemento padre del XML
547
         * @param elem        tag
548
         * @param textNode        valor
549
         */
550
        private void createSimpleElement(Element parent, String elem, String textNode){
551
                Element itemlevel1 = null;
552
                itemlevel1 = xmlDoc.createElement(elem);
553
                itemlevel1.appendChild(xmlDoc.createTextNode(textNode));
554 6641 caballero
                parent.appendChild(itemlevel1);
555 5217 nacho
        }
556 6641 caballero
557 5217 nacho
        /**
558
         * Crear un bloque que representa un viewport
559
         * @param parent Elemento padre del XML
560
         * @param elem tag
561
         * @param values lista de valores
562
         */
563
        private void createViewPortNode(Element parent, String elem, String[] values){
564
                Element itemlevel1 = null;
565
                Element itemlevel2 = null;
566
                itemlevel1 = xmlDoc.createElement(elem);
567 5352 nacho
                createSimpleElement(itemlevel1, RasterMetaFileTags.POINTS_PROJ, values[6]);
568
                itemlevel2 = xmlDoc.createElement(RasterMetaFileTags.POINTS_BBOX);
569
                createSimpleElement(itemlevel2, RasterMetaFileTags.POINTS_PX, values[0]);
570
                createSimpleElement(itemlevel2, RasterMetaFileTags.POINTS_PY, values[1]);
571
                createSimpleElement(itemlevel2, RasterMetaFileTags.POINTS_W, values[2]);
572
                createSimpleElement(itemlevel2, RasterMetaFileTags.POINTS_H, values[3]);
573 5217 nacho
                itemlevel1.appendChild(itemlevel2);
574 5352 nacho
                itemlevel2 = xmlDoc.createElement(RasterMetaFileTags.POINTS_DIM);
575
                createSimpleElement(itemlevel2, RasterMetaFileTags.WIDTH, values[4]);
576
                createSimpleElement(itemlevel2, RasterMetaFileTags.HEIGHT, values[5]);
577 6641 caballero
                itemlevel1.appendChild(itemlevel2);
578 5550 nacho
                if(values.length == 8)
579
                        createSimpleElement(itemlevel1, RasterMetaFileTags.POINTS_ZOOM, values[7]);
580 5217 nacho
                parent.appendChild(itemlevel1);
581
        }
582 6641 caballero
583 5217 nacho
        /**
584
         * Convierte la capa a georreferenciar a un elemento XML que ser? a?adidoo al
585 6641 caballero
         * documento.
586
         * @param lyrGeo Capa a georreferenciar
587 5217 nacho
         */
588
        private void createXMLFLyrGeoRasterNode(FLyrGeoRaster lyrGeo) {
589
                Element xmlGeoPoint;
590 5352 nacho
                xmlGeoPoint = xmlDoc.createElement(RasterMetaFileTags.POINTS_LYR);
591 5217 nacho
                generalTag.appendChild(xmlGeoPoint);
592
                xmlGeoPoint.setAttribute("Name", lyrGeo.getName());
593
                String[] vpData = {String.valueOf(lyrGeo.getMinX()),
594
                                                        String.valueOf(lyrGeo.getMinY()),
595
                                                        String.valueOf(lyrGeo.getWidth()),
596
                                                        String.valueOf(lyrGeo.getHeight()),
597
                                                        String.valueOf(lyrGeo.getImageWidth()),
598
                                                        String.valueOf(lyrGeo.getImageHeight()),
599 5550 nacho
                                                        lyrGeo.getProjection().getAbrev(),
600
                                                        };
601 5352 nacho
                createViewPortNode(xmlGeoPoint, RasterMetaFileTags.POINTS_VP, vpData);
602 5217 nacho
        }
603 6641 caballero
604 5217 nacho
        /**
605 6641 caballero
         * Convierte un geopunto a un elemento XML que ser? a?adido al
606
         * documento.
607 5217 nacho
         * @param geoPoint GeoPoint
608
         * @param i Posici?n del punto en la lista
609
         */
610
        private void createXMLGeoPointNode(GeoPoint geoPoint, int i) {
611
                Element xmlGeoPoint;
612
                Element itemlevel1;
613
614 5352 nacho
                xmlGeoPoint = xmlDoc.createElement(RasterMetaFileTags.GEOPOINT);
615 5217 nacho
                xmlGeoPoint.setAttribute("n", String.valueOf(i));
616
                generalTag.appendChild(xmlGeoPoint);
617 6641 caballero
618 5352 nacho
                createSimpleElement(xmlGeoPoint, RasterMetaFileTags.GEOPOINT_PX, String.valueOf(geoPoint.pixelPoint.getX()));
619
                createSimpleElement(xmlGeoPoint, RasterMetaFileTags.GEOPOINT_PY, String.valueOf(geoPoint.pixelPoint.getY()));
620
                createSimpleElement(xmlGeoPoint, RasterMetaFileTags.GEOPOINT_MAPX, String.valueOf(geoPoint.mapPoint.getX()));
621
                createSimpleElement(xmlGeoPoint, RasterMetaFileTags.GEOPOINT_MAPY, String.valueOf(geoPoint.mapPoint.getY()));
622
                createSimpleElement(xmlGeoPoint, RasterMetaFileTags.GEOPOINT_ACTIVE, String.valueOf(geoPoint.active));
623 6641 caballero
624 5352 nacho
                itemlevel1 = xmlDoc.createElement(RasterMetaFileTags.GEOPOINT_LCENTER);
625
                createSimpleElement(itemlevel1, RasterMetaFileTags.POSX, String.valueOf(geoPoint.leftCenterPoint.getX()));
626
                createSimpleElement(itemlevel1, RasterMetaFileTags.POSY, String.valueOf(geoPoint.leftCenterPoint.getY()));
627 5217 nacho
                xmlGeoPoint.appendChild(itemlevel1);
628 6641 caballero
629 5352 nacho
                itemlevel1 = xmlDoc.createElement(RasterMetaFileTags.GEOPOINT_RCENTER);
630
                createSimpleElement(itemlevel1, RasterMetaFileTags.POSX, String.valueOf(geoPoint.rightCenterPoint.getX()));
631
                createSimpleElement(itemlevel1, RasterMetaFileTags.POSY, String.valueOf(geoPoint.rightCenterPoint.getY()));
632 5217 nacho
                xmlGeoPoint.appendChild(itemlevel1);
633 6641 caballero
634 5217 nacho
                String[] values1 = {String.valueOf(geoPoint.leftViewPort.getExtent().getX()),
635
                                                        String.valueOf(geoPoint.leftViewPort.getExtent().getY()),
636
                                                        String.valueOf(geoPoint.leftViewPort.getExtent().getWidth()),
637
                                                        String.valueOf(geoPoint.leftViewPort.getExtent().getHeight()),
638
                                                        String.valueOf(geoPoint.leftViewPort.getImageWidth()),
639
                                                        String.valueOf(geoPoint.leftViewPort.getImageHeight()),
640 5550 nacho
                                                        geoPoint.leftViewPort.getProjection().getAbrev(),
641
                                                        String.valueOf(geoPoint.zoomLeft)};
642 5352 nacho
                createViewPortNode(xmlGeoPoint, RasterMetaFileTags.GEOPOINT_LVP, values1);
643 6641 caballero
644 5217 nacho
                String[] values2 = {String.valueOf(geoPoint.rightViewPort.getExtent().getX()),
645
                                                        String.valueOf(geoPoint.rightViewPort.getExtent().getY()),
646
                                                        String.valueOf(geoPoint.rightViewPort.getExtent().getWidth()),
647
                                                        String.valueOf(geoPoint.rightViewPort.getExtent().getHeight()),
648
                                                        String.valueOf(geoPoint.rightViewPort.getImageWidth()),
649
                                                        String.valueOf(geoPoint.rightViewPort.getImageHeight()),
650 5550 nacho
                                                        geoPoint.rightViewPort.getProjection().getAbrev(),
651
                                                        String.valueOf(geoPoint.zoomRight)};
652 5217 nacho
653 6641 caballero
                createViewPortNode(xmlGeoPoint, RasterMetaFileTags.GEOPOINT_RVP, values2);
654 5217 nacho
    }
655 6641 caballero
656 5217 nacho
        //****************************************************
657 6641 caballero
658 5217 nacho
        /**
659
         * escribe a disco el texto XML
660
         * @param textXML        Texto XML
661
         * @param fileName        Nombre del fichero
662
         */
663
        private void XML2File(String textXML, String fileName) {
664
            try {
665
              OutputStream fout= new FileOutputStream(fileName);
666
              OutputStream bout= new BufferedOutputStream(fout);
667
              OutputStreamWriter out = new OutputStreamWriter(bout);
668
              out.write(textXML);
669
              out.flush();
670
              out.close();
671 5328 nacho
              File rmfFile = new File(fileName.substring(0, fileName.lastIndexOf("."))+".rmf");
672
              if(rmfFile.exists())
673
                      mergeFiles(fileName);
674
              else
675 6641 caballero
                     newRmfFile(fileName, rmfFile);
676
677 5217 nacho
            }catch (IOException e) {
678
              System.out.println(e.getMessage());
679
            }
680
        }
681 6641 caballero
682 5217 nacho
        /**
683 5329 nacho
         * En el caso de que no exista ning?n fichero .rmf asociado a la imagen a georreferenciar lo creamos
684 6641 caballero
         * con la cabecera rmf y los puntos que hemos salvado en el fichero temporal (.grf)
685 5329 nacho
         * @param grfStr Nombre del fichero temporal .grf
686
         * @param rmf Fichero donde se salvaran los puntos .rmf
687 5328 nacho
         */
688
        private void newRmfFile(String grfStr, File rmf){
689
                try{
690
                        File grf = new File(grfStr);
691
                        BufferedReader inGrf = new BufferedReader(new InputStreamReader(new FileInputStream(grf)));
692
                        BufferedWriter outTmp = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(rmf)));
693 6641 caballero
694 5352 nacho
                        outTmp.write("<?xml version=\"1.0\" encoding=\""+RasterMetaFileTags.ENCODING+"\"?>\n");
695 5329 nacho
                        outTmp.write("<"+RasterMetaFileTags.MAIN_TAG+" "+"xmlns=\""+RasterMetaFileTags.NAMESPACE+"\">\n");
696 5328 nacho
                        String str = inGrf.readLine();
697 5329 nacho
                        str = inGrf.readLine();
698 5328 nacho
                        while(str != null){
699
                                outTmp.write(str+"\n");
700
                               str = inGrf.readLine();
701
                    }
702 5329 nacho
                        outTmp.write("</"+RasterMetaFileTags.MAIN_TAG+">\n");
703
                        grf.delete();
704 5328 nacho
                        inGrf.close();
705
                        outTmp.close();
706
                }catch(FileNotFoundException exc){
707 6641 caballero
708 5328 nacho
                }catch(IOException exc){
709 6641 caballero
710 5328 nacho
                }
711
        }
712 6641 caballero
713 5328 nacho
        /**
714 5329 nacho
         * En el caso de que ya exista un fichero .rmf asociado a la imagen habr? que mezclar este
715
         * con los puntos que hemos salvado en el fichero temporal .grf
716
         * @param fileName Nombre del fichero temporal
717 6641 caballero
         */
718 5329 nacho
        private void mergeFiles(String grfName){
719 5328 nacho
                try{
720 5329 nacho
                        File rmfFile = new File(grfName.substring(0, grfName.lastIndexOf("."))+".rmf");
721
                        File grfFile = new File(grfName);
722 5328 nacho
                        File out = new File(rmfFile+"_tmpOutput");
723 6641 caballero
724 5328 nacho
                        BufferedReader inRmf = new BufferedReader(new InputStreamReader(new FileInputStream(rmfFile)));
725
                        BufferedReader inGrf = new BufferedReader(new InputStreamReader(new FileInputStream(grfFile)));
726
                        BufferedWriter outTmp = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(out)));
727 6641 caballero
728 5328 nacho
                        //Leemos el principio del .rmf
729
                String str = inRmf.readLine();
730 6641 caballero
                while(!str.startsWith("</"+RasterMetaFileTags.LAYER) &&
731 5371 nacho
                          !str.startsWith("<"+RasterMetaFileTags.GEOPOINTS)){
732 5328 nacho
                        outTmp.write(str+"\n");
733
                        str = inRmf.readLine();
734
                }
735 5329 nacho
                if(str.startsWith("</"+RasterMetaFileTags.LAYER))
736
                        outTmp.write(str+"\n");
737 6641 caballero
738 5328 nacho
                //Leemos la lista de puntos
739
                str = inGrf.readLine();
740
                while(str != null){
741 5329 nacho
                        if(!str.startsWith("<?xml"))
742
                                outTmp.write(str+"\n");
743 5328 nacho
                        str = inGrf.readLine();
744
                }
745 6641 caballero
746 5328 nacho
                //Saltamos los puntos que ya existian en el .rmf
747 5352 nacho
                try{
748 5328 nacho
                        str = inRmf.readLine();
749 6641 caballero
                        while(str != null &&
750
                                  !str.startsWith("</"+RasterMetaFileTags.GEOPOINTS) &&
751 5352 nacho
                                  !str.startsWith("</"+RasterMetaFileTags.MAIN_TAG))
752
                                str = inRmf.readLine();
753
                }catch(Exception exc){
754 6641 caballero
755 5352 nacho
                }
756 6641 caballero
757 5328 nacho
                //Leemos el resto del fichero .rmf
758 5352 nacho
                if( !str.startsWith("</"+RasterMetaFileTags.MAIN_TAG))
759
                        str = inRmf.readLine();
760 5328 nacho
                while(str != null){
761 5329 nacho
                        if(!str.startsWith("<?xml"))
762
                                outTmp.write(str+"\n");
763 5328 nacho
                        str = inRmf.readLine();
764
                }
765 6641 caballero
766 5328 nacho
                outTmp.close();
767
                inRmf.close();
768
                inGrf.close();
769 6641 caballero
770 5328 nacho
                //Eliminamos el antiguo .rmf y lo sustituimos
771
                rmfFile.delete();
772
                out.renameTo(rmfFile);
773
                grfFile.delete();
774 6641 caballero
775 5328 nacho
                }catch(FileNotFoundException exc){
776 6641 caballero
777 5328 nacho
                }catch(IOException exc){
778 6641 caballero
779 5328 nacho
                }
780
        }
781 6641 caballero
782 5328 nacho
        /**
783 6641 caballero
         * Convierte el objeto Document que contiene el XML construido a
784 5217 nacho
         * texto XML para que podamos salvarlo a disco.
785
         * @return Cadena de texto XML
786
         */
787
        private String Document2Text() {
788
            StringWriter strWriter = null;
789
            XMLSerializer xmlSerializer = null;
790
            OutputFormat outFormat = null;
791
            try {
792
                    xmlSerializer = new XMLSerializer();
793
                    strWriter = new StringWriter();
794
                    outFormat = new OutputFormat();
795
796 5352 nacho
                    outFormat.setEncoding(RasterMetaFileTags.ENCODING);
797 5217 nacho
                    outFormat.setIndenting(true);
798
                    outFormat.setIndent(4);
799
800
                    xmlSerializer.setOutputCharStream(strWriter);
801
                    xmlSerializer.setOutputFormat(outFormat);
802
                    xmlSerializer.serialize(xmlDoc);
803
                    strWriter.close();
804
                   } catch (IOException ioEx) {
805
                      System.out.println("Error : " + ioEx);
806
                   }
807
                    return strWriter.toString();
808 6641 caballero
        }
809 5241 nacho
        //**********************End Methods***************************
810 6641 caballero
811 5241 nacho
        //**********************Getters & Setters*********************
812
        /**
813
         * Asigna la capa de puntos
814
         * @param lyrPoints
815
         */
816
        public void setLyrPoints(FLyrPoints lyrPoints) {
817
                this.geoPointList = lyrPoints.getListPoint();
818
                this.lyrPoints = lyrPoints;
819 5217 nacho
        }
820 5241 nacho
        //**********************End Getters & Setters*****************
821 5217 nacho
}