Statistics
| Revision:

root / trunk / applications / appgvSIG / src / com / iver / cit / gvsig / ProjectExtension.java @ 14821

History | View | Annotate | Download (25.3 KB)

1
/* gvSIG. Sistema de Informaci?n Geogr?fica de la Generalitat Valenciana
2
 *
3
 * Copyright (C) 2004-2007 IVER T.I. and Generalitat Valenciana.
4
 *
5
 * This program is free software; you can redistribute it and/or
6
 * modify it under the terms of the GNU General Public License
7
 * as published by the Free Software Foundation; either version 2
8
 * of the License, or (at your option) any later version.
9
 *
10
 * This program is distributed in the hope that it will be useful,
11
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13
 * GNU General Public License for more details.
14
 *
15
 * You should have received a copy of the GNU General Public License
16
 * along with this program; if not, write to the Free Software
17
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307,USA.
18
 *
19
 * For more information, contact:
20
 *
21
 *  Generalitat Valenciana
22
 *   Conselleria d'Infraestructures i Transport
23
 *   Av. Blasco Ib??ez, 50
24
 *   46010 VALENCIA
25
 *   SPAIN
26
 *
27
 *      +34 963862235
28
 *   gvsig@gva.es
29
 *      www.gvsig.gva.es
30
 *
31
 *    or
32
 *
33
 *   IVER T.I. S.A
34
 *   Salamanca 50
35
 *   46005 Valencia
36
 *   Spain
37
 *
38
 *   +34 963163400
39
 *   dac@iver.es
40
 */
41
package com.iver.cit.gvsig;
42

    
43
import java.awt.Component;
44
import java.io.BufferedReader;
45
import java.io.File;
46
import java.io.FileInputStream;
47
import java.io.FileNotFoundException;
48
import java.io.FileOutputStream;
49
import java.io.FileReader;
50
import java.io.IOException;
51
import java.io.InputStream;
52
import java.io.InputStreamReader;
53
import java.io.OutputStreamWriter;
54
import java.io.Reader;
55
import java.io.UnsupportedEncodingException;
56
import java.net.MalformedURLException;
57
import java.net.URL;
58
import java.text.DateFormat;
59
import java.util.Date;
60
import java.util.prefs.Preferences;
61

    
62
import javax.swing.ImageIcon;
63
import javax.swing.JFileChooser;
64
import javax.swing.JOptionPane;
65

    
66
import org.exolab.castor.xml.MarshalException;
67
import org.exolab.castor.xml.Marshaller;
68
import org.exolab.castor.xml.ValidationException;
69

    
70
import com.iver.andami.Launcher;
71
import com.iver.andami.PluginServices;
72
import com.iver.andami.Launcher.TerminationProcess;
73
import com.iver.andami.messages.NotificationManager;
74
import com.iver.andami.plugins.Extension;
75
import com.iver.andami.plugins.IExtension;
76
import com.iver.andami.plugins.status.IExtensionStatus;
77
import com.iver.andami.plugins.status.IUnsavedData;
78
import com.iver.andami.plugins.status.UnsavedData;
79
import com.iver.andami.ui.mdiManager.IWindow;
80
import com.iver.andami.ui.mdiManager.WindowInfo;
81
import com.iver.andami.ui.wizard.UnsavedDataPanel;
82
import com.iver.cit.gvsig.fmap.layers.LayerFactory;
83
import com.iver.cit.gvsig.project.Project;
84
import com.iver.cit.gvsig.project.ProjectFactory;
85
import com.iver.cit.gvsig.project.documents.ProjectDocument;
86
import com.iver.cit.gvsig.project.documents.exceptions.OpenException;
87
import com.iver.cit.gvsig.project.documents.gui.ProjectWindow;
88
import com.iver.cit.gvsig.project.documents.layout.ProjectMap;
89
import com.iver.cit.gvsig.project.documents.layout.ProjectMapFactory;
90
import com.iver.cit.gvsig.project.documents.layout.gui.Layout;
91
import com.iver.cit.gvsig.project.documents.table.ProjectTableFactory;
92
import com.iver.cit.gvsig.project.documents.view.ProjectViewFactory;
93
import com.iver.utiles.GenericFileFilter;
94
import com.iver.utiles.XMLEntity;
95
import com.iver.utiles.extensionPoints.ExtensionPoint;
96
import com.iver.utiles.extensionPoints.ExtensionPoints;
97
import com.iver.utiles.extensionPoints.ExtensionPointsSingleton;
98
import com.iver.utiles.swing.threads.IMonitorableTask;
99
import com.iver.utiles.xml.XMLEncodingUtils;
100
import com.iver.utiles.xmlEntity.generate.XmlTag;
101

    
102

    
103
/**
104
 * Extension que proporciona controles para crear proyectos nuevos, abrirlos y
105
 * guardarlos. Adem?s los tipos de tabla que soporta el proyecto son a?adidos
106
 * en esta clase.
107
 *
108
 * @author Fernando Gonz?lez Cort?s
109
 */
110
public class ProjectExtension extends Extension implements IExtensionStatus {
111
        private static String projectPath = null;
112
        //private ProjectWindow projectFrame;
113
        private ProjectWindow projectFrame;
114
        private Project p;
115
        private String lastPath;
116
        private String lastSavePath;
117
        private String templatesPath;
118
        private WindowInfo seedProjectWindow;
119
        /**
120
         * Use UTF-8 for encoding, as it can represent characters from
121
         * any language.
122
         *
123
         * Another sensible option would be
124
         * encoding = System.getProperty("file.encoding");
125
         * but this would need some extra testing.
126
         */
127
        public static String PROJECTENCODING = "UTF-8";
128

    
129
        /**
130
         * @see com.iver.mdiApp.plugins.IExtension#initialize()
131
         */
132
        public void initialize() {
133
            try {
134
            Class.forName("javax.media.jai.EnumeratedParameter");
135
        } catch (ClassNotFoundException e) {
136
            NotificationManager.addError("La m?quina virtual con la que se ejecuta gvSIG no tiene JAI instalado", e);
137
        }
138

    
139
                LayerFactory.setWritersPath(PluginServices.getPluginServices(this)
140
                                  .getPluginDirectory()
141
                                  .getAbsolutePath() +
142
                                  File.separator + "drivers");
143

    
144
        LayerFactory.setDriversPath(PluginServices.getPluginServices(this)
145
                                  .getPluginDirectory()
146
                                  .getAbsolutePath() +
147
                                  File.separator + "drivers");
148

    
149
        initializeDocumentActionsExtensionPoint();
150
        registerDocuments();
151

    
152
        // Recuperamos el ?ltimo argumento, que se supone
153
        // que ser? el fichero .gvp que queremos abrir.
154
        // (por enmedio pueden venir o no otros argumentos,
155
        // por ejemplo el idioma)
156
        // TODO: Aqu? Jaume podr?a meter lo del backup del proyecto
157
        // que ha hecho para ValenciaUrban?stica
158

    
159
                /*
160
                pe = (ProjectExtension) PluginServices.getExtension(com.iver.cit.gvsig.ProjectExtension.class);
161
                if (projectFile.length()!=0){
162
                        p=pe.readProject(projectFile);
163
                }
164
                else
165
                        p = restorePreviousProject();
166
                pe.setProject(p); */
167

    
168
        registerIcons();
169

    
170
        }
171

    
172
        private void registerIcons(){
173
                PluginServices.getIconTheme().register(
174
                                "project-new",
175
                                this.getClass().getClassLoader().getResource("images/new.png")
176
                        );
177

    
178
                PluginServices.getIconTheme().register(
179
                                "project-open",
180
                                this.getClass().getClassLoader().getResource("images/open.png")
181
                        );
182

    
183
                PluginServices.getIconTheme().register(
184
                                "project-save",
185
                                this.getClass().getClassLoader().getResource("images/save.png")
186
                        );
187

    
188
                PluginServices.getIconTheme().register(
189
                                "project-save-as",
190
                                this.getClass().getClassLoader().getResource("images/save.png")
191
                        );
192

    
193
                PluginServices.getIconTheme().register(
194
                                "layout-template-open",
195
                                this.getClass().getClassLoader().getResource("images/opentemplate.png")
196
                        );
197

    
198
                PluginServices.getIconTheme().register(
199
                                "application-exit",
200
                                this.getClass().getClassLoader().getResource("images/salir.png")
201
                        );
202
        }
203

    
204
        /**
205
         * @see com.iver.mdiApp.plugins.IExtension#postInitialize()
206
         */
207
        public void postInitialize() {
208
                String[] theArgs = PluginServices.getArguments();
209
        String lastArg = theArgs[theArgs.length-1];
210
        if ((lastArg.endsWith(".gvp")) ||
211
                        (lastArg.endsWith(".GVP")))
212
        {
213
                PluginServices.getLogger().debug("Intentando cargar el proyecto " + lastArg);
214
                //File projectFile = new File(lastArg);
215
                setProject(readProject(lastArg));
216
                PluginServices.getMainFrame().setTitle(p.getName());
217
                projectPath = lastArg;
218
        }
219
        else
220
        {
221
                        setProject(ProjectFactory.createProject());
222
                        p.setName(PluginServices.getText(this, "untitled"));
223
                        p.setModified(false);
224
                        PluginServices.getMainFrame().setTitle(PluginServices.getText(this, "sin_titulo"));
225
        }
226
                getProjectFrame().setProject(p);
227
                p.restoreWindowProperties();
228
        }
229

    
230
        public ProjectWindow getProjectFrame() {
231
                if (projectFrame==null)
232
                                projectFrame = new ProjectWindow();
233
                return projectFrame;
234
        }
235
        /**
236
         * Muestra la ventana con el gestor de proyectos.
237
         */
238
        public void showProjectWindow() {
239
                if (seedProjectWindow!=null) {
240
                        if (seedProjectWindow.isClosed()) {
241
                                // if it was closed, we just don't open the window now
242
                                seedProjectWindow.setClosed(false);
243
                                return;
244
                        }
245
                        WindowInfo winProps = seedProjectWindow;
246
                        seedProjectWindow = null;
247
                        PluginServices.getMDIManager().addWindow(getProjectFrame());
248
                        PluginServices.getMDIManager().changeWindowInfo(getProjectFrame(), winProps);
249
                }
250
                else
251
                        PluginServices.getMDIManager().addWindow(getProjectFrame());
252
        }
253

    
254
        /**
255
         * Muestra la ventana con el gestor de proyectos, con las propiedades
256
         * de ventana especificadas.
257
         */
258
        public void showProjectWindow(WindowInfo wi) {
259
                seedProjectWindow = wi;
260
                showProjectWindow();
261
        }
262

    
263
        /**
264
         * Guarda el proyecto actual en disco.
265
         */
266
        private boolean guardar() {
267
                boolean saved=false;
268
//                if (p.getPath() == null) {
269
                if (projectPath == null) {
270
                        saved=guardarDialogo();
271
                } else {
272
                        long t1,t2;
273
                        t1 = System.currentTimeMillis();
274
                        saved=writeProject(new File(projectPath), p, false);
275
                        t2 = System.currentTimeMillis();
276
                        PluginServices.getLogger().info("Project saved. " +  (t2-t1) + " miliseconds");
277
                        getProjectFrame().refreshControls();
278
                }
279
                return saved;
280
        }
281

    
282
        private boolean guardarDialogo(){
283
                boolean saved=false;
284

    
285
                if (lastSavePath == null)
286
                        lastSavePath = projectPath;
287

    
288
                if (lastSavePath == null) {
289
                        Preferences prefs = Preferences.userRoot().node( "gvsig.foldering" );
290
                        lastSavePath = prefs.get("ProjectsFolder", null);
291
                }
292

    
293
                JFileChooser jfc = new JFileChooser(lastSavePath);
294
                jfc.setDialogTitle(PluginServices.getText(this, "guardar_proyecto"));
295
                jfc.addChoosableFileFilter(new GenericFileFilter("gvp",
296
                                PluginServices.getText(this, "tipo_fichero_proyecto")));
297

    
298
                if (jfc.showSaveDialog((Component) PluginServices.getMainFrame()) == JFileChooser.APPROVE_OPTION) {
299
                        File file=jfc.getSelectedFile();
300
                        if (!(file.getPath().toLowerCase().endsWith(".gvp"))){
301
                                file=new File(file.getPath()+".gvp");
302
                        }
303
                        saved=writeProject(file, p);
304
                        String filePath = file.getAbsolutePath();
305
                        lastSavePath = filePath.substring(0, filePath.lastIndexOf(File.separatorChar));
306

    
307
                        getProjectFrame().refreshControls();
308
                }
309
                return saved;
310
        }
311

    
312
        /**
313
         * Checks whether the project and related unsaved data is modified,
314
         *  and allows the user to save it.
315
         *
316
         * @return true if the data has been correctly saved, false otherwise
317
         */
318
        private boolean askSave() {
319
                if (p != null && p.hasChanged()) {
320
                        TerminationProcess process = Launcher.getTerminationProcess();
321
                        UnsavedDataPanel panel = process.getUnsavedDataPanel();
322
                        panel.setHeaderText(PluginServices.getText(this, "Select_resources_to_save_before_closing_current_project"));
323
                        panel.setAcceptText(
324
                                        PluginServices.getText(this, "save_resources"),
325
                                        PluginServices.getText(this, "Save_the_selected_resources_and_close_current_project"));
326
                        panel.setCancelText(
327
                                        PluginServices.getText(this, "Dont_close"),
328
                                        PluginServices.getText(this, "Return_to_current_project"));
329
                        int closeCurrProj = process.manageUnsavedData();
330
                        if (closeCurrProj==JOptionPane.NO_OPTION) {
331
                                // the user chose to return to current project
332
                                return false;
333
                        }
334
                }
335
                return true;
336
        }
337

    
338
        /**
339
         * @see com.iver.mdiApp.plugins.IExtension#updateUI(java.lang.String)
340
         */
341
        public void execute(String actionCommand) {
342
                if (actionCommand.equals("NUEVO")) {
343
                        if (!askSave()) {
344
                                return;
345
                        }
346

    
347
                        projectPath=null;
348
                        ProjectDocument.initializeNUMS();
349
                        PluginServices.getMDIManager().closeAllWindows();
350
                        setProject(ProjectFactory.createProject());
351
                        getProjectFrame().setProject(p);
352
                        showProjectWindow();
353
                        PluginServices.getMainFrame().setTitle(PluginServices.getText(this, "sin_titulo"));
354
                } else if (actionCommand.equals("ABRIR")) {
355
                        if (!askSave()) {
356
                                return;
357
                        }
358

    
359
                        if (lastPath == null) {
360
                                Preferences prefs = Preferences.userRoot().node( "gvsig.foldering" );
361
                                lastPath = prefs.get("ProjectsFolder", null);
362
                        }
363

    
364
                        JFileChooser jfc = new JFileChooser(lastPath);
365
                        jfc.addChoosableFileFilter(new GenericFileFilter("gvp",
366
                                        PluginServices.getText(this, "tipo_fichero_proyecto")));
367

    
368
                        if (jfc.showOpenDialog((Component) PluginServices.getMainFrame()) == JFileChooser.APPROVE_OPTION) {
369
                                ProjectDocument.initializeNUMS();
370
                                PluginServices.getMDIManager().closeAllWindows();
371

    
372
                                File projectFile = jfc.getSelectedFile();
373
                                Project o = readProject(projectFile);
374
                                setPath(projectFile.getAbsolutePath());
375
                                lastPath = getPath();
376
                                if (o != null) {
377
                                        setProject(o);
378
                                }
379

    
380
                                getProjectFrame().setProject(p);
381
                                PluginServices.getMainFrame().setTitle(p.getName());
382
                                getProjectFrame().refreshControls();
383

    
384
//jaume                                p.setModified(true);
385
                                p.restoreWindowProperties();
386
                        }
387
                } else if (actionCommand.equals("GUARDAR")) {
388
                        guardar();
389
//jaume                        p.setModified(false);
390
                } else if (actionCommand.equals("GUARDAR_COMO")) {
391
                        guardarDialogo();
392
//jaume                        p.setModified(false);
393
                } else if (actionCommand.equals("SALIR")){
394
                        Launcher.closeApplication();
395
                } else if (actionCommand.compareTo("OPENTEMPLATE")==0){
396
                        openLayout();
397
//jaume                        p.setModified(true);
398
                }
399
        }
400
        public void openLayout() {
401
                //Project project = ((ProjectExtension) PluginServices.getExtension(ProjectExtension.class)).getProject();
402
                Layout layout=null;
403

    
404
                if (templatesPath == null) {
405
                        Preferences prefs = Preferences.userRoot().node( "gvsig.foldering" );
406
                        templatesPath = prefs.get("TemplatesFolder", null);
407
                }
408

    
409
                JFileChooser jfc = new JFileChooser(templatesPath);
410
                jfc.addChoosableFileFilter(new GenericFileFilter("gvt",
411
                                PluginServices.getText(this, "plantilla")));
412

    
413
                if (jfc.showOpenDialog((Component) PluginServices.getMainFrame()) == JFileChooser.APPROVE_OPTION) {
414
                        File file=jfc.getSelectedFile();
415
                        if (!(file.getPath().endsWith(".gvt") || file.getPath().endsWith(".GVT"))){
416
                                file=new File(file.getPath()+".gvt");
417
                        }
418
                        try {
419
                                File xmlFile = new File(file.getAbsolutePath());
420
                                FileReader reader;
421
                                reader = new FileReader(xmlFile);
422

    
423
                                XmlTag tag = (XmlTag) XmlTag.unmarshal(reader);
424
                                try {
425
                                        layout = Layout.createLayout(new XMLEntity(tag),p);
426
                                } catch (OpenException e) {
427
                                        e.showError();
428
                                }
429
                                //fPanelLegendManager.setRenderer(LegendFactory.createFromXML(new XMLEntity(tag)));
430
                        } catch (FileNotFoundException e) {
431
                                NotificationManager.addError(PluginServices.getText(this, "Al_leer_la_leyenda"), e);
432
                        } catch (MarshalException e) {
433
                                NotificationManager.addError(PluginServices.getText(this, "Al_leer_la_leyenda"), e);
434
                        } catch (ValidationException e) {
435
                                NotificationManager.addError(PluginServices.getText(this, "Al_leer_la_leyenda"), e);
436
                        }
437
                        ProjectMap pmap = ProjectFactory.createMap(file.getName());
438
                        pmap.setModel(layout);
439
                        pmap.getModel().setProjectMap(pmap);
440
                        p.addDocument(pmap);
441
                        PluginServices.getMDIManager().addWindow(layout);
442

    
443

    
444
                }
445
        }
446
        /**
447
         * Escribe el proyecto en XML.
448
         *
449
         * @param file Fichero.
450
         * @param p Proyecto.
451
         */
452
        public boolean writeProject(File file, Project p) {
453
                return writeProject(file, p, true);
454
        }
455

    
456
        /**
457
         * Escribe el proyecto en XML. Pero permite decidir si se
458
         * pide confirmaci?n para sobreescribir
459
         *
460
         * @param file Fichero.
461
         * @param p Proyecto.
462
         * @param askConfirmation boolean
463
         */
464
        public boolean writeProject(File file, Project p, boolean askConfirmation) {
465
                if( askConfirmation && file.exists()){
466
                        int resp = JOptionPane.showConfirmDialog(
467
                                        (Component) PluginServices.getMainFrame(),PluginServices.getText(this,"fichero_ya_existe_seguro_desea_guardarlo"),
468
                                        PluginServices.getText(this,"guardar"), JOptionPane.YES_NO_OPTION);
469
                        if (resp != JOptionPane.YES_OPTION) {
470
                                return false;
471
                        }
472
                }
473
                // write it out as XML
474
                try {
475
            FileOutputStream fos = new FileOutputStream(file.getAbsolutePath());
476
            OutputStreamWriter writer = new OutputStreamWriter(fos, PROJECTENCODING);
477
                        Marshaller m = new Marshaller(writer);
478
                        m.setEncoding(PROJECTENCODING);
479
                        p.setName(file.getName());
480
                        // p.setPath(file.toString());
481
                        p.setModificationDate(DateFormat.getDateInstance().format(new Date()));
482
                        p.setModified(false);
483
                        XMLEntity xml = p.getXMLEntity();
484
                        xml.putProperty("followHeaderEncoding", true, false);
485
                        m.marshal(xml.getXmlTag());
486
                        PluginServices.getMainFrame().setTitle(file.getName());
487
                        setPath(file.toString());
488

    
489
                } catch (Exception e) {
490
                        NotificationManager.addError("Error guardando el proyecto", e);
491
                        return false;
492
                }
493
                return true;
494
        }
495

    
496
        public Project readProject(String path) {
497
                BufferedReader reader =null;
498
                try {
499
                URL url=null;
500
                        url = new URL(path);
501
                        String encoding = XMLEncodingUtils.getEncoding(url.openStream());
502
                        InputStream is = url.openStream();
503
                        if (encoding!=null) {
504
                                Project proj=null;
505
                                try {
506
                                        reader = new BufferedReader(new InputStreamReader(is, encoding));
507
                                        proj=readProject(reader, true);
508
                                } catch (UnsupportedEncodingException e) {
509
                                        reader = new BufferedReader(new InputStreamReader(is));
510
                                        try {
511
                                                Project p=readProject(reader, false);
512
                                        } catch (UnsupportedEncodingException e1) {
513
                                                JOptionPane.showMessageDialog((Component)PluginServices.getMainFrame(),PluginServices.getText(this, e1.getLocalizedMessage()));
514
                                                return null;
515
                                        }
516
                                }
517
                                ProjectExtension.setPath(path);
518
                                return proj;
519
                        }
520
                        else {
521
                                reader = new BufferedReader(new InputStreamReader(is));
522
                                Project p;
523
                                try {
524
                                        p = readProject(reader, false);
525
                                } catch (UnsupportedEncodingException e) {
526
                                        JOptionPane.showMessageDialog((Component)PluginServices.getMainFrame(),PluginServices.getText(this, e.getLocalizedMessage()));
527
                                        return null;
528
                                }
529
                                ProjectExtension.setPath(path); //p.setPath(null);
530
                                return p;
531
                        }
532
                } catch (MalformedURLException e) {
533
                        File file=new File(path);
534
                        return readProject(file);
535
                } catch (IOException e) {
536
                        e.printStackTrace();
537
                        return null;
538
                }
539
        }
540

    
541
        /**
542
         * Lee del XML el proyecto.<br><br>
543
         *
544
         * Reads the XML of the project.<br>
545
         * It returns a project object holding all needed info that is not linked to the Project Dialog. <br>In case you want the project to be
546
         * linked to the window you must set this object to the extension:<br>
547
         *
548
         * <b>Example:</b><br>
549
         *
550
         * ...<br>
551
         * ...<br>
552
         * Project p = ProjectExtension.readProject(projectFile);<br>
553
         * ProjectExtension.setProject(p);
554
         * ...<br>
555
         * ...<br>
556
         * @param file Fichero.
557
         *
558
         * @return Project
559
         *
560
         */
561
        public Project readProject(File file) {
562
                File xmlFile = new File(file.getAbsolutePath());
563
                try {
564
                        String encoding = XMLEncodingUtils.getEncoding(new FileInputStream(xmlFile));
565
                        InputStreamReader reader=null;
566
                        if (encoding!=null) {
567
                                try {
568
                                        reader = new InputStreamReader(new FileInputStream(xmlFile), encoding);
569
                                        return readProject(reader, true);
570
                                } catch (UnsupportedEncodingException e) {
571
                                        reader = new InputStreamReader(new FileInputStream(xmlFile));
572
                                        try {
573
                                                return readProject(reader, false);
574
                                        } catch (UnsupportedEncodingException e1) {
575
                                                JOptionPane.showMessageDialog((Component)PluginServices.getMainFrame(),PluginServices.getText(this, e1.getLocalizedMessage()));
576
                                                return null;
577
                                        }
578
                                }
579
                        }
580
                        else {
581
                                reader = new InputStreamReader(new FileInputStream(xmlFile));
582
                                try {
583
                                        return readProject(reader, false);
584
                                } catch (UnsupportedEncodingException e1) {
585
                                        JOptionPane.showMessageDialog((Component)PluginServices.getMainFrame(),PluginServices.getText(this, e1.getLocalizedMessage()));
586
                                        return null;
587
                                }
588
                        }
589
                } catch (FileNotFoundException e) {
590
                        JOptionPane.showMessageDialog((Component)PluginServices.getMainFrame(),PluginServices.getText(this, "fichero_incorrecto"));
591
                        return null;
592
                }
593
        }
594

    
595
        /**
596
         * Lee del XML el proyecto.<br><br>
597
         *
598
         * Reads the XML of the project.<br>
599
         * It returns a project object holding all needed info that is not linked to the Project Dialog. <br>In case you want the project to be
600
         * linked to the window you must set this object to the extension:<br>
601
         *
602
         * <b>Example:</b><br>
603
         *
604
         * ...<br>
605
         * ...<br>
606
         * Project p = ProjectExtension.readProject(projectFile);<br>
607
         * ProjectExtension.setProject(p);
608
         * ...<br>
609
         * ...<br>
610
         * @param reader File reader
611
         * @param encodingFollowed Whether the encoded specified in the xml header was followed
612
         * when creating the reader. If the property followHeaderEncoding is false or not set,
613
         * then the encoding should have not been used when creating the reader, so it must be
614
         * recreated.
615
         *
616
         * @return Project
617
         * @throws UnsupportedEncodingException
618
         *
619
         */
620
        public Project readProject(Reader reader, boolean encodingFollowed) throws UnsupportedEncodingException {
621
                Project proj = null;
622

    
623
                try {
624
                        XmlTag tag = (XmlTag) XmlTag.unmarshal(reader);
625
                        XMLEntity xml=new XMLEntity(tag);
626
                        String VERSION=xml.getStringProperty("VERSION");
627

    
628
                        if (encodingFollowed) {
629
                                if (xml.contains("followHeaderEncoding")) {
630
                                        boolean useEncoding = xml.getBooleanProperty("followHeaderEncoding");
631
                                        if (!useEncoding) {
632
                                                throw new UnsupportedEncodingException("the encoding specified in the xml header is not safe");
633
                                        }
634
                                }
635
                                else {
636
                                        // Old projects didn't contain followHeaderEncoding and they were
637
                                        // not correctly encoded. We throw an exception now, and we'll try
638
                                        // to reopen the project
639
                                        // using the default system encoding.
640
                                        throw new UnsupportedEncodingException("the encoding specified in the xml header is not safe");
641
                                }
642
                        }
643

    
644
                        try {
645
                                // if ((VERSION!=null) && (VERSION.equals("0.5") || VERSION.equals("0.4") || (VERSION.indexOf("GISPLANET") != -1))){
646
                                if (VERSION != null) {
647
                                        proj = Project.createFromXML(xml);
648
                                }else{
649
                                        proj = Project.createFromXML03(new XMLEntity(tag));
650
                                }
651
                                return proj;
652
                        } catch (OpenException e){
653
                                e.showError();
654
                                //NotificationManager.addInfo("Al leer el proyecto", e);
655
                        }
656
                }  catch (MarshalException e) {
657
                        PluginServices.getLogger().error(PluginServices.getText(this, "formato_incorrecto"),e);
658
                        JOptionPane.showMessageDialog((Component)PluginServices.getMainFrame(),PluginServices.getText(this, "formato_incorrecto"));
659
                        //NotificationManager.addError("Al leer el proyecto", e);
660
                } catch (ValidationException e) {
661
                        PluginServices.getLogger().error(PluginServices.getText(this, "formato_incorrecto"),e);
662
                        JOptionPane.showMessageDialog((Component)PluginServices.getMainFrame(),PluginServices.getText(this, "formato_incorrecto"));
663
                        //NotificationManager.addError("Al leer el proyecto", e);
664
                }
665
                return null;
666
        }
667

    
668
        /**
669
         * Devuelve el proyecto.
670
         *
671
         * @return Proyecto.
672
         */
673
        public Project getProject() {
674
                return p;
675
        }
676

    
677
        /**
678
         * @see com.iver.andami.plugins.IExtension#isEnabled()
679
         */
680
        public boolean isEnabled() {
681
                return true;
682
        }
683

    
684
        /**
685
         * @see com.iver.andami.plugins.IExtension#isVisible()
686
         */
687
        public boolean isVisible() {
688
                return true;
689
        }
690

    
691
        /**
692
         * Sets the project
693
         * @param p
694
         */
695
        public void setProject(Project p){
696
                getProjectFrame().setProject(p);
697
                this.p=p;
698
        }
699

    
700
        private void registerDocuments() {
701
                ProjectViewFactory.register();
702
                ProjectTableFactory.register();
703
                ProjectMapFactory.register();
704
        }
705

    
706
        private void initializeDocumentActionsExtensionPoint() {
707
                ExtensionPoints extensionPoints = ExtensionPointsSingleton.getInstance();
708
                if (!extensionPoints.containsKey("DocumentActions_View")) {
709
                        extensionPoints.put(
710
                                new ExtensionPoint(
711
                                        "DocumentActions_View",
712
                                        "Context menu options of the view document list" +
713
                                                " in the project window "+
714
                                                "(register instances of " +
715
                                                "com.iver.cit.gvsig.project.AbstractDocumentContextMenuAction)"
716
                                )
717
                        );
718
                }
719
                if (!extensionPoints.containsKey("DocumentActions_Table")) {
720
                        extensionPoints.put(
721
                                new ExtensionPoint(
722
                                        "DocumentActions_Table",
723
                                        "Context menu options of the table document list" +
724
                                                " in the project window "+
725
                                                "(register instances of " +
726
                                                "com.iver.cit.gvsig.project.AbstractDocumentContextMenuAction)"
727
                                )
728
                        );
729
                }
730
                if (!extensionPoints.containsKey("DocumentActions_Map")) {
731
                        extensionPoints.put(
732
                                new ExtensionPoint(
733
                                        "DocumentActions_Map",
734
                                        "Context menu options of the map document list" +
735
                                                " in the project window "+
736
                                                "(register instances of " +
737
                                                "com.iver.cit.gvsig.project.AbstractDocumentContextMenuAction)"
738
                                )
739
                        );
740
                }
741
        }
742

    
743
        public static String getPath() {
744
                return projectPath;
745
        }
746

    
747
        public static void setPath(String path) {
748
                projectPath = path;
749
        }
750

    
751
        public IWindow getProjectWindow() {
752
                return getProjectFrame();
753
        }
754

    
755

    
756
        public IExtensionStatus getStatus() {
757
                return this;
758
        }
759

    
760
        public boolean hasUnsavedData() {
761
                return p.hasChanged();
762
        }
763

    
764
        public IUnsavedData[] getUnsavedData() {
765
                if (hasUnsavedData()) {
766
                        UnsavedProject data = new UnsavedProject(this);
767
                        IUnsavedData[] dataArray = {data};
768
                        return dataArray;
769
                }
770
                else
771
                        return null;
772
        }
773

    
774
        /**
775
         * Implements the IUnsavedData interface to show unsaved projects
776
         * in the Unsavad Data dialog.
777
         *
778
         * @author Cesar Martinez Izquierdo <cesar.martinez@iver.es>
779
         */
780
        public class UnsavedProject  extends UnsavedData {
781

    
782
                public UnsavedProject(IExtension extension) {
783
                        super(extension);
784
                }
785

    
786
                public String getDescription() {
787
                        if (getPath()==null) {
788
                                return PluginServices.getText(ProjectExtension.this, "Unnamed_new_gvsig_project_");
789
                        }
790
                        else {
791
                                return PluginServices.getText(ProjectExtension.this, "Modified_project_");
792
                        }
793
                }
794

    
795
                public String getResourceName() {
796
                        if (getPath()==null) {
797
                                return PluginServices.getText(ProjectExtension.this, "Unnamed");
798
                        }
799
                        else {
800
                                return getPath();
801
                        }
802

    
803
                }
804

    
805
                public boolean saveData() {
806
                        return guardar();
807
                }
808

    
809
                public ImageIcon getIcon() {
810
                        try {
811
                                URL imagePath = PluginServices.getPluginServices(ProjectExtension.this).getClassLoader().getResource("images/logoGVA.gif");
812
                                return new ImageIcon(imagePath);
813
                        }
814
                        catch (Exception ex) {}
815
                        return null;
816
                }
817
        }
818

    
819
        public IMonitorableTask[] getRunningProcesses() {
820
                // TODO Auto-generated method stub
821
                return null;
822
        }
823
        public boolean hasRunningProcesses() {
824
                // TODO Auto-generated method stub
825
                return false;
826
        }
827

    
828
}