Statistics
| Revision:

root / trunk / applications / appgvSIG / src / com / iver / cit / gvsig / project / Project.java @ 33261

History | View | Annotate | Download (63 KB)

1
/* gvSIG. Sistema de Informaci�n Geogr�fica de la Generalitat Valenciana
2
 *
3
 * Copyright (C) 2004 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
 * For more information, contact:
20
 *
21
 *  Generalitat Valenciana
22
 *   Conselleria d'Infraestructures i Transport
23
 *   Av. Blasco Ib��ez, 50
24
 *   46010 VALENCIA
25
 *   SPAIN
26
 *
27
 *      +34 963862235
28
 *   gvsig@gva.es
29
 *      www.gvsig.gva.es
30
 *
31
 *    or
32
 *
33
 *   IVER T.I. S.A
34
 *   Salamanca 50
35
 *   46005 Valencia
36
 *   Spain
37
 *
38
 *   +34 963163400
39
 *   dac@iver.es
40
 */
41
package com.iver.cit.gvsig.project;
42

    
43
import java.awt.Color;
44
import java.beans.PropertyChangeEvent;
45
import java.beans.PropertyChangeListener;
46
import java.beans.PropertyChangeSupport;
47
import java.io.File;
48
import java.io.Serializable;
49
import java.text.DateFormat;
50
import java.util.ArrayList;
51
import java.util.Comparator;
52
import java.util.Date;
53
import java.util.Hashtable;
54
import java.util.Iterator;
55
import java.util.List;
56
import java.util.Map;
57
import java.util.TreeMap;
58

    
59
import org.cresques.cts.IProjection;
60
import org.gvsig.tools.file.PathGenerator;
61

    
62
import com.hardcode.driverManager.DriverLoadException;
63
import com.hardcode.gdbms.driver.exceptions.ReadDriverException;
64
import com.hardcode.gdbms.driver.exceptions.WriteDriverException;
65
import com.hardcode.gdbms.engine.data.DataSource;
66
import com.hardcode.gdbms.engine.data.DataSourceFactory;
67
import com.hardcode.gdbms.engine.data.NoSuchTableException;
68
import com.hardcode.gdbms.engine.data.SourceInfo;
69
import com.hardcode.gdbms.engine.data.db.DBSourceInfo;
70
import com.hardcode.gdbms.engine.data.db.DBTableSourceInfo;
71
import com.hardcode.gdbms.engine.data.driver.DriverException;
72
import com.hardcode.gdbms.engine.data.file.FileSourceInfo;
73
import com.hardcode.gdbms.engine.data.object.ObjectSourceInfo;
74
import com.iver.andami.PluginServices;
75
import com.iver.andami.messages.NotificationManager;
76
import com.iver.andami.ui.mdiManager.IWindow;
77
import com.iver.andami.ui.mdiManager.SingletonWindow;
78
import com.iver.andami.ui.mdiManager.WindowInfo;
79
import com.iver.cit.gvsig.ProjectExtension;
80
import com.iver.cit.gvsig.Version;
81
import com.iver.cit.gvsig.fmap.MapContext;
82
import com.iver.cit.gvsig.fmap.ViewPort;
83
import com.iver.cit.gvsig.fmap.crs.CRSFactory;
84
import com.iver.cit.gvsig.fmap.drivers.DriverIOException;
85
import com.iver.cit.gvsig.fmap.layers.FLayer;
86
import com.iver.cit.gvsig.fmap.layers.FLayers;
87
import com.iver.cit.gvsig.fmap.layers.FLyrVect;
88
import com.iver.cit.gvsig.fmap.layers.LayerFactory;
89
import com.iver.cit.gvsig.fmap.layers.LayersIterator;
90
import com.iver.cit.gvsig.fmap.layers.SelectableDataSource;
91
import com.iver.cit.gvsig.fmap.layers.XMLException;
92
import com.iver.cit.gvsig.fmap.layers.layerOperations.AlphanumericData;
93
import com.iver.cit.gvsig.fmap.operations.selection.LinkSelectionListener;
94
import com.iver.cit.gvsig.project.documents.ProjectDocument;
95
import com.iver.cit.gvsig.project.documents.ProjectDocumentFactory;
96
import com.iver.cit.gvsig.project.documents.exceptions.OpenException;
97
import com.iver.cit.gvsig.project.documents.exceptions.SaveException;
98
import com.iver.cit.gvsig.project.documents.gui.IDocumentWindow;
99
import com.iver.cit.gvsig.project.documents.gui.ProjectWindow;
100
import com.iver.cit.gvsig.project.documents.gui.WindowData;
101
import com.iver.cit.gvsig.project.documents.layout.LayoutContext;
102
import com.iver.cit.gvsig.project.documents.layout.ProjectMap;
103
import com.iver.cit.gvsig.project.documents.layout.ProjectMapFactory;
104
import com.iver.cit.gvsig.project.documents.layout.fframes.FFrameView;
105
import com.iver.cit.gvsig.project.documents.layout.fframes.IFFrame;
106
import com.iver.cit.gvsig.project.documents.layout.gui.Layout;
107
import com.iver.cit.gvsig.project.documents.table.ProjectTable;
108
import com.iver.cit.gvsig.project.documents.table.ProjectTableFactory;
109
import com.iver.cit.gvsig.project.documents.view.ProjectView;
110
import com.iver.cit.gvsig.project.documents.view.ProjectViewFactory;
111
import com.iver.utiles.IPersistence;
112
import com.iver.utiles.PostProcessSupport;
113
import com.iver.utiles.StringUtilities;
114
import com.iver.utiles.XMLEntity;
115
import com.iver.utiles.extensionPoints.ExtensionPoint;
116
import com.iver.utiles.extensionPoints.ExtensionPoints;
117
import com.iver.utiles.extensionPoints.ExtensionPointsSingleton;
118

    
119
/**
120
 * Clase que representa un proyecto de openSIG
121
 *
122
 * @author Fernando Gonz�lez Cort�s
123
 */
124
public class Project implements Serializable, PropertyChangeListener {
125
        public static String VERSION = Version.format();
126

    
127
        static private IProjection defaultProjection = null;
128

    
129
        static private IProjection defaultFactoryProjection = CRSFactory
130
                        .getCRS("EPSG:23030");
131

    
132
        /*
133
         * distiguishing between a static field "defaultSelectionColor" and a
134
         * selectionColor field will allow to define default color in a multiple
135
         * project scenario
136
         */
137
        static private Color defaultSelectionColor = Color.YELLOW;
138

    
139
        private static int defaultMapUnits = -1;
140

    
141
        private static int defaultDistanceUnits = -1;
142

    
143
        private static int defaultDistanceArea = -1;
144

    
145
        private PropertyChangeSupport change;
146

    
147
        private boolean modified = false;
148

    
149
        private String name = PluginServices.getText(this, "untitled");
150

    
151
        // private String path;
152
        private String creationDate = new Date().toGMTString();
153

    
154
        private String modificationDate = new Date().toGMTString();
155

    
156
        private String owner = "";
157

    
158
        private String comments = "";
159

    
160
        private Color selectionColor = null;
161
        
162
        private boolean isAbsolutePath = true;
163

    
164
        // private ArrayList views = new ArrayList();
165
        // private ArrayList tables = new ArrayList();
166
        // private ArrayList maps = new ArrayList();
167
        private ArrayList<ProjectDocument> documents = new ArrayList<ProjectDocument>();
168

    
169
        private ArrayList extents = new ArrayList();
170

    
171
        // Lista de objetos del tipo camera. Necesarios para almacenar la posicion
172
        // del usuario haciendo uso de los marcadores
173
        private List cameras = new ArrayList();
174

    
175
        /**
176
         * this is a runtime-calculated value, do NOT persist it!
177
         */
178
        private long signatureAtStartup;
179
        private IProjection projection;
180

    
181
        /**
182
         * Stores the initial properties of the windows, to be restored just after
183
         * the project is loaded. It's an ordered iterator of XMLEntity objects,
184
         * each containing a XML version of a WindowInfo object.
185
         */
186
        private Iterator initialWindowProperties = null;
187
        
188
        private static PathGenerator pathGenerator=PathGenerator.getInstance();
189

    
190
        private TreeMap<ProjectDocument,Integer> sortedDocuments = new TreeMap<ProjectDocument,Integer>(new Comparator() {
191
                public int compare(Object o1, Object o2) {
192
                        if ((o1 != null) && (o2 != null)) {
193
                                int priority1 = ((ProjectDocument) o1)
194
                                                .getProjectDocumentFactory().getPriority();
195
                                int priority2 = ((ProjectDocument) o2)
196
                                                .getProjectDocumentFactory().getPriority();
197
                                if (priority1 >= priority2)
198
                                        return 1;
199
                                return -1;
200
                        }
201
                        return 0;
202
                }
203
        }); // Para poder ordenar
204

    
205
        /**
206
         * Creates a new Project object.
207
         */
208
        public Project() {
209
                change = new PropertyChangeSupport(this);
210

    
211
                // change.addPropertyChangeListener(this);
212
                creationDate = DateFormat.getDateInstance().format(new Date());
213
                modificationDate = creationDate;
214
                setSelectionColor(getDefaultSelectionColor());
215
                getDefaultProjection(); //For initialize it
216
                // signatureAtStartup = computeSignature();
217

    
218
                /*
219
                 * LayerFactory.setDriversPath(PluginServices.getPluginServices(this)
220
                 * .getPluginDirectory() .getAbsolutePath() + File.separator +
221
                 * "drivers");
222
                 */
223
        }
224

    
225
        /**
226
         * Obtiene la fecha de creaci�n del proyecto
227
         *
228
         * @return
229
         */
230
        public String getCreationDate() {
231
                return creationDate;
232
        }
233

    
234
        /**
235
         * Obtiene el nombre del proyecto
236
         *
237
         * @return
238
         */
239
        public String getName() {
240
                return name;
241
        }
242

    
243
        // /**
244
        // * Obtiene la ruta completa del fichero donde se guardo por �ltima vez el
245
        // * proyecto
246
        // *
247
        // * @return
248
        // */
249
        // public String getPath() {
250
        // return path;
251
        // }
252

    
253
        /**
254
         * Asigna la fecha de creaci�n del proyecto. Este m�todo tiene sentido s�lo
255
         * por que al recuperar la fecha del XML hay que asignarla al objeto
256
         * proyecto de alguna manera. La fecha se asigna en el constructor y no se
257
         * deber�a de modificar nunca
258
         *
259
         * @param string
260
         */
261
        public void setCreationDate(String string) {
262
                creationDate = string;
263
                //modified = true;
264
                change.firePropertyChange("", null, null);
265
        }
266

    
267
        /**
268
         * Establece el nombre del proyecto
269
         *
270
         * @param string
271
         */
272
        public void setName(String string) {
273
                name = string;
274
                //modified = true;
275
                change.firePropertyChange("", null, null);
276
        }
277

    
278
        /**
279
         * Devuelve a partir de la capa la tabla asociada.
280
         *
281
         * @param co
282
         *            Capa.
283
         *
284
         * @return ProjectTable de la tabla asociada.
285
         */
286
        public ProjectTable getTable(AlphanumericData co) {
287
                ArrayList tables = getDocumentsByType(ProjectTableFactory.registerName);
288
                /**
289
                 * Como las tablas se pueden a�adir cuando se pincha en "ver tabla" de
290
                 * una capa, se puede intentar a�adir dos veces la misma tabla
291
                 */
292
                for (int i = 0; i < tables.size(); i++) {
293
                        if (((ProjectTable) tables.get(i)).getAssociatedTable() == co) {
294
                                return (ProjectTable) tables.get(i);
295
                        }
296
                }
297

    
298
                return null;
299
        }
300

    
301
        /**
302
         * Devuelve a partir del nombre la tabla asociada.
303
         *
304
         * @param name
305
         *            Nombre.
306
         * @deprecated utilizar getProjectDocumentByName(...);
307
         * @return ProjectTable de la tabla asociada.
308
         */
309
        public ProjectTable getTable(String name) {
310
                ArrayList tables = getDocumentsByType(ProjectTableFactory.registerName);
311
                /**
312
                 * Como las tablas se pueden a�adir cuando se pincha en "ver tabla" de
313
                 * una capa, se puede intentar a�adir dos veces la misma tabla
314
                 */
315
                for (int i = 0; i < tables.size(); i++) {
316
                        if (((ProjectTable) tables.get(i)).getName().equals(name)) {
317
                                return (ProjectTable) tables.get(i);
318
                        }
319
                }
320

    
321
                return null;
322
        }
323

    
324
        private boolean isModifiedDocuments() {
325
                ProjectDocument[] documents=(ProjectDocument[])getDocuments().toArray(new ProjectDocument[0]);
326
                for (int i=0;i<documents.length;i++) {
327
                        if (documents[i].isModified()) {
328
                                return true;
329
                        }
330
                }
331
                return false;
332
        }
333
//        /**
334
//         * Devuelve true si el proyecto (o alguna tabla, vista o mapa que contiene)
335
//         * fue modificado
336
//         *
337
//         * @return
338
//         */
339
//        public boolean isModified() {
340
//                if ((this.getDocuments().size() == 0) && !modified && !isModifiedDocuments()) {
341
//                        return false;
342
//                }
343
//                return true;
344
//                // /return modified; TODO El atributo modified solo detecta cuando se
345
//                // elimina o a�ade una vista,
346
//                // /mapa o tabla pero no cuando se modifican.
347
//        }
348

    
349
        /**
350
         * Obtiene los comentarios
351
         *
352
         * @return
353
         */
354
        public String getComments() {
355
                return comments;
356
        }
357

    
358
        /**
359
         * Obtiene la fecha de la �ltima modificaci�n
360
         *
361
         * @return
362
         */
363
        public String getModificationDate() {
364
                return modificationDate;
365
        }
366

    
367
        /**
368
         * Obtiene el propietario del proyecto
369
         *
370
         * @return
371
         */
372
        public String getOwner() {
373
                return owner;
374
        }
375

    
376
        /**
377
         * Establece una cadena como comentarios al proyecto
378
         *
379
         * @param string
380
         */
381
        public void setComments(String string) {
382
                comments = string;
383
                //modified = true;
384
                change.firePropertyChange("", null, null);
385
        }
386

    
387
        /**
388
         * Establece la fecha de la �ltima modificaci�n
389
         *
390
         * @param string
391
         */
392
        public void setModificationDate(String string) {
393
                modificationDate = string;
394
                //modified = true;
395
                change.firePropertyChange("", null, null);
396
        }
397

    
398
        /**
399
         * Establece el propietario del proyecto
400
         *
401
         * @param string
402
         */
403
        public void setOwner(String string) {
404
                owner = string;
405
                //modified = true;
406
                change.firePropertyChange("", null, null);
407
        }
408

    
409
        /**
410
         * Establece el flag de modificado del proyecto
411
         *
412
         * @param b
413
         */
414
        public void setModified(boolean b) {
415
                modified = b;
416
                if (modified==false) {
417
                        ProjectDocument[] documents=(ProjectDocument[])getDocuments().toArray(new ProjectDocument[0]);
418
                        for (int i=0;i<documents.length;i++) {
419
                                documents[i].setModified(false);
420
                        }
421
                }
422
        }
423

    
424
        /**
425
         * Obtiene el color de selecci�n que se usar� en el proyecto
426
         *
427
         * @return
428
         */
429
        public Color getSelectionColor() {
430
                if (selectionColor == null) {
431
                        selectionColor = defaultSelectionColor;
432
                }
433
                return selectionColor;
434
        }
435

    
436
        /**
437
         * Establece el color de selecci�n
438
         *
439
         * @param color
440
         */
441
        public void setSelectionColor(Color color) {
442
                selectionColor = color;
443
                MapContext.setSelectionColor(color);
444
                //modified = true;
445
                change.firePropertyChange("selectionColor", null, color);
446
        }
447

    
448
        /**
449
         * Obtiene el color como un entero para su serializaci�n a XML
450
         *
451
         * @return
452
         */
453
        public String getColor() {
454
                return StringUtilities.color2String(selectionColor);
455
        }
456

    
457
        /**
458
         * M�todo invocado al recuperar de XML para establecer el color de seleccion
459
         * del proyecto
460
         *
461
         * @param color
462
         *            Entero que representa un color
463
         */
464
        public void setColor(String color) {
465
                //modified = true;
466
                selectionColor = StringUtilities.string2Color(color);
467
        }
468

    
469
        /*
470
         * (non-Javadoc)
471
         *
472
         * @see java.beans.PropertyChangeListener#propertyChange(java.beans.PropertyChangeEvent)
473
         */
474
        public void propertyChange(PropertyChangeEvent evt) {
475
                //this.modified = true;
476
                change.firePropertyChange(evt);
477
        }
478

    
479
        /**
480
         * DOCUMENT ME!
481
         *
482
         * @param arg1
483
         */
484
        public void addExtent(ProjectExtent arg1) {
485
                extents.add(arg1);
486
                //modified = true;
487
                change.firePropertyChange("addExtent", null, null);
488
        }
489

    
490
        /**
491
         * DOCUMENT ME!
492
         *
493
         * @param arg0
494
         *
495
         * @return
496
         */
497
        public Object removeExtent(int arg0) {
498
                //modified = true;
499
                change.firePropertyChange("delExtent", null, null);
500

    
501
                return extents.remove(arg0);
502
        }
503

    
504
        /**
505
         * DOCUMENT ME!
506
         *
507
         * @return DOCUMENT ME!
508
         */
509
        public ProjectExtent[] getExtents() {
510
                return (ProjectExtent[]) extents.toArray(new ProjectExtent[0]);
511
        }
512

    
513
        /**
514
         * Metodo que a�ade una nueva camera a la lista de cameras
515
         *
516
         * @param arg1
517
         *            camera introducida
518
         */
519
        public void addCamera(Object arg1) {
520
                this.cameras.add(arg1);
521
                //modified = true;
522
                change.firePropertyChange("addCamera", null, null);
523
        }
524

    
525
        /**
526
         * Metodo que borra de la lisat un elemento seleccionado
527
         *
528
         * @param arg0
529
         *            indice del elemento que se va a borrar
530
         *
531
         * @return resultado de la operacion de borrado
532
         */
533
        public Object removeCamera(int arg0) {
534
                //modified = true;
535
                change.firePropertyChange("delCamera", null, null);
536

    
537
                return this.cameras.remove(arg0);
538
        }
539

    
540
        /**
541
         * Metodo que devuelve la lista de cameras
542
         *
543
         * @return lista de objetos de tipo camera
544
         */
545
        public Object[] getCameras() {
546
                return (Object[]) this.cameras.toArray(new Object[0]);
547
        }
548

    
549
        /**
550
         * DOCUMENT ME!
551
         *
552
         * @param arg0
553
         */
554
        public synchronized void addPropertyChangeListener(
555
                        PropertyChangeListener arg0) {
556
                change.addPropertyChangeListener(arg0);
557
        }
558

    
559
        /**
560
         * DOCUMENT ME!
561
         *
562
         * @deprecated utilizar getDocument(String s);
563
         * @return
564
         */
565
        public ArrayList getMaps() {
566
                return getDocumentsByType(ProjectMapFactory.registerName);
567
        }
568

    
569
        /**
570
         * DOCUMENT ME!
571
         *
572
         * @deprecated utilizar getDocument(String s);
573
         * @return
574
         */
575
        public ArrayList getTables() {
576
                return getDocumentsByType(ProjectTableFactory.registerName);
577
        }
578

    
579
        /**
580
         * DOCUMENT ME!
581
         *
582
         * @deprecated utilizar getDocument(String s);
583
         * @return
584
         */
585
        public ArrayList getViews() {
586
                return getDocumentsByType(ProjectViewFactory.registerName);
587
        }
588

    
589
        /**
590
         * A�ade un mapa al proyecto
591
         *
592
         * @deprecated utilizar addDocument(ProjectDocument pD);
593
         * @param m
594
         */
595
        public void addMap(ProjectMap m) {
596
                addDocument(m);
597
        }
598

    
599
        /**
600
         * Elimina un mapa del proyecto
601
         *
602
         * @deprecated utilizar delDocument(ProjectDocument pD);
603
         * @param i
604
         *            indice del mapa
605
         */
606
        public void delMap(int i) {
607
                ArrayList list = getDocumentsByType(ProjectMapFactory.registerName);
608
                delDocument((ProjectDocument) list.get(i));
609
        }
610

    
611
        /**
612
         * A�ade una tabla al proyecto
613
         *
614
         * @deprecated utilizar addDocument(ProjectDocument pD);
615
         * @param t
616
         */
617
        public void addTable(ProjectTable t) {
618
                addDocument(t);
619
        }
620

    
621
        /**
622
         * Elimina una tabla del proyecto
623
         *
624
         * @deprecated utilizar delDocument(ProjectDocument pD);
625
         * @param i
626
         *            indice de la tabla
627
         */
628
        public void delTable(int i) {
629
                ArrayList list = getDocumentsByType(ProjectTableFactory.registerName);
630
                delDocument((ProjectDocument) list.get(i));
631
        }
632

    
633
        /**
634
         * A�ade una vista al proyecto
635
         *
636
         * @deprecated utilizar addDocument(ProjectDocument pD);
637
         * @param v
638
         */
639
        public void addView(ProjectView v) {
640
                addDocument(v);
641
        }
642

    
643
        /**
644
         * Elimina una tabla del proyecto
645
         *
646
         * @deprecated utilizar delDocument(ProjectDocument pD);
647
         * @param i
648
         *            indice del proyecto
649
         */
650
        public void delView(int i) {
651
                ArrayList list = getDocumentsByType(ProjectViewFactory.registerName);
652
                delDocument((ProjectDocument) list.get(i));
653
        }
654

    
655
        /**
656
         * DOCUMENT ME!
657
         *
658
         * @return DOCUMENT ME!
659
         *
660
         * @throws DriverException
661
         * @throws XMLException
662
         */
663
        public XMLEntity getXMLEntity() {
664
                XMLEntity xml = new XMLEntity();
665
                xml.putProperty("className", this.getClass().getName());
666
                xml.putProperty("VERSION", VERSION);
667
                xml.putProperty("comments", getComments());
668
                xml.putProperty("creationDate", creationDate);
669
                xml.putProperty("isAbsolutePath", isAbsolutePath);
670
                
671
                int numExtents = extents.size();
672
                xml.putProperty("numExtents", numExtents);
673

    
674
                for (int i = 0; i < numExtents; i++) {
675
                        xml.addChild(((ProjectExtent) extents.get(i)).getXMLEntity());
676
                }
677

    
678
                // Guardando propiedades de las camaras
679
                int numCameras = this.cameras.size();
680
                xml.putProperty("numCameras", numCameras);
681

    
682
                for (int i = 0; i < numCameras; i++) {
683
                        xml.addChild(((IPersistence) this.cameras.get(i)).getXMLEntity());
684
                }
685

    
686
                // NUEVO: ESTO ESTA EN PRUEBAS. SIRVE PARA
687
                // BORRAR LAS REFERENCIAS A DATASOURCES QUE HEMOS
688
                // BORRADO. Hay que probar a borrarlos cuando se
689
                // borra una tabla y cuando se borra una capa.
690
                try {
691
//                        cleanBadReferences();
692
                }catch (Exception e) {
693
                        NotificationManager.addError("clean_bad_references",e);
694
                }
695
                SourceInfo[] infos = LayerFactory.getDataSourceFactory()
696
                                .getDriverInfos();
697
                xml.putProperty("data-source-count", infos.length);
698

    
699
                for (int i = 0; i < infos.length; i++) {
700
                        SourceInfo di = infos[i];
701
                        XMLEntity child = this.getSourceInfoXMLEntity(di);
702
                        xml.addChild(child);
703
                }
704
                int numDocuments = 0;
705
                for (int i = 0; i < documents.size(); i++) {
706
                        try {
707
                                XMLEntity xmlchild = ((ProjectDocument) documents.get(i))
708
                                                .getXMLEntity();
709
                                xml.addChild(xmlchild);
710
                                numDocuments++;
711
                        } catch (SaveException e) {
712
                                e.showError();
713
                        }
714
                }
715
                xml.putProperty("numDocuments", numDocuments);
716
                /*
717
                 * int numViews=0; for (int i = 0; i < views.size(); i++) { try {
718
                 * XMLEntity xmlchild=((ProjectView) views.get(i)).getXMLEntity();
719
                 * xml.addChild(xmlchild); numViews++; } catch (SaveException e) {
720
                 * e.showError(); } } xml.putProperty("numViews", numViews);
721
                 *
722
                 * int numMaps=0; for (int i = 0; i < maps.size(); i++) { try {
723
                 * XMLEntity xmlchild=((ProjectMap) maps.get(i)).getXMLEntity();
724
                 * xml.addChild(xmlchild); numMaps++; } catch (SaveException e) {
725
                 * e.showError(); } } xml.putProperty("numMaps", numMaps);
726
                 */
727
                xml.putProperty("modificationDate", modificationDate);
728
                xml.putProperty("name", name, false);
729
                xml.putProperty("owner", owner);
730
                xml.putProperty("selectionColor", StringUtilities
731
                                .color2String(selectionColor));
732
                /*
733
                 * int numTables=0; for (int i = 0; i < tables.size(); i++) { try {
734
                 * XMLEntity xmlchild=((ProjectTable) tables.get(i)).getXMLEntity();
735
                 * xml.addChild(xmlchild); numTables++; } catch (SaveException e) {
736
                 *
737
                 * e.showError(); } } xml.putProperty("numTables", numTables);
738
                 */
739
                xml.putProperty("projection", defaultProjection.getAbrev());
740

    
741
                saveWindowProperties(xml);
742
                return xml;
743
        }
744

    
745
        private void saveWindowProperties(XMLEntity xml) {
746
                XMLEntity propertyList = new XMLEntity();
747

    
748
                propertyList.setName("AndamiPersistence");
749
                propertyList.putProperty("className", Project.class.getName(), false);
750

    
751
                boolean projectWindowSaved = false;
752

    
753
                IWindow[] windowList = PluginServices.getMDIManager()
754
                                .getOrderedWindows();
755
                WindowInfo wi;
756
                XMLEntity windowProperties;
757
                for (int winIndex = windowList.length - 1; winIndex >= 0; winIndex--) {
758
                        wi = PluginServices.getMDIManager().getWindowInfo(
759
                                        windowList[winIndex]);
760
                        if (wi != null && wi.checkPersistence()) {
761
                                if (windowList[winIndex] instanceof Layout) { // for the
762
                                        // moment we
763
                                        // can't do this
764
                                        // for Maps
765
                                        // because they
766
                                        // don't have a
767
                                        // standard
768
                                        // model
769
                                        Layout layoutWindow = (Layout) windowList[winIndex];
770
                                        windowProperties = wi.getXMLEntity();
771
                                        windowProperties.putProperty("documentType",
772
                                                        ProjectMapFactory.registerName, false);
773
                                        windowProperties.putProperty("documentName", layoutWindow
774
                                                        .getName(), false);
775
                                        windowProperties.putProperty("zPosition", winIndex, false);
776
                                        propertyList.addChild(windowProperties);
777
                                } else if (windowList[winIndex] instanceof ProjectWindow) {
778
                                        projectWindowSaved = true;
779
                                        windowProperties = wi.getXMLEntity();
780
                                        windowProperties
781
                                                        .putProperty("className",
782
                                                                        "com.iver.cit.gvsig.project.document.gui.ProjectWindow", false);
783
                                        windowProperties.putProperty("zPosition", winIndex, false);
784
                                        propertyList.addChild(windowProperties);
785
                                } else if (windowList[winIndex] instanceof SingletonWindow) { // for
786
                                        // table,
787
                                        // view
788
                                        // and
789
                                        // maybe
790
                                        // other
791
                                        // documents
792
                                        SingletonWindow viewWindow = (SingletonWindow) windowList[winIndex];
793
                                        if (viewWindow.getWindowModel() instanceof ProjectDocument) {
794
                                                ProjectDocument doc = (ProjectDocument) viewWindow
795
                                                                .getWindowModel();
796
                                                windowProperties = wi.getXMLEntity();
797
                                                windowProperties.putProperty("documentType", doc
798
                                                                .getProjectDocumentFactory().getRegisterName(), false);
799
                                                windowProperties.putProperty("documentName",
800
                                                                ((ProjectDocument) viewWindow.getWindowModel())
801
                                                                                .getName(), false);
802
                                                windowProperties.putProperty("zPosition", winIndex, false);
803

    
804
                                                // TODO this will be generalized to all ProjectDocuments as soon as possible
805
//                                                if (viewWindow instanceof BaseView) {
806
//                                                        BaseView win = (BaseView) viewWindow;
807
//                                                        windowProperties.addChild(win.getWindowData().getXMLEntity());
808
//                                                }
809
                                                if (viewWindow instanceof IDocumentWindow) {
810
                                                        IDocumentWindow win = (IDocumentWindow) viewWindow;
811
                                                        windowProperties.addChild(win.getWindowData().getXMLEntity());
812
                                                }
813

    
814
                                                propertyList.addChild(windowProperties);
815
                                        }
816
                                }
817
                        }
818
                }
819

    
820
                if (projectWindowSaved == false) {
821
                        // If the Project Manager was closed, it was not in the
822
                        // previous window list. Save it now
823
                        ProjectExtension pe = (ProjectExtension) PluginServices
824
                                        .getExtension(com.iver.cit.gvsig.ProjectExtension.class);
825

    
826
                        if (pe != null) {
827
                                IWindow projectWindow = pe.getProjectWindow();
828
                                wi = PluginServices.getMDIManager()
829
                                                .getWindowInfo(projectWindow);
830
                                if (wi != null && wi.checkPersistence()) {
831
                                        windowProperties = wi.getXMLEntity();
832
                                        if (windowProperties != null) {
833
                                                windowProperties
834
                                                                .putProperty("className",
835
                                                                                "com.iver.cit.gvsig.project.document.gui.ProjectWindow", false);
836
                                                propertyList.addChild(windowProperties);
837
                                        }
838
                                }
839
                        }
840
                }
841

    
842
                xml.addChild(propertyList);
843
        }
844

    
845
        /**
846
         * Store the initial window properties, to later restore the window sizes
847
         * and positions
848
         */
849
        private void storeInitialWindowProperties(XMLEntity xml) {
850
                XMLEntity child;
851
                int childNumb;
852

    
853
                // order the window properties before restoring them, so that we also
854
                // restore the zPosition
855
                TreeMap orderedProperties = new TreeMap();
856
                int maximum = 1;
857
                for (childNumb = xml.getChildrenCount() - 1; childNumb >= 0; childNumb--) {
858
                        child = xml.getChild(childNumb);
859
                        if (child.contains("zPosition")) {
860
                                orderedProperties.put(new Integer(-child
861
                                                .getIntProperty("zPosition")), child); // reverse the
862
                                // order, so
863
                                // that we add
864
                                // the back
865
                                // windows first
866
                        } else {
867
                                orderedProperties.put(new Integer(maximum++), child); // the
868
                                // windows
869
                                // without
870
                                // zPosition
871
                                // will
872
                                // be on
873
                                // the
874
                                // fore
875
                        }
876
                }
877

    
878
                this.initialWindowProperties = orderedProperties.values().iterator();
879
        }
880

    
881
        /**
882
         * Store the initial window properties, to later restore the window sizes
883
         * and positions
884
         */
885
        private void storeInitialWindowProperties061(XMLEntity xml) {
886
                XMLEntity child;
887
                int childNumb = 0;
888
                ArrayList windowList = new ArrayList();
889

    
890
                child = xml.getChild(xml.getChildrenCount() - 1);
891
                if (child.contains("className")
892
                                && child.getStringProperty("className").equals(
893
                                                "com.iver.cit.gvsig.project.Project")
894
                                && child.contains("name")
895
                                && child.getStringProperty("name").equals("ViewInfoProperties")) {
896
                        child.putProperty("className",
897
                                        "com.iver.cit.gvsig.project.document.gui.ProjectWindow");
898
                        windowList.add(child);
899
                }
900

    
901
                // try to open the views
902
                if (xml.contains("numExtents"))
903
                        childNumb += xml.getIntProperty("numExtents");
904
                if (xml.contains("data-source-count"))
905
                        childNumb += xml.getIntProperty("data-source-count");
906
                int limit = 0;
907
                if (xml.contains("numViews"))
908
                        limit = xml.getIntProperty("numViews")+childNumb;
909

    
910
                XMLEntity view;
911
                for (int i = childNumb; i < limit; i++) {
912
                        view = xml.getChild(i);
913
                        child = view.getChild(view.getChildrenCount() - 1);
914
                        if (child.contains("className")
915
                                        && child.getStringProperty("className").equals(
916
                                                        "com.iver.cit.gvsig.project.ProjectView")
917
                                        && child.contains("name")
918
                                        && child.getStringProperty("name").equals(
919
                                                        "ViewInfoProperties")) {
920
                                child.putProperty("documentName", view
921
                                                .getStringProperty("name"));
922
                                child.putProperty("documentType",
923
                                                ProjectViewFactory.registerName);
924
                                windowList.add(child);
925
                        }
926
                }
927

    
928
                if (xml.contains("numViews"))
929
                        childNumb += xml.getIntProperty("numViews");
930

    
931
                if (xml.contains("numMaps"))
932
                        limit = childNumb + xml.getIntProperty("numMaps");
933

    
934
                // try to open the maps
935
                XMLEntity map;
936
                for (int i = childNumb; i < limit; i++) {
937
                        map = xml.getChild(i);
938
                        for (int j = 0; j < map.getChildrenCount(); j++) {
939
                                child = map.getChild(j);
940
                                if (child.contains("className")
941
                                                && child.getStringProperty("className").equals(
942
                                                                "com.iver.cit.gvsig.project.ProjectMap")
943
                                                && child.contains("name")
944
                                                && child.getStringProperty("name").equals(
945
                                                                "ViewInfoProperties")) {
946
                                        child.putProperty("documentName", map
947
                                                        .getStringProperty("name"));
948
                                        child.putProperty("documentType",
949
                                                        ProjectMapFactory.registerName);
950
                                        windowList.add(child);
951
                                }
952
                        }
953
                }
954

    
955
                this.initialWindowProperties = windowList.iterator();
956
        }
957

    
958
        /**
959
         * Restores the size, position and order of the windows, according to
960
         * variable initialWindowProperties. If this variable is null, the method
961
         * just opens the project manager window.
962
         *
963
         */
964
        public void restoreWindowProperties() {
965
                boolean projectWindowRestored = false;
966
                XMLEntity child;
967

    
968
                Iterator propertiesIterator = this.initialWindowProperties;
969
                if (propertiesIterator != null) {
970
                        this.initialWindowProperties = null;
971

    
972
                        while (propertiesIterator.hasNext()) {
973
                                child = (XMLEntity) propertiesIterator.next();
974
                                if (child.contains("name") // restore the position of the
975
                                                // document windows
976
                                                && child.getStringProperty("name").equals(
977
                                                                "ViewInfoProperties")
978
                                                && child.contains("documentType")) {
979
                                        boolean isClosed = true;
980
                                        if (child.contains("isClosed"))
981
                                                isClosed = child.getBooleanProperty("isClosed");
982
                                        if (isClosed == false) {
983
                                                WindowInfo windowProps = WindowInfo
984
                                                                .createFromXMLEntity(child);
985
                                                String documentName = child
986
                                                                .getStringProperty("documentName");
987
                                                String documentType = child
988
                                                                .getStringProperty("documentType");
989
                                                ProjectDocument pd = this.getProjectDocumentByName(
990
                                                                documentName, documentType);
991
                                                if (pd==null) continue;
992
                                                IWindow win = null;
993
                                                if (pd instanceof ProjectDocument
994
                                                                && child.getChildrenCount()>0
995
                                                                && child.getChild(0).getName().equals("windowData")) {
996
                                                        // this will be generalized to all ProjectDocuments as soon as possible
997
                                                        WindowData windowData = new WindowData();
998
                                                        windowData.setXMLEntity(child.getChild(0));
999
                                                        pd.storeWindowData(windowData);
1000
                                                        win = ((ProjectDocument)pd).createWindow();
1001
                                                } else {
1002
                                                        win = pd.createWindow();
1003
                                                }
1004
                                                if (win == null){
1005
                                                        continue;
1006
                                                }
1007
                                                PluginServices.getMDIManager().addWindow(win);
1008
                                                PluginServices.getMDIManager().changeWindowInfo(win,
1009
                                                                windowProps);
1010
                                        }
1011
                                } else if (child.contains("className") // restore the position
1012
                                                // of the project
1013
                                                // manager window
1014
                                                && child
1015
                                                                .getStringProperty("className")
1016
                                                                .equals(
1017
                                                                                "com.iver.cit.gvsig.project.document.gui.ProjectWindow")
1018
                                                && child.contains("name")
1019
                                                && child.getStringProperty("name").equals(
1020
                                                                "ViewInfoProperties")) {
1021
                                        WindowInfo wi = WindowInfo.createFromXMLEntity(child);
1022
                                        // don't restore size for ProjectManager window, as it's not resizable
1023
                                        wi.setHeight(-1);
1024
                                        wi.setWidth(-1);
1025
                                        ProjectExtension pe = (ProjectExtension) PluginServices
1026
                                                        .getExtension(com.iver.cit.gvsig.ProjectExtension.class);
1027
                                        if (pe != null) {
1028
                                                pe.setProject(this);
1029
                                                pe.showProjectWindow(wi);
1030
                                        }
1031
                                        projectWindowRestored = true;
1032
                                }
1033
                        }
1034
                }
1035

    
1036
                if (!projectWindowRestored) { // if the project window was not stored
1037
                        // in the project, open it now
1038
                        ProjectExtension pe = (ProjectExtension) PluginServices
1039
                                        .getExtension(com.iver.cit.gvsig.ProjectExtension.class);
1040

    
1041
                        if (pe != null) {
1042
                                pe.setProject(this);
1043
                                pe.showProjectWindow();
1044
                        }
1045
                }
1046
        }
1047

    
1048
        /**
1049
         * DOCUMENT ME!
1050
         *
1051
         * @param xml
1052
         *            DOCUMENT ME!
1053
         *
1054
         * @return DOCUMENT ME!
1055
         * @throws XMLException
1056
         * @throws DriverException
1057
         * @throws DriverIOException
1058
         * @throws OpenException
1059
         */
1060
        public static Project createFromXML03(XMLEntity xml) throws OpenException {
1061
                Project p = new Project();
1062
                try {
1063
                        p.comments = xml.getStringProperty("comments");
1064
                        p.creationDate = xml.getStringProperty("creationDate");
1065

    
1066
                        int numExtents = xml.getIntProperty("numExtents");
1067
                        for (int i = 0; i < numExtents; i++) {
1068
                                ProjectExtent pe = ProjectExtent.createFromXML03(xml
1069
                                                .getChild(i));
1070
                                p.extents.add(pe);
1071
                        }
1072

    
1073
                        int numDocuments = 0;
1074
                        if (xml.contains("numDocuments")) {
1075
                                numDocuments = xml.getIntProperty("numDocuments");
1076
                        } else {
1077
                                int numViews = xml.getIntProperty("numViews");
1078
                                int numMaps = xml.getIntProperty("numMaps");
1079
                                int numTables = xml.getIntProperty("numTables");
1080
                                numDocuments = numViews + numMaps + numTables;
1081
                        }
1082
                        for (int i = numExtents; i < numDocuments + numExtents; i++) {
1083
                                ProjectDocument pD = ProjectDocument.createFromXML03(xml
1084
                                                .getChild(i), p);
1085
                                p.addDocument(pD);
1086
                                p.sortedDocuments.put(pD, new Integer(i));
1087
                        }
1088
                        ProjectDocument[] sortDocKeys = (ProjectDocument[]) p.sortedDocuments
1089
                                        .keySet().toArray(new ProjectDocument[0]);
1090
                        Integer[] sortDocValues = (Integer[]) p.sortedDocuments.values()
1091
                                        .toArray(new Integer[0]);
1092

    
1093
                        int i = 0;
1094
                        for (int k = numExtents; k < (numDocuments + numExtents); k++) {
1095
                                sortDocKeys[i].setXMLEntity(xml.getChild(sortDocValues[i]
1096
                                                .intValue()));
1097
                                i++;
1098
                        }
1099

    
1100
                        p.modificationDate = xml.getStringProperty("modificationDate");
1101
                        //p.modified = xml.getBooleanProperty("modified");
1102
                        p.name = xml.getStringProperty("name");
1103
                        p.owner = xml.getStringProperty("owner");
1104
                        p.selectionColor = StringUtilities.string2Color(xml
1105
                                        .getStringProperty("selectionColor"));
1106

    
1107
                        String strProj = xml.getStringProperty("projection");
1108
                        if (strProj != null)
1109
                                p.setProjection(CRSFactory.getCRS(strProj));
1110
                } catch (Exception e) {
1111
                        throw new OpenException(e, p.getClass().getName());
1112
                }
1113
                return p;
1114
        }
1115

    
1116
        /**
1117
         * DOCUMENT ME!
1118
         *
1119
         * @param xml
1120
         *            DOCUMENT ME!
1121
         *
1122
         * @return DOCUMENT ME!
1123
         *
1124
         * @throws XMLException
1125
         * @throws DriverException
1126
         * @throws DriverIOException
1127
         * @throws OpenException
1128
         * @throws VersionException
1129
         */
1130
        public static Project createFromXML(XMLEntity xml) throws OpenException {
1131

    
1132
                int childNumber = 0;
1133
                Project p = new Project();
1134

    
1135
                try {
1136
                        p.comments = xml.getStringProperty("comments");
1137
                        p.creationDate = xml.getStringProperty("creationDate");
1138
                        PathGenerator pg=PathGenerator.getInstance();
1139
                        if (xml.contains("isAbsolutePath")){
1140
                                p.isAbsolutePath=xml.getBooleanProperty("isAbsolutePath");
1141
                                pg.setIsAbsolutePath(p.isAbsolutePath);
1142
                        }else{
1143
                                pg.setIsAbsolutePath(true);
1144
                        }
1145
                        int numExtents = xml.getIntProperty("numExtents");
1146

    
1147
                        for (int i = 0; i < numExtents; i++) {
1148
                                ProjectExtent pe = ProjectExtent.createFromXML(xml.getChild(i));
1149
                                p.extents.add(pe);
1150
                        }
1151

    
1152
                        // Leemos el ultiom hijo recogido
1153
                        childNumber = numExtents;
1154

    
1155
                        // Recogiendo el numero de cameras
1156
                        int numCameras = 0;
1157
                        if (xml.contains("numCameras"))
1158
                                numCameras = xml.getIntProperty("numCameras");
1159

    
1160
                        // Recogiendo todo las camaras
1161
                        for (int i = childNumber; i < (childNumber + numCameras); i++) {
1162
                                XMLEntity xmlProp = xml.getChild(i);
1163
                                try {
1164
                                        String className = xmlProp.getStringProperty("className");
1165
                                        Class classProp = Class.forName(className);
1166
                                        Object obj = classProp.newInstance();
1167
                                        IPersistence objPersist = (IPersistence) obj;
1168
                                        objPersist.setXMLEntity(xmlProp);
1169
                                        p.cameras.add(obj);
1170
                                } catch (Exception e) {
1171
                                        continue;
1172
                                }
1173
                        }
1174

    
1175
                        childNumber += numCameras;
1176

    
1177
                        int numDataSources = xml.getIntProperty("data-source-count");
1178

    
1179
                        for (int i = childNumber; i < (childNumber + numDataSources); i++) {
1180
                                XMLEntity child = xml.getChild(i);
1181
                                registerDataSourceFromXML(child);
1182
                        }
1183

    
1184
                        childNumber += numDataSources;
1185
                        int numDocuments = 0;
1186
                        if (xml.contains("numDocuments")) {
1187
                                numDocuments = xml.getIntProperty("numDocuments");
1188
                        } else {
1189
                                int numViews = xml.getIntProperty("numViews");
1190
                                int numMaps = xml.getIntProperty("numMaps");
1191
                                int numTables = xml.getIntProperty("numTables");
1192
                                numDocuments = numViews + numMaps + numTables;
1193
                        }
1194
                        int i=0;
1195
                        for (i = childNumber; i < (numDocuments + childNumber); i++) {
1196
                                try {
1197
                                        ProjectDocument pD = ProjectDocument.createFromXML(xml
1198
                                                        .getChild(i), p);
1199
                                        p.addDocument(pD);
1200
                                        p.sortedDocuments.put(pD, new Integer(i));
1201
                                } catch (OpenException e) {
1202
                                        XMLEntity childXML=xml.getChild(i);
1203
                                        e.showMessageError(childXML.getName()+"\n  "+childXML.getStringProperty("className"));
1204
                                }
1205
                        }
1206
                        ProjectDocument[] sortDocKeys = (ProjectDocument[]) p.sortedDocuments
1207
                                        .keySet().toArray(new ProjectDocument[0]);
1208
                        Integer[] sortDocValues = (Integer[]) p.sortedDocuments.values()
1209
                                        .toArray(new Integer[0]);
1210

    
1211
                        i=0;
1212
                        for ( i = 0; i < sortDocValues.length; i++) {
1213
                                try {
1214
                                        sortDocKeys[i].setXMLEntity(xml.getChild(sortDocValues[i]
1215
                                                        .intValue()));
1216
                                } catch (OpenException e) {
1217
                                        p.delDocument(sortDocKeys[i]);
1218
                                        XMLEntity childXML=xml.getChild(sortDocValues[i].intValue());
1219
                                        e.showMessageError(childXML.getName()+"\n  "+childXML.getStringProperty("className"));
1220
                                }
1221
                        }
1222
                        childNumber += numDocuments;
1223

    
1224
                        p.modificationDate = xml.getStringProperty("modificationDate");
1225
                        //p.modified = xml.getBooleanProperty("modified");
1226
                        p.name = xml.getStringProperty("name");
1227
                        p.owner = xml.getStringProperty("owner");
1228
                        p.selectionColor = StringUtilities.string2Color(xml
1229
                                        .getStringProperty("selectionColor"));
1230

    
1231
                        p.setLinkTable();
1232
                        String strProj = xml.getStringProperty("projection");
1233

    
1234
                        if (strProj != null) {
1235
                                p.setProjection(CRSFactory.getCRS(strProj));
1236
                        }
1237

    
1238
                        if (childNumber < xml.getChildrenCount()) { // restore the position
1239
                                // of the windows
1240
                                XMLEntity child = xml.getChild(childNumber);
1241
                                if (child.contains("name")
1242
                                                && child.getStringProperty("name").equals(
1243
                                                                "AndamiPersistence")) {
1244
                                        p.storeInitialWindowProperties(child);
1245
                                } else if (child.contains("className")
1246
                                                && child.getStringProperty("className").equals(
1247
                                                                "com.iver.cit.gvsig.project.Project")
1248
                                                && child.contains("name")
1249
                                                && child.getStringProperty("name").equals(
1250
                                                                "ViewInfoProperties")) {
1251
                                        p.storeInitialWindowProperties061(xml);
1252
                                }
1253
                        }
1254

    
1255
                        PostProcessSupport.executeCalls();
1256
                } catch (Exception e) {
1257
                        throw new OpenException(e, p.getClass().getName());
1258
                }
1259

    
1260
                return p;
1261

    
1262
        }
1263

    
1264
        /**
1265
         * Reestablece los link que ten�a cada tabla con las dem�s.
1266
         */
1267
        public void setLinkTable() {
1268
                ArrayList tables = getDocumentsByType(ProjectTableFactory.registerName);
1269

    
1270
                for (int i = 0; i < tables.size(); i++) {
1271
                        for (int j = 0; j < tables.size(); j++) {
1272
                                /*
1273
                                 * System.out.println("name = " + ((ProjectTable)
1274
                                 * tables.get(j)).getModelo().getName());
1275
                                 * System.out.println("linktable = " + ((ProjectTable)
1276
                                 * tables.get(i)).getLinkTable());
1277
                                 */
1278
                                try {
1279
                                        if ((((ProjectTable) tables.get(i)).getLinkTable() != null)
1280
                                                        && ((ProjectTable) tables.get(i)).getLinkTable()
1281
                                                        .equals(
1282
                                                                        ((ProjectTable) tables.get(j))
1283
                                                                        .getModelo().getRecordset()
1284
                                                                        .getName())) {
1285
                                                LinkSelectionListener lsl;
1286

    
1287
                                                lsl = new LinkSelectionListener(((ProjectTable) tables
1288
                                                                .get(i)).getModelo().getRecordset(),
1289
                                                                ((ProjectTable) tables.get(j)).getModelo()
1290
                                                                .getRecordset(), ((ProjectTable) tables
1291
                                                                                .get(i)).getField1(),
1292
                                                                                ((ProjectTable) tables.get(i)).getField2());
1293

    
1294
                                                (((ProjectTable) tables.get(i)).getModelo()
1295
                                                                .getRecordset()).addSelectionListener(lsl);
1296

    
1297
                                        }
1298
                                } catch (ReadDriverException e) {
1299
                                        e.printStackTrace();
1300
                                }
1301
                        }
1302
                }
1303
        }
1304

    
1305
        /**
1306
         * Obtiene la vista que contiene a la capa que se pasa como par�metro
1307
         *
1308
         * @param layer
1309
         *            Capa cuya vista se quiere obtener
1310
         *
1311
         * @return
1312
         *
1313
         * @throws RuntimeException
1314
         *             Si la capa que se pasa como par�metro no se encuentra en
1315
         *             ninguna vista
1316
         */
1317
        public String getView(FLayer layer) {
1318
                ArrayList views = getDocumentsByType(ProjectViewFactory.registerName);
1319
                for (int v = 0; v < views.size(); v++) {
1320
                        ProjectView pView = (ProjectView) views.get(v);
1321
                        FLayers layers = pView.getMapContext().getLayers();
1322
                        if (isView(layers, layer))
1323
                                return pView.getName();
1324
                }
1325

    
1326
                throw new RuntimeException("The layer '"+layer.getName()+"' is not in a view");
1327
        }
1328

    
1329
        public boolean isView(FLayers layers, FLayer layer) {
1330
                for (int i = 0; i < layers.getLayersCount(); i++) {
1331
                        if (layers.getLayer(i) instanceof FLayers) {
1332
                                if (isView((FLayers) layers.getLayer(i), layer)){
1333
                                        return true;
1334
                                }
1335
                        }
1336
                        if (layers.getLayer(i) == layer) {
1337
                                return true;
1338
                        }
1339
                }
1340
                return false;
1341
        }
1342

    
1343
        /**
1344
         * Devuelve la vista cuyo nombre coincide (sensible a mayusculas) con el que
1345
         * se pasa como par�metro. Devuelve null si no hay ninguna vista con ese
1346
         * nombre
1347
         *
1348
         * @param viewName
1349
         *            Nombre de la vista que se quiere obtener
1350
         *
1351
         * @return DOCUMENT ME!
1352
         */
1353
        /*
1354
         * public ProjectView getViewByName(String viewName) { ArrayList
1355
         * views=getDocuments(PluginServices.getText(this,"Vista")); Object o =
1356
         * getProjectDocumentByName(viewName, PluginServices.getText(this,"Vista"));
1357
         *
1358
         * if (o == null) { return null; }
1359
         *
1360
         * return (ProjectView) o; }
1361
         */
1362
        /**
1363
         * DOCUMENT ME!
1364
         *
1365
         * @return DOCUMENT ME!
1366
         */
1367
        public IProjection getProjection() {
1368
                if (projection == null)
1369
                        projection = Project.defaultProjection;
1370
                return projection;
1371
        }
1372

    
1373
        /**
1374
         * DOCUMENT ME!
1375
         *
1376
         * @param defaultProjection
1377
         *            DOCUMENT ME!
1378
         */
1379
        public void setProjection(IProjection projection) {
1380
                this.projection = projection;
1381
        }
1382

    
1383
        /**
1384
         * Sets the projection used when no projection is defined
1385
         *
1386
         * @param defaultProjection
1387
         *            DOCUMENT ME!
1388
         */
1389
        public static void setDefaultProjection(IProjection defaultProjection) {
1390
                Project.defaultProjection = defaultProjection;
1391
        }
1392

    
1393
        public static IProjection getDefaultProjection() {
1394
                if (defaultProjection == null){
1395
                        XMLEntity xml = PluginServices.getPluginServices("com.iver.cit.gvsig")
1396
                        .getPersistentXML();
1397

    
1398
                        // Default Projection
1399
                        String projCode = null;
1400
                        if (xml.contains("DefaultProjection")) {
1401
                                projCode = xml.getStringProperty("DefaultProjection");
1402
                                Project.setDefaultProjection(CRSFactory.getCRS(projCode));
1403
                        } else {
1404
                                Project.setDefaultProjection(defaultFactoryProjection);
1405
                        }
1406

    
1407
                }
1408
                return Project.defaultProjection;
1409
        }
1410

    
1411
        /**
1412
         * Obtiene un documento a partir de su nombre y el nombre de registro en el
1413
         * pointExtension, este �ltimo se puede obtener del
1414
         * Project****Factory.registerName.
1415
         *
1416
         * @param name
1417
         *            Nombre del documento
1418
         * @param type
1419
         *            nombre de registro en el extensionPoint
1420
         *
1421
         * @return Documento
1422
         */
1423
        public ProjectDocument getProjectDocumentByName(String name, String type) {
1424
                ArrayList docs = getDocumentsByType(type);
1425
                for (Iterator iter = docs.iterator(); iter.hasNext();) {
1426
                        ProjectDocument elem = (ProjectDocument) iter.next();
1427

    
1428
                        if (elem.getName().equals(name)) {
1429
                                return elem;
1430
                        }
1431
                }
1432

    
1433
                return null;
1434
        }
1435

    
1436
        /**
1437
         * DOCUMENT ME!
1438
         *
1439
         * @param name
1440
         *
1441
         * @return
1442
         */
1443
        /*
1444
         * public ProjectTable getTableByName(String name) { ArrayList
1445
         * tables=getDocuments(PluginServices.getText(this,"Tabla")); Object o =
1446
         * getProjectElementByName(name, tables);
1447
         *
1448
         * if (o == null) { return null; }
1449
         *
1450
         * return (ProjectTable) o; }
1451
         */
1452
        /**
1453
         * DOCUMENT ME!
1454
         *
1455
         * @param name
1456
         *
1457
         * @return
1458
         */
1459
        /*
1460
         * public ProjectMap getLayoutByName(String name) { Object o =
1461
         * getProjectElementByName(name, maps);
1462
         *
1463
         * if (o == null) { return null; }
1464
         *
1465
         * return (ProjectMap) o; }
1466
         */
1467
        public SelectableDataSource getDataSourceByLayer(FLayer layer)
1468
                        throws ReadDriverException {
1469
                ArrayList tables = getDocumentsByType(ProjectTableFactory.registerName);
1470
                SelectableDataSource dataSource = null;
1471
                for (int i = 0; i < tables.size(); i++) {
1472
                        ProjectTable pt = (ProjectTable) tables.get(i);
1473
                        if (pt.getOriginal() == ((AlphanumericData) layer)
1474
                                        .getRecordset()) {
1475
                                dataSource = pt.getModelo().getRecordset();
1476
                                break;
1477
                        } else if (pt.getModelo() == ((AlphanumericData) layer)
1478
                                        .getRecordset()) {
1479
                                        dataSource = pt.getModelo().getRecordset();
1480
                                        break;
1481
                        }
1482
                }
1483

    
1484
                if (dataSource == null) {
1485
                        // No se ha creado la tabla asociada al tema
1486
                        dataSource = ((AlphanumericData) layer).getRecordset();
1487
                }
1488

    
1489
                return dataSource;
1490

    
1491
        }
1492

    
1493
        /**
1494
         * Recorremos las capas y las tablas del proyecto, y creamos una lista con
1495
         * todos los datasources de GDBMS que estamos usando. Luego recorremos los
1496
         * que est�n registrados, y borramos aquellos que no est�n siendo usados, es
1497
         * decir, aquellos que no est�n en nuestra lista (un Hash con clave el
1498
         * nombre del GDBMS)
1499
         *
1500
         */
1501
        private void cleanBadReferences() {
1502
                ArrayList tables = getDocumentsByType(ProjectTableFactory.registerName);
1503
                Hashtable usedDataSources = new Hashtable();
1504
                // Primero las tablas
1505
                int i, j;
1506
                try {
1507
                        for (i = 0; i < tables.size(); i++) {
1508
                                ProjectTable t = (ProjectTable) tables.get(i);
1509
                                SelectableDataSource ds;
1510
                                if (t.getModelo() == null){
1511
                                        /*
1512
                                         * if a broken table was found
1513
                                         * we don't clean any source
1514
                                         */
1515
                                        return;
1516
                                }
1517

    
1518
                                ds = t.getModelo().getRecordset();
1519

    
1520
                                if (t.getOriginal() != null)
1521
                                        usedDataSources.put(t.getOriginal().getRecordset()
1522
                                                        .getName(), t.getOriginal());
1523
                                usedDataSources.put(ds.getName(), ds);
1524
                        }
1525
                } catch (ReadDriverException e) {
1526
                        e.printStackTrace();
1527
                }
1528
                // Ahora las vistas
1529
                ProjectView pv;
1530
                ArrayList views = getDocumentsByType(ProjectViewFactory.registerName);
1531
                try {
1532
                        for (i = 0; i < views.size(); i++) {
1533
                                pv = (ProjectView) views.get(i);
1534
                                this.findLayersVectDataSorces(pv.getMapContext(), usedDataSources);
1535

    
1536
                                MapContext aux = pv.getMapOverViewContext();
1537
                                if (aux != null) {
1538
                                        if (!this.findLayersVectDataSorces(aux, usedDataSources)){
1539
                                                /*
1540
                                                 * if a broken layer was found
1541
                                                 * we don't clean any source
1542
                                                 */
1543
                                                return;
1544
                                        }
1545

    
1546
                                }
1547

    
1548
                        } // for i
1549

    
1550
                } catch (ReadDriverException e) {
1551
                        e.printStackTrace();
1552
                }
1553

    
1554
                // Ahora los mapas
1555
                ArrayList maps = getDocumentsByType(ProjectMapFactory.registerName);
1556
                ProjectMap pm;
1557
                LayoutContext lContext;
1558
                IFFrame[] fframes;
1559
                try {
1560
                        for (i = 0; i < maps.size(); i++) {
1561
                                pm = (ProjectMap) maps.get(i);
1562
                                fframes = pm.getModel().getLayoutContext().getFFrames();
1563
                                for (j=0;j < fframes.length; j++){
1564
                                        if (!(fframes[j] instanceof FFrameView)){
1565
                                                continue;
1566
                                        }
1567
                                        if (!this.findLayersVectDataSorces(((FFrameView)fframes[i]).getMapContext(), usedDataSources)){
1568
                                                /*
1569
                                                 * if a broken layer was found
1570
                                                 * we don't clean any source
1571
                                                 */
1572
                                                return;
1573

    
1574
                                        }
1575
                                } //for j
1576

    
1577
                        } // for i
1578

    
1579
                } catch (ReadDriverException e) {
1580
                        e.printStackTrace();
1581
                }
1582

    
1583

    
1584
                // Recorremos los dataSources y los borramos si no
1585
                // los estamos usando.
1586
                SourceInfo[] infos = LayerFactory.getDataSourceFactory()
1587
                                .getDriverInfos();
1588
                try {
1589
                        for (i = 0; i < infos.length; i++) {
1590
                                if (!usedDataSources.containsKey(infos[i].name)) {
1591
                                        DataSource ds;
1592
                                        ds = LayerFactory.getDataSourceFactory()
1593
                                                        .createRandomDataSource(infos[i].name);
1594
                                        ds.remove();
1595
                                }
1596
                        }
1597
                } catch (DriverLoadException e) {
1598
                        e.printStackTrace();
1599
                } catch (NoSuchTableException e) {
1600
                        e.printStackTrace();
1601
                } catch (ReadDriverException e) {
1602
                        e.printStackTrace();
1603
                } catch (WriteDriverException e) {
1604
                        e.printStackTrace();
1605
                }
1606
        }
1607

    
1608
        /**
1609
         * Find DataSorces of the layers in the mapContext and store them in dataSourcesMap
1610
         *
1611
         * @param mapContext
1612
         * @param dataSourcesMap
1613
         * @return false if find a no Available layer
1614
         * @throws ReadDriverException
1615
         */
1616
        private boolean findLayersVectDataSorces(MapContext mapContext,Map dataSourcesMap) throws ReadDriverException{
1617
                LayersIterator iter = new LayersIterator(mapContext.getLayers()){
1618

    
1619
                        //@Override
1620
                        public boolean evaluate(FLayer layer) {
1621
                                if (!(layer instanceof FLyrVect))
1622
                                        return false;
1623
                                return super.evaluate(layer);
1624
                        }
1625

    
1626
                };
1627
                FLyrVect layer;
1628
                while (iter.hasNext()){
1629
                        layer = (FLyrVect)iter.nextLayer();
1630
                        if (!layer.isAvailable()){
1631
                                return false;
1632
                        }
1633

    
1634
                        dataSourcesMap.put(layer.getRecordset().getName(), layer.getRecordset());
1635
                        if (layer.isJoined()){
1636
                                dataSourcesMap.put(layer.getSource().getRecordset().getName(),layer.getSource().getRecordset());
1637
                        }
1638

    
1639
                }
1640
                return true;
1641
        }
1642

    
1643
        /**
1644
         * DOCUMENT ME!
1645
         *
1646
         * @return DOCUMENT ME!
1647
         * @throws SaveException
1648
         * @throws XMLException
1649
         * @throws SaveException
1650
         */
1651
        public XMLEntity getWindowInfoXMLEntity(IWindow window)
1652
                        throws SaveException {
1653
                if (window != null
1654
                                && PluginServices.getMDIManager().getWindowInfo(window) != null) {
1655
                        WindowInfo vi = PluginServices.getMDIManager()
1656
                                        .getWindowInfo(window);
1657
                        XMLEntity xml = new XMLEntity();
1658
                        // xml.putProperty("nameClass", this.getClass().getName());
1659
                        try {
1660
                                xml.setName("ViewInfoProperties");
1661
                                xml.putProperty("className", this.getClass().getName());
1662
                                xml.putProperty("X", vi.getX());
1663
                                xml.putProperty("Y", vi.getY());
1664
                                xml.putProperty("Width", vi.getWidth());
1665
                                xml.putProperty("Height", vi.getHeight());
1666
                                xml.putProperty("isVisible", vi.isVisible());
1667
                                xml.putProperty("isResizable", vi.isResizable());
1668
                                xml.putProperty("isMaximizable", vi.isMaximizable());
1669
                                xml.putProperty("isModal", vi.isModal());
1670
                                xml.putProperty("isModeless", vi.isModeless());
1671
                                xml.putProperty("isClosed", vi.isClosed());
1672
                                if (vi.isMaximized() == true) {
1673
                                        xml.putProperty("isMaximized", vi.isMaximized());
1674
                                        xml.putProperty("normalX", vi.getNormalX());
1675
                                        xml.putProperty("normalY", vi.getNormalY());
1676
                                        xml.putProperty("normalWidth", vi.getNormalWidth());
1677
                                        xml.putProperty("normalHeight", vi.getNormalHeight());
1678
}
1679
                        } catch (Exception e) {
1680
                                throw new SaveException(e, this.getClass().getName());
1681
                        }
1682
                        return xml;
1683
                }
1684
                return null;
1685
        }
1686

    
1687
        public static WindowInfo createWindowInfoFromXMLEntity(XMLEntity xml) {
1688
                WindowInfo result = new WindowInfo();
1689
                result.setX(xml.getIntProperty("X"));
1690
                result.setY(xml.getIntProperty("Y"));
1691
                result.setHeight(xml.getIntProperty("Height"));
1692
                result.setWidth(xml.getIntProperty("Width"));
1693
                result.setClosed(xml.getBooleanProperty("isClosed"));
1694
                if (xml.contains("isMaximized")) {
1695
                        boolean maximized = xml.getBooleanProperty("isMaximized");
1696
                        result.setMaximized(maximized);
1697
                        if (maximized == true) {
1698
                                result.setNormalBounds(xml.getIntProperty("normalX"), xml
1699
                                                .getIntProperty("normalY"), xml
1700
                                                .getIntProperty("normalWidth"), xml
1701
                                                .getIntProperty("normalHeight"));
1702
                        } else {
1703
                                result.setNormalBounds(result.getBounds());
1704
                        }
1705
                }
1706

    
1707
                return result;
1708
        }
1709

    
1710
        public XMLEntity getSourceInfoXMLEntity(SourceInfo di) {
1711
                XMLEntity child = new XMLEntity();
1712

    
1713
                if (di instanceof ObjectSourceInfo) {
1714
                        ObjectSourceInfo driver = (ObjectSourceInfo) di;
1715
                        child.putProperty("type", "sameDriverFile");
1716
                        child.putProperty("gdbmsname", driver.name);
1717
                } else if (di instanceof FileSourceInfo) {
1718
                        FileSourceInfo vfdi = (FileSourceInfo) di;
1719
                        child.putProperty("type", "otherDriverFile");
1720
                        child.putProperty("gdbmsname", vfdi.name);
1721
                        child.putProperty("file", pathGenerator.getPath(vfdi.file));
1722
                        child.putProperty("driverName", vfdi.driverName);
1723
                } else if (di instanceof DBSourceInfo) {
1724
                        DBTableSourceInfo dbdi = (DBTableSourceInfo) di;
1725
                        child.putProperty("type", "db");
1726
                        child.putProperty("gdbmsname", dbdi.name);
1727
                        child.putProperty("dbms", dbdi.dbms);
1728
                        child.putProperty("host", dbdi.host);
1729
                        child.putProperty("port", dbdi.port);
1730
                        child.putProperty("user", dbdi.user);
1731
                        child.putProperty("password", dbdi.password);
1732
                        child.putProperty("dbName", dbdi.dbName);
1733
                        child.putProperty("tableName", dbdi.tableName);
1734
                        child.putProperty("driverInfo", dbdi.driverName);
1735
                }
1736

    
1737
                return child;
1738
        }
1739

    
1740
        /**
1741
         * Devuelve un arrayList con todos los documentos del tipo especificado como
1742
         * par�metro.
1743
         *
1744
         * @param registerName
1745
         *            nombre de registro en el extensionPoint
1746
         *
1747
         * @return Documentos del tipo especificado
1748
         */
1749
        public ArrayList<ProjectDocument> getDocumentsByType(String registerName) {
1750
                ArrayList<ProjectDocument> docuArray = new ArrayList<ProjectDocument>();
1751
                for (int i = 0; i < documents.size(); i++) {
1752
                        ProjectDocument projectDocument = (ProjectDocument) documents
1753
                                        .get(i);
1754
                        ProjectDocumentFactory pdf = projectDocument
1755
                                        .getProjectDocumentFactory();
1756
                        if (pdf == null)
1757
                                continue;
1758
                        if (pdf.getRegisterName().equals(registerName)) {
1759
                                docuArray.add(projectDocument);
1760
                        }
1761
                }
1762
                return docuArray;
1763
        }
1764

    
1765
        /**
1766
         * Devuelve un arrayList con todos los documentos.
1767
         *
1768
         * @return Documentos
1769
         */
1770
        public ArrayList<ProjectDocument> getDocuments() {
1771
                ArrayList<ProjectDocument> docuArray = new ArrayList<ProjectDocument>();
1772
                for (int i = 0; i < documents.size(); i++) {
1773
                        ProjectDocument projectDocument = (ProjectDocument) documents
1774
                                        .get(i);
1775
                        docuArray.add(projectDocument);
1776
                }
1777
                return docuArray;
1778
        }
1779

    
1780
        /**
1781
         * Inserta un documento.
1782
         *
1783
         * @param doc
1784
         *            Documento
1785
         */
1786
        public void addDocument(ProjectDocument doc) {
1787
                documents.add(doc);
1788
                doc.addPropertyChangeListener(this);
1789
                //modified = true;
1790
                change.firePropertyChange("addDocument", "", doc);
1791
                doc.setProject(this, 0);
1792
                doc.afterAdd();
1793
        }
1794

    
1795
        /**
1796
         * Borra un documento.
1797
         *
1798
         * @param doc
1799
         *            Documento
1800
         */
1801
        public void delDocument(ProjectDocument doc) {
1802
                documents.remove(doc);
1803
                //modified = true;
1804
                change.firePropertyChange("", null, null);
1805
                doc.afterRemove();
1806
        }
1807

    
1808
        /**
1809
         * Sets the default selection color that will be used in subsequent
1810
         * projects.
1811
         *
1812
         * @param color
1813
         */
1814
        public static void setDefaultSelectionColor(Color color) {
1815
                defaultSelectionColor = color;
1816
        }
1817

    
1818
        /**
1819
         * Returns the current default selection color defined which is the color
1820
         * defined when the user does not define any other one
1821
         *
1822
         * @return java.awt.Color
1823
         */
1824
        public static Color getDefaultSelectionColor() {
1825
                // TODO es millorable?
1826
                XMLEntity xml = PluginServices.getPluginServices("com.iver.cit.gvsig")
1827
                                .getPersistentXML();
1828
                if (xml.contains("DefaultSelectionColor"))
1829
                        defaultSelectionColor = StringUtilities.string2Color(xml
1830
                                        .getStringProperty("DefaultSelectionColor"));
1831
                return defaultSelectionColor;
1832
        }
1833

    
1834
        /**
1835
         * Returns the user's default map units. This is the cartography data
1836
         * distance units.
1837
         *
1838
         * @return int (index of the <b>Attributes.NAMES array</b>)
1839
         */
1840
        public static int getDefaultMapUnits() {
1841
                if (defaultMapUnits == -1) {
1842
                        XMLEntity xml = PluginServices.getPluginServices(
1843
                                        "com.iver.cit.gvsig").getPersistentXML();
1844
                        if (xml.contains("DefaultMapUnits")) {
1845
                                defaultMapUnits = xml.getIntProperty("DefaultMapUnits");
1846
                        } else {
1847
                                // first app run case
1848
                                String[] unitNames = MapContext.getDistanceNames();
1849
                                for (int i = 0; i < unitNames.length; i++) {
1850
                                        // meter is the factory default's map unit
1851
                                        if (unitNames[i].equals("Metros")) {
1852
                                                defaultMapUnits = i;
1853
                                                break;
1854
                                        }
1855
                                }
1856
                        }
1857
                        if (defaultMapUnits == -1 || defaultMapUnits >= MapContext.getDistanceNames().length)
1858
                                defaultMapUnits = MapContext.getDistancePosition("Metros");
1859
                }
1860
                return defaultMapUnits;
1861
        }
1862

    
1863
        /**
1864
         * Returns the user's default view units for measuring distances. This is
1865
         * the units that the user will see in the status bar of the view.
1866
         *
1867
         * @return int (index of the <b>Attributes.NAMES array</b>)
1868
         */
1869
        public static int getDefaultDistanceUnits() {
1870
                if (defaultDistanceUnits == -1) {
1871
                        XMLEntity xml = PluginServices.getPluginServices(
1872
                                        "com.iver.cit.gvsig").getPersistentXML();
1873
                        if (xml.contains("DefaultDistanceUnits")) {
1874
                                defaultDistanceUnits = xml
1875
                                                .getIntProperty("DefaultDistanceUnits");
1876
                        } else {
1877
                                // first app run case
1878
                                String[] unitNames = MapContext.getDistanceNames();
1879
                                for (int i = 0; i < unitNames.length; i++) {
1880
                                        // meter is the factory default's distance unit
1881
                                        if (unitNames[i].equals("Metros")) {
1882
                                                defaultDistanceUnits = i;
1883
                                                break;
1884
                                        }
1885
                                }
1886
                        }
1887
                        if (defaultDistanceUnits == -1 || defaultDistanceUnits >= MapContext.getDistanceNames().length)
1888
                                defaultDistanceUnits = MapContext.getDistancePosition("Metros");
1889
                }
1890
                return defaultDistanceUnits;
1891
        }
1892
        /**
1893
         * Returns the user's default view units for measuring areas. This is
1894
         * the units that the user will see in the status bar of the view.
1895
         *
1896
         * @return int (index of the <b>Attributes.NAMES array</b>)
1897
         */
1898
        public static int getDefaultDistanceArea() {
1899
                if (defaultDistanceArea == -1) {
1900
                        XMLEntity xml = PluginServices.getPluginServices(
1901
                                        "com.iver.cit.gvsig").getPersistentXML();
1902
                        if (xml.contains("DefaultDistanceArea")) {
1903
                                defaultDistanceArea = xml
1904
                                                .getIntProperty("DefaultDistanceArea");
1905
                        } else {
1906
                                // first app run case
1907
                                String[] unitNames = MapContext.getAreaNames();
1908
                                for (int i = 0; i < unitNames.length; i++) {
1909
                                        // meter is the factory default's distance unit
1910
                                        if (unitNames[i].equals("Metros")) {
1911
                                                defaultDistanceArea = i;
1912
                                                break;
1913
                                        }
1914
                                }
1915
                        }
1916
                        if (defaultDistanceArea == -1 || defaultDistanceArea >= MapContext.getAreaNames().length){
1917
                                defaultDistanceArea=getDefaultDistanceUnits();
1918
                        }
1919
                }
1920
                return defaultDistanceArea;
1921
        }
1922
        /**
1923
         * Sets the default map unit (the units used by the data).
1924
         *
1925
         * @param mapUnits
1926
         */
1927
        public static void setDefaultMapUnits(int mapUnits) {
1928
                defaultMapUnits = mapUnits;
1929
        }
1930

    
1931
        /**
1932
         * Sets the default distance units (the units shown in the status bar)
1933
         *
1934
         * @param distanceUnits
1935
         */
1936
        public static void setDefaultDistanceUnits(int distanceUnits) {
1937
                defaultDistanceUnits = distanceUnits;
1938
        }
1939
        /**
1940
         * Sets the default distance area (the units shown in the status bar)
1941
         *
1942
         * @param distanceUnits
1943
         */
1944
        public static void setDefaultDistanceArea(int distanceArea) {
1945
                defaultDistanceArea = distanceArea;
1946
        }
1947
        public String exportToXML() throws SaveException {
1948
                XMLEntity xml = this.newExportXMLRootNode();
1949

    
1950
                Iterator iter = this.documents.iterator();
1951
                ProjectDocument document;
1952
                // FIXME: Falta atrapar los errores
1953
                while (iter.hasNext()) {
1954
                        document = (ProjectDocument) iter.next();
1955
                        document.exportToXML(xml, this);
1956
                }
1957

    
1958
                return xml.toString();
1959
        }
1960

    
1961
        public String exportToXML(ProjectDocument[] documents) throws SaveException {
1962
                XMLEntity xml = this.newExportXMLRootNode();
1963

    
1964
                for (int i = 0; i < documents.length; i++) {
1965
                        documents[i].exportToXML(xml, this);
1966
                }
1967

    
1968
                return xml.toString();
1969
        }
1970

    
1971
        public void importFromXML(String xml) throws Exception {
1972
                throw new Exception("Not Implemented");
1973
                /*
1974
                 * // FIXME: ?? Exceptions XMLEntity xmlEntity = new XMLEntity();
1975
                 *
1976
                 * try { xmlEntity.parse(xml); } catch (Exception e) { throw new
1977
                 * Exception(e); }
1978
                 *
1979
                 * if (!checkExportXMLRootNode(xmlEntity)) { throw new Exception("Check
1980
                 * Error"); //FIXME: traducir }
1981
                 *
1982
                 * int i;
1983
                 *
1984
                 * XMLEntity xmlDocumentRoot; ProjectDocument document = null;
1985
                 * ProjectDocumentFactory documentFactory = null; for (i=0;i<xmlEntity.getChildrenCount();i++) {
1986
                 * xmlDocumentRoot = xmlEntity.getChild(i); if
1987
                 * (!xmlDocumentRoot.contains("type")) { throw new Exception("Document
1988
                 * root "+i+ "error"); } documentFactory =
1989
                 * Project.getProjectDocumentFactory(xmlDocumentRoot.getStringProperty("type"));
1990
                 * int j; }
1991
                 */
1992

    
1993
        }
1994

    
1995
        public void importFromXML(String xml, String type) throws Exception {
1996
                // FIXME: EXCEPTIONS!!!!
1997
                XMLEntity xmlEntity = XMLEntity.parse(xml);
1998

    
1999
                if (!checkExportXMLRootNode(xmlEntity)) {
2000
                        throw new Exception();
2001
                }
2002

    
2003
                XMLEntity typeRoot = xmlEntity.firstChild("type", type);
2004
                if (typeRoot.getChildrenCount() == 0) {
2005
                        return;
2006
                }
2007

    
2008
                ProjectDocumentFactory documentFactory = getProjectDocumentFactory(type);
2009

    
2010
                Hashtable conflicts = getConflicts(xmlEntity);
2011

    
2012
                if (conflicts.size() != 0) {
2013
                        if (!documentFactory.resolveImportXMLConflicts(xmlEntity, this,
2014
                                        conflicts)) {
2015
                                return;
2016
                        }
2017
                }
2018
                this.registerDataSources(this.getExportXMLTypeRootNode(xmlEntity,
2019
                                "dataSources"));
2020

    
2021
                int i;
2022
                ProjectDocument document;
2023
                for (i = 0; i < typeRoot.getChildrenCount(); i++) {
2024
                        document = documentFactory.create(this);
2025
                        document.importFromXML(xmlEntity, typeRoot, i, this);
2026
                }
2027

    
2028
        }
2029

    
2030
        private Hashtable getConflicts(XMLEntity xml) {
2031
                int iType;
2032
                Hashtable conflicts = new Hashtable();
2033
                ArrayList elements;
2034
                XMLEntity typeRoot;
2035
                for (iType = 0; iType < xml.getChildrenCount(); iType++) {
2036
                        typeRoot = xml.getChild(iType);
2037
                        elements = getDocumentsByType(typeRoot.getStringProperty("type"));
2038
                        Hashtable conflictsType = new Hashtable();
2039
                        for (int iXML = 0; iXML < typeRoot.getChildrenCount(); iXML++) {
2040
                                XMLEntity child = typeRoot.getChild(iXML);
2041
                                Iterator iter = elements.iterator();
2042
                                while (iter.hasNext()) {
2043
                                        ProjectDocument element = (ProjectDocument) iter.next();
2044
                                        if (element.getName().equalsIgnoreCase(
2045
                                                        child.getStringProperty("name"))) {
2046
                                                conflictsType.put(new Integer(iXML), child);
2047
                                                break;
2048
                                        }
2049

    
2050
                                }
2051
                        }
2052
                        if (conflictsType.size() > 0) {
2053
                                conflicts
2054
                                                .put(typeRoot.getStringProperty("type"), conflictsType);
2055
                        }
2056
                }
2057
                return conflicts;
2058
        }
2059

    
2060
        public boolean isValidXMLForImport(String xml) {
2061
                XMLEntity xmlEntity;
2062
                try {
2063
                        xmlEntity = XMLEntity.parse(xml);
2064
                } catch (Exception e) {
2065
                        return false;
2066
                }
2067

    
2068
                return checkExportXMLRootNode(xmlEntity);
2069
        }
2070

    
2071
        public boolean isValidXMLForImport(String xml, String type) {
2072
                XMLEntity xmlEntity;
2073
                try {
2074
                        xmlEntity = XMLEntity.parse(xml);
2075
                } catch (Exception e) {
2076
                        return false;
2077
                }
2078

    
2079
                if (!checkExportXMLRootNode(xmlEntity)) {
2080
                        return false;
2081
                }
2082

    
2083
                XMLEntity typeRoot = xmlEntity.firstChild("type", type);
2084

    
2085
                if (typeRoot == null) {
2086
                        return false;
2087
                }
2088

    
2089
                return (typeRoot.getChildrenCount() > 0);
2090
        }
2091

    
2092
        private boolean checkExportXMLRootNode(XMLEntity xml) {
2093
                if (!xml.contains("applicationName"))
2094
                        return false;
2095
                if (!xml.getStringProperty("applicationName").equalsIgnoreCase("gvSIG"))
2096
                        return false;
2097

    
2098
                if (!xml.contains("version"))
2099
                        return false;
2100
                if (!xml.getStringProperty("version")
2101
                                .equalsIgnoreCase(Version.format()))
2102
                        return false;
2103

    
2104
                return true;
2105
        }
2106

    
2107
        public void exportToXMLDataSource(XMLEntity root, String dataSourceName) {
2108
                XMLEntity dsRoot = this.getExportXMLTypeRootNode(root, "dataSources");
2109
                SourceInfo sourceInfo = LayerFactory.getDataSourceFactory()
2110
                                .getDriverInfo(dataSourceName);
2111
                dsRoot.addChild(this.getSourceInfoXMLEntity(sourceInfo));
2112
        }
2113

    
2114
        private XMLEntity newExportXMLRootNode() {
2115
                XMLEntity xml = new XMLEntity();
2116
                xml.putProperty("applicationName", "gvSIG");
2117
                xml.putProperty("version", Version.format());
2118
                return xml;
2119
        }
2120

    
2121
        public XMLEntity getExportXMLTypeRootNode(XMLEntity root, String type) {
2122
                XMLEntity typeRoot = root.firstChild("type", type);
2123
                if (typeRoot == null) {
2124
                        typeRoot = this.newExportXMLTypeNode(type);
2125
                        root.addChild(typeRoot);
2126
                }
2127
                return typeRoot;
2128
        }
2129

    
2130
        private XMLEntity newExportXMLTypeNode(String type) {
2131
                XMLEntity xmlDataSources = new XMLEntity();
2132
                xmlDataSources.putProperty("type", type);
2133
                return xmlDataSources;
2134
        }
2135

    
2136
        private static boolean registerDataSourceFromXML(XMLEntity xmlDataSource) {
2137
                String name = xmlDataSource.getStringProperty("gdbmsname");
2138

    
2139
                if (LayerFactory.getDataSourceFactory().getDriverInfo(name) == null) {
2140
                        if (xmlDataSource.getStringProperty("type").equals(
2141
                                        "otherDriverFile")) {
2142
                                LayerFactory.getDataSourceFactory().addFileDataSource(
2143
                                                xmlDataSource.getStringProperty("driverName"), name,
2144
                                                pathGenerator.getAbsolutePath(xmlDataSource.getStringProperty("file")));
2145

    
2146
                        } else if (xmlDataSource.getStringProperty("type").equals(
2147
                                        "sameDriverFile")) {
2148

    
2149
                        } else if (xmlDataSource.getStringProperty("type").equals("db")) {
2150
                                LayerFactory.getDataSourceFactory().addDBDataSourceByTable(
2151
                                                name, xmlDataSource.getStringProperty("host"),
2152
                                                xmlDataSource.getIntProperty("port"),
2153
                                                xmlDataSource.getStringProperty("user"),
2154
                                                xmlDataSource.getStringProperty("password"),
2155
                                                xmlDataSource.getStringProperty("dbName"),
2156
                                                xmlDataSource.getStringProperty("tableName"),
2157
                                                xmlDataSource.getStringProperty("driverInfo"));
2158
                        } else {
2159
                                return false;
2160
                        }
2161

    
2162
                }
2163
                return true;
2164
        }
2165

    
2166
        private boolean registerDataSources(XMLEntity xmlDataSources) {
2167
                try {
2168
                        int numDataSources = xmlDataSources.getChildrenCount();
2169

    
2170
                        if (numDataSources == 0)
2171
                                return true;
2172
                        DataSourceFactory dsFactory = LayerFactory.getDataSourceFactory();
2173

    
2174
                        for (int i = 0; i < numDataSources; i++) {
2175
                                XMLEntity child = xmlDataSources.getChild(i);
2176
                                if (!this.registerDataSourceFromXML(child)) {
2177
                                        return false;
2178
                                }
2179
                        }
2180

    
2181
                        return true;
2182
                } catch (Exception e) {
2183
                        e.printStackTrace();
2184
                        return false;
2185
                }
2186
        }
2187

    
2188
        public static ProjectDocumentFactory getProjectDocumentFactory(String type) {
2189
                ProjectDocumentFactory pde = null;
2190
                try {
2191
                        ExtensionPoints extensionPoints = ExtensionPointsSingleton
2192
                                        .getInstance();
2193
                        ExtensionPoint extPoint = ((ExtensionPoint) extensionPoints
2194
                                        .get("Documents"));
2195
                        try {
2196
                                pde = (ProjectDocumentFactory) extPoint.create(type);
2197
                        } catch (InstantiationException e) {
2198
                                NotificationManager.addError(
2199
                                                "Clase de ProjectDocument no reconocida", e);
2200
                        } catch (IllegalAccessException e) {
2201
                                NotificationManager.addError(
2202
                                                "Clase de ProjectDocument no reconocida", e);
2203
                        }
2204

    
2205
                } catch (Exception e1) {
2206
                        return null;
2207
                }
2208
                return pde;
2209
        }
2210

    
2211
         public boolean hasChanged() {
2212
                 // we return true if the project is not empty (until we have a better method...)
2213
                 if ((this.getDocuments().size() != 0) || modified) {
2214
                         return true;
2215
                 }
2216
                 return false;
2217
//                 return signatureAtStartup != getXMLEntity().hash();
2218
         }
2219

    
2220
        public void setSignature(long hash) {
2221
                signatureAtStartup = hash;
2222
        }
2223

    
2224
        public boolean isAbsolutePath() {
2225
                return isAbsolutePath;
2226
        }
2227

    
2228
        public void setIsAbsolutePath(boolean selected) {
2229
                isAbsolutePath=selected;
2230
        }
2231
}