Statistics
| Revision:

root / branches / v10 / applications / appgvSIG / src / com / iver / cit / gvsig / ProjectExtension.java @ 10666

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.gui.layout.Layout;
78
import com.iver.cit.gvsig.project.Project;
79
import com.iver.cit.gvsig.project.ProjectFactory;
80
import com.iver.cit.gvsig.project.documents.ProjectDocument;
81
import com.iver.cit.gvsig.project.documents.exceptions.OpenException;
82
import com.iver.cit.gvsig.project.documents.gui.ProjectWindow;
83
import com.iver.cit.gvsig.project.documents.layout.ProjectMap;
84
import com.iver.cit.gvsig.project.documents.layout.ProjectMapFactory;
85
import com.iver.cit.gvsig.project.documents.table.ProjectTableFactory;
86
import com.iver.cit.gvsig.project.documents.view.ProjectView;
87
import com.iver.cit.gvsig.project.documents.view.ProjectViewFactory;
88
import com.iver.utiles.GenericFileFilter;
89
import com.iver.utiles.XMLEntity;
90
import com.iver.utiles.extensionPoints.ExtensionPoint;
91
import com.iver.utiles.extensionPoints.ExtensionPoints;
92
import com.iver.utiles.extensionPoints.ExtensionPointsSingleton;
93
import com.iver.utiles.xml.XMLEncodingUtils;
94
import com.iver.utiles.xmlEntity.generate.XmlTag;
95

    
96

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

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

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

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

    
143
        initializeDocumentActionsExtensionPoint();
144
        registerDocuments();
145

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

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

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

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

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

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

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

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

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

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

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

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

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

    
289
                return true;
290
        }
291

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

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

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

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

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

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

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

    
363
                if (templatesPath == null) {
364
                        Preferences prefs = Preferences.userRoot().node( "gvsig.foldering" );
365
                        templatesPath = prefs.get("TemplatesFolder", null);
366
                }
367

    
368
                JFileChooser jfc = new JFileChooser(templatesPath);
369
                jfc.addChoosableFileFilter(new GenericFileFilter("gvt",
370
                                PluginServices.getText(this, "plantilla")));
371

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

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

    
402

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

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

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

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

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

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

    
582
                try {
583
                        XmlTag tag = (XmlTag) XmlTag.unmarshal(reader);
584
                        XMLEntity xml=new XMLEntity(tag);
585
                        String VERSION=xml.getStringProperty("VERSION");
586

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

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

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

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

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

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

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

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

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

    
719
        public static String getPath() {
720
                return projectPath;
721
        }
722

    
723
        public static void setPath(String path) {
724
                projectPath = path;
725
        }
726

    
727
        public IWindow getProjectWindow() {
728
                return getProjectFrame();
729
        }
730
}