Statistics
| Revision:

svn-gvsig-desktop / trunk / applications / appgvSIG / src / com / iver / cit / gvsig / ProjectExtension.java @ 10626

History | View | Annotate | Download (23.2 KB)

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

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

    
69
import com.iver.andami.Launcher;
70
import com.iver.andami.PluginServices;
71
import com.iver.andami.messages.Messages;
72
import com.iver.andami.messages.NotificationManager;
73
import com.iver.andami.plugins.Extension;
74
import com.iver.andami.ui.mdiManager.IWindow;
75
import com.iver.andami.ui.mdiManager.WindowInfo;
76
import com.iver.cit.gvsig.fmap.layers.LayerFactory;
77
import com.iver.cit.gvsig.project.Project;
78
import com.iver.cit.gvsig.project.ProjectFactory;
79
import com.iver.cit.gvsig.project.documents.ProjectDocument;
80
import com.iver.cit.gvsig.project.documents.exceptions.OpenException;
81
import com.iver.cit.gvsig.project.documents.gui.ProjectWindow;
82
import com.iver.cit.gvsig.project.documents.layout.ProjectMap;
83
import com.iver.cit.gvsig.project.documents.layout.ProjectMapFactory;
84
import com.iver.cit.gvsig.project.documents.layout.gui.Layout;
85
import com.iver.cit.gvsig.project.documents.table.ProjectTableFactory;
86
import com.iver.cit.gvsig.project.documents.view.ProjectViewFactory;
87
import com.iver.utiles.GenericFileFilter;
88
import com.iver.utiles.XMLEntity;
89
import com.iver.utiles.extensionPoints.ExtensionPoint;
90
import com.iver.utiles.extensionPoints.ExtensionPoints;
91
import com.iver.utiles.extensionPoints.ExtensionPointsSingleton;
92
import com.iver.utiles.xml.XMLEncodingUtils;
93
import com.iver.utiles.xmlEntity.generate.XmlTag;
94

    
95

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

    
122
        /**
123
         * @see com.iver.mdiApp.plugins.IExtension#initialize()
124
         */
125
        public void initialize() {
126
            try {
127
            Class.forName("javax.media.jai.EnumeratedParameter");
128
        } catch (ClassNotFoundException e) {
129
            NotificationManager.addError("La m?quina virtual con la que se ejecuta gvSIG no tiene JAI instalado", e);
130
        }
131

    
132
                LayerFactory.setWritersPath(PluginServices.getPluginServices(this)
133
                                  .getPluginDirectory()
134
                                  .getAbsolutePath() +
135
                                  File.separator + "drivers");
136

    
137
        LayerFactory.setDriversPath(PluginServices.getPluginServices(this)
138
                                  .getPluginDirectory()
139
                                  .getAbsolutePath() +
140
                                  File.separator + "drivers");
141

    
142
        initializeDocumentActionsExtensionPoint();
143
        registerDocuments();
144

    
145
        // Recuperamos el ?ltimo argumento, que se supone
146
        // que ser? el fichero .gvp que queremos abrir.
147
        // (por enmedio pueden venir o no otros argumentos,
148
        // por ejemplo el idioma)
149
        // TODO: Aqu? Jaume podr?a meter lo del backup del proyecto
150
        // que ha hecho para ValenciaUrban?stica
151

    
152
                /*
153
                pe = (ProjectExtension) PluginServices.getExtension(com.iver.cit.gvsig.ProjectExtension.class);
154
                if (projectFile.length()!=0){
155
                        p=pe.readProject(projectFile);
156
                }
157
                else
158
                        p = restorePreviousProject();
159
                pe.setProject(p); */
160
        String[] theArgs = PluginServices.getArguments();
161
        String lastArg = theArgs[theArgs.length-1];
162
        if ((lastArg.endsWith(".gvp")) ||
163
                        (lastArg.endsWith(".GVP")))
164
        {
165
                PluginServices.getLogger().debug("Intentando cargar el proyecto " + lastArg);
166
                //File projectFile = new File(lastArg);
167
                p = readProject(lastArg);
168
                PluginServices.getMainFrame().setTitle(p.getName());
169
                projectPath = lastArg;
170
        }
171
        else
172
        {
173
                        p = ProjectFactory.createProject();
174
                        p.setName(PluginServices.getText(this, "untitled"));
175
                        p.setModified(false);
176
                        PluginServices.getMainFrame().setTitle(PluginServices.getText(this, "sin_titulo"));
177
        }
178
        }
179
        /**
180
         * @see com.iver.mdiApp.plugins.IExtension#postInitialize()
181
         */
182
        public void postInitialize() {
183
                getProjectFrame().setProject(p);
184
                p.restoreWindowProperties();
185
        }
186

    
187
        public ProjectWindow getProjectFrame() {
188
                if (projectFrame==null)
189
                                projectFrame = new ProjectWindow();
190
                return projectFrame;
191
        }
192
        /**
193
         * Muestra la ventana con el gestor de proyectos.
194
         */
195
        public void showProjectWindow() {
196
                if (seedProjectWindow!=null) {
197
                        if (seedProjectWindow.isClosed()) {
198
                                // if it was closed, we just don't open the window now
199
                                seedProjectWindow.setClosed(false);
200
                                return;
201
                        }
202
                        WindowInfo winProps = seedProjectWindow;
203
                        seedProjectWindow = null;
204
                        PluginServices.getMDIManager().addWindow(getProjectFrame());
205
                        PluginServices.getMDIManager().changeWindowInfo(getProjectFrame(), winProps);
206
                }
207
                else
208
                        PluginServices.getMDIManager().addWindow(getProjectFrame());
209
        }
210

    
211
        /**
212
         * Muestra la ventana con el gestor de proyectos, con las propiedades
213
         * de ventana especificadas.
214
         */
215
        public void showProjectWindow(WindowInfo wi) {
216
                seedProjectWindow = wi;
217
                showProjectWindow();
218
        }
219

    
220
        /**
221
         * Guarda el proyecto actual en disco.
222
         */
223
        private boolean guardar() {
224
                boolean saved=false;
225
//                if (p.getPath() == null) {
226
                if (projectPath == null) {
227
                        saved=guardarDialogo();
228
                } else {
229
                        saved=writeProject(new File(projectPath), p); //new File(p.getPath()), p);
230
                        getProjectFrame().refreshControls();
231
                }
232
                return saved;
233
        }
234

    
235
        private boolean guardarDialogo(){
236
                boolean saved=false;
237

    
238
                if (lastSavePath == null)
239
                        lastSavePath = projectPath;
240

    
241
                if (lastSavePath == null) {
242
                        Preferences prefs = Preferences.userRoot().node( "gvsig.foldering" );
243
                        lastSavePath = prefs.get("ProjectsFolder", null);
244
                }
245

    
246
                JFileChooser jfc = new JFileChooser(lastSavePath);
247
                jfc.addChoosableFileFilter(new GenericFileFilter("gvp",
248
                                PluginServices.getText(this, "tipo_fichero_proyecto")));
249

    
250
                if (jfc.showSaveDialog((Component) PluginServices.getMainFrame()) == JFileChooser.APPROVE_OPTION) {
251
                        File file=jfc.getSelectedFile();
252
                        if (!(file.getPath().toLowerCase().endsWith(".gvp"))){
253
                                file=new File(file.getPath()+".gvp");
254
                        }
255
                        saved=writeProject(file, p);
256
                        String filePath = file.getAbsolutePath();
257
                        lastSavePath = filePath.substring(0, filePath.lastIndexOf(File.separatorChar));
258

    
259
                        getProjectFrame().refreshControls();
260
                }
261
                return saved;
262
        }
263
        /**
264
         * Guarda si el proyecto ha sido modificado.
265
         *
266
         * @return True si se ha guardado correctamente.
267
         */
268
        private boolean modificado() {
269
                if (p.isModified()) {
270
                ///if (true) {
271
                        //TODO de momento se queda como modificado siempre menos cuando est? totalmente vacio que se tomar? como no modificado,
272
                        //para poder controlar perfectamente cuando un proyecto ha sido modificado
273
                        //hay que recoger los eventos de cambio de leyenda, cambio de extent, a?adir una capa, etc que se encuentran en FMap.
274

    
275
                        int res = JOptionPane.showConfirmDialog((Component) PluginServices.getMainFrame(),
276
                                        PluginServices.getText(this, "guardar_cambios"),
277
                                        "gvSIG",
278
                                        JOptionPane.YES_NO_CANCEL_OPTION,
279
                                        JOptionPane.INFORMATION_MESSAGE);
280

    
281
                        if (res == JOptionPane.YES_OPTION) {
282
                                guardar();
283
                        } else if (res == JOptionPane.CANCEL_OPTION) {
284
                                return false;
285
                        }
286
                }
287

    
288
                return true;
289
        }
290

    
291
        /**
292
         * @see com.iver.mdiApp.plugins.IExtension#updateUI(java.lang.String)
293
         */
294
        public void execute(String actionCommand) {
295
                if (actionCommand.equals("NUEVO")) {
296
                        //Si est? modificado se pregunta si se quiere guardar el anterior
297
                        if (!modificado()) {
298
                                return;
299
                        }
300
                        ProjectDocument.initializeNUMS();
301
                        PluginServices.getMDIManager().closeAllWindows();
302
                        p = ProjectFactory.createProject();
303
                        p.setName(PluginServices.getText(this, "untitled"));
304
                        p.setModified(true);
305
                        getProjectFrame().setProject(p);
306
                        showProjectWindow();
307
                        PluginServices.getMainFrame().setTitle(PluginServices.getText(this, "sin_titulo"));
308
                } else if (actionCommand.equals("ABRIR")) {
309
                        //Si est? modificado se pregunta si se quiere guardar el anterior
310
                        if (!modificado()) {
311
                                ProjectDocument.initializeNUMS();
312
                                return;
313
                        }
314

    
315
                        if (lastPath == null) {
316
                                Preferences prefs = Preferences.userRoot().node( "gvsig.foldering" );
317
                                lastPath = prefs.get("ProjectsFolder", null);
318
                        }
319

    
320
                        JFileChooser jfc = new JFileChooser(lastPath);
321
                        jfc.addChoosableFileFilter(new GenericFileFilter("gvp",
322
                                        PluginServices.getText(this, "tipo_fichero_proyecto")));
323

    
324
                        if (jfc.showOpenDialog((Component) PluginServices.getMainFrame()) == JFileChooser.APPROVE_OPTION) {
325
                                ProjectDocument.initializeNUMS();
326
                                PluginServices.getMDIManager().closeAllWindows();
327

    
328
                                File projectFile = jfc.getSelectedFile();
329
                                Project o = readProject(projectFile);
330
                                setPath(projectFile.getAbsolutePath());
331
                                lastPath = getPath();
332
                                if (o != null) {
333
                                        p = o;
334
                                }
335

    
336
                                getProjectFrame().setProject(p);
337
                                PluginServices.getMainFrame().setTitle(p.getName());
338
                                getProjectFrame().refreshControls();
339
                                p.setModified(true);
340
                                p.restoreWindowProperties();
341
                        }
342
                } else if (actionCommand.equals("GUARDAR")) {
343
                        guardar();
344
                        p.setModified(false);
345
                } else if (actionCommand.equals("GUARDAR_COMO")) {
346
                        guardarDialogo();
347
                        p.setModified(false);
348
                } else if (actionCommand.equals("SALIR")){
349
                        int option = JOptionPane.showConfirmDialog((Component)PluginServices.getMainFrame(),
350
                                        Messages.getString("MDIFrame.quiere_salir"),
351
                                        Messages.getString("MDIFrame.salir"),
352
                                        JOptionPane.YES_NO_OPTION);
353

    
354
                        if (option == JOptionPane.YES_OPTION) {
355
                                Launcher.closeApplication();
356
                        }
357
                } else if (actionCommand.compareTo("OPENTEMPLATE")==0){
358
                        openLayout();
359
                        p.setModified(true);
360
                }
361
        }
362
        public void openLayout() {
363
                //Project project = ((ProjectExtension) PluginServices.getExtension(ProjectExtension.class)).getProject();
364
                Layout layout=null;
365

    
366
                if (templatesPath == null) {
367
                        Preferences prefs = Preferences.userRoot().node( "gvsig.foldering" );
368
                        templatesPath = prefs.get("TemplatesFolder", null);
369
                }
370

    
371
                JFileChooser jfc = new JFileChooser(templatesPath);
372
                jfc.addChoosableFileFilter(new GenericFileFilter("gvt",
373
                                PluginServices.getText(this, "plantilla")));
374

    
375
                if (jfc.showOpenDialog((Component) PluginServices.getMainFrame()) == JFileChooser.APPROVE_OPTION) {
376
                        File file=jfc.getSelectedFile();
377
                        if (!(file.getPath().endsWith(".gvt") || file.getPath().endsWith(".GVT"))){
378
                                file=new File(file.getPath()+".gvt");
379
                        }
380
                        try {
381
                                File xmlFile = new File(file.getAbsolutePath());
382
                                FileReader reader;
383
                                reader = new FileReader(xmlFile);
384

    
385
                                XmlTag tag = (XmlTag) XmlTag.unmarshal(reader);
386
                                try {
387
                                        layout = Layout.createLayout(new XMLEntity(tag),p);
388
                                } catch (OpenException e) {
389
                                        e.showError();
390
                                }
391
                                //fPanelLegendManager.setRenderer(LegendFactory.createFromXML(new XMLEntity(tag)));
392
                        } catch (FileNotFoundException e) {
393
                                NotificationManager.addError(PluginServices.getText(this, "Al_leer_la_leyenda"), e);
394
                        } catch (MarshalException e) {
395
                                NotificationManager.addError(PluginServices.getText(this, "Al_leer_la_leyenda"), e);
396
                        } catch (ValidationException e) {
397
                                NotificationManager.addError(PluginServices.getText(this, "Al_leer_la_leyenda"), e);
398
                        }
399
                        ProjectMap pmap = ProjectFactory.createMap(file.getName());
400
                        pmap.setModel(layout);
401
                        pmap.getModel().setProjectMap(pmap);
402
                        p.addDocument(pmap);
403
                        PluginServices.getMDIManager().addWindow(layout);
404

    
405

    
406
                }
407
        }
408
        /**
409
         * Escribe el proyecto en XML.
410
         *
411
         * @param file Fichero.
412
         * @param p Proyecto.
413
         */
414
        public boolean writeProject(File file, Project p) {
415
                return writeProject(file, p, true);
416
        }
417

    
418
        /**
419
         * Escribe el proyecto en XML. Pero permite decidir si se
420
         * pide confirmaci?n para sobreescribir
421
         *
422
         * @param file Fichero.
423
         * @param p Proyecto.
424
         * @param askConfirmation boolean
425
         */
426
        public boolean writeProject(File file, Project p, boolean askConfirmation) {
427
                if( askConfirmation && file.exists()){
428
                        int resp = JOptionPane.showConfirmDialog(
429
                                        (Component) PluginServices.getMainFrame(),PluginServices.getText(this,"fichero_ya_existe_seguro_desea_guardarlo"),
430
                                        PluginServices.getText(this,"guardar"), JOptionPane.YES_NO_OPTION);
431
                        if (resp != JOptionPane.YES_OPTION) {
432
                                return false;
433
                        }
434
                }
435
                // write it out as XML
436
                try {
437
            FileOutputStream fos = new FileOutputStream(file.getAbsolutePath());
438
            OutputStreamWriter writer = new OutputStreamWriter(fos, PROJECTENCODING);
439
                        Marshaller m = new Marshaller(writer);
440
                        m.setEncoding(PROJECTENCODING);
441
                        p.setName(file.getName());
442
                        // p.setPath(file.toString());
443
                        p.setModificationDate(DateFormat.getDateInstance().format(new Date()));
444
                        p.setModified(false);
445
                        XMLEntity xml = p.getXMLEntity();
446
                        xml.putProperty("followHeaderEncoding", true);
447
                        m.marshal(xml.getXmlTag());
448
                        PluginServices.getMainFrame().setTitle(file.getName());
449
                        setPath(file.toString());
450

    
451
                } catch (Exception e) {
452
                        NotificationManager.addError("Error guardando el proyecto", e);
453
                        return false;
454
                }
455
                return true;
456
        }
457

    
458
        public Project readProject(String path) {
459
                BufferedReader reader =null;
460
                try {
461
                URL url=null;
462
                        url = new URL(path);
463
                        String encoding = XMLEncodingUtils.getEncoding(url.openStream());
464
                        InputStream is = url.openStream();
465
                        if (encoding!=null) {
466
                                Project proj=null;
467
                                try {
468
                                        reader = new BufferedReader(new InputStreamReader(is, encoding));
469
                                        proj=readProject(reader, true);
470
                                } catch (UnsupportedEncodingException e) {
471
                                        reader = new BufferedReader(new InputStreamReader(is));
472
                                        try {
473
                                                Project p=readProject(reader, false);
474
                                        } catch (UnsupportedEncodingException e1) {
475
                                                JOptionPane.showMessageDialog((Component)PluginServices.getMainFrame(),PluginServices.getText(this, e1.getLocalizedMessage()));
476
                                                return null;
477
                                        }
478
                                }
479
                                ProjectExtension.setPath(path);
480
                                return proj;
481
                        }
482
                        else {
483
                                reader = new BufferedReader(new InputStreamReader(is));
484
                                Project p;
485
                                try {
486
                                        p = readProject(reader, false);
487
                                } catch (UnsupportedEncodingException e) {
488
                                        JOptionPane.showMessageDialog((Component)PluginServices.getMainFrame(),PluginServices.getText(this, e.getLocalizedMessage()));
489
                                        return null;
490
                                }
491
                                ProjectExtension.setPath(path); //p.setPath(null);
492
                                return p;
493
                        }
494
                } catch (MalformedURLException e) {
495
                        File file=new File(path);
496
                        return readProject(file);
497
                } catch (IOException e) {
498
                        e.printStackTrace();
499
                        return null;
500
                }
501
        }
502

    
503
        /**
504
         * Lee del XML el proyecto.<br><br>
505
         *
506
         * Reads the XML of the project.<br>
507
         * 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
508
         * linked to the window you must set this object to the extension:<br>
509
         *
510
         * <b>Example:</b><br>
511
         *
512
         * ...<br>
513
         * ...<br>
514
         * Project p = ProjectExtension.readProject(projectFile);<br>
515
         * ProjectExtension.setProject(p);
516
         * ...<br>
517
         * ...<br>
518
         * @param file Fichero.
519
         *
520
         * @return Project
521
         *
522
         */
523
        public Project readProject(File file) {
524
                File xmlFile = new File(file.getAbsolutePath());
525
                try {
526
                        String encoding = XMLEncodingUtils.getEncoding(new FileInputStream(xmlFile));
527
                        InputStreamReader reader=null;
528
                        if (encoding!=null) {
529
                                try {
530
                                        reader = new InputStreamReader(new FileInputStream(xmlFile), encoding);
531
                                        return readProject(reader, true);
532
                                } catch (UnsupportedEncodingException e) {
533
                                        reader = new InputStreamReader(new FileInputStream(xmlFile));
534
                                        try {
535
                                                return readProject(reader, false);
536
                                        } catch (UnsupportedEncodingException e1) {
537
                                                JOptionPane.showMessageDialog((Component)PluginServices.getMainFrame(),PluginServices.getText(this, e1.getLocalizedMessage()));
538
                                                return null;
539
                                        }
540
                                }
541
                        }
542
                        else {
543
                                reader = new InputStreamReader(new FileInputStream(xmlFile));
544
                                try {
545
                                        return readProject(reader, false);
546
                                } catch (UnsupportedEncodingException e1) {
547
                                        JOptionPane.showMessageDialog((Component)PluginServices.getMainFrame(),PluginServices.getText(this, e1.getLocalizedMessage()));
548
                                        return null;
549
                                }
550
                        }
551
                } catch (FileNotFoundException e) {
552
                        JOptionPane.showMessageDialog((Component)PluginServices.getMainFrame(),PluginServices.getText(this, "fichero_incorrecto"));
553
                        return null;
554
                }
555
        }
556

    
557
        /**
558
         * Lee del XML el proyecto.<br><br>
559
         *
560
         * Reads the XML of the project.<br>
561
         * 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
562
         * linked to the window you must set this object to the extension:<br>
563
         *
564
         * <b>Example:</b><br>
565
         *
566
         * ...<br>
567
         * ...<br>
568
         * Project p = ProjectExtension.readProject(projectFile);<br>
569
         * ProjectExtension.setProject(p);
570
         * ...<br>
571
         * ...<br>
572
         * @param reader File reader
573
         * @param encodingFollowed Whether the encoded specified in the xml header was followed
574
         * when creating the reader. If the property followHeaderEncoding is false or not set,
575
         * then the encoding should have not been used when creating the reader, so it must be
576
         * recreated.
577
         *
578
         * @return Project
579
         * @throws UnsupportedEncodingException
580
         *
581
         */
582
        public Project readProject(Reader reader, boolean encodingFollowed) throws UnsupportedEncodingException {
583
                Project proj = null;
584

    
585
                try {
586
                        XmlTag tag = (XmlTag) XmlTag.unmarshal(reader);
587
                        XMLEntity xml=new XMLEntity(tag);
588
                        String VERSION=xml.getStringProperty("VERSION");
589

    
590
                        if (encodingFollowed) {
591
                                if (xml.contains("followHeaderEncoding")) {
592
                                        boolean useEncoding = xml.getBooleanProperty("followHeaderEncoding");
593
                                        if (!useEncoding) {
594
                                                throw new UnsupportedEncodingException("the encoding specified in the xml header is not safe");
595
                                        }
596
                                }
597
                                else {
598
                                        // Old projects didn't contain followHeaderEncoding and they were
599
                                        // not correctly encoded. We throw an exception now, and we'll try
600
                                        // to reopen the project
601
                                        // using the default system encoding.
602
                                        throw new UnsupportedEncodingException("the encoding specified in the xml header is not safe");
603
                                }
604
                        }
605

    
606
                        try {
607
                                // if ((VERSION!=null) && (VERSION.equals("0.5") || VERSION.equals("0.4") || (VERSION.indexOf("GISPLANET") != -1))){
608
                                if (VERSION != null) {
609
                                        proj = Project.createFromXML(xml);
610
                                }else{
611
                                        proj = Project.createFromXML03(new XMLEntity(tag));
612
                                }
613
                                return proj;
614
                        } catch (OpenException e){
615
                                e.showError();
616
                                //NotificationManager.addInfo("Al leer el proyecto", e);
617
                        }
618
                }  catch (MarshalException e) {
619
                        PluginServices.getLogger().error(PluginServices.getText(this, "formato_incorrecto"),e);
620
                        JOptionPane.showMessageDialog((Component)PluginServices.getMainFrame(),PluginServices.getText(this, "formato_incorrecto"));
621
                        //NotificationManager.addError("Al leer el proyecto", e);
622
                } catch (ValidationException e) {
623
                        PluginServices.getLogger().error(PluginServices.getText(this, "formato_incorrecto"),e);
624
                        JOptionPane.showMessageDialog((Component)PluginServices.getMainFrame(),PluginServices.getText(this, "formato_incorrecto"));
625
                        //NotificationManager.addError("Al leer el proyecto", e);
626
                }
627
                return null;
628
        }
629

    
630
        /**
631
         * Devuelve el proyecto.
632
         *
633
         * @return Proyecto.
634
         */
635
        public Project getProject() {
636
                return p;
637
        }
638

    
639
        /**
640
         * @see com.iver.andami.plugins.IExtension#isEnabled()
641
         */
642
        public boolean isEnabled() {
643
                return true;
644
        }
645

    
646
        /**
647
         * @see com.iver.andami.plugins.IExtension#isVisible()
648
         */
649
        public boolean isVisible() {
650
                return true;
651
        }
652

    
653
        /**
654
         * Sets the project
655
         * @param p
656
         */
657
        public void setProject(Project p){
658
                getProjectFrame().setProject(p);
659
                this.p=p;
660
        }
661

    
662
        //Finalizar y preguntar si se quiere guardar el proyecto o cancelar.
663
        public void terminate() {
664
                long t1,t2;
665
                t1 = System.currentTimeMillis();
666
                //if (getProject().hasChanged()) {
667
                        int option = JOptionPane.showConfirmDialog((Component)PluginServices.getMainFrame(),PluginServices.getText(this,"guardar_cambios"),
668
                                        PluginServices.getText(this,"guardar_proyecto"),
669
                                        JOptionPane.YES_NO_OPTION);
670

    
671
                        if (option == JOptionPane.YES_OPTION) {
672
                                if (!guardar())
673
                                        terminate();
674
                        }
675
                //}
676
                t2 = System.currentTimeMillis();
677
                System.err.println("ProjectExtension.terminate() " +  (t2-t1) + "milisecs");
678
        }
679

    
680
        private void registerDocuments() {
681
                ProjectViewFactory.register();
682
                ProjectTableFactory.register();
683
                ProjectMapFactory.register();
684
        }
685
        private void initializeDocumentActionsExtensionPoint() {
686
                ExtensionPoints extensionPoints = ExtensionPointsSingleton.getInstance();
687
                if (!extensionPoints.containsKey("DocumentActions_View")) {
688
                        extensionPoints.put(
689
                                new ExtensionPoint(
690
                                        "DocumentActions_View",
691
                                        "Context menu options of the view document list" +
692
                                                " in the project window "+
693
                                                "(register instances of " +
694
                                                "com.iver.cit.gvsig.project.AbstractDocumentContextMenuAction)"
695
                                )
696
                        );
697
                }
698
                if (!extensionPoints.containsKey("DocumentActions_Table")) {
699
                        extensionPoints.put(
700
                                new ExtensionPoint(
701
                                        "DocumentActions_Table",
702
                                        "Context menu options of the table document list" +
703
                                                " in the project window "+
704
                                                "(register instances of " +
705
                                                "com.iver.cit.gvsig.project.AbstractDocumentContextMenuAction)"
706
                                )
707
                        );
708
                }
709
                if (!extensionPoints.containsKey("DocumentActions_Map")) {
710
                        extensionPoints.put(
711
                                new ExtensionPoint(
712
                                        "DocumentActions_Map",
713
                                        "Context menu options of the map document list" +
714
                                                " in the project window "+
715
                                                "(register instances of " +
716
                                                "com.iver.cit.gvsig.project.AbstractDocumentContextMenuAction)"
717
                                )
718
                        );
719
                }
720
        }
721

    
722
        public static String getPath() {
723
                return projectPath;
724
        }
725

    
726
        public static void setPath(String path) {
727
                projectPath = path;
728
        }
729

    
730
        public IWindow getProjectWindow() {
731
                return getProjectFrame();
732
        }
733
}