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

History | View | Annotate | Download (45.8 KB)

1 40558 jjdelcerro
/**
2
 * gvSIG. Desktop Geographic Information System.
3 40435 jjdelcerro
 *
4 40558 jjdelcerro
 * Copyright (C) 2007-2013 gvSIG Association.
5
 *
6 41148 jjdelcerro
 * 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 40558 jjdelcerro
 *
11 41148 jjdelcerro
 * 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 40558 jjdelcerro
 *
16 41148 jjdelcerro
 * 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 40558 jjdelcerro
 *
20 41148 jjdelcerro
 * For any additional information, do not hesitate to contact us at info AT
21
 * gvsig.com, or visit our website www.gvsig.com.
22 40435 jjdelcerro
 */
23
package org.gvsig.app.project;
24
25
import java.awt.Color;
26 43913 jjdelcerro
import java.awt.image.BufferedImage;
27 40435 jjdelcerro
import java.beans.PropertyChangeEvent;
28
import java.beans.PropertyChangeListener;
29
import java.beans.PropertyChangeSupport;
30
import java.io.File;
31
import java.io.FileInputStream;
32
import java.io.FileNotFoundException;
33
import java.io.FileOutputStream;
34 43820 jjdelcerro
import java.io.IOException;
35 40435 jjdelcerro
import java.io.InputStream;
36
import java.io.OutputStream;
37
import java.io.Serializable;
38
import java.text.DateFormat;
39
import java.text.MessageFormat;
40 44088 omartinez
import java.text.SimpleDateFormat;
41 40435 jjdelcerro
import java.util.ArrayList;
42
import java.util.Collections;
43
import java.util.Date;
44
import java.util.HashMap;
45 42711 fdiaz
import java.util.HashSet;
46 40435 jjdelcerro
import java.util.Iterator;
47
import java.util.List;
48
import java.util.Map;
49 42711 fdiaz
import java.util.Set;
50 43913 jjdelcerro
import java.util.zip.ZipEntry;
51 43820 jjdelcerro
import java.util.zip.ZipException;
52
import java.util.zip.ZipFile;
53 43913 jjdelcerro
import java.util.zip.ZipOutputStream;
54
import javax.imageio.ImageIO;
55 44485 jjdelcerro
import javax.swing.JOptionPane;
56 44088 omartinez
import org.apache.commons.io.FileUtils;
57
import org.apache.commons.io.FilenameUtils;
58 43913 jjdelcerro
import org.apache.commons.io.IOUtils;
59 42711 fdiaz
60 40435 jjdelcerro
import org.cresques.cts.IProjection;
61 42711 fdiaz
62 40435 jjdelcerro
import org.gvsig.andami.PluginServices;
63
import org.gvsig.andami.ui.mdiManager.IWindow;
64
import org.gvsig.andami.ui.mdiManager.MDIManager;
65
import org.gvsig.andami.ui.mdiManager.SingletonWindow;
66
import org.gvsig.andami.ui.mdiManager.WindowInfo;
67
import org.gvsig.app.ApplicationLocator;
68
import org.gvsig.app.ApplicationManager;
69
import org.gvsig.app.extension.ProjectExtension;
70
import org.gvsig.app.extension.Version;
71 43879 jjdelcerro
import org.gvsig.app.project.ProjectManager.NewProjectEvent;
72 40435 jjdelcerro
import org.gvsig.app.project.documents.AbstractDocument;
73
import org.gvsig.app.project.documents.Document;
74
import org.gvsig.app.project.documents.exceptions.SaveException;
75
import org.gvsig.app.project.documents.gui.IDocumentWindow;
76
import org.gvsig.app.project.documents.gui.ProjectWindow;
77
import org.gvsig.app.project.documents.view.DefaultViewDocument;
78
import org.gvsig.app.project.documents.view.ViewManager;
79
import org.gvsig.fmap.mapcontext.MapContext;
80 41350 jjdelcerro
import org.gvsig.fmap.mapcontext.layers.ExtendedPropertiesHelper;
81 40435 jjdelcerro
import org.gvsig.fmap.mapcontext.layers.FLayer;
82
import org.gvsig.fmap.mapcontext.layers.FLayers;
83
import org.gvsig.tools.ToolsLocator;
84
import org.gvsig.tools.dynobject.DynStruct;
85 44485 jjdelcerro
import org.gvsig.tools.i18n.I18nManager;
86 40435 jjdelcerro
import org.gvsig.tools.observer.ObservableHelper;
87
import org.gvsig.tools.observer.Observer;
88
import org.gvsig.tools.persistence.PersistenceManager;
89
import org.gvsig.tools.persistence.Persistent;
90 42711 fdiaz
import org.gvsig.tools.persistence.PersistentContext;
91 40435 jjdelcerro
import org.gvsig.tools.persistence.PersistentState;
92
import org.gvsig.tools.persistence.exception.PersistenceException;
93 44485 jjdelcerro
import org.gvsig.tools.swing.api.ToolsSwingLocator;
94
import org.gvsig.tools.swing.api.threadsafedialogs.ThreadSafeDialogsManager;
95 40435 jjdelcerro
import org.gvsig.utils.StringUtilities;
96 42711 fdiaz
97 40435 jjdelcerro
import org.slf4j.Logger;
98
import org.slf4j.LoggerFactory;
99
100
/**
101
 * Clase que representa un proyecto de gvSIG
102 41148 jjdelcerro
 *
103 40435 jjdelcerro
 */
104
public class DefaultProject implements Serializable, PropertyChangeListener,
105 41148 jjdelcerro
        Project {
106 40435 jjdelcerro
107 41148 jjdelcerro
    private Logger LOG = LoggerFactory.getLogger(DefaultProject.class);
108
    /**
109
     * @deprecated see ApplicationLocator.getManager().getVersion()
110
     */
111
    public static String VERSION = Version.format();
112 40435 jjdelcerro
113 41350 jjdelcerro
    private ExtendedPropertiesHelper propertiesHelper = new ExtendedPropertiesHelper();
114 42088 fdiaz
115 40435 jjdelcerro
    private ObservableHelper observableHelper = new ObservableHelper();
116
117 41148 jjdelcerro
    /**
118
     *
119
     */
120
    private static final long serialVersionUID = -4449622027521773178L;
121 40435 jjdelcerro
122 41148 jjdelcerro
    private static final Logger logger = LoggerFactory.getLogger(Project.class);
123 40435 jjdelcerro
124 41148 jjdelcerro
    private static ProjectPreferences preferences = new ProjectPreferences();
125 40435 jjdelcerro
126 41148 jjdelcerro
    /**
127
     * Index used by the generator of unique names of documents.
128
     */
129
    private Map<String, Integer> nextDocumentIndexByType = new HashMap<String, Integer>();
130 40435 jjdelcerro
131 41148 jjdelcerro
    private PropertyChangeSupport change;
132 40435 jjdelcerro
133 41148 jjdelcerro
    private boolean modified = false;
134 40435 jjdelcerro
135 41148 jjdelcerro
    private String name = null;
136 40435 jjdelcerro
137 41148 jjdelcerro
    private String creationDate = null;
138 40435 jjdelcerro
139 41148 jjdelcerro
    private String modificationDate = null;
140 40435 jjdelcerro
141 41148 jjdelcerro
    private String owner = null;
142 40435 jjdelcerro
143 41148 jjdelcerro
    private String comments = null;
144 40435 jjdelcerro
145 41148 jjdelcerro
    private Color selectionColor = null;
146 40435 jjdelcerro
147 41148 jjdelcerro
    private List<Document> documents = null;
148 40435 jjdelcerro
149 41148 jjdelcerro
    private List<ProjectExtent> extents = null;
150 40435 jjdelcerro
151 41148 jjdelcerro
    private IProjection projection;
152 40435 jjdelcerro
153 42466 jjdelcerro
    private File fname = null;
154 42711 fdiaz
155
    private Set<String> unloadedObjects;
156 43439 jjdelcerro
    private PersistenceException loadErrors = null;
157 42711 fdiaz
158 41148 jjdelcerro
    /**
159
     * Creates a new Project object.
160
     */
161
    DefaultProject() {
162
        this.change = new PropertyChangeSupport(this);
163
        this.clean();
164 43879 jjdelcerro
        ProjectManager.getInstance().notifyProjectEvent(new NewProjectEvent() {
165
            @Override
166
            public Project getProject() {
167
                return DefaultProject.this;
168
            }
169
        });
170 41148 jjdelcerro
    }
171 40435 jjdelcerro
172 41148 jjdelcerro
    protected void clean() {
173
        this.owner = "";
174
        this.comments = "";
175
        this.name = PluginServices.getText(this, "untitled");
176
        this.creationDate = DateFormat.getDateInstance().format(new Date());
177
        this.modificationDate = this.creationDate;
178 40435 jjdelcerro
179 41148 jjdelcerro
        this.documents = new ArrayList<Document>();
180
        this.extents = new ArrayList<ProjectExtent>();
181 40435 jjdelcerro
182 41148 jjdelcerro
        this.setSelectionColor(getPreferences().getDefaultSelectionColor());
183 40435 jjdelcerro
184 41148 jjdelcerro
        this.projection = null; // se inicializa en el getProjection()
185
    }
186 40435 jjdelcerro
187 41148 jjdelcerro
    public static ProjectPreferences getPreferences() {
188
        return preferences;
189
    }
190 40435 jjdelcerro
191 44088 omartinez
    @Override
192 41148 jjdelcerro
    public void propertyChange(PropertyChangeEvent evt) {
193
        change.firePropertyChange(evt);
194
    }
195 40435 jjdelcerro
196 43913 jjdelcerro
    @Override
197 41148 jjdelcerro
    public synchronized void addPropertyChangeListener(
198
            PropertyChangeListener arg0) {
199
        change.addPropertyChangeListener(arg0);
200
    }
201 40435 jjdelcerro
202 43913 jjdelcerro
    @Override
203
    public void removePropertyChangeListener(PropertyChangeListener listener) {
204
        change.removePropertyChangeListener(listener);
205
    }
206
207 41148 jjdelcerro
    /**
208
     * Return the creation date of the project
209
     *
210
     * @return
211
     */
212 44088 omartinez
    @Override
213 41148 jjdelcerro
    public String getCreationDate() {
214
        return creationDate;
215
    }
216 40435 jjdelcerro
217 41148 jjdelcerro
    protected void setCreationDate(String creationDate) {
218
        this.creationDate = creationDate;
219
        change.firePropertyChange("setCreationDate", null, null);
220
    }
221 40435 jjdelcerro
222 44088 omartinez
    @Override
223 40435 jjdelcerro
    public Document createDocument(String type) {
224 41148 jjdelcerro
        logger.info("createDocument('{}')", type);
225 40435 jjdelcerro
        return ProjectManager.getInstance().createDocument(type);
226
    }
227
228
    /**
229
     * Return the name of the project
230 41148 jjdelcerro
     *
231 40435 jjdelcerro
     * @return
232
     */
233 44088 omartinez
    @Override
234 40435 jjdelcerro
    public String getName() {
235
        return name;
236
    }
237
238 41148 jjdelcerro
    /**
239
     * Set the name of he project.
240
     *
241
     * @param string
242
     */
243 44088 omartinez
    @Override
244 41148 jjdelcerro
    public void setName(String name) {
245
        this.name = name;
246
        change.firePropertyChange("setName", null, null);
247
    }
248 40435 jjdelcerro
249 41148 jjdelcerro
    /**
250
     * Return the comments associateds with the project
251
     *
252
     * @return comments
253
     */
254 44088 omartinez
    @Override
255 41148 jjdelcerro
    public String getComments() {
256
        return comments;
257
    }
258 40435 jjdelcerro
259 41148 jjdelcerro
    /**
260
     * Set the comments associateds with the project
261
     *
262
     * @param comments as string
263
     */
264 44088 omartinez
    @Override
265 41148 jjdelcerro
    public void setComments(String string) {
266
        comments = string;
267
        change.firePropertyChange("setComments", null, null);
268
    }
269 40435 jjdelcerro
270 41148 jjdelcerro
    /**
271
     * Retuen the modification date of the project.
272
     *
273
     * @return modification date as string
274
     */
275 44088 omartinez
    @Override
276 41148 jjdelcerro
    public String getModificationDate() {
277
        return modificationDate;
278
    }
279 40435 jjdelcerro
280 41148 jjdelcerro
    protected void setModificationDate(String string) {
281
        modificationDate = string;
282
        change.firePropertyChange("setModificationDate", null, null);
283
    }
284 40435 jjdelcerro
285 41148 jjdelcerro
    /**
286
     * Return the author of the project,
287
     *
288
     * @return author as string
289
     */
290 44088 omartinez
    @Override
291 41148 jjdelcerro
    public String getOwner() {
292
        return owner;
293
    }
294 40435 jjdelcerro
295 41148 jjdelcerro
    /**
296
     * Sets the author of the project
297
     *
298
     * @param author name as string
299
     */
300 44088 omartinez
    @Override
301 41148 jjdelcerro
    public void setOwner(String owner) {
302
        this.owner = owner;
303
        change.firePropertyChange("setOwner", null, null);
304
    }
305 40435 jjdelcerro
306 41148 jjdelcerro
    /**
307
     * Obtiene el color de selecci�n que se usar� en el proyecto
308
     *
309
     * @return
310
     */
311 44088 omartinez
    @Override
312 41148 jjdelcerro
    public Color getSelectionColor() {
313
        if (selectionColor == null) {
314
            selectionColor = getPreferences().getDefaultSelectionColor();
315
        }
316
        return selectionColor;
317
    }
318 40435 jjdelcerro
319 41148 jjdelcerro
    /**
320
     * Sets the selecction color
321
     *
322
     * @param selection color as string
323
     */
324 44088 omartinez
    @Override
325 41148 jjdelcerro
    public void setSelectionColor(String selectionColor) {
326
        this.setSelectionColor(StringUtilities.string2Color(selectionColor));
327
    }
328 40435 jjdelcerro
329 41148 jjdelcerro
    /**
330
     * Sets the selecction color
331
     *
332
     * @param selection color as Color
333
     */
334 44088 omartinez
    @Override
335 41148 jjdelcerro
    public void setSelectionColor(Color selectionColor) {
336
        this.selectionColor = selectionColor;
337
        MapContext.setSelectionColor(selectionColor);
338
        change.firePropertyChange("selectionColor", null, selectionColor);
339
    }
340 40435 jjdelcerro
341 44088 omartinez
    @Override
342 41148 jjdelcerro
    public IProjection getProjection() {
343
        if (projection == null) {
344
            projection = getPreferences().getDefaultProjection();
345
        }
346
        return projection;
347
    }
348 40435 jjdelcerro
349 44088 omartinez
    @Override
350 41148 jjdelcerro
    public void setProjection(IProjection projection) {
351
        this.projection = projection;
352
    }
353 40435 jjdelcerro
354 41148 jjdelcerro
    /**
355
     * Sets the modified state of project.
356
     *
357
     * Can't set to not modified.
358
     *
359
     * @param modified as boolean
360
     */
361 44088 omartinez
    @Override
362 41148 jjdelcerro
    public void setModified(boolean modified) {
363
        this.modified = modified;
364
        if (modified == false) {
365
            List<Document> documents = this.getDocuments();
366
            for (int i = 0; i < documents.size(); i++) {
367
                documents.get(i).setModified(false);
368
            }
369
        }
370
    }
371 40435 jjdelcerro
372 44088 omartinez
    @Override
373 41148 jjdelcerro
    public boolean hasChanged() {
374 40435 jjdelcerro
                // we return true if the project is not empty (until we have a better
375 41148 jjdelcerro
        // method...)
376
        if ((this.getDocuments().size() != 0) || modified) {
377
            return true;
378
        }
379
        return false;
380
    }
381 40435 jjdelcerro
382 41148 jjdelcerro
    /**
383
     * Return a list of documents in the project.
384
     *
385
     * @return documents as List of IProjectDocument
386
     */
387 44088 omartinez
    @Override
388 41148 jjdelcerro
    public List<Document> getDocuments() {
389
        return Collections.unmodifiableList(documents);
390
    }
391 40435 jjdelcerro
392 41148 jjdelcerro
    /**
393
     * Return a list with all documents of especified type.
394
     *
395
     * @param type of document
396
     *
397
     * @return List of IProjectDocument
398
     */
399 44088 omartinez
    @Override
400 41148 jjdelcerro
    public List<Document> getDocuments(String type) {
401
        List<Document> docs = new ArrayList<Document>();
402
        if (type != null) {
403
            for (Document document : this.documents) {
404
                if (type.equalsIgnoreCase(document.getTypeName())) {
405
                    docs.add(document);
406
                }
407
            }
408
        }
409
        return Collections.unmodifiableList(docs);
410
    }
411 40435 jjdelcerro
412 41148 jjdelcerro
    /**
413
     * Adds a document to the project
414
     *
415 41248 jjdelcerro
     * @param document as Document
416 41148 jjdelcerro
     */
417 44088 omartinez
    @Override
418 41148 jjdelcerro
    public void add(Document document) {
419 41248 jjdelcerro
        this.addDocument(document);
420
    }
421 42088 fdiaz
422 44088 omartinez
    @Override
423 41248 jjdelcerro
    public void addDocument(Document document) {
424 40435 jjdelcerro
        logger.info("add('{}')", document.toString());
425
426 41148 jjdelcerro
        if (notifyObservers(ProjectNotification.BEFORE_ADD_DOCUMENT, document).isProcessCanceled()) {
427
            return;
428 40435 jjdelcerro
        }
429 41148 jjdelcerro
        document.addPropertyChangeListener(this);
430
        document.setProject(this);
431
        document.setName(this.getUniqueNameForDocument(document.getTypeName(),
432
                document.getName()));
433
        documents.add(document);
434
        document.afterAdd();
435
        this.setModified(true);
436
        notifyObservers(ProjectNotification.AFTER_ADD_DOCUMENT, document);
437 40435 jjdelcerro
        change.firePropertyChange("addDocument", null, document);
438 41148 jjdelcerro
    }
439 40435 jjdelcerro
440 44088 omartinez
    @Override
441 41148 jjdelcerro
    public void remove(Document doc) {
442 41248 jjdelcerro
        this.removeDocument(doc);
443
    }
444 42088 fdiaz
445 44088 omartinez
    @Override
446 41248 jjdelcerro
    public void removeDocument(Document doc) {
447 40435 jjdelcerro
        logger.info("remove('{}')", doc.toString());
448 41148 jjdelcerro
        if (notifyObservers(ProjectNotification.BEFORE_REMOVE_DOCUMENT, doc).isProcessCanceled()) {
449
            return;
450 40435 jjdelcerro
        }
451 41148 jjdelcerro
        documents.remove(doc);
452
        this.setModified(true);
453 40435 jjdelcerro
        change.firePropertyChange("delDocument", doc, null);
454 41148 jjdelcerro
        doc.afterRemove();
455
        notifyObservers(ProjectNotification.AFTER_REMOVE_DOCUMENT, doc);
456
    }
457 40435 jjdelcerro
458 44088 omartinez
    @Override
459 41148 jjdelcerro
    public Iterator<Document> iterator() {
460
        return documents.iterator();
461
    }
462 40435 jjdelcerro
463 44088 omartinez
    @Override
464 41148 jjdelcerro
    public boolean isEmpty() {
465
        return documents.isEmpty();
466
    }
467 40435 jjdelcerro
468 41148 jjdelcerro
    /**
469
     * Return the view that contains the especified layer.
470
     *
471
     * @param layer
472
     *
473
     * @return name of the view that contains the layer
474
     *
475
     * @throws RuntimeException Si la capa que se pasa como par�metro no se
476
     * encuentra en ninguna vista
477
     */
478 44088 omartinez
    @Override
479 41148 jjdelcerro
    public String getViewName(FLayer layer) {
480
        List<Document> views = getDocuments(ViewManager.TYPENAME);
481
        for (int v = 0; v < views.size(); v++) {
482
            DefaultViewDocument pView = (DefaultViewDocument) views.get(v);
483
            FLayers layers = pView.getMapContext().getLayers();
484
            if (isView(layers, layer)) {
485
                return pView.getName();
486
            }
487
        }
488 40435 jjdelcerro
489 41148 jjdelcerro
        throw new RuntimeException(MessageFormat.format(
490
                "The layer '{1}' is not in a view", layer.getName()));
491
    }
492 40435 jjdelcerro
493 41148 jjdelcerro
    private boolean isView(FLayers layers, FLayer layer) {
494
        for (int i = 0; i < layers.getLayersCount(); i++) {
495
            if (layers.getLayer(i) instanceof FLayers) {
496
                if (isView((FLayers) layers.getLayer(i), layer)) {
497
                    return true;
498
                }
499
            }
500
            if (layers.getLayer(i) == layer) {
501
                return true;
502
            }
503
        }
504
        return false;
505
    }
506 40435 jjdelcerro
507 44088 omartinez
    @Override
508 41148 jjdelcerro
    public void addExtent(ProjectExtent arg1) {
509
        extents.add(arg1);
510
        change.firePropertyChange("addExtent", null, null);
511
    }
512 40435 jjdelcerro
513 44088 omartinez
    @Override
514 41148 jjdelcerro
    public ProjectExtent removeExtent(int arg0) {
515
        change.firePropertyChange("delExtent", null, null);
516
        return extents.remove(arg0);
517
    }
518 40435 jjdelcerro
519 44088 omartinez
    @Override
520 41148 jjdelcerro
    public ProjectExtent[] getExtents() {
521
        return (ProjectExtent[]) extents.toArray(new ProjectExtent[0]);
522
    }
523 40435 jjdelcerro
524 41148 jjdelcerro
    /**
525
     * Obtiene un documento a partir de su nombre y el nombre de registro en el
526
     * pointExtension, este �ltimo se puede obtener del
527
     * Project****Factory.registerName.
528
     *
529
     * @param name Nombre del documento
530
     * @param type nombre de registro en el extensionPoint
531
     *
532
     * @return Documento
533
     */
534 44088 omartinez
    @Override
535 41148 jjdelcerro
    public Document getDocument(String name, String type) {
536 42293 jjdelcerro
        if (type == null) {
537 41148 jjdelcerro
            for (int i = 0; i < documents.size(); i++) {
538
                Document document = documents.get(i);
539 42293 jjdelcerro
                if ( name.equalsIgnoreCase(document.getName())) {
540
                    return document;
541
                }
542
            }
543
        } else {
544
            for (int i = 0; i < documents.size(); i++) {
545
                Document document = documents.get(i);
546 41148 jjdelcerro
                if (type.equalsIgnoreCase(document.getTypeName())
547
                        && name.equalsIgnoreCase(document.getName())) {
548
                    return document;
549
                }
550
            }
551
        }
552
        return null;
553
    }
554 42711 fdiaz
555 44088 omartinez
    @Override
556 42293 jjdelcerro
    public Document getDocument(String name) {
557
        return this.getDocument(name, null);
558 42711 fdiaz
    }
559 40435 jjdelcerro
560 41148 jjdelcerro
    public String getUniqueNameForDocument(String type, String name) {
561
        Document document = getDocument(name, type);
562
        if (document == null) {
563
            return name;
564
        }
565 40435 jjdelcerro
566 41148 jjdelcerro
        String newName = null;
567
        int num = this.getNextDocumentIndex(type);
568
        while (document != null) {
569
            newName = name + " - " + num++;
570
            document = getDocument(newName, type);
571
        }
572
        this.setNextDocumentIndex(type, num);
573
        return newName;
574
    }
575 40435 jjdelcerro
576 41148 jjdelcerro
    private int getNextDocumentIndex(String type) {
577
        if (nextDocumentIndexByType.get(type) == null) {
578
            nextDocumentIndexByType.put(type, new Integer(1));
579
            return 1;
580
        }
581
        return nextDocumentIndexByType.get(type).intValue();
582
    }
583 40435 jjdelcerro
584 41148 jjdelcerro
    private void setNextDocumentIndex(String type, int newIndex) {
585
        if (nextDocumentIndexByType.get(type) == null) {
586
            nextDocumentIndexByType.put(type, new Integer(newIndex));
587
        } else {
588
            nextDocumentIndexByType.put(type, new Integer(newIndex));
589
        }
590
    }
591 40435 jjdelcerro
592 44088 omartinez
    @Override
593 41148 jjdelcerro
    public void saveState(File out) throws PersistenceException {
594
        FileOutputStream fout;
595
        if (notifyObservers(ProjectNotification.BEFORE_SAVE_TO_FILE, out).isProcessCanceled()) {
596
            return;
597 40435 jjdelcerro
        }
598 41148 jjdelcerro
        try {
599
            fout = new FileOutputStream(out);
600
            saveState(fout, new File(out.getParent()));
601
        } catch (FileNotFoundException e) {
602 44088 omartinez
            createProjectCopy(true);
603 41148 jjdelcerro
            throw new PersistenceException(e);
604
        }
605 43820 jjdelcerro
        if( !isValidZIP(out) ) {
606
            throw new PersistenceException(new ZipException());
607
        }
608 42466 jjdelcerro
        this.fname = out;
609 44088 omartinez
        //sacar copia al bak
610
        createProjectCopy(false);
611 41148 jjdelcerro
        notifyObservers(ProjectNotification.AFTER_SAVE_TO_FILE, out);
612
    }
613 40435 jjdelcerro
614 43820 jjdelcerro
    boolean isValidZIP(final File file) {
615
        ZipFile zipfile = null;
616
        try {
617
            zipfile = new ZipFile(file);
618
            return true;
619
        } catch (IOException e) {
620 44088 omartinez
            //sacar copia.
621 43820 jjdelcerro
            return false;
622
        } finally {
623
            try {
624
                if (zipfile != null) {
625
                    zipfile.close();
626
                    zipfile = null;
627
                }
628
            } catch (IOException e) {
629
            }
630
        }
631
    }
632
633 43913 jjdelcerro
    @Override
634 42466 jjdelcerro
    public File getFile() {
635
        return this.fname;
636
    }
637 42711 fdiaz
638 43913 jjdelcerro
    @Deprecated
639
    @Override
640 41148 jjdelcerro
    public void saveState(OutputStream out) throws PersistenceException {
641
        saveState(out, null);
642
    }
643 43913 jjdelcerro
644
    @Override
645
    public void saveState(File file, BufferedImage preview) {
646
        FileOutputStream fout=null;
647
        ZipOutputStream zout=null;
648
        try {
649
            fout = new FileOutputStream(file);
650
            zout = new ZipOutputStream(fout);
651
            this.saveState(zout, file.getParentFile());
652 40435 jjdelcerro
653 43913 jjdelcerro
            zout.putNextEntry(new ZipEntry("preview.jpg"));
654
            try {
655
                ImageIO.write(preview, "jpg", zout);
656
            } catch (IOException ex) {
657
                LOG.warn("Can't save preview image'.", ex);
658
            }
659
            IOUtils.closeQuietly(zout);
660
            IOUtils.closeQuietly(fout);
661
662
            if( !isValidZIP(file) ) {
663
                throw new ZipException("Invalid project file '"+file.getAbsolutePath()+"'");
664
            }
665
            this.fname = file;
666 44088 omartinez
            if (file.exists()) {
667
                createProjectCopy(false);
668
            }
669 44485 jjdelcerro
            I18nManager i18n = ToolsLocator.getI18nManager();
670
            ThreadSafeDialogsManager dialog = ToolsSwingLocator.getThreadSafeDialogsManager();
671
            dialog.message(
672
                    i18n.getTranslation("wrote_project"),
673
                    JOptionPane.INFORMATION_MESSAGE
674
            );
675 43913 jjdelcerro
        } catch (Exception ex) {
676 44088 omartinez
            createProjectCopy(true);
677
            throw new RuntimeException("Can't write project in '" + file.getAbsolutePath() + ".", ex);
678 43913 jjdelcerro
        } finally {
679
            IOUtils.closeQuietly(zout);
680 44088 omartinez
            IOUtils.closeQuietly(fout);
681
682 43913 jjdelcerro
        }
683
    }
684
685
    @Override
686 41148 jjdelcerro
    public void saveState(OutputStream out, File rootFolder)
687
            throws PersistenceException {
688 43913 jjdelcerro
        if (notifyObservers(ProjectNotification.BEFORE_SAVE_TO_STREAM, rootFolder).isProcessCanceled()) {
689 41148 jjdelcerro
            return;
690 40435 jjdelcerro
        }
691 41148 jjdelcerro
        PersistenceManager manager = ToolsLocator.getPersistenceManager();
692
        PersistentState state = null;
693
        state = manager.getState(this, true);
694
        try {
695
            if (rootFolder != null) {
696
                state.relativizeFiles(rootFolder);
697
            }
698
        } catch (Exception ex) {
699
            state.getContext().addError(ex);
700
        }
701 43077 jjdelcerro
        manager.saveState(state, out, true);
702 41148 jjdelcerro
        if (state.getContext().getErrors() != null) {
703 44088 omartinez
            createProjectCopy(true);
704 41148 jjdelcerro
            throw state.getContext().getErrors();
705
        }
706 42466 jjdelcerro
        this.fname = null;
707 43913 jjdelcerro
        notifyObservers(ProjectNotification.AFTER_SAVE_TO_STREAM, rootFolder);
708 41148 jjdelcerro
    }
709 44088 omartinez
710
    private File getNameFileForProject(File actualProjectFile, boolean error) {
711
        // if there is a error, creates a file with a unique timecode
712
        // not error: return path with .gvsproj.bak extension that could exists
713
714
        if (actualProjectFile==null) {
715
            LOG.info("Doesn't have previous project to create a bak");
716
            return null;
717
        }
718
        String noExt = FilenameUtils.removeExtension(actualProjectFile.getAbsolutePath());
719
        String timeCode = new SimpleDateFormat("_MMddHHmmss").format(new Date());
720
        String ext = ".gvsproj.bak";
721 40435 jjdelcerro
722 44088 omartinez
        int code = 0;
723
        if (noExt.length() > 230) {
724
            noExt = noExt.substring(0, 229);
725
        }
726
727
        File bakProjectFile;
728
        if (error) {
729
            bakProjectFile = new File(noExt + timeCode + ext);
730
            while (bakProjectFile.exists()) {
731
                code = code + 1;
732
                bakProjectFile = new File(noExt + timeCode + "_" + code + ext);
733
            }
734
        } else {
735
            bakProjectFile = new File(noExt + ext);
736
        }
737
        return bakProjectFile;
738
    }
739
    public File createProjectCopy(boolean error) {
740
        File actualProjectFile = ApplicationLocator.getProjectManager().getCurrentProject().getFile();
741
        File bakProjectFile = getNameFileForProject(actualProjectFile, error);
742
        if (bakProjectFile==null){
743
            return null;
744
        }
745
        if (!error){
746
            try {
747
                if (bakProjectFile.exists()){
748
                    FileUtils.deleteQuietly(bakProjectFile);
749
                }
750
            } catch (Exception ex) {
751
                LOG.error("Not possible to delete file", ex);
752
            }
753
            try {
754
                FileUtils.copyFile(actualProjectFile, bakProjectFile);
755
            } catch (IOException ex) {
756
                LOG.error("Can't create bak copy from project", ex);
757
            }
758
        } else {
759 44204 omartinez
            File bakProjectFileOld = getNameFileForProject(actualProjectFile, false);
760
            if (bakProjectFileOld.exists()) {
761
                try {
762
                    FileUtils.moveFile(bakProjectFileOld, bakProjectFile);
763
                } catch (IOException ex) {
764
                    LOG.error("Can't rename file", ex);
765
                }
766
            } else {
767
                LOG.warn("Can't find bak project. Probably doesn't exist or already has been renamed");
768 44088 omartinez
            }
769
        }
770
771
        return bakProjectFile;
772
    }
773
774 43913 jjdelcerro
    @Deprecated
775 44088 omartinez
    @Override
776 41148 jjdelcerro
    public void loadState(InputStream in) {
777
        loadState(in, null);
778
    }
779 40435 jjdelcerro
780 41148 jjdelcerro
    public void loadState(InputStream in, File rootFolder) {
781 43913 jjdelcerro
        if (notifyObservers(ProjectNotification.BEFORE_LOAD_FROM_STREAM, rootFolder).isProcessCanceled()) {
782 41148 jjdelcerro
            return;
783
        }
784
        PersistenceManager manager = ToolsLocator.getPersistenceManager();
785
        try {
786 43439 jjdelcerro
            PersistentContext context = manager.getNewContext();
787
            context.setCollectErrors(true);
788
            PersistentState state = manager.loadState(in, context);
789 41148 jjdelcerro
            try {
790
                if (rootFolder != null) {
791
                    state.derelativizeFiles(rootFolder);
792
                }
793
            } catch (Exception ex) {
794
                state.getContext().addError(ex);
795
            }
796
            this.loadFromState(state);
797 42711 fdiaz
            this.unloadedObjects = getUnloadedObjects(state.getContext());
798 43439 jjdelcerro
            this.loadErrors = state.getContext().getErrors();
799 43879 jjdelcerro
800 41148 jjdelcerro
        } catch (PersistenceException e) {
801
            LOG.info("Can't load project to stream", e);
802
        }
803 42466 jjdelcerro
        this.fname = null;
804 43913 jjdelcerro
        notifyObservers(ProjectNotification.AFTER_LOAD_FROM_STREAM, rootFolder);
805 40435 jjdelcerro
806 41148 jjdelcerro
    }
807 40435 jjdelcerro
808 42711 fdiaz
809
810
    /**
811
     * @param context
812
     * @return
813
     */
814
    private Set<String> getUnloadedObjects(PersistentContext context) {
815
        Set unloadedObjects = new HashSet();
816
817
        Iterator statesIterator = context.iterator();
818
        String className = null;
819
820
        while (statesIterator.hasNext()) {
821
            PersistentState aState = (PersistentState) statesIterator.next();
822
            try {
823
                className = aState.getTheClassName();
824
                DynStruct definition = aState.getDefinition();
825
                if (definition == null) {
826
                    unloadedObjects.add(className);
827
                }
828
            } catch (Throwable e) {
829
                // do nothing
830
            }
831
        }
832
833
        if(unloadedObjects.isEmpty()){
834
            return null;
835
        }
836
837
        return unloadedObjects;
838
    }
839
840 43439 jjdelcerro
    @Override
841 42711 fdiaz
    public Set<String> getUnloadedObjects() {
842
        return this.unloadedObjects;
843
    }
844
845 43439 jjdelcerro
    @Override
846
    public List<Exception> getLoadErrors() {
847
        return this.loadErrors;
848
    }
849
850
    @Override
851 41148 jjdelcerro
    public void loadState(File in) {
852
        if (notifyObservers(ProjectNotification.BEFORE_LOAD_FROM_FILE, in).isProcessCanceled()) {
853
            return;
854
        }
855
        FileInputStream fin;
856
        try {
857
            fin = new FileInputStream(in);
858
            loadState(fin, new File(in.getParent()));
859
        } catch (FileNotFoundException e) {
860 42466 jjdelcerro
            LOG.info("Can't load project to stream", e);
861 41148 jjdelcerro
        }
862 44088 omartinez
        if ("bak".equals(FilenameUtils.getExtension(in.getAbsolutePath()))) {
863
            this.fname =  null;
864
        } else {
865
            this.fname = in;
866
        }
867 41148 jjdelcerro
        notifyObservers(ProjectNotification.AFTER_LOAD_FROM_FILE, in);
868
    }
869 40435 jjdelcerro
870 43913 jjdelcerro
    //@SuppressWarnings("unchecked")
871
    @Override
872 41148 jjdelcerro
    public void loadFromState(PersistentState state)
873
            throws PersistenceException {
874
        this.clean();
875 43976 jjdelcerro
        PersistentContext context = state.getContext();
876
877 43913 jjdelcerro
        notifyObservers(ProjectNotification.BEFORE_LOAD_FROM_STATE, state);
878 40435 jjdelcerro
879 41148 jjdelcerro
        this.setComments(state.getString("comments"));
880
        this.setCreationDate(state.getString("creationDate"));
881
        this.setModificationDate(state.getString("modificationDate"));
882
        this.setName(state.getString("name"));
883
        this.setOwner(state.getString("owner"));
884
        this.setSelectionColor((Color) state.get("selectionColor"));
885
        this.setProjection((IProjection) state.get("projection"));
886 40435 jjdelcerro
887 41350 jjdelcerro
        this.propertiesHelper = (ExtendedPropertiesHelper) state.get("propertiesHelper");
888 42088 fdiaz
889 41148 jjdelcerro
        List<ProjectExtent> extents = (List<ProjectExtent>) state
890
                .get("extents");
891
        for (int i = 0; i < extents.size(); i++) {
892
            this.addExtent(extents.get(i));
893
        }
894 40435 jjdelcerro
895 41148 jjdelcerro
        List<AbstractDocument> documents = (List<AbstractDocument>) state
896
                .get("documents");
897
        for (int i = 0; i < documents.size(); i++) {
898 43913 jjdelcerro
            AbstractDocument doc = documents.get(i);
899
            if( doc != null ) {
900
                this.add(doc);
901
            }
902 41148 jjdelcerro
        }
903 40435 jjdelcerro
904 43976 jjdelcerro
        try {
905
            List<DocumentWindowInfo> persistentWindows = (List<DocumentWindowInfo>) state.get("documentWindowsInformation");
906 40435 jjdelcerro
907 43976 jjdelcerro
            for (int i = 0; i < persistentWindows.size(); i++) {
908
                try {
909
                    DocumentWindowInfo persistentWindow = persistentWindows.get(i);
910
                    String docName = persistentWindow.getDocumentName();
911
                    String docType = persistentWindow.getDocumentType();
912
                    Document doc = this.getDocument(docName, docType);
913
                    IWindow win = doc.getFactory().getMainWindow(doc);
914
                    if(win!=null){
915
                        win.getWindowInfo().setWindowInfo(persistentWindow.getWindowInfo());
916
                        PluginServices.getMDIManager().addWindow(win);
917
                    }
918
                } catch(Exception ex) {
919
                    if( !context.getCollectErrors() ) {
920
                        throw ex;
921
                    }
922
                    context.addError(ex);
923
                }
924 42088 fdiaz
            }
925 40435 jjdelcerro
926 43976 jjdelcerro
            if (state.hasValue("projectWindowInfo")) {
927
                WindowInfo projectWindowInfo = (WindowInfo) state.get("projectWindowInfo");
928
                ProjectExtension pe = (ProjectExtension) PluginServices.getExtension(org.gvsig.app.extension.ProjectExtension.class);
929
                pe.setProject(this);
930
                pe.showProjectWindow(projectWindowInfo);
931
            }
932
        } catch(Exception ex) {
933
            if( !context.getCollectErrors() ) {
934
                throw ex;
935
            }
936
            context.addError(ex);
937 41148 jjdelcerro
        }
938 43913 jjdelcerro
        notifyObservers(ProjectNotification.AFTER_LOAD_FROM_STATE, state);
939 41148 jjdelcerro
    }
940 40435 jjdelcerro
941 44088 omartinez
    @Override
942 41148 jjdelcerro
    public void saveToState(PersistentState state) throws PersistenceException {
943
        state.set("version", VERSION);
944
        state.set("comments", getComments());
945
        state.set("creationDate", this.getCreationDate());
946 40435 jjdelcerro
947 41148 jjdelcerro
        state.set("modificationDate", this.getModificationDate());
948
        state.set("name", this.getName());
949
        state.set("owner", this.getOwner());
950
        state.set("selectionColor", this.getSelectionColor());
951 40435 jjdelcerro
952 41148 jjdelcerro
        state.set("projection", this.getProjection());
953 40435 jjdelcerro
954 41148 jjdelcerro
        state.set("extents", this.extents);
955 42088 fdiaz
        List<Document> docs = this.getDocuments();
956 44443 jjdelcerro
        List<Document> noTempDocs = new ArrayList<>();
957
        for (Document document : docs) {
958 42088 fdiaz
            if(!document.isTemporary()){
959
                noTempDocs.add(document);
960
            }
961
        }
962
        state.set("documents", noTempDocs);
963 40435 jjdelcerro
964 41350 jjdelcerro
        state.set("propertiesHelper",propertiesHelper);
965 42088 fdiaz
966 44443 jjdelcerro
        List<DocumentWindowInfo> persistentWindows = new ArrayList<>();
967 41148 jjdelcerro
        MDIManager mdiMan = PluginServices.getMDIManager();
968
        IWindow[] windows = mdiMan.getOrderedWindows();
969
        for (int i = windows.length - 1; i >= 0; i--) {
970
            IWindow window = windows[i];
971
            if (window instanceof IDocumentWindow) {
972
                WindowInfo wi = mdiMan.getWindowInfo(window);
973
                DocumentWindowInfo dwi = new DocumentWindowInfo(
974
                        wi,
975
                        ((IDocumentWindow) window).getDocument().getTypeName(),
976
                        ((IDocumentWindow) window).getDocument().getName());
977
                persistentWindows.add(dwi);
978
            } else if (window instanceof ProjectWindow) {
979
                state.set("projectWindowInfo", mdiMan.getWindowInfo(window));
980
            }
981
        }
982
        state.set("documentWindowsInformation", persistentWindows);
983 40435 jjdelcerro
984 41148 jjdelcerro
    }
985 40435 jjdelcerro
986 44088 omartinez
    @Override
987 41350 jjdelcerro
    public Object getProperty(Object key) {
988
        return this.propertiesHelper.getProperty(key);
989
    }
990
991 44088 omartinez
    @Override
992 41350 jjdelcerro
    public void setProperty(Object key, Object obj) {
993
        this.propertiesHelper.setProperty(key, obj);
994
    }
995
996 44088 omartinez
    @Override
997 41350 jjdelcerro
    public Map getExtendedProperties() {
998
        return this.propertiesHelper.getExtendedProperties();
999
    }
1000
1001 41148 jjdelcerro
    public static class DocumentWindowInfo implements Persistent {
1002 40435 jjdelcerro
1003 41148 jjdelcerro
        public static final String PERSISTENCE_DEFINITION_NAME = "DocumentWindowInfo";
1004 40435 jjdelcerro
1005 41148 jjdelcerro
        private WindowInfo windowInfo;
1006
        private String documentType;
1007
        private String documentName;
1008 40435 jjdelcerro
1009 41148 jjdelcerro
        public DocumentWindowInfo() {
1010
        }
1011 40435 jjdelcerro
1012 41148 jjdelcerro
        DocumentWindowInfo(WindowInfo wi, String docType, String docName) {
1013
            windowInfo = wi;
1014
            documentType = docType;
1015
            documentName = docName;
1016
        }
1017 40435 jjdelcerro
1018 41148 jjdelcerro
        public WindowInfo getWindowInfo() {
1019
            return windowInfo;
1020
        }
1021 40435 jjdelcerro
1022 41148 jjdelcerro
        public String getDocumentType() {
1023
            return documentType;
1024
        }
1025 40435 jjdelcerro
1026 41148 jjdelcerro
        public String getDocumentName() {
1027
            return documentName;
1028
        }
1029 40435 jjdelcerro
1030 41148 jjdelcerro
        public void saveToState(PersistentState state)
1031
                throws PersistenceException {
1032
            state.set("windowInfo", this.windowInfo);
1033
            state.set("documentType", this.documentType);
1034
            state.set("documentName", this.documentName);
1035
        }
1036 40435 jjdelcerro
1037 41148 jjdelcerro
        public void loadFromState(PersistentState state)
1038
                throws PersistenceException {
1039
            this.windowInfo = (WindowInfo) state.get("windowInfo");
1040
            this.documentType = state.getString("documentType");
1041
            this.documentName = state.getString("documentName");
1042
        }
1043 40435 jjdelcerro
1044 41148 jjdelcerro
        public static void registerPersistent() {
1045
            PersistenceManager manager = ToolsLocator.getPersistenceManager();
1046
            DynStruct definition = manager.getDefinition(PERSISTENCE_DEFINITION_NAME);
1047
            if (definition == null) {
1048
                definition = manager.addDefinition(
1049
                        DocumentWindowInfo.class,
1050
                        PERSISTENCE_DEFINITION_NAME,
1051
                        "DocumentWindowInfo persistence definition",
1052
                        null,
1053
                        null
1054
                );
1055
                definition.addDynFieldObject("windowInfo").setMandatory(true).setClassOfValue(WindowInfo.class);
1056
                definition.addDynFieldString("documentType").setMandatory(true);
1057
                definition.addDynFieldString("documentName").setMandatory(true);
1058
            }
1059 40435 jjdelcerro
1060 41148 jjdelcerro
        }
1061
    }
1062 40435 jjdelcerro
1063 41148 jjdelcerro
    public static void registerPersistent() {
1064
        AbstractDocument.registerPersistent();
1065
        DocumentWindowInfo.registerPersistent();
1066
        ProjectExtent.registerPersistent();
1067 40435 jjdelcerro
1068 41148 jjdelcerro
        PersistenceManager manager = ToolsLocator.getPersistenceManager();
1069
        DynStruct definition = manager.addDefinition(DefaultProject.class,
1070
                "Project", "Project Persistence definition", null, null);
1071
        definition.addDynFieldString("version").setMandatory(true);
1072
        definition.addDynFieldString("comments").setMandatory(true);
1073
        definition.addDynFieldString("creationDate").setMandatory(true);
1074
        definition.addDynFieldString("modificationDate").setMandatory(true);
1075
        definition.addDynFieldString("name").setMandatory(true);
1076
        definition.addDynFieldString("owner").setMandatory(true);
1077 40435 jjdelcerro
1078 41148 jjdelcerro
        definition.addDynFieldObject("selectionColor")
1079
                .setClassOfValue(Color.class).setMandatory(true);
1080
        definition.addDynFieldObject("projection")
1081
                .setClassOfValue(IProjection.class).setMandatory(true);
1082 40435 jjdelcerro
1083 41148 jjdelcerro
        definition.addDynFieldList("extents")
1084
                .setClassOfItems(ProjectExtent.class).setMandatory(true);
1085 40435 jjdelcerro
1086 41148 jjdelcerro
        definition.addDynFieldList("documents").setClassOfItems(Document.class)
1087
                .setMandatory(true);
1088 40435 jjdelcerro
1089 41148 jjdelcerro
        definition.addDynFieldObject("projectWindowInfo").setClassOfValue(WindowInfo.class).setMandatory(false);
1090 40435 jjdelcerro
1091 41148 jjdelcerro
        definition.addDynFieldList("documentWindowsInformation").setClassOfItems(WindowInfo.class).setMandatory(false);
1092 40435 jjdelcerro
1093 42088 fdiaz
1094 41350 jjdelcerro
        definition.addDynFieldObject("propertiesHelper").setClassOfValue(ExtendedPropertiesHelper.class)
1095
                        .setMandatory(false);
1096
1097 41148 jjdelcerro
    }
1098 40435 jjdelcerro
1099 41148 jjdelcerro
    /**
1100
     * @deprecated use getPreferences().setDefaultSelectionColor()
1101
     */
1102
    public static void setDefaultSelectionColor(Color color) {
1103
        getPreferences().setDefaultSelectionColor(color);
1104
    }
1105 40435 jjdelcerro
1106 41148 jjdelcerro
    /**
1107
     * @deprecated use getPreferences().getDefaultSelectionColor()
1108
     */
1109
    public static Color getDefaultSelectionColor() {
1110
        return getPreferences().getDefaultSelectionColor();
1111
    }
1112 40435 jjdelcerro
1113 41148 jjdelcerro
    /**
1114
     * @deprecated use getPreferences().getDefaultMapUnits()
1115
     */
1116
    public static int getDefaultMapUnits() {
1117
        return getPreferences().getDefaultMapUnits();
1118
    }
1119 40435 jjdelcerro
1120 41148 jjdelcerro
    /**
1121
     * @deprecated use getPreferences().getDefaultDistanceUnits()
1122
     */
1123
    public static int getDefaultDistanceUnits() {
1124
        return getPreferences().getDefaultDistanceUnits();
1125
    }
1126 40435 jjdelcerro
1127 41148 jjdelcerro
    /**
1128
     * @deprecated use getPreferences().getDefaultDistanceArea()
1129
     */
1130
    public static int getDefaultDistanceArea() {
1131
        return getPreferences().getDefaultDistanceArea();
1132
    }
1133 40435 jjdelcerro
1134 41148 jjdelcerro
    /**
1135
     * @deprecated use getPreferences().setDefaultMapUnits()
1136
     */
1137
    public static void setDefaultMapUnits(int mapUnits) {
1138
        getPreferences().setDefaultMapUnits(mapUnits);
1139
    }
1140 40435 jjdelcerro
1141 41148 jjdelcerro
    /**
1142
     * @deprecated use getPreferences().setDefaultDistanceUnits()
1143
     */
1144
    public static void setDefaultDistanceUnits(int distanceUnits) {
1145
        getPreferences().setDefaultDistanceUnits(distanceUnits);
1146
    }
1147 40435 jjdelcerro
1148 41148 jjdelcerro
    /**
1149
     * @deprecated use getPreferences().setDefaultDistanceArea()
1150
     */
1151
    public static void setDefaultDistanceArea(int distanceArea) {
1152
        getPreferences().setDefaultDistanceArea(distanceArea);
1153
    }
1154 40435 jjdelcerro
1155 41148 jjdelcerro
    /**
1156
     * @deprecated use getPreferences().setDefaultProjection()
1157
     */
1158
    public static void setDefaultProjection(IProjection defaultProjection) {
1159
        getPreferences().setDefaultProjection(defaultProjection);
1160
    }
1161 40435 jjdelcerro
1162 41148 jjdelcerro
    /**
1163
     * @deprecated use getPreferences().getDefaultProjection()
1164
     */
1165
    public static IProjection getDefaultProjection() {
1166
        return getPreferences().getDefaultProjection();
1167
    }
1168 40435 jjdelcerro
1169 41148 jjdelcerro
    /**
1170
     * @deprecated see {@link #setSelectionColor(String)}, to be remove in gvSIG
1171
     * 2.1.0
1172
     */
1173
    public void setColor(String color) {
1174
        this.setSelectionColor(StringUtilities.string2Color(color));
1175
    }
1176 40435 jjdelcerro
1177 41148 jjdelcerro
    /**
1178
     * Return the selection color
1179
     *
1180
     * @return selection color as string
1181
     * @deprecated use {@link #getSelectionColor()}
1182
     */
1183
    public String getColor() {
1184
        return StringUtilities.color2String(selectionColor);
1185
    }
1186 40435 jjdelcerro
1187 41148 jjdelcerro
    /**
1188
     * Return the list of views of the project
1189
     *
1190
     * @return views as ArrayList of ProjectDocument
1191
     *
1192
     * @deprecated see {@link #getDocumentsByType(String)}
1193
     */
1194
    public List<Document> getViews() {
1195
        return getDocuments(ViewManager.TYPENAME);
1196
    }
1197 40435 jjdelcerro
1198 41148 jjdelcerro
    /**
1199
     * Add a view to the project
1200
     *
1201
     * @deprecated see {@link #add(AbstractDocument)}
1202
     */
1203
    public void addView(DefaultViewDocument v) {
1204
        add(v);
1205
    }
1206 40435 jjdelcerro
1207 41148 jjdelcerro
    /**
1208
     * Remove a view of the project
1209
     *
1210
     * @param index of the view as integer
1211
     *
1212
     * @deprecated see {@link #remove(AbstractDocument)}
1213
     */
1214
    public void delView(int i) {
1215
        List<Document> list = getDocuments(ViewManager.TYPENAME);
1216
        remove(list.get(i));
1217
    }
1218 40435 jjdelcerro
1219 41148 jjdelcerro
    /**
1220
     * @deprecated see {@link #getDocument(String, String)}
1221
     */
1222
    public Document getProjectDocumentByName(String name, String type) {
1223
        return this.getDocument(name, type);
1224
    }
1225 40435 jjdelcerro
1226 41148 jjdelcerro
    /**
1227
     * @deprecated see {@link #getDocuments(String)}
1228
     */
1229
    public List<Document> getDocumentsByType(String type) {
1230
        return this.getDocuments(type);
1231
    }
1232 40435 jjdelcerro
1233 41148 jjdelcerro
    /**
1234
     * @deprecated aun por decidir que API darle al copy/paste
1235
     */
1236
    public String exportToXML(AbstractDocument[] selectedItems)
1237
            throws SaveException {
1238
        // FIXME jjdc:hay que decirdir que API darle al copy/paste
1239
        throw new UnsupportedOperationException("This method is not supported");
1240
    }
1241 40435 jjdelcerro
1242 41148 jjdelcerro
    /**
1243
     * @deprecated aun por decidir que API darle al copy/paste
1244
     */
1245
    public void importFromXML(String sourceString, String docType) {
1246
        // FIXME jjdc:hay que decirdir que API darle al copy/paste
1247
        throw new UnsupportedOperationException("This method is not supported");
1248
    }
1249 40435 jjdelcerro
1250 41148 jjdelcerro
    /**
1251
     * @deprecated aun por decidir que API darle al copy/paste
1252
     */
1253
    public boolean isValidXMLForImport(String sourceString, String docType) {
1254
        // FIXME jjdc:hay que decirdir que API darle al copy/paste
1255
        throw new UnsupportedOperationException("This method is not supported");
1256
    }
1257
1258 44088 omartinez
    @Override
1259 41148 jjdelcerro
    public boolean canImportDocuments(String data, String doctype) {
1260
        // TODO Auto-generated method stub
1261
        return false;
1262
    }
1263
1264 44088 omartinez
    @Override
1265 41148 jjdelcerro
    public String exportDocumentsAsText(List<Document> documents) {
1266
        // TODO Auto-generated method stub
1267
        return null;
1268
    }
1269
1270 44088 omartinez
    @Override
1271 41148 jjdelcerro
    public void importDocuments(String data, String doctype) {
1272
        // TODO Auto-generated method stub
1273
1274
    }
1275
1276 44088 omartinez
    @Override
1277 41148 jjdelcerro
    public Document getActiveDocument() {
1278 41248 jjdelcerro
        return this.getActiveDocument((Class<? extends Document>)null);
1279 41148 jjdelcerro
    }
1280
1281 44088 omartinez
    @Override
1282 41248 jjdelcerro
    public Document getActiveDocument(String documentTypeName) {
1283
        ApplicationManager application = ApplicationLocator.getManager();
1284
1285
        Document document = null;
1286
        IWindow[] windows = application.getUIManager().getOrderedWindows();
1287
        IWindow window = null;
1288
        for (int i = 0; i < windows.length; i++) {
1289
            window = windows[i];
1290
            if (window instanceof SingletonWindow) {
1291
                // Cogemos no la primera ventana, si no la primera
1292
                // ventana de tipo documento (SingletonWindow).
1293
                // Y por si las mosca no es un documento, atrapamos
1294
                // los errores y continuamos si no puede hacer un cast
1295
                // del Model a Document
1296
                try {
1297
                    document = (Document) ((SingletonWindow) window).getWindowModel();
1298
                    if (documentTypeName == null) {
1299
                        return document;
1300
                    }
1301
                    if( document.getTypeName().equalsIgnoreCase(documentTypeName) ) {
1302
                        return document;
1303
                    }
1304
                    if( document instanceof DocumentsContainer ) {
1305
                        Document subdoc = ((DocumentsContainer)document).getActiveDocument(documentTypeName);
1306
                        return subdoc;
1307
                    }
1308 42088 fdiaz
1309 41248 jjdelcerro
                } catch (ClassCastException e) {
1310
                    // Do nothing, skip this window
1311
                }
1312
            }
1313
        }
1314
        return null;
1315
    }
1316 42088 fdiaz
1317 44088 omartinez
    @Override
1318 41148 jjdelcerro
    public Document getActiveDocument(Class<? extends Document> documentClass) {
1319
        ApplicationManager application = ApplicationLocator.getManager();
1320
1321
        Document document = null;
1322
        IWindow[] windows = application.getUIManager().getOrderedWindows();
1323
        IWindow window = null;
1324
        for (int i = 0; i < windows.length; i++) {
1325
            window = windows[i];
1326 42165 fdiaz
            if (window instanceof SingletonWindow && window instanceof IDocumentWindow) {
1327 41248 jjdelcerro
                // Cogemos no la primera ventana, si no la primera
1328 41148 jjdelcerro
                // ventana de tipo documento (SingletonWindow).
1329
                // Y por si las mosca no es un documento, atrapamos
1330
                // los errores y continuamos si no puede hacer un cast
1331
                // del Model a Document
1332
                try {
1333
                    document = (Document) ((SingletonWindow) window).getWindowModel();
1334
                    if (documentClass == null) {
1335
                        return document;
1336
                    }
1337
                    if (documentClass.isAssignableFrom(document.getClass())) {
1338
                        return document;
1339
                    }
1340 41248 jjdelcerro
                    if( document instanceof DocumentsContainer ) {
1341
                        Document subdoc = ((DocumentsContainer)document).getActiveDocument(documentClass);
1342
                        return subdoc;
1343
                    }
1344 42088 fdiaz
1345 41148 jjdelcerro
                } catch (ClassCastException e) {
1346
                    // Do nothing, skip this window
1347
                }
1348
            }
1349
        }
1350
        return null;
1351
    }
1352 40435 jjdelcerro
1353 44088 omartinez
    @Override
1354 41148 jjdelcerro
    public void addObserver(Observer o) {
1355
        observableHelper.addObserver(o);
1356
    }
1357 40435 jjdelcerro
1358 44088 omartinez
    @Override
1359 41148 jjdelcerro
    public void deleteObserver(Observer o) {
1360
        observableHelper.deleteObserver(o);
1361
    }
1362
1363 44088 omartinez
    @Override
1364 41148 jjdelcerro
    public void deleteObservers() {
1365
        observableHelper.deleteObservers();
1366
    }
1367
1368
    private ProjectNotification notifyObservers(int type) {
1369 43913 jjdelcerro
        return notifyObservers(new DefaultProjectNotification(type));
1370 41148 jjdelcerro
    }
1371 40435 jjdelcerro
1372 41148 jjdelcerro
    private ProjectNotification notifyObservers(int type, Document document) {
1373 43913 jjdelcerro
        return notifyObservers(new DefaultProjectNotification(type, document));
1374 41148 jjdelcerro
    }
1375 43913 jjdelcerro
1376
    private ProjectNotification notifyObservers(int type, PersistentState state) {
1377
        return notifyObservers(new DefaultProjectNotification(type, state));
1378
    }
1379 40435 jjdelcerro
1380 41148 jjdelcerro
    private ProjectNotification notifyObservers(int type, File file) {
1381 43913 jjdelcerro
        return notifyObservers(new DefaultProjectNotification(type, file));
1382
    }
1383
1384
    private ProjectNotification notifyObservers(ProjectNotification notifycation) {
1385 41148 jjdelcerro
        try {
1386
            observableHelper.notifyObservers(this, notifycation);
1387
        } catch (Exception ex) {
1388
            LOG.info("Can't notify observers", ex);
1389
        }
1390
        return notifycation;
1391
    }
1392 43913 jjdelcerro
1393 41148 jjdelcerro
    class DefaultProjectNotification implements ProjectNotification {
1394 40435 jjdelcerro
1395 41148 jjdelcerro
        private int type;
1396
        private Document document;
1397
        private File file;
1398
        private boolean processCanceled = false;
1399 43913 jjdelcerro
        private PersistentState state = null;
1400 40435 jjdelcerro
1401 43913 jjdelcerro
        DefaultProjectNotification(int type) {
1402 41148 jjdelcerro
            this.type = type;
1403 43913 jjdelcerro
        }
1404
1405
        DefaultProjectNotification(int type, Document document) {
1406
            this(type);
1407 41148 jjdelcerro
            this.document = document;
1408 43913 jjdelcerro
        }
1409
1410
        DefaultProjectNotification(int type, File file) {
1411
            this(type);
1412 41148 jjdelcerro
            this.file = file;
1413
        }
1414 40435 jjdelcerro
1415 43913 jjdelcerro
        DefaultProjectNotification(int type, PersistentState state) {
1416
            this(type);
1417
            this.state = state;
1418
        }
1419
1420
        @Override
1421 41148 jjdelcerro
        public int getNotificationType() {
1422
            return type;
1423
        }
1424 40435 jjdelcerro
1425 43913 jjdelcerro
        @Override
1426 41148 jjdelcerro
        public Document getDocument() {
1427
            return document;
1428
        }
1429
1430 43913 jjdelcerro
        @Override
1431 41148 jjdelcerro
        public void cancelProcess() {
1432
            processCanceled = true;
1433
        }
1434
1435 43913 jjdelcerro
        @Override
1436 41148 jjdelcerro
        public boolean isProcessCanceled() {
1437
            return processCanceled;
1438
        }
1439
1440 43913 jjdelcerro
        @Override
1441 41148 jjdelcerro
        public File getFile() {
1442
            return file;
1443
        }
1444
1445 43913 jjdelcerro
        @Override
1446
        public PersistentState getState() {
1447
            return this.state;
1448
        }
1449
1450
        @Override
1451
        public Project getProject() {
1452
            return DefaultProject.this;
1453
        }
1454 41148 jjdelcerro
    }
1455
1456 40435 jjdelcerro
}