Statistics
| Revision:

svn-gvsig-desktop / tags / v10_RC2c / applications / appgvSIG / src / com / iver / cit / gvsig / project / Project.java @ 8745

History | View | Annotate | Download (47 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.Serializable;
48
import java.text.DateFormat;
49
import java.util.ArrayList;
50
import java.util.Date;
51
import java.util.Hashtable;
52
import java.util.Iterator;
53
import java.util.TreeMap;
54

    
55
import org.cresques.cts.IProjection;
56
import org.cresques.cts.ProjectionPool;
57

    
58
import com.hardcode.driverManager.DriverLoadException;
59
import com.hardcode.gdbms.engine.data.DataSource;
60
import com.hardcode.gdbms.engine.data.NoSuchTableException;
61
import com.hardcode.gdbms.engine.data.SourceInfo;
62
import com.hardcode.gdbms.engine.data.db.DBSourceInfo;
63
import com.hardcode.gdbms.engine.data.db.DBTableSourceInfo;
64
import com.hardcode.gdbms.engine.data.file.FileSourceInfo;
65
import com.hardcode.gdbms.engine.data.object.ObjectSourceInfo;
66
import com.iver.andami.PluginServices;
67
import com.iver.andami.ui.mdiManager.IWindow;
68
import com.iver.andami.ui.mdiManager.SingletonWindow;
69
import com.iver.andami.ui.mdiManager.WindowInfo;
70
import com.iver.cit.gvsig.ProjectExtension;
71
import com.iver.cit.gvsig.fmap.DriverException;
72
import com.iver.cit.gvsig.fmap.MapContext;
73
import com.iver.cit.gvsig.fmap.core.v02.FSymbol;
74
import com.iver.cit.gvsig.fmap.crs.CRSFactory;
75
import com.iver.cit.gvsig.fmap.drivers.DriverIOException;
76
import com.iver.cit.gvsig.fmap.layers.CancelationException;
77
import com.iver.cit.gvsig.fmap.layers.FLayer;
78
import com.iver.cit.gvsig.fmap.layers.FLayers;
79
import com.iver.cit.gvsig.fmap.layers.FLyrVect;
80
import com.iver.cit.gvsig.fmap.layers.LayerFactory;
81
import com.iver.cit.gvsig.fmap.layers.SelectableDataSource;
82
import com.iver.cit.gvsig.fmap.layers.XMLException;
83
import com.iver.cit.gvsig.fmap.layers.layerOperations.AlphanumericData;
84
import com.iver.cit.gvsig.fmap.operations.selection.LinkSelectionListener;
85
import com.iver.cit.gvsig.gui.Table;
86
import com.iver.cit.gvsig.gui.View;
87
import com.iver.cit.gvsig.gui.layout.Layout;
88
import com.iver.cit.gvsig.gui.project.OpenException;
89
import com.iver.cit.gvsig.gui.project.ProjectWindow;
90
import com.iver.cit.gvsig.gui.project.SaveException;
91
import com.iver.utiles.NotExistInXMLEntity;
92
import com.iver.utiles.PostProcessSupport;
93
import com.iver.utiles.StringUtilities;
94
import com.iver.utiles.XMLEntity;
95

    
96

    
97
/**
98
 * Clase que representa un proyecto de openSIG
99
 *
100
 * @author Fernando Gonz?lez Cort?s
101
 */
102
public class Project implements Serializable, PropertyChangeListener {
103
        public static String VERSION = "1.0";
104
        static private IProjection defaultProjection = CRSFactory.getCRS(
105
                        "EPSG:23030");
106
        private PropertyChangeSupport change;
107
        boolean modified = false;
108
        private String name;
109
        //private String path;
110
        private String creationDate;
111
        private String modificationDate;
112
        private String owner;
113
        private String comments;
114
        private Color selectionColor = new Color(255, 255, 0);
115
        /**
116
         * Stores the list of ProjectViews in the project
117
         */
118
        private ArrayList views = new ArrayList();
119
        private ArrayList tables = new ArrayList();
120
        private ArrayList maps = new ArrayList();
121
        private ArrayList extents = new ArrayList();
122
        private int signatureAtStartup;
123
        // used to restore the position of the Project Manager window when loading a project from file
124
        private WindowInfo seedProjectWindow = null;
125
        private IProjection projection;
126

    
127

    
128
        /**
129
         * Creates a new Project object.
130
         */
131
        public Project() {
132
                change = new PropertyChangeSupport(this);
133

    
134
                //        change.addPropertyChangeListener(this);
135
                creationDate = DateFormat.getDateInstance().format(new Date());
136
                modificationDate = creationDate;
137
//                signatureAtStartup = computeSignature();
138

    
139
                /*                LayerFactory.setDriversPath(PluginServices.getPluginServices(this)
140
                   .getPluginDirectory()
141
                   .getAbsolutePath() +
142
                   File.separator + "drivers");
143
                 */
144
        }
145

    
146
        /**
147
         * Obtiene la fecha de creaci?n del proyecto
148
         *
149
         * @return
150
         */
151
        public String getCreationDate() {
152
                return creationDate;
153
        }
154

    
155
        /**
156
         * Obtiene el nombre del proyecto
157
         *
158
         * @return
159
         */
160
        public String getName() {
161
                return name;
162
        }
163

    
164
//        /**
165
//         * Obtiene la ruta completa del fichero donde se guardo por ?ltima vez el
166
//         * proyecto
167
//         *
168
//         * @return
169
//         */
170
//        public String getPath() {
171
//                return path;
172
//        }
173

    
174
        /**
175
         * Asigna la fecha de creaci?n del proyecto. Este m?todo tiene sentido s?lo
176
         * por que al recuperar la fecha del XML hay que asignarla al objeto
177
         * proyecto de alguna manera. La fecha se asigna en el constructor y no se
178
         * deber?a de modificar nunca
179
         *
180
         * @param string
181
         */
182
        public void setCreationDate(String string) {
183
                creationDate = string;
184
                modified = true;
185
                change.firePropertyChange("", null, null);
186
        }
187

    
188
        /**
189
         * A?ade un mapa al proyecto
190
         *
191
         * @param m
192
         */
193
        public void addMap(ProjectMap m) {
194
                maps.add(m);
195
                m.addPropertyChangeListener(this);
196
                modified = true;
197
                change.firePropertyChange("", null, null);
198
                m.setProject(this, maps.size() - 1);
199
        }
200

    
201
        /**
202
         * Elimina un mapa del proyecto
203
         *
204
         * @param i indice del mapa
205
         */
206
        public void delMap(int i) {
207
                maps.remove(i);
208
                modified = true;
209
                change.firePropertyChange("", null, null);
210
        }
211

    
212
        /**
213
         * Establece el nombre del proyecto
214
         *
215
         * @param string
216
         */
217
        public void setName(String string) {
218
                name = string;
219
                modified = true;
220
                change.firePropertyChange("", null, null);
221
        }
222

    
223
//        /**
224
//         * establece la ruta completa de donde se encuentra guardado el proyecto
225
//         *
226
//         * @param string
227
//         */
228
//        public void setPath(String string) {
229
//                path = string;
230
//                modified = true;
231
//                change.firePropertyChange("", null, null);
232
//        }
233

    
234
        /**
235
         * DOCUMENT ME!
236
         *
237
         * @param co DOCUMENT ME!
238
         *
239
         * @return DOCUMENT ME!
240
         */
241
        public ProjectTable getTable(AlphanumericData co) {
242
                /**
243
                 * Como las tablas se pueden a?adir cuando se pincha en "ver tabla" de
244
                 * una capa, se puede intentar a?adir dos veces la misma tabla
245
                 */
246
                for (int i = 0; i < tables.size(); i++) {
247
                        if (((ProjectTable) tables.get(i)).getAssociatedTable() == co) {
248
                                return (ProjectTable) tables.get(i);
249
                        }
250
                }
251

    
252
                return null;
253
        }
254

    
255
        public ProjectTable getTable(String name) {
256
                /**
257
                 * Como las tablas se pueden a?adir cuando se pincha en "ver tabla" de
258
                 * una capa, se puede intentar a?adir dos veces la misma tabla
259
                 */
260
                for (int i = 0; i < tables.size(); i++) {
261
                        if (((ProjectTable) tables.get(i)).getName().equals(name)) {
262
                                return (ProjectTable) tables.get(i);
263
                        }
264
                }
265

    
266
                return null;
267
        }
268

    
269
        /**
270
         * A?ade una tabla al proyecto
271
         *
272
         * @param t
273
         */
274
        public void addTable(ProjectTable t) {
275
                tables.add(t);
276
                t.addPropertyChangeListener(this);
277
                modified = true;
278
                change.firePropertyChange("", null, null);
279
                t.setProject(this, tables.size() - 1);
280
        }
281

    
282
        /**
283
         * Elimina una tabla del proyecto
284
         *
285
         * @param i indice de la tabla
286
         */
287
        public void delTable(int i) {
288
                tables.remove(i);
289
                modified = true;
290
                change.firePropertyChange("", null, null);
291
        }
292

    
293
        /**
294
         * Opens a window for provided ProjectTable, which has been previously created,
295
         * and it's present in the project manager. 
296
         *
297
         * @return The window created to open the table
298
         */
299
        public static IWindow openTable(ProjectTable pt) {
300
                com.iver.cit.gvsig.gui.Table tableWindow = new com.iver.cit.gvsig.gui.Table();
301
                tableWindow.setModel(pt);
302
                pt.setAndamiWindow(tableWindow);
303
                PluginServices.getMDIManager().addWindow(tableWindow);
304
                return tableWindow;
305
        }
306
        
307
        /**
308
         * Opens the provided ProjectView, which has been previously created, and
309
         * it's present in the project manager. 
310
         *         
311
         * @return The window created to open the view
312
         */
313
        public static IWindow openView(ProjectView pv) {
314
                com.iver.cit.gvsig.gui.View viewWindow = new com.iver.cit.gvsig.gui.View();
315
                viewWindow.setModel(pv);
316
                PluginServices.getMDIManager().addWindow(viewWindow);
317
                return viewWindow;
318
        }
319
        
320
        /**
321
         * Opens a window for provided ProjectMap, which has been previously created,
322
         * and it's present in the project manager. 
323
         * 
324
         * @return The window created to open the map
325
         */
326
        public static IWindow openMap(ProjectMap pm) {
327
                pm.getModel().setProjectMap(pm);
328
                PluginServices.getMDIManager().addWindow(pm.getModel());
329

    
330
                return pm.getModel();
331
        }
332

    
333
        /**
334
         * A?ade una vista al proyecto
335
         *
336
         * @param v
337
         */
338
        public void addView(ProjectView v) {
339
                views.add(v);
340
                v.addPropertyChangeListener(this);
341
                modified = true;
342
                change.firePropertyChange("", null, null);
343
                v.setProject(this, views.size() - 1);
344
        }
345

    
346
        /**
347
         * Elimina una tabla del proyecto
348
         *
349
         * @param i indice del proyecto
350
         */
351
        public void delView(int k) {
352
                ProjectView pv=(ProjectView)views.get(k);
353
                FLayers layers=pv.getMapContext().getLayers();
354

    
355
                for (int i = layers.getLayersCount()-1; i>=0; i--){
356
                try {
357
                        if (layers.getLayer(i) instanceof AlphanumericData){
358
                    Project project = ((ProjectExtension)PluginServices.getExtension(ProjectExtension.class)).getProject();
359
                    ProjectTable pt = project.getTable((AlphanumericData) layers.getLayer(i));
360

    
361
                    ArrayList tables = project.getTables();
362
                    for (int j = 0; j < tables.size(); j++) {
363
                        if (tables.get(j) == pt){
364
                            project.delTable(j);
365
                            break;
366
                        }
367
                    }
368

    
369
                    PluginServices.getMDIManager().closeSingletonWindow(pt);
370
                }
371
                layers.getLayer(i).getParentLayer().removeLayer(layers.getLayer(i));
372
                        } catch (CancelationException e1) {
373
                            e1.printStackTrace();
374
                    }
375
            }
376
                views.remove(k);
377
                modified = true;
378
                change.firePropertyChange("", null, null);
379
        }
380

    
381
        /**
382
         * Devuelve true si el proyecto (o alguna tabla, vista o mapa que contiene)
383
         * fue modificado
384
         *
385
         * @return
386
         */
387
        public boolean isModified() {
388
                if (this.getMaps().size()==0 && this.getViews().size()==0 && this.getTables().size() == 0){
389
                        return false;
390
                }
391
                return true;
392
                ///return modified;    TODO El atributo modified solo detecta cuando se elimina o a?ade una vista,
393
                ///mapa o tabla pero no cuando se modifican.
394
        }
395

    
396
        /**
397
         * Obtiene los comentarios
398
         *
399
         * @return
400
         */
401
        public String getComments() {
402
                return comments;
403
        }
404

    
405
        /**
406
         * Obtiene la fecha de la ?ltima modificaci?n
407
         *
408
         * @return
409
         */
410
        public String getModificationDate() {
411
                return modificationDate;
412
        }
413

    
414
        /**
415
         * Obtiene el propietario del proyecto
416
         *
417
         * @return
418
         */
419
        public String getOwner() {
420
                return owner;
421
        }
422

    
423
        /**
424
         * Establece una cadena como comentarios al proyecto
425
         *
426
         * @param string
427
         */
428
        public void setComments(String string) {
429
                comments = string;
430
                modified = true;
431
                change.firePropertyChange("", null, null);
432
        }
433

    
434
        /**
435
         * Establece la fecha de la ?ltima modificaci?n
436
         *
437
         * @param string
438
         */
439
        public void setModificationDate(String string) {
440
                modificationDate = string;
441
                modified = true;
442
                change.firePropertyChange("", null, null);
443
        }
444

    
445
        /**
446
         * Establece el propietario del proyecto
447
         *
448
         * @param string
449
         */
450
        public void setOwner(String string) {
451
                owner = string;
452
                modified = true;
453
                change.firePropertyChange("", null, null);
454
        }
455

    
456
        /**
457
         * Establece el flag de modificado del proyecto
458
         *
459
         * @param b
460
         */
461
        public void setModified(boolean b) {
462
                modified = b;
463
        }
464

    
465
        /**
466
         * Obtiene el color de selecci?n que se usar? en el proyecto
467
         *
468
         * @return
469
         */
470
        public Color getSelectionColor() {
471
                return selectionColor;
472
        }
473

    
474
        /**
475
         * Establece el color de selecci?n
476
         *
477
         * @param color
478
         */
479
        public void setSelectionColor(Color color) {
480
                selectionColor = color;
481
                FSymbol.setSelectionColor(color);
482
                modified = true;
483
                change.firePropertyChange("selectionColor", null, color);
484
        }
485

    
486
        /**
487
         * Obtiene el color como un entero para su serializaci?n a XML
488
         *
489
         * @return
490
         */
491
        public String getColor() {
492
                return StringUtilities.color2String(selectionColor);
493
        }
494

    
495
        /**
496
         * M?todo invocado al recuperar de XML para establecer el color de
497
         * seleccion del proyecto
498
         *
499
         * @param color Entero que representa un color
500
         */
501
        public void setColor(String color) {
502
                modified = true;
503
                selectionColor = StringUtilities.string2Color(color);
504
        }
505

    
506
        /* (non-Javadoc)
507
         * @see java.beans.PropertyChangeListener#propertyChange(java.beans.PropertyChangeEvent)
508
         */
509
        public void propertyChange(PropertyChangeEvent evt) {
510
                this.modified = true;
511
                change.firePropertyChange(evt);
512
        }
513

    
514
        /**
515
         * DOCUMENT ME!
516
         *
517
         * @param arg1
518
         */
519
        public void addExtent(ProjectExtent arg1) {
520
                extents.add(arg1);
521
                modified = true;
522
                change.firePropertyChange("addExtent", null, null);
523
        }
524

    
525
        /**
526
         * DOCUMENT ME!
527
         *
528
         * @param arg0
529
         *
530
         * @return
531
         */
532
        public Object removeExtent(int arg0) {
533
                modified = true;
534
                change.firePropertyChange("delExtent", null, null);
535

    
536
                return extents.remove(arg0);
537
        }
538

    
539
        /**
540
         * DOCUMENT ME!
541
         *
542
         * @return DOCUMENT ME!
543
         */
544
        public ProjectExtent[] getExtents() {
545
                return (ProjectExtent[]) extents.toArray(new ProjectExtent[0]);
546
        }
547

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

    
558
        /**
559
         * Get the list of maps in the project.
560
         *
561
         * @return
562
         */
563
        public ArrayList getMaps() {
564
                return maps;
565
        }
566

    
567
        /**
568
         * Get the list of tables in the project.
569
         *
570
         * @return
571
         */
572
        public ArrayList getTables() {
573
                return tables;
574
        }
575

    
576
        /**
577
         * Get the list of ProjectViews in the project.
578
         *
579
         * @return
580
         */
581
        public ArrayList getViews() {
582
                return views;
583
        }
584

    
585
        /**
586
         * DOCUMENT ME!
587
         *
588
         * @return DOCUMENT ME!
589
         *
590
         * @throws DriverException
591
         * @throws XMLException
592
         */
593
        public XMLEntity getXMLEntity() throws DriverException, XMLException {
594
                XMLEntity xml = new XMLEntity();
595
                xml.putProperty("className", this.getClass().getName());
596
                xml.putProperty("VERSION", VERSION);
597
                xml.putProperty("comments", comments);
598
                xml.putProperty("creationDate", creationDate);
599

    
600
                int numExtents = extents.size();
601

    
602
                /*double[] xs = new double[size];
603
                   double[] ys = new double[size];
604
                   double[] ws = new double[size];
605
                   double[] hs = new double[size];
606
                 */
607
                xml.putProperty("numExtents", numExtents);
608

    
609
                for (int i = 0; i < numExtents; i++) {
610
                        /*        Rectangle2D rect = (Rectangle2D) extents.get(i);
611
                           xs[i] = rect.getX();
612
                           ys[i] = rect.getY();
613
                           ws[i] = rect.getWidth();
614
                           hs[i] = rect.getHeight();
615
                         */
616
                        xml.addChild(((ProjectExtent) extents.get(i)).getXMLEntity());
617
                }
618

    
619
        // NUEVO: ESTO ESTA EN PRUEBAS. SIRVE PARA
620
        // BORRAR LAS REFERENCIAS A DATASOURCES QUE HEMOS
621
        // BORRADO. Hay que probar a borrarlos cuando se
622
        // borra una tabla y cuando se borra una capa.
623
        cleanBadReferences();
624
                SourceInfo[] infos = LayerFactory.getDataSourceFactory().getDriverInfos();
625
                xml.putProperty("data-source-count", infos.length);
626

    
627
                for (int i = 0; i < infos.length; i++) {
628
                        SourceInfo di = infos[i];
629
                        XMLEntity child = this.getSourceInfoXMLEntity(di);
630
                        xml.addChild(child);
631
                }
632

    
633
                /*
634
                   xml.putProperty("extentsX", xs);
635
                   xml.putProperty("extentsY", ys);
636
                   xml.putProperty("extentsW", ws);
637
                   xml.putProperty("extentsH", hs);
638
                 */
639

    
640
                int numViews=0;
641
                for (int i = 0; i < views.size(); i++) {
642
                        try {
643
                                XMLEntity xmlchild=((ProjectView) views.get(i)).getXMLEntity();
644
                                xml.addChild(xmlchild);
645
                                numViews++;
646
                        } catch (SaveException e) {
647
                                e.showError();
648
                        }
649
                }
650
                xml.putProperty("numViews", numViews);
651

    
652
                int numMaps=0;
653
                for (int i = 0; i < maps.size(); i++) {
654
                        try {
655
                                XMLEntity xmlchild=((ProjectMap) maps.get(i)).getXMLEntity();
656
                                xml.addChild(xmlchild);
657
                                numMaps++;
658
                        } catch (SaveException e) {
659
                                e.showError();
660
                        }
661
                }
662
                xml.putProperty("numMaps", numMaps);
663
                xml.putProperty("modificationDate", modificationDate);
664
                xml.putProperty("modified", modified);
665
                xml.putProperty("name", name);
666
                xml.putProperty("owner", owner);
667
                //xml.putProperty("path", path);
668
                xml.putProperty("selectionColor",
669
                        StringUtilities.color2String(selectionColor));
670

    
671
                int numTables=0;
672
                for (int i = 0; i < tables.size(); i++) {
673
                        try {
674
                                XMLEntity xmlchild=((ProjectTable) tables.get(i)).getXMLEntity();
675
                                xml.addChild(xmlchild);
676
                                numTables++;
677
                        } catch (SaveException e) {
678

    
679
                                e.showError();
680
                        }
681
                }
682
                xml.putProperty("numTables", numTables);
683
                xml.putProperty("projection", defaultProjection.getAbrev());
684

    
685
                saveWindowProperties(xml);
686
                
687
                return xml;
688
        }
689
        
690
        private void saveWindowProperties(XMLEntity xml) {
691
                XMLEntity propertyList = new XMLEntity();
692
                
693
                propertyList.setName("AndamiPersistence");
694
                propertyList.putProperty("className", Project.class.getName());
695
                
696
                boolean projectWindowSaved = false;
697
                
698
                IWindow[] windowList = PluginServices.getMDIManager().getOrderedWindows();
699
                WindowInfo wi;
700
                XMLEntity windowProperties;
701
                for (int winIndex=windowList.length-1; winIndex>=0; winIndex--) {
702
                        wi = PluginServices.getMDIManager().getWindowInfo(windowList[winIndex]);
703
                        if (wi!=null && wi.checkPersistence()) {
704
                                if (windowList[winIndex] instanceof View) {
705
                                        View viewWindow = (View) windowList[winIndex];
706
                                        windowProperties = wi.getXMLEntity();
707
                                        windowProperties.putProperty("documentType", "ProjectView");
708
                                        windowProperties.putProperty("documentName", viewWindow.getModel().getName());
709
                                        windowProperties.putProperty("zPosition", winIndex);
710
                                        propertyList.addChild(windowProperties);
711
                                }
712
                                else if (windowList[winIndex] instanceof Table) {
713
                                        Table tableWindow = (Table) windowList[winIndex];
714
                                        windowProperties = wi.getXMLEntity();
715
                                        windowProperties.putProperty("documentType", "ProjectTable");
716
                                        windowProperties.putProperty("documentName", tableWindow.getModel().getName());
717
                                        windowProperties.putProperty("zPosition", winIndex);
718
                                        propertyList.addChild(windowProperties);
719
                                }
720
                                else if (windowList[winIndex] instanceof Layout) {
721
                                        Layout layoutWindow = (Layout) windowList[winIndex];
722
                                        windowProperties = wi.getXMLEntity();
723
                                        windowProperties.putProperty("documentType", "ProjectMap");
724
                                        windowProperties.putProperty("documentName", layoutWindow.getName());
725
                                        windowProperties.putProperty("zPosition", winIndex);
726
                                        propertyList.addChild(windowProperties);
727
                                }
728
                                else if (windowList[winIndex] instanceof ProjectWindow) {
729
                                        projectWindowSaved = true;
730
                                        windowProperties = wi.getXMLEntity();        
731
                                        windowProperties.putProperty("className", "com.iver.cit.gvsig.project.document.gui.ProjectWindow");
732
                                        windowProperties.putProperty("zPosition", winIndex);
733
                                        propertyList.addChild(windowProperties);
734
                                }
735
                        }
736
                }
737
                
738
                if (projectWindowSaved == false) {
739
                        // If the Project Manager was closed, it was not in the
740
                        // previous window list. Save it now
741
                        ProjectExtension pe =(ProjectExtension) PluginServices.getExtension(com.iver.cit.gvsig.ProjectExtension.class);
742
                        
743
                        if (pe!=null) {
744
                                IWindow projectWindow = pe.getProjectWindow();
745
                                wi = PluginServices.getMDIManager().getWindowInfo(projectWindow);
746
                                if (wi!=null && wi.checkPersistence()) {
747
                                        windowProperties = wi.getXMLEntity();
748
                                        if (windowProperties!=null) {
749
                                                windowProperties.putProperty("className", "com.iver.cit.gvsig.project.document.gui.ProjectWindow");
750
                                                propertyList.addChild(windowProperties);
751
                                        }
752
                                }
753
                        }
754
                }
755
                
756
                xml.addChild(propertyList);
757
        }
758
        
759
        /**
760
         * Restores the position ans size of windows from projects
761
         * (gvSIG > 1.0rc1). It also restores the order of the windows
762
         * (which windows are on the foreground).
763
         *  
764
         * @param xml An XMLEntity object containing the properties of the
765
         * windows
766
         */
767
        private void restoreWindowProperties(XMLEntity xml) {
768
                XMLEntity child;
769
                int childNumb;
770
                
771
                boolean projectWindowRestored = false;
772
                
773
                if (xml.contains("className") // the current window persistence method (>1.0rc2)
774
                                && xml.getStringProperty("className").equals(Project.class.getName())
775
                                && xml.contains("name")
776
                                && xml.getStringProperty("name").equals("AndamiPersistence")) {
777
                        
778
                        // order the window properties before restoring them, so that we also
779
                        // restore the zPosition
780
                        TreeMap orderedProperties = new TreeMap();
781
                        int maximum = 1;
782
                        for (childNumb=xml.getChildrenCount()-1; childNumb>=0; childNumb--) {
783
                                child = xml.getChild(childNumb);
784
                                if (child.contains("zPosition")) {
785
                                        orderedProperties.put(new Integer(-child.getIntProperty("zPosition")), child); // reverse the order, so that we add the background windows first
786
                                }
787
                                else {
788
                                        orderedProperties.put(new Integer(maximum++), child); // the windows without zPosition will be on the foreground
789
                                }
790
                        }
791
                        
792
                        Iterator propertiesIterator = orderedProperties.values().iterator();
793
                        while (propertiesIterator.hasNext()) {
794
                                child = (XMLEntity) propertiesIterator.next();
795
                                 if (child.contains("documentType") // restore the position of the layout windows
796
                                                        && child.getStringProperty("documentType").equals("ProjectView")
797
                                                        && child.contains("name")
798
                                                        && child.getStringProperty("name").equals("ViewInfoProperties")) {
799
                                                boolean isClosed = true;
800
                                                if (child.contains("isClosed"))
801
                                                        isClosed = child.getBooleanProperty("isClosed");
802
                                                if (isClosed==false) {
803
                                                        WindowInfo windowProps = WindowInfo.createFromXMLEntity(child);
804
                                                        String documentName = child.getStringProperty("documentName");
805
                                                        ProjectView pv = this.getViewByName(documentName);
806
                                                        IWindow win = Project.openView(pv);
807
                                                        PluginServices.getMDIManager().changeWindowInfo(win, windowProps);
808
                                                }
809
                                }
810
                                else if (child.contains("className") // restore the position of the project manager window
811
                                                && child.getStringProperty("className").equals("com.iver.cit.gvsig.project.document.gui.ProjectWindow")
812
                                                && child.contains("name")
813
                                                && child.getStringProperty("name").equals("ViewInfoProperties")) {
814
                                        this.seedProjectWindow = WindowInfo.createFromXMLEntity(child);
815

    
816
                                        ProjectExtension pe =(ProjectExtension) PluginServices.getExtension(com.iver.cit.gvsig.ProjectExtension.class);
817
                                        
818
                                        if (pe!=null) {
819
                                                pe.setProject(this);
820
                                                pe.showProjectWindow();
821
                                                projectWindowRestored = true;
822
                                        }
823
                                }
824
                                else if (child.contains("documentType") // restore the position of the layout windows
825
                                                && child.getStringProperty("documentType").equals("ProjectMap")
826
                                                && child.contains("name")
827
                                                && child.getStringProperty("name").equals("ViewInfoProperties")) {
828
                                        boolean isClosed = true;
829
                                        if (child.contains("isClosed"))
830
                                                isClosed = child.getBooleanProperty("isClosed");
831
                                        if (isClosed==false) {
832
                                                WindowInfo windowProps = WindowInfo.createFromXMLEntity(child);
833
                                                String documentName = child.getStringProperty("documentName");
834
                                                ProjectMap pm = this.getLayoutByName(documentName);
835
                                                IWindow win = Project.openMap(pm);
836
                                                PluginServices.getMDIManager().changeWindowInfo(win, windowProps);
837
                                        }
838
                                }
839
                                else if (child.contains("documentType") // restore the position of the table windows
840
                                                && child.getStringProperty("documentType").equals("ProjectTable")
841
                                                && child.contains("name")
842
                                                && child.getStringProperty("name").equals("ViewInfoProperties")) {
843
                                        boolean isClosed = true;
844
                                        if (child.contains("isClosed"))
845
                                                isClosed = child.getBooleanProperty("isClosed");
846
                                        if (isClosed==false) {
847
                                                WindowInfo windowProps = WindowInfo.createFromXMLEntity(child);
848
                                                String documentName = child.getStringProperty("documentName");
849
                                                ProjectTable pt = this.getTableByName(documentName);
850
                                                IWindow win = Project.openTable(pt);
851
                                                PluginServices.getMDIManager().changeWindowInfo(win, windowProps);
852
                                        }
853
                                }
854

    
855
                        }
856
                }
857
                
858
                if (!projectWindowRestored) { // if the project manager window was not stored in the project, just open it
859
                        ProjectExtension pe =(ProjectExtension) PluginServices.getExtension(com.iver.cit.gvsig.ProjectExtension.class);
860
                        
861
                        if (pe!=null) {
862
                                pe.setProject(this);
863
                                pe.showProjectWindow();
864
                        }
865
                }
866
        }
867

    
868
        /**
869
         * Restores the position ans size of windows from old projects
870
         * (gvSIG 0.6.1, 1.0alpha, 1.0rc1). Previous versions did not
871
         * store any information about the window properties. Later
872
         * versions use a new system which also stores the window order.
873
         * 
874
         * It just restores positions of the Project Manager window, the
875
         * Views and the Maps (not the tables, they were not stored).
876
         * The window order (which windows are on the foreground)
877
         * is not restored (it was not stored).
878
         *  
879
         * @param xml An XMLEntity object containing the whole project.
880
         */
881
        private void restoreWindowProperties061(XMLEntity xml) {
882
                XMLEntity child;
883
                int childNumb;
884
                
885
                child = xml.getChild(xml.getChildrenCount()-1);
886
                if (child.contains("className")
887
                                && child.getStringProperty("className").equals("com.iver.cit.gvsig.project.Project")
888
                                && child.contains("name")
889
                                && child.getStringProperty("name").equals("ViewInfoProperties")) {
890
                        this.seedProjectWindow = WindowInfo.createFromXMLEntity(child);
891
                        
892
                        ProjectExtension pe =(ProjectExtension) PluginServices.getExtension(com.iver.cit.gvsig.ProjectExtension.class);
893
                        
894
                        if (pe!=null) {
895
                                pe.setProject(this);
896
                                pe.showProjectWindow();
897
                        }
898
                        
899
                }
900
                else  { // if the project manager window was not stored in the project, just open it
901
                        ProjectExtension pe =(ProjectExtension) PluginServices.getExtension(com.iver.cit.gvsig.ProjectExtension.class);
902
                        
903
                        if (pe!=null) {
904
                                pe.setProject(this);
905
                                pe.showProjectWindow();
906
                        }
907
                }
908
                
909
                // try to open the views
910
                childNumb = xml.getIntProperty("numExtents") + xml.getIntProperty("data-source-count");
911
                int limit = (xml.getIntProperty("numViews") + childNumb);
912
                WindowInfo winProps;
913
                XMLEntity view;
914
                for (int i = childNumb; i < limit; i++) {
915
                        view = xml.getChild(i);
916
                        child = view.getChild(view.getChildrenCount()-1);
917
                        if (child.contains("className") && child.getStringProperty("className").equals("com.iver.cit.gvsig.project.ProjectView") && child.contains("name") && child.getStringProperty("name").equals("ViewInfoProperties")) {
918
                                winProps = WindowInfo.createFromXMLEntity(child);
919
                                String documentName = view.getStringProperty("name");
920
                                ProjectView pv = this.getViewByName(documentName);
921
                                IWindow win = Project.openView(pv);
922
                                PluginServices.getMDIManager().changeWindowInfo(win, winProps);
923
                        }
924
                }
925
                
926
                childNumb += xml.getIntProperty("numViews");
927
                limit = childNumb + xml.getIntProperty("numMaps"); 
928

    
929
                // try to open the maps
930
                XMLEntity map;
931
                for (int i = childNumb; i < limit; i++) {
932
                        map = xml.getChild(i);
933
                        for (int j=0; j<map.getChildrenCount(); j++)
934
                        {
935
                                child = map.getChild(j);
936
                                if (child.contains("className") && child.getStringProperty("className").equals("com.iver.cit.gvsig.project.ProjectMap") && child.contains("name") && child.getStringProperty("name").equals("ViewInfoProperties")) {
937
                                        winProps = WindowInfo.createFromXMLEntity(child);
938
                                        String documentName = map.getStringProperty("name");
939
                                        ProjectMap pm = this.getLayoutByName(documentName);
940
                                        IWindow win = Project.openMap(pm);
941
                                        PluginServices.getMDIManager().changeWindowInfo(win, winProps);
942
                                }
943
                        }
944
                }
945
        }
946

    
947
        
948
        /**
949
         * DOCUMENT ME!
950
         *
951
         * @param xml DOCUMENT ME!
952
         *
953
         * @return DOCUMENT ME!
954
         * @throws XMLException
955
         * @throws DriverException
956
         * @throws DriverIOException
957
         * @throws OpenException
958
         */
959
        public static Project createFromXML03(XMLEntity xml)
960
                throws OpenException {
961
                Project p = new Project();
962
                try{
963
                p.comments = xml.getStringProperty("comments");
964
                p.creationDate = xml.getStringProperty("creationDate");
965
/*
966
                double[] xs = xml.getDoubleArrayProperty("extentsX");
967
                double[] ys = xml.getDoubleArrayProperty("extentsY");
968
                double[] ws = xml.getDoubleArrayProperty("extentsW");
969
                double[] hs = xml.getDoubleArrayProperty("extentsH");
970
*/
971
                int numExtents=xml.getIntProperty("numExtents");
972
                for (int i = 0; i < numExtents; i++) {
973
                        ProjectExtent pe=ProjectExtent.createFromXML03(xml.getChild(i));
974
                        p.extents.add(pe);
975
                }
976

    
977
                int numViews = xml.getIntProperty("numViews");
978

    
979
                for (int i = numExtents; i < numViews+numExtents; i++) {
980
                        p.views.add(ProjectView.createFromXML03(xml.getChild(i), p));
981
                }
982

    
983
                int numMaps = xml.getIntProperty("numMaps");
984

    
985
                for (int i = numViews+numExtents; i < (numMaps + numViews+numExtents); i++) {
986
                        p.maps.add(ProjectMap.createFromXML03(xml.getChild(i), p));
987
                }
988

    
989
                p.modificationDate = xml.getStringProperty("modificationDate");
990
                p.modified = xml.getBooleanProperty("modified");
991
                p.name = xml.getStringProperty("name");
992
                p.owner = xml.getStringProperty("owner");
993
//                p.path = xml.getStringProperty("path");
994
                p.selectionColor = StringUtilities.string2Color(xml.getStringProperty(
995
                                        "selectionColor"));
996

    
997
                int numTables = xml.getIntProperty("numTables");
998

    
999
                for (int i = numExtents+numMaps + numViews; i < (numExtents+numTables + numMaps + numViews);
1000
                                i++) {
1001
                        p.tables.add(ProjectTable.createFromXML03(xml.getChild(i), p));
1002
                }
1003
                String strProj = xml.getStringProperty("projection");
1004
                if (strProj != null)
1005
                        p.setProjection(CRSFactory.getCRS(strProj));
1006
                }catch (Exception e) {
1007
                        throw new OpenException(e,p.getClass().getName());
1008
                }
1009
                return p;
1010
        }
1011

    
1012
        /**
1013
         * DOCUMENT ME!
1014
         *
1015
         * @param xml DOCUMENT ME!
1016
         *
1017
         * @return DOCUMENT ME!
1018
         *
1019
         * @throws XMLException
1020
         * @throws DriverException
1021
         * @throws DriverIOException
1022
         * @throws OpenException
1023
         * @throws VersionException
1024
         */
1025
        public static Project createFromXML(XMLEntity xml)
1026
                throws OpenException {
1027

    
1028
                int childNumber = 0;
1029
                Project p = new Project();
1030
                try{
1031
                p.comments = xml.getStringProperty("comments");
1032
                p.creationDate = xml.getStringProperty("creationDate");
1033

    
1034
                /*
1035
                   double[] xs = xml.getDoubleArrayProperty("extentsX");
1036
                   double[] ys = xml.getDoubleArrayProperty("extentsY");
1037
                   double[] ws = xml.getDoubleArrayProperty("extentsW");
1038
                   double[] hs = xml.getDoubleArrayProperty("extentsH");
1039
                 */
1040
                int numExtents = xml.getIntProperty("numExtents");
1041

    
1042
                for (int i = 0; i < numExtents; i++) {
1043
                        ProjectExtent pe = ProjectExtent.createFromXML(xml.getChild(i));
1044
                        p.extents.add(pe);
1045
                }
1046

    
1047
                childNumber = numExtents;
1048

    
1049
                int numDataSources = xml.getIntProperty("data-source-count");
1050

    
1051
                for (int i = childNumber; i < (childNumber + numDataSources); i++) {
1052
                        XMLEntity child = xml.getChild(i);
1053

    
1054
                        if (child.getStringProperty("type").equals("otherDriverFile")) {
1055
                                LayerFactory.getDataSourceFactory().addFileDataSource(child.getStringProperty(
1056
                                                "driverName"), child.getStringProperty("gdbmsname"),
1057
                                        child.getStringProperty("file"));
1058
                        } else if (child.getStringProperty("type").equals("sameDriverFile")) {
1059
                                /*                                String layerName = child.getStringProperty("layerName");
1060
                                   ProjectView vista = project.getViewByName(child.getStringProperty(
1061
                                   "viewName"));
1062
                                   FLayer layer = vista.getMapContext().getLayers().getLayer(layerName);
1063

1064
                                   modelo = ((AlphanumericData) layer).getRecordset();
1065
                                   associatedTable = (AlphanumericData) layer;
1066
                                 */
1067
                        } else if (child.getStringProperty("type").equals("db")) {
1068
                                LayerFactory.getDataSourceFactory().addDBDataSourceByTable(child.getStringProperty(
1069
                                                "gdbmsname"), child.getStringProperty("host"),
1070
                                        child.getIntProperty("port"),
1071
                                        child.getStringProperty("user"),
1072
                                        child.getStringProperty("password"),
1073
                                        child.getStringProperty("dbName"),
1074
                                        child.getStringProperty("tableName"),
1075
                                        child.getStringProperty("driverInfo"));
1076
                        }
1077
                }
1078

    
1079
                childNumber += numDataSources;
1080

    
1081
                int numViews = xml.getIntProperty("numViews");
1082

    
1083
                for (int i = childNumber; i < (numViews + childNumber); i++) {
1084
                        try{
1085
                                ProjectView pv = (ProjectView) ProjectView.createFromXML(xml.getChild(i), p);
1086
                                p.addView(pv);
1087
                        }catch(OpenException e){
1088
                                e.showError();
1089
                        }
1090
                }
1091

    
1092
                childNumber += numViews;
1093

    
1094
                int numMaps = xml.getIntProperty("numMaps");
1095

    
1096
                for (int i = childNumber; i < (numMaps + childNumber); i++) {
1097
                        try{
1098
                                ProjectMap map = (ProjectMap) ProjectMap.createFromXML(xml.getChild(i), p);
1099
                                p.maps.add(map);
1100
                        }catch(OpenException e){
1101
                                e.showError();
1102
                        }
1103
                }
1104

    
1105
                childNumber += numMaps;
1106
                p.modificationDate = xml.getStringProperty("modificationDate");
1107
                p.modified = xml.getBooleanProperty("modified");
1108
                p.name = xml.getStringProperty("name");
1109
                p.owner = xml.getStringProperty("owner");
1110
//                p.path = xml.getStringProperty("path");
1111
                p.selectionColor = StringUtilities.string2Color(xml.getStringProperty(
1112
                                        "selectionColor"));
1113

    
1114
                int numTables = xml.getIntProperty("numTables");
1115

    
1116
                for (int i = childNumber; i < (childNumber + numTables); i++) {
1117
                        try{
1118
                                ProjectTable ptable = (ProjectTable) ProjectTable.createFromXML(xml.getChild(i), p);
1119
                                p.tables.add(ptable);
1120
                        }catch(OpenException e){
1121
                                e.showError();
1122
                        }
1123
                }
1124

    
1125
                childNumber += numTables;
1126
                
1127
                if (childNumber < xml.getChildrenCount()) { // restore the position of the windows
1128
                        XMLEntity child = xml.getChild(childNumber);
1129
                        if (child.contains("className")
1130
                                        && child.getStringProperty("className").equals(Project.class.getName())
1131
                                        && child.contains("name")
1132
                                        && child.getStringProperty("name").equals("AndamiPersistence")) {
1133
                                p.restoreWindowProperties(child);
1134
                        }
1135
                        else if (child.contains("className")
1136
                                        && child.getStringProperty("className").equals("com.iver.cit.gvsig.project.Project")
1137
                                        && child.contains("name")
1138
                                        && child.getStringProperty("name").equals("ViewInfoProperties")) {
1139
                                p.restoreWindowProperties061(xml); 
1140
                        }
1141
                }
1142
                else { // if there was no info about the windows, just open the project manager window
1143
                        ProjectExtension pe =(ProjectExtension) PluginServices.getExtension(com.iver.cit.gvsig.ProjectExtension.class);                        
1144
                        if (pe!=null) {
1145
                                pe.setProject(p);
1146
                                pe.showProjectWindow();
1147
                        }
1148
                }
1149

    
1150
                p.setLinkTable();
1151

    
1152
                String strProj = xml.getStringProperty("projection");
1153

    
1154
                if (strProj != null) {
1155
                        p.setProjection(CRSFactory.getCRS(strProj));
1156
                }
1157
        PostProcessSupport.executeCalls();
1158
                }catch (Exception e) {
1159
                        throw new OpenException(e,p.getClass().getName());
1160
                }
1161
//                p.setSignature( p.hashCode());
1162
                return p;
1163

    
1164
        }
1165
        
1166
        
1167
//        private void setSignature(int signature) {
1168
//                this.signatureAtStartup = computeSignature();
1169
//        }
1170

    
1171
        /**
1172
         * Reestablece los link que ten?a cada tabla con las dem?s.
1173
         */
1174
        public void setLinkTable() {
1175
                ArrayList tables = getTables();
1176

    
1177
                for (int i = 0; i < tables.size(); i++) {
1178
                        for (int j = 0; j < tables.size(); j++) {
1179
                                /*System.out.println("name = " +
1180
                                        ((ProjectTable) tables.get(j)).getModelo().getName());
1181
                                System.out.println("linktable = " +
1182
                                        ((ProjectTable) tables.get(i)).getLinkTable());
1183
*/
1184
                                try {
1185
                                if ((((ProjectTable) tables.get(i)).getLinkTable() != null) &&
1186
                                                ((ProjectTable) tables.get(i)).getLinkTable().equals(((ProjectTable) tables
1187
                                                                                                                                                                  .get(
1188
                                                                j)).getModelo().getRecordset().getName())) {
1189
                                        LinkSelectionListener lsl;
1190

    
1191
                                                lsl = new LinkSelectionListener((SelectableDataSource)((ProjectTable) tables.get(
1192
                                                                        i)).getModelo().getRecordset(),
1193
                                                                        (SelectableDataSource)((ProjectTable) tables.get(j)).getModelo().getRecordset(),
1194
                                                                ((ProjectTable) tables.get(i)).getField1(),
1195
                                                                ((ProjectTable) tables.get(i)).getField2());
1196

    
1197
                                                ((SelectableDataSource)((ProjectTable) tables.get(i)).getModelo().getRecordset())
1198
                                         .addSelectionListener(lsl);
1199

    
1200
                                }
1201
                                } catch (DriverLoadException e) {
1202
                                        // TODO Auto-generated catch block
1203
                                        e.printStackTrace();
1204
                                }
1205
                        }
1206
                }
1207
        }
1208

    
1209
        /**
1210
         * Obtiene la vista que contiene a la capa que se pasa como par?metro
1211
         *
1212
         * @param layer Capa cuya vista se quiere obtener
1213
         *
1214
         * @return
1215
         *
1216
         * @throws RuntimeException Si la capa que se pasa como par?metro no se
1217
         *                    encuentra en ninguna vista
1218
         */
1219
        public String getView(FLayer layer) {
1220
                for (int v = 0; v < views.size(); v++) {
1221
                        ProjectView pView = (ProjectView) views.get(v);
1222
                        FLayers layers = pView.getMapContext().getLayers();
1223
                        if (isView(layers,layer))return pView.getName();
1224
                }
1225

    
1226
                throw new RuntimeException("The layer is not in a view");
1227
        }
1228

    
1229
        public boolean isView(FLayers layers, FLayer layer) {
1230
                for (int i = 0; i < layers.getLayersCount(); i++) {
1231
                        if (layers.getLayer(i) instanceof FLayers){
1232
                                return isView((FLayers)layers.getLayer(i),layer);
1233
                        }else{
1234
                                if (layers.getLayer(i) == layer) {
1235
                                        return true;
1236
                                }
1237
                        }
1238
                }
1239
                return false;
1240
        }
1241

    
1242
        /**
1243
         * Devuelve la vista cuyo nombre coincide (sensible a mayusculas) con el
1244
         * que se pasa como par?metro. Devuelve null si no hay ninguna vista con
1245
         * ese nombre
1246
         *
1247
         * @param viewName Nombre de la vista que se quiere obtener
1248
         *
1249
         * @return DOCUMENT ME!
1250
         */
1251
        public ProjectView getViewByName(String viewName) {
1252
                Object o = getProjectElementByName(viewName, views);
1253

    
1254
                if (o == null) {
1255
                        return null;
1256
                }
1257

    
1258
                return (ProjectView) o;
1259
        }
1260

    
1261
        /**
1262
         * DOCUMENT ME!
1263
         *
1264
         * @return DOCUMENT ME!
1265
         */
1266
        public IProjection getProjection() {
1267
                if (projection == null)
1268
                        projection = defaultProjection;
1269
                return defaultProjection;
1270
        }
1271

    
1272
        /**
1273
         * DOCUMENT ME!
1274
         *
1275
         * @param defaultProjection DOCUMENT ME!
1276
         */
1277
        public void setProjection(IProjection defaultProjection) {
1278
                Project.defaultProjection = defaultProjection;
1279
        }
1280

    
1281
        /**
1282
         * DOCUMENT ME!
1283
         *
1284
         * @param name DOCUMENT ME!
1285
         * @param l DOCUMENT ME!
1286
         *
1287
         * @return DOCUMENT ME!
1288
         */
1289
        private Object getProjectElementByName(String name, ArrayList l) {
1290
                for (Iterator iter = l.iterator(); iter.hasNext();) {
1291
                        ProjectElement elem = (ProjectElement) iter.next();
1292

    
1293
                        if (elem.getName().equals(name)) {
1294
                                return elem;
1295
                        }
1296
                }
1297

    
1298
                return null;
1299
        }
1300

    
1301
        /**
1302
         * DOCUMENT ME!
1303
         *
1304
         * @param name
1305
         *
1306
         * @return
1307
         */
1308
        public ProjectTable getTableByName(String name) {
1309
                Object o = getProjectElementByName(name, tables);
1310

    
1311
                if (o == null) {
1312
                        return null;
1313
                }
1314

    
1315
                return (ProjectTable) o;
1316
        }
1317

    
1318
        /**
1319
         * DOCUMENT ME!
1320
         *
1321
         * @param name
1322
         *
1323
         * @return
1324
         */
1325
        public ProjectMap getLayoutByName(String name) {
1326
                Object o = getProjectElementByName(name, maps);
1327

    
1328
                if (o == null) {
1329
                        return null;
1330
                }
1331

    
1332
                return (ProjectMap) o;
1333
        }
1334

    
1335
    public SelectableDataSource getDataSourceByLayer(FLayer layer) throws DriverException {
1336
        ArrayList tables = getTables();
1337
        SelectableDataSource dataSource = null;
1338
        try {
1339
        for (int i = 0; i < tables.size(); i++) {
1340
            ProjectTable pt = (ProjectTable) tables.get(i);
1341
            if (pt.getOriginal() == ((AlphanumericData) layer).getRecordset()){
1342
                dataSource = (SelectableDataSource)pt.getModelo().getRecordset();
1343
                break;
1344
            }else if (pt.getModelo() == ((AlphanumericData) layer).getRecordset()){
1345

    
1346
                                        dataSource = (SelectableDataSource)pt.getModelo().getRecordset();
1347

    
1348
                break;
1349
            }
1350
        }
1351
        } catch (DriverLoadException e) {
1352
                        // TODO Auto-generated catch block
1353
                        e.printStackTrace();
1354
                }
1355

    
1356
        if (dataSource == null){
1357
            //No se ha creado la tabla asociada al tema
1358
            dataSource = ((AlphanumericData) layer).getRecordset();
1359
        }
1360

    
1361
        return dataSource;
1362

    
1363
    }
1364

    
1365
    /**
1366
     * Recorremos las capas y las tablas del proyecto, y creamos una lista
1367
     * con todos los datasources de GDBMS que estamos usando.
1368
     * Luego recorremos los que est?n registrados, y borramos
1369
     * aquellos que no est?n siendo usados, es decir, aquellos
1370
     * que no est?n en nuestra lista (un Hash con clave el nombre
1371
     * del GDBMS)
1372
     *
1373
     */
1374
    private void cleanBadReferences()
1375
    {
1376
        Hashtable usedDataSources = new Hashtable();
1377
        // Primero las tablas
1378
        int i, j;
1379
        try {
1380
        for (i=0; i<tables.size(); i++)
1381
        {
1382
            ProjectTable t = (ProjectTable) tables.get(i);
1383
            SelectableDataSource ds;
1384

    
1385
                                ds = (SelectableDataSource)t.getModelo().getRecordset();
1386

    
1387
            if (t.getOriginal() != null)
1388
                usedDataSources.put(t.getOriginal().getRecordset().getName(), t.getOriginal());
1389
            usedDataSources.put(ds.getName(), ds);
1390
        }
1391
        } catch (DriverLoadException e) {
1392
                        // TODO Auto-generated catch block
1393
                        e.printStackTrace();
1394
                }
1395
        // Ahora las vistas
1396
        try {
1397
            for (i=0; i<views.size(); i++)
1398
            {
1399
                ProjectView pv = (ProjectView) views.get(i);
1400

    
1401
                FLayers lyrs = pv.getMapContext().getLayers();
1402

    
1403
                for (j=0; j<lyrs.getLayersCount(); j++)
1404
                {
1405
                    FLayer lyr = lyrs.getLayer(j);
1406
                    if (lyr instanceof FLyrVect)
1407
                    {
1408
                        FLyrVect lyrVect = (FLyrVect) lyr;
1409
                        if (lyrVect.isAvailable())
1410
                                usedDataSources.put(lyrVect.getRecordset().getName(), lyrVect.getSource().getRecordset());
1411
                    }
1412
                }
1413
                MapContext aux = pv.getMapOverViewContext();
1414
                if (aux != null)
1415
                {
1416
                    FLayers lyrsOverview = aux.getLayers();
1417
                    for (j=0; j<lyrsOverview.getLayersCount(); j++)
1418
                    {
1419
                        FLayer lyr = lyrsOverview.getLayer(j);
1420
                        if (lyr instanceof FLyrVect)
1421
                        {
1422
                            FLyrVect lyrVect = (FLyrVect) lyr;
1423
                            usedDataSources.put(lyrVect.getSource().getRecordset().getName(), lyrVect.getSource().getRecordset());
1424
                        }
1425
                    }
1426
                }
1427

    
1428
            } // for i
1429
        } catch (DriverLoadException e) {
1430
                        // TODO Auto-generated catch block
1431
                        e.printStackTrace();
1432
                } catch (DriverException e) {
1433
                        // TODO Auto-generated catch block
1434
                        e.printStackTrace();
1435
                }
1436
        // Recorremos los dataSources y los borramos si no
1437
        // los estamos usando.
1438
        SourceInfo[] infos = LayerFactory.getDataSourceFactory().getDriverInfos();
1439
        try {
1440
            for (i=0; i < infos.length; i++)
1441
            {
1442
                if (!usedDataSources.containsKey(infos[i].name))
1443
                {
1444
                    DataSource ds;
1445
                    ds = LayerFactory.getDataSourceFactory().createRandomDataSource(infos[i].name);
1446
                    ds.remove();
1447
                }
1448
            }
1449
        } catch (DriverLoadException e) {
1450
            // TODO Auto-generated catch block
1451
            e.printStackTrace();
1452
        } catch (NoSuchTableException e) {
1453
            // TODO Auto-generated catch block
1454
            e.printStackTrace();
1455
        } catch (com.hardcode.gdbms.engine.data.driver.DriverException e) {
1456
            // TODO Auto-generated catch block
1457
            e.printStackTrace();
1458
        }
1459
    }
1460

    
1461
        public WindowInfo getSeedProjectWindow() {
1462
                return seedProjectWindow;
1463
        }
1464
        
1465
        public void setSeedProjectWindow(WindowInfo projectWindow) {
1466
                seedProjectWindow = projectWindow;
1467
        }
1468

    
1469
        public XMLEntity getSourceInfoXMLEntity(SourceInfo di) {
1470
                XMLEntity child = new XMLEntity();
1471

    
1472

    
1473
                if (di instanceof ObjectSourceInfo) {
1474
                        ObjectSourceInfo driver = (ObjectSourceInfo) di;
1475
                        child.putProperty("type", "sameDriverFile");
1476
                        child.putProperty("gdbmsname", driver.name);
1477
                } else if (di instanceof FileSourceInfo) {
1478
                        FileSourceInfo vfdi = (FileSourceInfo) di;
1479
                        child.putProperty("type", "otherDriverFile");
1480
                        child.putProperty("gdbmsname", vfdi.name);
1481
                        child.putProperty("file", vfdi.file);
1482
                        child.putProperty("driverName", vfdi.driverName);
1483
                } else if (di instanceof DBSourceInfo) {
1484
                        DBTableSourceInfo dbdi = (DBTableSourceInfo) di;
1485
                        child.putProperty("type", "db");
1486
                        child.putProperty("gdbmsname", dbdi.name);
1487
                        child.putProperty("dbms", dbdi.dbms);
1488
                        child.putProperty("host", dbdi.host);
1489
                        child.putProperty("port", dbdi.port);
1490
                        child.putProperty("user", dbdi.user);
1491
                        child.putProperty("password", dbdi.password);
1492
                        child.putProperty("dbName", dbdi.dbName);
1493
                        child.putProperty("tableName", dbdi.tableName);
1494
                        child.putProperty("driverInfo", dbdi.driverName);
1495
                }
1496

    
1497
                return child;
1498
        }
1499

    
1500

    
1501
        /**
1502
         * Sets the projection used when no projection is defined
1503
         * @param defaultProjection DOCUMENT ME!
1504
         */
1505
        public static void setDefaultProjection(IProjection defaultProjection) {
1506
                Project.defaultProjection = defaultProjection;
1507
        }
1508

    
1509
        public static IProjection getDefaultProjection() {
1510
                return Project.defaultProjection;
1511
        }
1512

    
1513
//        public boolean hasChanged() {
1514
//                return signatureAtStartup != computeSignature();
1515
//        }
1516

    
1517
//        public int computeSignature() {
1518
//
1519
////                /* TODO method also present in ProjectMap, ProjectTable,
1520
////                 *  ProjectView and ProjectExtent
1521
////                 */
1522
//                int result = 17;
1523
////
1524
////                Class clazz = getClass();
1525
////                Field[] fields = clazz.getDeclaredFields();
1526
////                for (int i = 0; i < fields.length; i++) {
1527
////                        try {
1528
////                                // don't compute following fields
1529
////                                if (fields[i].getName().equals("modificationDate")
1530
////                                                || fields[i].getName().equals("creationDate")
1531
////                                                || fields[i].getName().equals("signatureAtStartup")
1532
////                                                || fields[i].getName().equals("change")
1533
////                                                || Modifier.isStatic(fields[i].getModifiers()))
1534
////                                        continue;
1535
////
1536
////
1537
////                                String type = fields[i].getType().getName();
1538
////                                if (type.equals("boolean")) {
1539
////                                        result += 37 + ((fields[i].getBoolean(this)) ? 1 : 0);
1540
////                                } else if (type.equals("java.lang.String")) {
1541
////                                        Object v = fields[i].get(this);
1542
////                                        if (v == null) {
1543
////                                                result += 37;
1544
////                                                continue;
1545
////                                        }
1546
////                                        char[] chars = ((String) v).toCharArray();
1547
////                                        for (int j = 0; j < chars.length; j++) {
1548
////                                                result += 37 + (int) chars[i];
1549
////                                        }
1550
////                                } else if (type.equals("byte")) {
1551
////                                        result += 37 + (int) fields[i].getByte(this);
1552
////                                } else if (type.equals("char")) {
1553
////                                        result += 37 + (int) fields[i].getChar(this);
1554
////                                } else if (type.equals("short")) {
1555
////                                        result += 37 + (int) fields[i].getShort(this);
1556
////                                } else if (type.equals("int")) {
1557
////                                        result += 37 + fields[i].getInt(this);
1558
////                                } else if (type.equals("long")) {
1559
////                                        long f = fields[i].getLong(this) ;
1560
////                                        result += 37 + (f ^ (f >>> 32));
1561
////                                } else if (type.equals("float")) {
1562
////                                        result += 37 + Float.floatToIntBits(fields[i].getFloat(this));
1563
////                                } else if (type.equals("double")) {
1564
////                                        long f = Double.doubleToLongBits(fields[i].getDouble(this));
1565
////                                        result += 37 + (f ^ (f >>> 32));
1566
////                                } else {
1567
//////                                        Object obj = fields[i].get(this);
1568
//////                                        result += 37 + ((obj != null)? obj.hashCode() : 0);
1569
////                                }
1570
////                        } catch (Exception e) { e.printStackTrace(); }
1571
////
1572
////                }
1573
////
1574
////                for (int i = 0; i < views.size(); i++) {
1575
////                        ProjectView e = (ProjectView) views.get(i);
1576
////                        result += 37 + e.computeSignature();
1577
////                }
1578
////
1579
////                for (int i = 0; i < tables.size(); i++) {
1580
////                        ProjectTable e = (ProjectTable) tables.get(i);
1581
////                        result += 37 + e.computeSignature();
1582
////                }
1583
////
1584
////                for (int i = 0; i < maps.size(); i++) {
1585
////                        ProjectMap e = (ProjectMap) maps.get(i);
1586
////                        result += 37 + e.computeSignature();
1587
////                }
1588
////
1589
////                for (int i = 0; i < extents.size(); i++) {
1590
////                        ProjectExtent e = (ProjectExtent) extents.get(i);
1591
////                        result += 37 + e.computeSignature();
1592
////                }
1593
//
1594
//
1595
//                return result;
1596
//        }
1597

    
1598
}