Statistics
| Revision:

svn-gvsig-desktop / trunk / org.gvsig.desktop / org.gvsig.desktop.plugin / org.gvsig.app / org.gvsig.app.mainplugin / src / main / java / org / gvsig / app / project / DefaultProject.java @ 42293

History | View | Annotate | Download (36.7 KB)

1
/**
2
 * gvSIG. Desktop Geographic Information System.
3
 *
4
 * Copyright (C) 2007-2013 gvSIG Association.
5
 *
6
 * This program is free software; you can redistribute it and/or modify it under
7
 * the terms of the GNU General Public License as published by the Free Software
8
 * Foundation; either version 3 of the License, or (at your option) any later
9
 * version.
10
 *
11
 * This program is distributed in the hope that it will be useful, but WITHOUT
12
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
13
 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
14
 * details.
15
 *
16
 * You should have received a copy of the GNU General Public License along with
17
 * this program; if not, write to the Free Software Foundation, Inc., 51
18
 * Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
19
 *
20
 * For any additional information, do not hesitate to contact us at info AT
21
 * gvsig.com, or visit our website www.gvsig.com.
22
 */
23
package org.gvsig.app.project;
24

    
25
import java.awt.Color;
26
import java.beans.PropertyChangeEvent;
27
import java.beans.PropertyChangeListener;
28
import java.beans.PropertyChangeSupport;
29
import java.io.File;
30
import java.io.FileInputStream;
31
import java.io.FileNotFoundException;
32
import java.io.FileOutputStream;
33
import java.io.InputStream;
34
import java.io.OutputStream;
35
import java.io.Serializable;
36
import java.text.DateFormat;
37
import java.text.MessageFormat;
38
import java.util.ArrayList;
39
import java.util.Collections;
40
import java.util.Date;
41
import java.util.HashMap;
42
import java.util.Iterator;
43
import java.util.List;
44
import java.util.Map;
45
import org.cresques.cts.IProjection;
46
import org.gvsig.andami.PluginServices;
47
import org.gvsig.andami.ui.mdiManager.IWindow;
48
import org.gvsig.andami.ui.mdiManager.MDIManager;
49
import org.gvsig.andami.ui.mdiManager.SingletonWindow;
50
import org.gvsig.andami.ui.mdiManager.WindowInfo;
51
import org.gvsig.app.ApplicationLocator;
52
import org.gvsig.app.ApplicationManager;
53
import org.gvsig.app.extension.ProjectExtension;
54
import org.gvsig.app.extension.Version;
55
import org.gvsig.app.project.documents.AbstractDocument;
56
import org.gvsig.app.project.documents.Document;
57
import org.gvsig.app.project.documents.exceptions.SaveException;
58
import org.gvsig.app.project.documents.gui.IDocumentWindow;
59
import org.gvsig.app.project.documents.gui.ProjectWindow;
60
import org.gvsig.app.project.documents.view.DefaultViewDocument;
61
import org.gvsig.app.project.documents.view.ViewManager;
62
import org.gvsig.fmap.mapcontext.MapContext;
63
import org.gvsig.fmap.mapcontext.layers.ExtendedPropertiesHelper;
64
import org.gvsig.fmap.mapcontext.layers.FLayer;
65
import org.gvsig.fmap.mapcontext.layers.FLayers;
66
import org.gvsig.tools.ToolsLocator;
67
import org.gvsig.tools.dynobject.DynStruct;
68
import org.gvsig.tools.observer.ObservableHelper;
69
import org.gvsig.tools.observer.Observer;
70
import org.gvsig.tools.persistence.PersistenceManager;
71
import org.gvsig.tools.persistence.Persistent;
72
import org.gvsig.tools.persistence.PersistentState;
73
import org.gvsig.tools.persistence.exception.PersistenceException;
74
import org.gvsig.utils.StringUtilities;
75
import org.slf4j.Logger;
76
import org.slf4j.LoggerFactory;
77

    
78
/**
79
 * Clase que representa un proyecto de gvSIG
80
 *
81
 */
82
public class DefaultProject implements Serializable, PropertyChangeListener,
83
        Project {
84

    
85
    private Logger LOG = LoggerFactory.getLogger(DefaultProject.class);
86
    /**
87
     * @deprecated see ApplicationLocator.getManager().getVersion()
88
     */
89
    public static String VERSION = Version.format();
90

    
91
    private ExtendedPropertiesHelper propertiesHelper = new ExtendedPropertiesHelper();
92

    
93
    private ObservableHelper observableHelper = new ObservableHelper();
94

    
95
    /**
96
     *
97
     */
98
    private static final long serialVersionUID = -4449622027521773178L;
99

    
100
    private static final Logger logger = LoggerFactory.getLogger(Project.class);
101

    
102
    private static ProjectPreferences preferences = new ProjectPreferences();
103

    
104
    /**
105
     * Index used by the generator of unique names of documents.
106
     */
107
    private Map<String, Integer> nextDocumentIndexByType = new HashMap<String, Integer>();
108

    
109
    private PropertyChangeSupport change;
110

    
111
    private boolean modified = false;
112

    
113
    private String name = null;
114

    
115
    private String creationDate = null;
116

    
117
    private String modificationDate = null;
118

    
119
    private String owner = null;
120

    
121
    private String comments = null;
122

    
123
    private Color selectionColor = null;
124

    
125
    private List<Document> documents = null;
126

    
127
    private List<ProjectExtent> extents = null;
128

    
129
    private IProjection projection;
130

    
131
    /**
132
     * Creates a new Project object.
133
     */
134
    DefaultProject() {
135
        this.change = new PropertyChangeSupport(this);
136
        this.clean();
137
    }
138

    
139
    protected void clean() {
140
        this.owner = "";
141
        this.comments = "";
142
        this.name = PluginServices.getText(this, "untitled");
143
        this.creationDate = DateFormat.getDateInstance().format(new Date());
144
        this.modificationDate = this.creationDate;
145

    
146
        this.documents = new ArrayList<Document>();
147
        this.extents = new ArrayList<ProjectExtent>();
148

    
149
        this.setSelectionColor(getPreferences().getDefaultSelectionColor());
150

    
151
        this.projection = null; // se inicializa en el getProjection()
152
    }
153

    
154
    public static ProjectPreferences getPreferences() {
155
        return preferences;
156
    }
157

    
158
    public void propertyChange(PropertyChangeEvent evt) {
159
        change.firePropertyChange(evt);
160
    }
161

    
162
    public synchronized void addPropertyChangeListener(
163
            PropertyChangeListener arg0) {
164
        change.addPropertyChangeListener(arg0);
165
    }
166

    
167
    /**
168
     * Return the creation date of the project
169
     *
170
     * @return
171
     */
172
    public String getCreationDate() {
173
        return creationDate;
174
    }
175

    
176
    protected void setCreationDate(String creationDate) {
177
        this.creationDate = creationDate;
178
        change.firePropertyChange("setCreationDate", null, null);
179
    }
180

    
181
    public Document createDocument(String type) {
182
        logger.info("createDocument('{}')", type);
183
        return ProjectManager.getInstance().createDocument(type);
184
    }
185

    
186
    /**
187
     * Return the name of the project
188
     *
189
     * @return
190
     */
191
    public String getName() {
192
        return name;
193
    }
194

    
195
    /**
196
     * Set the name of he project.
197
     *
198
     * @param string
199
     */
200
    public void setName(String name) {
201
        this.name = name;
202
        change.firePropertyChange("setName", null, null);
203
    }
204

    
205
    /**
206
     * Return the comments associateds with the project
207
     *
208
     * @return comments
209
     */
210
    public String getComments() {
211
        return comments;
212
    }
213

    
214
    /**
215
     * Set the comments associateds with the project
216
     *
217
     * @param comments as string
218
     */
219
    public void setComments(String string) {
220
        comments = string;
221
        change.firePropertyChange("setComments", null, null);
222
    }
223

    
224
    /**
225
     * Retuen the modification date of the project.
226
     *
227
     * @return modification date as string
228
     */
229
    public String getModificationDate() {
230
        return modificationDate;
231
    }
232

    
233
    protected void setModificationDate(String string) {
234
        modificationDate = string;
235
        change.firePropertyChange("setModificationDate", null, null);
236
    }
237

    
238
    /**
239
     * Return the author of the project,
240
     *
241
     * @return author as string
242
     */
243
    public String getOwner() {
244
        return owner;
245
    }
246

    
247
    /**
248
     * Sets the author of the project
249
     *
250
     * @param author name as string
251
     */
252
    public void setOwner(String owner) {
253
        this.owner = owner;
254
        change.firePropertyChange("setOwner", null, null);
255
    }
256

    
257
    /**
258
     * Obtiene el color de selecci�n que se usar� en el proyecto
259
     *
260
     * @return
261
     */
262
    public Color getSelectionColor() {
263
        if (selectionColor == null) {
264
            selectionColor = getPreferences().getDefaultSelectionColor();
265
        }
266
        return selectionColor;
267
    }
268

    
269
    /**
270
     * Sets the selecction color
271
     *
272
     * @param selection color as string
273
     */
274
    public void setSelectionColor(String selectionColor) {
275
        this.setSelectionColor(StringUtilities.string2Color(selectionColor));
276
    }
277

    
278
    /**
279
     * Sets the selecction color
280
     *
281
     * @param selection color as Color
282
     */
283
    public void setSelectionColor(Color selectionColor) {
284
        this.selectionColor = selectionColor;
285
        MapContext.setSelectionColor(selectionColor);
286
        change.firePropertyChange("selectionColor", null, selectionColor);
287
    }
288

    
289
    public IProjection getProjection() {
290
        if (projection == null) {
291
            projection = getPreferences().getDefaultProjection();
292
        }
293
        return projection;
294
    }
295

    
296
    public void setProjection(IProjection projection) {
297
        this.projection = projection;
298
    }
299

    
300
    /**
301
     * Sets the modified state of project.
302
     *
303
     * Can't set to not modified.
304
     *
305
     * @param modified as boolean
306
     */
307
    public void setModified(boolean modified) {
308
        this.modified = modified;
309
        if (modified == false) {
310
            List<Document> documents = this.getDocuments();
311
            for (int i = 0; i < documents.size(); i++) {
312
                documents.get(i).setModified(false);
313
            }
314
        }
315
    }
316

    
317
    public boolean hasChanged() {
318
                // we return true if the project is not empty (until we have a better
319
        // method...)
320
        if ((this.getDocuments().size() != 0) || modified) {
321
            return true;
322
        }
323
        return false;
324
    }
325

    
326
    /**
327
     * Return a list of documents in the project.
328
     *
329
     * @return documents as List of IProjectDocument
330
     */
331
    public List<Document> getDocuments() {
332
        return Collections.unmodifiableList(documents);
333
    }
334

    
335
    /**
336
     * Return a list with all documents of especified type.
337
     *
338
     * @param type of document
339
     *
340
     * @return List of IProjectDocument
341
     */
342
    public List<Document> getDocuments(String type) {
343
        List<Document> docs = new ArrayList<Document>();
344
        if (type != null) {
345
            for (Document document : this.documents) {
346
                if (type.equalsIgnoreCase(document.getTypeName())) {
347
                    docs.add(document);
348
                }
349
            }
350
        }
351
        return Collections.unmodifiableList(docs);
352
    }
353

    
354
    /**
355
     * Adds a document to the project
356
     *
357
     * @param document as Document
358
     */
359
    public void add(Document document) {
360
        this.addDocument(document);
361
    }
362

    
363
    public void addDocument(Document document) {
364
        logger.info("add('{}')", document.toString());
365

    
366
        if (notifyObservers(ProjectNotification.BEFORE_ADD_DOCUMENT, document).isProcessCanceled()) {
367
            return;
368
        }
369
        document.addPropertyChangeListener(this);
370
        document.setProject(this);
371
        document.setName(this.getUniqueNameForDocument(document.getTypeName(),
372
                document.getName()));
373
        documents.add(document);
374
        document.afterAdd();
375
        this.setModified(true);
376
        notifyObservers(ProjectNotification.AFTER_ADD_DOCUMENT, document);
377
        change.firePropertyChange("addDocument", null, document);
378
    }
379

    
380
    public void remove(Document doc) {
381
        this.removeDocument(doc);
382
    }
383

    
384
    public void removeDocument(Document doc) {
385
        logger.info("remove('{}')", doc.toString());
386
        if (notifyObservers(ProjectNotification.BEFORE_REMOVE_DOCUMENT, doc).isProcessCanceled()) {
387
            return;
388
        }
389
        documents.remove(doc);
390
        this.setModified(true);
391
        change.firePropertyChange("delDocument", doc, null);
392
        doc.afterRemove();
393
        notifyObservers(ProjectNotification.AFTER_REMOVE_DOCUMENT, doc);
394
    }
395

    
396
    public Iterator<Document> iterator() {
397
        return documents.iterator();
398
    }
399

    
400
    public boolean isEmpty() {
401
        return documents.isEmpty();
402
    }
403

    
404
    /**
405
     * Return the view that contains the especified layer.
406
     *
407
     * @param layer
408
     *
409
     * @return name of the view that contains the layer
410
     *
411
     * @throws RuntimeException Si la capa que se pasa como par�metro no se
412
     * encuentra en ninguna vista
413
     */
414
    public String getViewName(FLayer layer) {
415
        List<Document> views = getDocuments(ViewManager.TYPENAME);
416
        for (int v = 0; v < views.size(); v++) {
417
            DefaultViewDocument pView = (DefaultViewDocument) views.get(v);
418
            FLayers layers = pView.getMapContext().getLayers();
419
            if (isView(layers, layer)) {
420
                return pView.getName();
421
            }
422
        }
423

    
424
        throw new RuntimeException(MessageFormat.format(
425
                "The layer '{1}' is not in a view", layer.getName()));
426
    }
427

    
428
    private boolean isView(FLayers layers, FLayer layer) {
429
        for (int i = 0; i < layers.getLayersCount(); i++) {
430
            if (layers.getLayer(i) instanceof FLayers) {
431
                if (isView((FLayers) layers.getLayer(i), layer)) {
432
                    return true;
433
                }
434
            }
435
            if (layers.getLayer(i) == layer) {
436
                return true;
437
            }
438
        }
439
        return false;
440
    }
441

    
442
    public void addExtent(ProjectExtent arg1) {
443
        extents.add(arg1);
444
        change.firePropertyChange("addExtent", null, null);
445
    }
446

    
447
    public ProjectExtent removeExtent(int arg0) {
448
        change.firePropertyChange("delExtent", null, null);
449
        return extents.remove(arg0);
450
    }
451

    
452
    public ProjectExtent[] getExtents() {
453
        return (ProjectExtent[]) extents.toArray(new ProjectExtent[0]);
454
    }
455

    
456
    /**
457
     * Obtiene un documento a partir de su nombre y el nombre de registro en el
458
     * pointExtension, este �ltimo se puede obtener del
459
     * Project****Factory.registerName.
460
     *
461
     * @param name Nombre del documento
462
     * @param type nombre de registro en el extensionPoint
463
     *
464
     * @return Documento
465
     */
466
    public Document getDocument(String name, String type) {
467
        if (type == null) {
468
            for (int i = 0; i < documents.size(); i++) {
469
                Document document = documents.get(i);
470
                if ( name.equalsIgnoreCase(document.getName())) {
471
                    return document;
472
                }
473
            }
474
        } else {
475
            for (int i = 0; i < documents.size(); i++) {
476
                Document document = documents.get(i);
477
                if (type.equalsIgnoreCase(document.getTypeName())
478
                        && name.equalsIgnoreCase(document.getName())) {
479
                    return document;
480
                }
481
            }
482
        }
483
        return null;
484
    }
485
    
486
    public Document getDocument(String name) {
487
        return this.getDocument(name, null);
488
    }    
489

    
490
    public String getUniqueNameForDocument(String type, String name) {
491
        Document document = getDocument(name, type);
492
        if (document == null) {
493
            return name;
494
        }
495

    
496
        String newName = null;
497
        int num = this.getNextDocumentIndex(type);
498
        while (document != null) {
499
            newName = name + " - " + num++;
500
            document = getDocument(newName, type);
501
        }
502
        this.setNextDocumentIndex(type, num);
503
        return newName;
504
    }
505

    
506
    private int getNextDocumentIndex(String type) {
507
        if (nextDocumentIndexByType.get(type) == null) {
508
            nextDocumentIndexByType.put(type, new Integer(1));
509
            return 1;
510
        }
511
        return nextDocumentIndexByType.get(type).intValue();
512
    }
513

    
514
    private void setNextDocumentIndex(String type, int newIndex) {
515
        if (nextDocumentIndexByType.get(type) == null) {
516
            nextDocumentIndexByType.put(type, new Integer(newIndex));
517
        } else {
518
            nextDocumentIndexByType.put(type, new Integer(newIndex));
519
        }
520
    }
521

    
522
    public void saveState(File out) throws PersistenceException {
523
        FileOutputStream fout;
524
        if (notifyObservers(ProjectNotification.BEFORE_SAVE_TO_FILE, out).isProcessCanceled()) {
525
            return;
526
        }
527
        try {
528
            fout = new FileOutputStream(out);
529
            saveState(fout, new File(out.getParent()));
530
        } catch (FileNotFoundException e) {
531
            throw new PersistenceException(e);
532
        }
533
        notifyObservers(ProjectNotification.AFTER_SAVE_TO_FILE, out);
534
    }
535

    
536
    public void saveState(OutputStream out) throws PersistenceException {
537
        saveState(out, null);
538
    }
539

    
540
    public void saveState(OutputStream out, File rootFolder)
541
            throws PersistenceException {
542
        if (notifyObservers(ProjectNotification.BEFORE_SAVE_TO_STREAM).isProcessCanceled()) {
543
            return;
544
        }
545
        PersistenceManager manager = ToolsLocator.getPersistenceManager();
546
        PersistentState state = null;
547
        state = manager.getState(this, true);
548
        try {
549
            if (rootFolder != null) {
550
                state.relativizeFiles(rootFolder);
551
            }
552
        } catch (Exception ex) {
553
            state.getContext().addError(ex);
554
        }
555
        manager.saveState(state, out);
556
        if (state.getContext().getErrors() != null) {
557
            throw state.getContext().getErrors();
558
        }
559
        notifyObservers(ProjectNotification.AFTER_SAVE_TO_STREAM);
560
    }
561

    
562
    public void loadState(InputStream in) {
563
        loadState(in, null);
564
    }
565

    
566
    public void loadState(InputStream in, File rootFolder) {
567
        if (notifyObservers(ProjectNotification.BEFORE_LOAD_FROM_STREAM).isProcessCanceled()) {
568
            return;
569
        }
570
        PersistenceManager manager = ToolsLocator.getPersistenceManager();
571
        try {
572
            PersistentState state = manager.loadState(in);
573
            try {
574
                if (rootFolder != null) {
575
                    state.derelativizeFiles(rootFolder);
576
                }
577
            } catch (Exception ex) {
578
                state.getContext().addError(ex);
579
            }
580
            this.loadFromState(state);
581
        } catch (PersistenceException e) {
582
            LOG.info("Can't load project to stream", e);
583
        }
584
        notifyObservers(ProjectNotification.AFTER_LOAD_FROM_STREAM);
585

    
586
    }
587

    
588
    public void loadState(File in) {
589
        if (notifyObservers(ProjectNotification.BEFORE_LOAD_FROM_FILE, in).isProcessCanceled()) {
590
            return;
591
        }
592
        FileInputStream fin;
593
        try {
594
            fin = new FileInputStream(in);
595
            loadState(fin, new File(in.getParent()));
596
        } catch (FileNotFoundException e) {
597
            // TODO Auto-generated catch block
598
            e.printStackTrace();
599
        }
600
        notifyObservers(ProjectNotification.AFTER_LOAD_FROM_FILE, in);
601
    }
602

    
603
    @SuppressWarnings("unchecked")
604
    public void loadFromState(PersistentState state)
605
            throws PersistenceException {
606
        this.clean();
607

    
608
        this.setComments(state.getString("comments"));
609
        this.setCreationDate(state.getString("creationDate"));
610
        this.setModificationDate(state.getString("modificationDate"));
611
        this.setName(state.getString("name"));
612
        this.setOwner(state.getString("owner"));
613
        this.setSelectionColor((Color) state.get("selectionColor"));
614
        this.setProjection((IProjection) state.get("projection"));
615

    
616
        this.propertiesHelper = (ExtendedPropertiesHelper) state.get("propertiesHelper");
617

    
618
        List<ProjectExtent> extents = (List<ProjectExtent>) state
619
                .get("extents");
620
        for (int i = 0; i < extents.size(); i++) {
621
            this.addExtent(extents.get(i));
622
        }
623

    
624
        List<AbstractDocument> documents = (List<AbstractDocument>) state
625
                .get("documents");
626
        for (int i = 0; i < documents.size(); i++) {
627
            this.add(documents.get(i));
628
        }
629

    
630
        List<DocumentWindowInfo> persistentWindows = (List<DocumentWindowInfo>) state.get("documentWindowsInformation");
631

    
632
        for (int i = 0; i < persistentWindows.size(); i++) {
633
            DocumentWindowInfo persistentWindow = persistentWindows.get(i);
634
            String docName = persistentWindow.getDocumentName();
635
            String docType = persistentWindow.getDocumentType();
636
            Document doc = this.getDocument(docName, docType);
637
            IWindow win = doc.getFactory().getMainWindow(doc);
638
            if(win!=null){
639
                win.getWindowInfo().setWindowInfo(persistentWindow.getWindowInfo());
640
                PluginServices.getMDIManager().addWindow(win);
641
            }
642
        }
643

    
644
        if (state.hasValue("projectWindowInfo")) {
645
            WindowInfo projectWindowInfo = (WindowInfo) state.get("projectWindowInfo");
646
            ProjectExtension pe = (ProjectExtension) PluginServices.getExtension(org.gvsig.app.extension.ProjectExtension.class);
647
            pe.setProject(this);
648
            pe.showProjectWindow(projectWindowInfo);
649
        }
650

    
651
    }
652

    
653
    public void saveToState(PersistentState state) throws PersistenceException {
654
        state.set("version", VERSION);
655
        state.set("comments", getComments());
656
        state.set("creationDate", this.getCreationDate());
657

    
658
        state.set("modificationDate", this.getModificationDate());
659
        state.set("name", this.getName());
660
        state.set("owner", this.getOwner());
661
        state.set("selectionColor", this.getSelectionColor());
662

    
663
        state.set("projection", this.getProjection());
664

    
665
        state.set("extents", this.extents);
666
        List<Document> docs = this.getDocuments();
667
        List<Document> noTempDocs = new ArrayList<Document>();
668
        for (Iterator iterator = docs.iterator(); iterator.hasNext();) {
669
            Document document = (Document) iterator.next();
670
            if(!document.isTemporary()){
671
                noTempDocs.add(document);
672
            }
673
        }
674
        state.set("documents", noTempDocs);
675

    
676
        state.set("propertiesHelper",propertiesHelper);
677

    
678
        List<DocumentWindowInfo> persistentWindows = new ArrayList<DocumentWindowInfo>();
679
        MDIManager mdiMan = PluginServices.getMDIManager();
680
        IWindow[] windows = mdiMan.getOrderedWindows();
681
        for (int i = windows.length - 1; i >= 0; i--) {
682
            IWindow window = windows[i];
683
            if (window instanceof IDocumentWindow) {
684
                WindowInfo wi = mdiMan.getWindowInfo(window);
685
                DocumentWindowInfo dwi = new DocumentWindowInfo(
686
                        wi,
687
                        ((IDocumentWindow) window).getDocument().getTypeName(),
688
                        ((IDocumentWindow) window).getDocument().getName());
689
                persistentWindows.add(dwi);
690
            } else if (window instanceof ProjectWindow) {
691
                state.set("projectWindowInfo", mdiMan.getWindowInfo(window));
692
            }
693
        }
694
        state.set("documentWindowsInformation", persistentWindows);
695

    
696
    }
697

    
698
    public Object getProperty(Object key) {
699
        return this.propertiesHelper.getProperty(key);
700
    }
701

    
702
    public void setProperty(Object key, Object obj) {
703
        this.propertiesHelper.setProperty(key, obj);
704
    }
705

    
706
    public Map getExtendedProperties() {
707
        return this.propertiesHelper.getExtendedProperties();
708
    }
709

    
710
    public static class DocumentWindowInfo implements Persistent {
711

    
712
        public static final String PERSISTENCE_DEFINITION_NAME = "DocumentWindowInfo";
713

    
714
        private WindowInfo windowInfo;
715
        private String documentType;
716
        private String documentName;
717

    
718
        public DocumentWindowInfo() {
719
        }
720

    
721
        DocumentWindowInfo(WindowInfo wi, String docType, String docName) {
722
            windowInfo = wi;
723
            documentType = docType;
724
            documentName = docName;
725
        }
726

    
727
        public WindowInfo getWindowInfo() {
728
            return windowInfo;
729
        }
730

    
731
        public String getDocumentType() {
732
            return documentType;
733
        }
734

    
735
        public String getDocumentName() {
736
            return documentName;
737
        }
738

    
739
        public void saveToState(PersistentState state)
740
                throws PersistenceException {
741
            state.set("windowInfo", this.windowInfo);
742
            state.set("documentType", this.documentType);
743
            state.set("documentName", this.documentName);
744
        }
745

    
746
        public void loadFromState(PersistentState state)
747
                throws PersistenceException {
748
            this.windowInfo = (WindowInfo) state.get("windowInfo");
749
            this.documentType = state.getString("documentType");
750
            this.documentName = state.getString("documentName");
751
        }
752

    
753
        public static void registerPersistent() {
754
            PersistenceManager manager = ToolsLocator.getPersistenceManager();
755
            DynStruct definition = manager.getDefinition(PERSISTENCE_DEFINITION_NAME);
756
            if (definition == null) {
757
                definition = manager.addDefinition(
758
                        DocumentWindowInfo.class,
759
                        PERSISTENCE_DEFINITION_NAME,
760
                        "DocumentWindowInfo persistence definition",
761
                        null,
762
                        null
763
                );
764
                definition.addDynFieldObject("windowInfo").setMandatory(true).setClassOfValue(WindowInfo.class);
765
                definition.addDynFieldString("documentType").setMandatory(true);
766
                definition.addDynFieldString("documentName").setMandatory(true);
767
            }
768

    
769
        }
770
    }
771

    
772
    public static void registerPersistent() {
773
        AbstractDocument.registerPersistent();
774
        DocumentWindowInfo.registerPersistent();
775
        ProjectExtent.registerPersistent();
776

    
777
        PersistenceManager manager = ToolsLocator.getPersistenceManager();
778
        DynStruct definition = manager.addDefinition(DefaultProject.class,
779
                "Project", "Project Persistence definition", null, null);
780
        definition.addDynFieldString("version").setMandatory(true);
781
        definition.addDynFieldString("comments").setMandatory(true);
782
        definition.addDynFieldString("creationDate").setMandatory(true);
783
        definition.addDynFieldString("modificationDate").setMandatory(true);
784
        definition.addDynFieldString("name").setMandatory(true);
785
        definition.addDynFieldString("owner").setMandatory(true);
786

    
787
        definition.addDynFieldObject("selectionColor")
788
                .setClassOfValue(Color.class).setMandatory(true);
789
        definition.addDynFieldObject("projection")
790
                .setClassOfValue(IProjection.class).setMandatory(true);
791

    
792
        definition.addDynFieldList("extents")
793
                .setClassOfItems(ProjectExtent.class).setMandatory(true);
794

    
795
        definition.addDynFieldList("documents").setClassOfItems(Document.class)
796
                .setMandatory(true);
797

    
798
        definition.addDynFieldObject("projectWindowInfo").setClassOfValue(WindowInfo.class).setMandatory(false);
799

    
800
        definition.addDynFieldList("documentWindowsInformation").setClassOfItems(WindowInfo.class).setMandatory(false);
801

    
802

    
803
        definition.addDynFieldObject("propertiesHelper").setClassOfValue(ExtendedPropertiesHelper.class)
804
                        .setMandatory(false);
805

    
806
    }
807

    
808
    /**
809
     * @deprecated use getPreferences().setDefaultSelectionColor()
810
     */
811
    public static void setDefaultSelectionColor(Color color) {
812
        getPreferences().setDefaultSelectionColor(color);
813
    }
814

    
815
    /**
816
     * @deprecated use getPreferences().getDefaultSelectionColor()
817
     */
818
    public static Color getDefaultSelectionColor() {
819
        return getPreferences().getDefaultSelectionColor();
820
    }
821

    
822
    /**
823
     * @deprecated use getPreferences().getDefaultMapUnits()
824
     */
825
    public static int getDefaultMapUnits() {
826
        return getPreferences().getDefaultMapUnits();
827
    }
828

    
829
    /**
830
     * @deprecated use getPreferences().getDefaultDistanceUnits()
831
     */
832
    public static int getDefaultDistanceUnits() {
833
        return getPreferences().getDefaultDistanceUnits();
834
    }
835

    
836
    /**
837
     * @deprecated use getPreferences().getDefaultDistanceArea()
838
     */
839
    public static int getDefaultDistanceArea() {
840
        return getPreferences().getDefaultDistanceArea();
841
    }
842

    
843
    /**
844
     * @deprecated use getPreferences().setDefaultMapUnits()
845
     */
846
    public static void setDefaultMapUnits(int mapUnits) {
847
        getPreferences().setDefaultMapUnits(mapUnits);
848
    }
849

    
850
    /**
851
     * @deprecated use getPreferences().setDefaultDistanceUnits()
852
     */
853
    public static void setDefaultDistanceUnits(int distanceUnits) {
854
        getPreferences().setDefaultDistanceUnits(distanceUnits);
855
    }
856

    
857
    /**
858
     * @deprecated use getPreferences().setDefaultDistanceArea()
859
     */
860
    public static void setDefaultDistanceArea(int distanceArea) {
861
        getPreferences().setDefaultDistanceArea(distanceArea);
862
    }
863

    
864
    /**
865
     * @deprecated use getPreferences().setDefaultProjection()
866
     */
867
    public static void setDefaultProjection(IProjection defaultProjection) {
868
        getPreferences().setDefaultProjection(defaultProjection);
869
    }
870

    
871
    /**
872
     * @deprecated use getPreferences().getDefaultProjection()
873
     */
874
    public static IProjection getDefaultProjection() {
875
        return getPreferences().getDefaultProjection();
876
    }
877

    
878
    /**
879
     * @deprecated see {@link #setSelectionColor(String)}, to be remove in gvSIG
880
     * 2.1.0
881
     */
882
    public void setColor(String color) {
883
        this.setSelectionColor(StringUtilities.string2Color(color));
884
    }
885

    
886
    /**
887
     * Return the selection color
888
     *
889
     * @return selection color as string
890
     * @deprecated use {@link #getSelectionColor()}
891
     */
892
    public String getColor() {
893
        return StringUtilities.color2String(selectionColor);
894
    }
895

    
896
    /**
897
     * Return the list of views of the project
898
     *
899
     * @return views as ArrayList of ProjectDocument
900
     *
901
     * @deprecated see {@link #getDocumentsByType(String)}
902
     */
903
    public List<Document> getViews() {
904
        return getDocuments(ViewManager.TYPENAME);
905
    }
906

    
907
    /**
908
     * Add a view to the project
909
     *
910
     * @deprecated see {@link #add(AbstractDocument)}
911
     */
912
    public void addView(DefaultViewDocument v) {
913
        add(v);
914
    }
915

    
916
    /**
917
     * Remove a view of the project
918
     *
919
     * @param index of the view as integer
920
     *
921
     * @deprecated see {@link #remove(AbstractDocument)}
922
     */
923
    public void delView(int i) {
924
        List<Document> list = getDocuments(ViewManager.TYPENAME);
925
        remove(list.get(i));
926
    }
927

    
928
    /**
929
     * @deprecated see {@link #getDocument(String, String)}
930
     */
931
    public Document getProjectDocumentByName(String name, String type) {
932
        return this.getDocument(name, type);
933
    }
934

    
935
    /**
936
     * @deprecated see {@link #getDocuments(String)}
937
     */
938
    public List<Document> getDocumentsByType(String type) {
939
        return this.getDocuments(type);
940
    }
941

    
942
    /**
943
     * @deprecated aun por decidir que API darle al copy/paste
944
     */
945
    public String exportToXML(AbstractDocument[] selectedItems)
946
            throws SaveException {
947
        // FIXME jjdc:hay que decirdir que API darle al copy/paste
948
        throw new UnsupportedOperationException("This method is not supported");
949
    }
950

    
951
    /**
952
     * @deprecated aun por decidir que API darle al copy/paste
953
     */
954
    public void importFromXML(String sourceString, String docType) {
955
        // FIXME jjdc:hay que decirdir que API darle al copy/paste
956
        throw new UnsupportedOperationException("This method is not supported");
957
    }
958

    
959
    /**
960
     * @deprecated aun por decidir que API darle al copy/paste
961
     */
962
    public boolean isValidXMLForImport(String sourceString, String docType) {
963
        // FIXME jjdc:hay que decirdir que API darle al copy/paste
964
        throw new UnsupportedOperationException("This method is not supported");
965
    }
966

    
967
    public boolean canImportDocuments(String data, String doctype) {
968
        // TODO Auto-generated method stub
969
        return false;
970
    }
971

    
972
    public String exportDocumentsAsText(List<Document> documents) {
973
        // TODO Auto-generated method stub
974
        return null;
975
    }
976

    
977
    public void importDocuments(String data, String doctype) {
978
        // TODO Auto-generated method stub
979

    
980
    }
981

    
982
    public Document getActiveDocument() {
983
        return this.getActiveDocument((Class<? extends Document>)null);
984
    }
985

    
986
    public Document getActiveDocument(String documentTypeName) {
987
        ApplicationManager application = ApplicationLocator.getManager();
988

    
989
        Document document = null;
990
        IWindow[] windows = application.getUIManager().getOrderedWindows();
991
        IWindow window = null;
992
        for (int i = 0; i < windows.length; i++) {
993
            window = windows[i];
994
            if (window instanceof SingletonWindow) {
995
                // Cogemos no la primera ventana, si no la primera
996
                // ventana de tipo documento (SingletonWindow).
997
                // Y por si las mosca no es un documento, atrapamos
998
                // los errores y continuamos si no puede hacer un cast
999
                // del Model a Document
1000
                try {
1001
                    document = (Document) ((SingletonWindow) window).getWindowModel();
1002
                    if (documentTypeName == null) {
1003
                        return document;
1004
                    }
1005
                    if( document.getTypeName().equalsIgnoreCase(documentTypeName) ) {
1006
                        return document;
1007
                    }
1008
                    if( document instanceof DocumentsContainer ) {
1009
                        Document subdoc = ((DocumentsContainer)document).getActiveDocument(documentTypeName);
1010
                        return subdoc;
1011
                    }
1012

    
1013
                } catch (ClassCastException e) {
1014
                    // Do nothing, skip this window
1015
                }
1016
            }
1017
        }
1018
        return null;
1019
    }
1020

    
1021
    public Document getActiveDocument(Class<? extends Document> documentClass) {
1022
        ApplicationManager application = ApplicationLocator.getManager();
1023

    
1024
        Document document = null;
1025
        IWindow[] windows = application.getUIManager().getOrderedWindows();
1026
        IWindow window = null;
1027
        for (int i = 0; i < windows.length; i++) {
1028
            window = windows[i];
1029
            if (window instanceof SingletonWindow && window instanceof IDocumentWindow) {
1030
                // Cogemos no la primera ventana, si no la primera
1031
                // ventana de tipo documento (SingletonWindow).
1032
                // Y por si las mosca no es un documento, atrapamos
1033
                // los errores y continuamos si no puede hacer un cast
1034
                // del Model a Document
1035
                try {
1036
                    document = (Document) ((SingletonWindow) window).getWindowModel();
1037
                    if (documentClass == null) {
1038
                        return document;
1039
                    }
1040
                    if (documentClass.isAssignableFrom(document.getClass())) {
1041
                        return document;
1042
                    }
1043
                    if( document instanceof DocumentsContainer ) {
1044
                        Document subdoc = ((DocumentsContainer)document).getActiveDocument(documentClass);
1045
                        return subdoc;
1046
                    }
1047

    
1048
                } catch (ClassCastException e) {
1049
                    // Do nothing, skip this window
1050
                }
1051
            }
1052
        }
1053
        return null;
1054
    }
1055

    
1056
    public void addObserver(Observer o) {
1057
        observableHelper.addObserver(o);
1058
    }
1059

    
1060
    public void deleteObserver(Observer o) {
1061
        observableHelper.deleteObserver(o);
1062
    }
1063

    
1064
    public void deleteObservers() {
1065
        observableHelper.deleteObservers();
1066
    }
1067

    
1068
//        private void notifyObservers(ProjectNotifycation notifycation) {
1069
//                observableHelper.notifyObservers(this, notifycation);
1070
//        }
1071
    private ProjectNotification notifyObservers(int type) {
1072
        DefaultProjectNotification notifycation
1073
                = new DefaultProjectNotification(type, null, null);
1074
        try {
1075
            observableHelper.notifyObservers(this, notifycation);
1076
        } catch (Exception ex) {
1077
            LOG.info("Can't notify observers", ex);
1078
        }
1079
        return notifycation;
1080
    }
1081

    
1082
    private ProjectNotification notifyObservers(int type, Document document) {
1083
        DefaultProjectNotification notifycation
1084
                = new DefaultProjectNotification(type, document, null);
1085
        try {
1086
            observableHelper.notifyObservers(this, notifycation);
1087
        } catch (Exception ex) {
1088
            LOG.info("Can't notify observers", ex);
1089
        }
1090
        return notifycation;
1091
    }
1092

    
1093
    private ProjectNotification notifyObservers(int type, File file) {
1094
        DefaultProjectNotification notifycation
1095
                = new DefaultProjectNotification(type, null, file);
1096
        try {
1097
            observableHelper.notifyObservers(this, notifycation);
1098
        } catch (Exception ex) {
1099
            LOG.info("Can't notify observers", ex);
1100
        }
1101
        return notifycation;
1102
    }
1103

    
1104
    class DefaultProjectNotification implements ProjectNotification {
1105

    
1106
        private int type;
1107
        private Document document;
1108
        private File file;
1109
        private boolean processCanceled = false;
1110

    
1111
        DefaultProjectNotification(int type, Document document, File file) {
1112
            this.type = type;
1113
            this.document = document;
1114
            this.file = file;
1115
        }
1116

    
1117
        public int getNotificationType() {
1118
            return type;
1119
        }
1120

    
1121
        public Document getDocument() {
1122
            return document;
1123
        }
1124

    
1125
        public void cancelProcess() {
1126
            processCanceled = true;
1127
        }
1128

    
1129
        public boolean isProcessCanceled() {
1130
            return processCanceled;
1131
        }
1132

    
1133
        public File getFile() {
1134
            return file;
1135
        }
1136

    
1137
    }
1138

    
1139
}