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 @ 42165

History | View | Annotate | Download (36.3 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 (type.equalsIgnoreCase(document.getTypeName())
471
                        && name.equalsIgnoreCase(document.getName())) {
472
                    return document;
473
                }
474
            }
475
        }
476
        return null;
477
    }
478

    
479
    public String getUniqueNameForDocument(String type, String name) {
480
        Document document = getDocument(name, type);
481
        if (document == null) {
482
            return name;
483
        }
484

    
485
        String newName = null;
486
        int num = this.getNextDocumentIndex(type);
487
        while (document != null) {
488
            newName = name + " - " + num++;
489
            document = getDocument(newName, type);
490
        }
491
        this.setNextDocumentIndex(type, num);
492
        return newName;
493
    }
494

    
495
    private int getNextDocumentIndex(String type) {
496
        if (nextDocumentIndexByType.get(type) == null) {
497
            nextDocumentIndexByType.put(type, new Integer(1));
498
            return 1;
499
        }
500
        return nextDocumentIndexByType.get(type).intValue();
501
    }
502

    
503
    private void setNextDocumentIndex(String type, int newIndex) {
504
        if (nextDocumentIndexByType.get(type) == null) {
505
            nextDocumentIndexByType.put(type, new Integer(newIndex));
506
        } else {
507
            nextDocumentIndexByType.put(type, new Integer(newIndex));
508
        }
509
    }
510

    
511
    public void saveState(File out) throws PersistenceException {
512
        FileOutputStream fout;
513
        if (notifyObservers(ProjectNotification.BEFORE_SAVE_TO_FILE, out).isProcessCanceled()) {
514
            return;
515
        }
516
        try {
517
            fout = new FileOutputStream(out);
518
            saveState(fout, new File(out.getParent()));
519
        } catch (FileNotFoundException e) {
520
            throw new PersistenceException(e);
521
        }
522
        notifyObservers(ProjectNotification.AFTER_SAVE_TO_FILE, out);
523
    }
524

    
525
    public void saveState(OutputStream out) throws PersistenceException {
526
        saveState(out, null);
527
    }
528

    
529
    public void saveState(OutputStream out, File rootFolder)
530
            throws PersistenceException {
531
        if (notifyObservers(ProjectNotification.BEFORE_SAVE_TO_STREAM).isProcessCanceled()) {
532
            return;
533
        }
534
        PersistenceManager manager = ToolsLocator.getPersistenceManager();
535
        PersistentState state = null;
536
        state = manager.getState(this, true);
537
        try {
538
            if (rootFolder != null) {
539
                state.relativizeFiles(rootFolder);
540
            }
541
        } catch (Exception ex) {
542
            state.getContext().addError(ex);
543
        }
544
        manager.saveState(state, out);
545
        if (state.getContext().getErrors() != null) {
546
            throw state.getContext().getErrors();
547
        }
548
        notifyObservers(ProjectNotification.AFTER_SAVE_TO_STREAM);
549
    }
550

    
551
    public void loadState(InputStream in) {
552
        loadState(in, null);
553
    }
554

    
555
    public void loadState(InputStream in, File rootFolder) {
556
        if (notifyObservers(ProjectNotification.BEFORE_LOAD_FROM_STREAM).isProcessCanceled()) {
557
            return;
558
        }
559
        PersistenceManager manager = ToolsLocator.getPersistenceManager();
560
        try {
561
            PersistentState state = manager.loadState(in);
562
            try {
563
                if (rootFolder != null) {
564
                    state.derelativizeFiles(rootFolder);
565
                }
566
            } catch (Exception ex) {
567
                state.getContext().addError(ex);
568
            }
569
            this.loadFromState(state);
570
        } catch (PersistenceException e) {
571
            LOG.info("Can't load project to stream", e);
572
        }
573
        notifyObservers(ProjectNotification.AFTER_LOAD_FROM_STREAM);
574

    
575
    }
576

    
577
    public void loadState(File in) {
578
        if (notifyObservers(ProjectNotification.BEFORE_LOAD_FROM_FILE, in).isProcessCanceled()) {
579
            return;
580
        }
581
        FileInputStream fin;
582
        try {
583
            fin = new FileInputStream(in);
584
            loadState(fin, new File(in.getParent()));
585
        } catch (FileNotFoundException e) {
586
            // TODO Auto-generated catch block
587
            e.printStackTrace();
588
        }
589
        notifyObservers(ProjectNotification.AFTER_LOAD_FROM_FILE, in);
590
    }
591

    
592
    @SuppressWarnings("unchecked")
593
    public void loadFromState(PersistentState state)
594
            throws PersistenceException {
595
        this.clean();
596

    
597
        this.setComments(state.getString("comments"));
598
        this.setCreationDate(state.getString("creationDate"));
599
        this.setModificationDate(state.getString("modificationDate"));
600
        this.setName(state.getString("name"));
601
        this.setOwner(state.getString("owner"));
602
        this.setSelectionColor((Color) state.get("selectionColor"));
603
        this.setProjection((IProjection) state.get("projection"));
604

    
605
        this.propertiesHelper = (ExtendedPropertiesHelper) state.get("propertiesHelper");
606

    
607
        List<ProjectExtent> extents = (List<ProjectExtent>) state
608
                .get("extents");
609
        for (int i = 0; i < extents.size(); i++) {
610
            this.addExtent(extents.get(i));
611
        }
612

    
613
        List<AbstractDocument> documents = (List<AbstractDocument>) state
614
                .get("documents");
615
        for (int i = 0; i < documents.size(); i++) {
616
            this.add(documents.get(i));
617
        }
618

    
619
        List<DocumentWindowInfo> persistentWindows = (List<DocumentWindowInfo>) state.get("documentWindowsInformation");
620

    
621
        for (int i = 0; i < persistentWindows.size(); i++) {
622
            DocumentWindowInfo persistentWindow = persistentWindows.get(i);
623
            String docName = persistentWindow.getDocumentName();
624
            String docType = persistentWindow.getDocumentType();
625
            Document doc = this.getDocument(docName, docType);
626
            IWindow win = doc.getFactory().getMainWindow(doc);
627
            if(win!=null){
628
                win.getWindowInfo().setWindowInfo(persistentWindow.getWindowInfo());
629
                PluginServices.getMDIManager().addWindow(win);
630
            }
631
        }
632

    
633
        if (state.hasValue("projectWindowInfo")) {
634
            WindowInfo projectWindowInfo = (WindowInfo) state.get("projectWindowInfo");
635
            ProjectExtension pe = (ProjectExtension) PluginServices.getExtension(org.gvsig.app.extension.ProjectExtension.class);
636
            pe.setProject(this);
637
            pe.showProjectWindow(projectWindowInfo);
638
        }
639

    
640
    }
641

    
642
    public void saveToState(PersistentState state) throws PersistenceException {
643
        state.set("version", VERSION);
644
        state.set("comments", getComments());
645
        state.set("creationDate", this.getCreationDate());
646

    
647
        state.set("modificationDate", this.getModificationDate());
648
        state.set("name", this.getName());
649
        state.set("owner", this.getOwner());
650
        state.set("selectionColor", this.getSelectionColor());
651

    
652
        state.set("projection", this.getProjection());
653

    
654
        state.set("extents", this.extents);
655
        List<Document> docs = this.getDocuments();
656
        List<Document> noTempDocs = new ArrayList<Document>();
657
        for (Iterator iterator = docs.iterator(); iterator.hasNext();) {
658
            Document document = (Document) iterator.next();
659
            if(!document.isTemporary()){
660
                noTempDocs.add(document);
661
            }
662
        }
663
        state.set("documents", noTempDocs);
664

    
665
        state.set("propertiesHelper",propertiesHelper);
666

    
667
        List<DocumentWindowInfo> persistentWindows = new ArrayList<DocumentWindowInfo>();
668
        MDIManager mdiMan = PluginServices.getMDIManager();
669
        IWindow[] windows = mdiMan.getOrderedWindows();
670
        for (int i = windows.length - 1; i >= 0; i--) {
671
            IWindow window = windows[i];
672
            if (window instanceof IDocumentWindow) {
673
                WindowInfo wi = mdiMan.getWindowInfo(window);
674
                DocumentWindowInfo dwi = new DocumentWindowInfo(
675
                        wi,
676
                        ((IDocumentWindow) window).getDocument().getTypeName(),
677
                        ((IDocumentWindow) window).getDocument().getName());
678
                persistentWindows.add(dwi);
679
            } else if (window instanceof ProjectWindow) {
680
                state.set("projectWindowInfo", mdiMan.getWindowInfo(window));
681
            }
682
        }
683
        state.set("documentWindowsInformation", persistentWindows);
684

    
685
    }
686

    
687
    public Object getProperty(Object key) {
688
        return this.propertiesHelper.getProperty(key);
689
    }
690

    
691
    public void setProperty(Object key, Object obj) {
692
        this.propertiesHelper.setProperty(key, obj);
693
    }
694

    
695
    public Map getExtendedProperties() {
696
        return this.propertiesHelper.getExtendedProperties();
697
    }
698

    
699
    public static class DocumentWindowInfo implements Persistent {
700

    
701
        public static final String PERSISTENCE_DEFINITION_NAME = "DocumentWindowInfo";
702

    
703
        private WindowInfo windowInfo;
704
        private String documentType;
705
        private String documentName;
706

    
707
        public DocumentWindowInfo() {
708
        }
709

    
710
        DocumentWindowInfo(WindowInfo wi, String docType, String docName) {
711
            windowInfo = wi;
712
            documentType = docType;
713
            documentName = docName;
714
        }
715

    
716
        public WindowInfo getWindowInfo() {
717
            return windowInfo;
718
        }
719

    
720
        public String getDocumentType() {
721
            return documentType;
722
        }
723

    
724
        public String getDocumentName() {
725
            return documentName;
726
        }
727

    
728
        public void saveToState(PersistentState state)
729
                throws PersistenceException {
730
            state.set("windowInfo", this.windowInfo);
731
            state.set("documentType", this.documentType);
732
            state.set("documentName", this.documentName);
733
        }
734

    
735
        public void loadFromState(PersistentState state)
736
                throws PersistenceException {
737
            this.windowInfo = (WindowInfo) state.get("windowInfo");
738
            this.documentType = state.getString("documentType");
739
            this.documentName = state.getString("documentName");
740
        }
741

    
742
        public static void registerPersistent() {
743
            PersistenceManager manager = ToolsLocator.getPersistenceManager();
744
            DynStruct definition = manager.getDefinition(PERSISTENCE_DEFINITION_NAME);
745
            if (definition == null) {
746
                definition = manager.addDefinition(
747
                        DocumentWindowInfo.class,
748
                        PERSISTENCE_DEFINITION_NAME,
749
                        "DocumentWindowInfo persistence definition",
750
                        null,
751
                        null
752
                );
753
                definition.addDynFieldObject("windowInfo").setMandatory(true).setClassOfValue(WindowInfo.class);
754
                definition.addDynFieldString("documentType").setMandatory(true);
755
                definition.addDynFieldString("documentName").setMandatory(true);
756
            }
757

    
758
        }
759
    }
760

    
761
    public static void registerPersistent() {
762
        AbstractDocument.registerPersistent();
763
        DocumentWindowInfo.registerPersistent();
764
        ProjectExtent.registerPersistent();
765

    
766
        PersistenceManager manager = ToolsLocator.getPersistenceManager();
767
        DynStruct definition = manager.addDefinition(DefaultProject.class,
768
                "Project", "Project Persistence definition", null, null);
769
        definition.addDynFieldString("version").setMandatory(true);
770
        definition.addDynFieldString("comments").setMandatory(true);
771
        definition.addDynFieldString("creationDate").setMandatory(true);
772
        definition.addDynFieldString("modificationDate").setMandatory(true);
773
        definition.addDynFieldString("name").setMandatory(true);
774
        definition.addDynFieldString("owner").setMandatory(true);
775

    
776
        definition.addDynFieldObject("selectionColor")
777
                .setClassOfValue(Color.class).setMandatory(true);
778
        definition.addDynFieldObject("projection")
779
                .setClassOfValue(IProjection.class).setMandatory(true);
780

    
781
        definition.addDynFieldList("extents")
782
                .setClassOfItems(ProjectExtent.class).setMandatory(true);
783

    
784
        definition.addDynFieldList("documents").setClassOfItems(Document.class)
785
                .setMandatory(true);
786

    
787
        definition.addDynFieldObject("projectWindowInfo").setClassOfValue(WindowInfo.class).setMandatory(false);
788

    
789
        definition.addDynFieldList("documentWindowsInformation").setClassOfItems(WindowInfo.class).setMandatory(false);
790

    
791

    
792
        definition.addDynFieldObject("propertiesHelper").setClassOfValue(ExtendedPropertiesHelper.class)
793
                        .setMandatory(false);
794

    
795
    }
796

    
797
    /**
798
     * @deprecated use getPreferences().setDefaultSelectionColor()
799
     */
800
    public static void setDefaultSelectionColor(Color color) {
801
        getPreferences().setDefaultSelectionColor(color);
802
    }
803

    
804
    /**
805
     * @deprecated use getPreferences().getDefaultSelectionColor()
806
     */
807
    public static Color getDefaultSelectionColor() {
808
        return getPreferences().getDefaultSelectionColor();
809
    }
810

    
811
    /**
812
     * @deprecated use getPreferences().getDefaultMapUnits()
813
     */
814
    public static int getDefaultMapUnits() {
815
        return getPreferences().getDefaultMapUnits();
816
    }
817

    
818
    /**
819
     * @deprecated use getPreferences().getDefaultDistanceUnits()
820
     */
821
    public static int getDefaultDistanceUnits() {
822
        return getPreferences().getDefaultDistanceUnits();
823
    }
824

    
825
    /**
826
     * @deprecated use getPreferences().getDefaultDistanceArea()
827
     */
828
    public static int getDefaultDistanceArea() {
829
        return getPreferences().getDefaultDistanceArea();
830
    }
831

    
832
    /**
833
     * @deprecated use getPreferences().setDefaultMapUnits()
834
     */
835
    public static void setDefaultMapUnits(int mapUnits) {
836
        getPreferences().setDefaultMapUnits(mapUnits);
837
    }
838

    
839
    /**
840
     * @deprecated use getPreferences().setDefaultDistanceUnits()
841
     */
842
    public static void setDefaultDistanceUnits(int distanceUnits) {
843
        getPreferences().setDefaultDistanceUnits(distanceUnits);
844
    }
845

    
846
    /**
847
     * @deprecated use getPreferences().setDefaultDistanceArea()
848
     */
849
    public static void setDefaultDistanceArea(int distanceArea) {
850
        getPreferences().setDefaultDistanceArea(distanceArea);
851
    }
852

    
853
    /**
854
     * @deprecated use getPreferences().setDefaultProjection()
855
     */
856
    public static void setDefaultProjection(IProjection defaultProjection) {
857
        getPreferences().setDefaultProjection(defaultProjection);
858
    }
859

    
860
    /**
861
     * @deprecated use getPreferences().getDefaultProjection()
862
     */
863
    public static IProjection getDefaultProjection() {
864
        return getPreferences().getDefaultProjection();
865
    }
866

    
867
    /**
868
     * @deprecated see {@link #setSelectionColor(String)}, to be remove in gvSIG
869
     * 2.1.0
870
     */
871
    public void setColor(String color) {
872
        this.setSelectionColor(StringUtilities.string2Color(color));
873
    }
874

    
875
    /**
876
     * Return the selection color
877
     *
878
     * @return selection color as string
879
     * @deprecated use {@link #getSelectionColor()}
880
     */
881
    public String getColor() {
882
        return StringUtilities.color2String(selectionColor);
883
    }
884

    
885
    /**
886
     * Return the list of views of the project
887
     *
888
     * @return views as ArrayList of ProjectDocument
889
     *
890
     * @deprecated see {@link #getDocumentsByType(String)}
891
     */
892
    public List<Document> getViews() {
893
        return getDocuments(ViewManager.TYPENAME);
894
    }
895

    
896
    /**
897
     * Add a view to the project
898
     *
899
     * @deprecated see {@link #add(AbstractDocument)}
900
     */
901
    public void addView(DefaultViewDocument v) {
902
        add(v);
903
    }
904

    
905
    /**
906
     * Remove a view of the project
907
     *
908
     * @param index of the view as integer
909
     *
910
     * @deprecated see {@link #remove(AbstractDocument)}
911
     */
912
    public void delView(int i) {
913
        List<Document> list = getDocuments(ViewManager.TYPENAME);
914
        remove(list.get(i));
915
    }
916

    
917
    /**
918
     * @deprecated see {@link #getDocument(String, String)}
919
     */
920
    public Document getProjectDocumentByName(String name, String type) {
921
        return this.getDocument(name, type);
922
    }
923

    
924
    /**
925
     * @deprecated see {@link #getDocuments(String)}
926
     */
927
    public List<Document> getDocumentsByType(String type) {
928
        return this.getDocuments(type);
929
    }
930

    
931
    /**
932
     * @deprecated aun por decidir que API darle al copy/paste
933
     */
934
    public String exportToXML(AbstractDocument[] selectedItems)
935
            throws SaveException {
936
        // FIXME jjdc:hay que decirdir que API darle al copy/paste
937
        throw new UnsupportedOperationException("This method is not supported");
938
    }
939

    
940
    /**
941
     * @deprecated aun por decidir que API darle al copy/paste
942
     */
943
    public void importFromXML(String sourceString, String docType) {
944
        // FIXME jjdc:hay que decirdir que API darle al copy/paste
945
        throw new UnsupportedOperationException("This method is not supported");
946
    }
947

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

    
956
    public boolean canImportDocuments(String data, String doctype) {
957
        // TODO Auto-generated method stub
958
        return false;
959
    }
960

    
961
    public String exportDocumentsAsText(List<Document> documents) {
962
        // TODO Auto-generated method stub
963
        return null;
964
    }
965

    
966
    public void importDocuments(String data, String doctype) {
967
        // TODO Auto-generated method stub
968

    
969
    }
970

    
971
    public Document getActiveDocument() {
972
        return this.getActiveDocument((Class<? extends Document>)null);
973
    }
974

    
975
    public Document getActiveDocument(String documentTypeName) {
976
        ApplicationManager application = ApplicationLocator.getManager();
977

    
978
        Document document = null;
979
        IWindow[] windows = application.getUIManager().getOrderedWindows();
980
        IWindow window = null;
981
        for (int i = 0; i < windows.length; i++) {
982
            window = windows[i];
983
            if (window instanceof SingletonWindow) {
984
                // Cogemos no la primera ventana, si no la primera
985
                // ventana de tipo documento (SingletonWindow).
986
                // Y por si las mosca no es un documento, atrapamos
987
                // los errores y continuamos si no puede hacer un cast
988
                // del Model a Document
989
                try {
990
                    document = (Document) ((SingletonWindow) window).getWindowModel();
991
                    if (documentTypeName == null) {
992
                        return document;
993
                    }
994
                    if( document.getTypeName().equalsIgnoreCase(documentTypeName) ) {
995
                        return document;
996
                    }
997
                    if( document instanceof DocumentsContainer ) {
998
                        Document subdoc = ((DocumentsContainer)document).getActiveDocument(documentTypeName);
999
                        return subdoc;
1000
                    }
1001

    
1002
                } catch (ClassCastException e) {
1003
                    // Do nothing, skip this window
1004
                }
1005
            }
1006
        }
1007
        return null;
1008
    }
1009

    
1010
    public Document getActiveDocument(Class<? extends Document> documentClass) {
1011
        ApplicationManager application = ApplicationLocator.getManager();
1012

    
1013
        Document document = null;
1014
        IWindow[] windows = application.getUIManager().getOrderedWindows();
1015
        IWindow window = null;
1016
        for (int i = 0; i < windows.length; i++) {
1017
            window = windows[i];
1018
            if (window instanceof SingletonWindow && window instanceof IDocumentWindow) {
1019
                // Cogemos no la primera ventana, si no la primera
1020
                // ventana de tipo documento (SingletonWindow).
1021
                // Y por si las mosca no es un documento, atrapamos
1022
                // los errores y continuamos si no puede hacer un cast
1023
                // del Model a Document
1024
                try {
1025
                    document = (Document) ((SingletonWindow) window).getWindowModel();
1026
                    if (documentClass == null) {
1027
                        return document;
1028
                    }
1029
                    if (documentClass.isAssignableFrom(document.getClass())) {
1030
                        return document;
1031
                    }
1032
                    if( document instanceof DocumentsContainer ) {
1033
                        Document subdoc = ((DocumentsContainer)document).getActiveDocument(documentClass);
1034
                        return subdoc;
1035
                    }
1036

    
1037
                } catch (ClassCastException e) {
1038
                    // Do nothing, skip this window
1039
                }
1040
            }
1041
        }
1042
        return null;
1043
    }
1044

    
1045
    public void addObserver(Observer o) {
1046
        observableHelper.addObserver(o);
1047
    }
1048

    
1049
    public void deleteObserver(Observer o) {
1050
        observableHelper.deleteObserver(o);
1051
    }
1052

    
1053
    public void deleteObservers() {
1054
        observableHelper.deleteObservers();
1055
    }
1056

    
1057
//        private void notifyObservers(ProjectNotifycation notifycation) {
1058
//                observableHelper.notifyObservers(this, notifycation);
1059
//        }
1060
    private ProjectNotification notifyObservers(int type) {
1061
        DefaultProjectNotification notifycation
1062
                = new DefaultProjectNotification(type, null, null);
1063
        try {
1064
            observableHelper.notifyObservers(this, notifycation);
1065
        } catch (Exception ex) {
1066
            LOG.info("Can't notify observers", ex);
1067
        }
1068
        return notifycation;
1069
    }
1070

    
1071
    private ProjectNotification notifyObservers(int type, Document document) {
1072
        DefaultProjectNotification notifycation
1073
                = new DefaultProjectNotification(type, document, 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, File file) {
1083
        DefaultProjectNotification notifycation
1084
                = new DefaultProjectNotification(type, null, file);
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
    class DefaultProjectNotification implements ProjectNotification {
1094

    
1095
        private int type;
1096
        private Document document;
1097
        private File file;
1098
        private boolean processCanceled = false;
1099

    
1100
        DefaultProjectNotification(int type, Document document, File file) {
1101
            this.type = type;
1102
            this.document = document;
1103
            this.file = file;
1104
        }
1105

    
1106
        public int getNotificationType() {
1107
            return type;
1108
        }
1109

    
1110
        public Document getDocument() {
1111
            return document;
1112
        }
1113

    
1114
        public void cancelProcess() {
1115
            processCanceled = true;
1116
        }
1117

    
1118
        public boolean isProcessCanceled() {
1119
            return processCanceled;
1120
        }
1121

    
1122
        public File getFile() {
1123
            return file;
1124
        }
1125

    
1126
    }
1127

    
1128
}