Statistics
| Revision:

svn-gvsig-desktop / branches / v2_0_0_prep / applications / appgvSIG / src / com / iver / cit / gvsig / ProjectExtension.java @ 21743

History | View | Annotate | Download (26.2 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.JOptionPane;
64

    
65
import org.exolab.castor.xml.MarshalException;
66
import org.exolab.castor.xml.Marshaller;
67
import org.exolab.castor.xml.ValidationException;
68
import org.gvsig.fmap.mapcontext.layers.LayerFactory;
69
import org.gvsig.gui.beans.swing.JFileChooser;
70

    
71
import com.iver.andami.Launcher;
72
import com.iver.andami.PluginServices;
73
import com.iver.andami.Launcher.TerminationProcess;
74
import com.iver.andami.messages.NotificationManager;
75
import com.iver.andami.plugins.Extension;
76
import com.iver.andami.plugins.IExtension;
77
import com.iver.andami.plugins.status.IExtensionStatus;
78
import com.iver.andami.plugins.status.IUnsavedData;
79
import com.iver.andami.plugins.status.UnsavedData;
80
import com.iver.andami.ui.mdiManager.IWindow;
81
import com.iver.andami.ui.mdiManager.WindowInfo;
82
import com.iver.andami.ui.wizard.UnsavedDataPanel;
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
        public static final String LAYOUT_TEMPLATE_FILECHOOSER_ID = "LAYOUT_TEMPLATE_FILECHOOSER_ID";
120
        public static final String PROJECT_FILE_CHOOSER_ID = "PROJECT_FILECHOOSER_ID";
121
        /**
122
         * Use UTF-8 for encoding, as it can represent characters from
123
         * any language.
124
         *
125
         * Another sensible option would be
126
         * encoding = System.getProperty("file.encoding");
127
         * but this would need some extra testing.
128
         */
129
        public static String PROJECTENCODING = "UTF-8";
130

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

    
141
//                LayerFactory.setWritersPath(PluginServices.getPluginServices(this)
142
//                                  .getPluginDirectory()
143
//                                  .getAbsolutePath() +
144
//                                  File.separator + "drivers");
145
//
146
//        LayerFactory.setDriversPath(PluginServices.getPluginServices(this)
147
//                                  .getPluginDirectory()
148
//                                  .getAbsolutePath() +
149
//                                  File.separator + "drivers");
150

    
151
        initializeDocumentActionsExtensionPoint();
152
        registerDocuments();
153

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

    
161
            registerIcons();
162

    
163
        }
164

    
165
        private void registerIcons(){
166
                PluginServices.getIconTheme().registerDefault(
167
                                "project-new",
168
                                this.getClass().getClassLoader().getResource("images/new.png")
169
                        );
170

    
171
                PluginServices.getIconTheme().registerDefault(
172
                                "project-open",
173
                                this.getClass().getClassLoader().getResource("images/open.png")
174
                        );
175

    
176
                PluginServices.getIconTheme().registerDefault(
177
                                "project-save",
178
                                this.getClass().getClassLoader().getResource("images/save.png")
179
                        );
180

    
181
                PluginServices.getIconTheme().registerDefault(
182
                                "project-save-as",
183
                                this.getClass().getClassLoader().getResource("images/save.png")
184
                        );
185

    
186
                PluginServices.getIconTheme().registerDefault(
187
                                "layout-template-open",
188
                                this.getClass().getClassLoader().getResource("images/opentemplate.png")
189
                        );
190

    
191
                PluginServices.getIconTheme().registerDefault(
192
                                "application-exit",
193
                                this.getClass().getClassLoader().getResource("images/salir.png")
194
                        );
195
        }
196
        private void loadInitialProject(){
197
                String[] theArgs = PluginServices.getArguments();
198
        String lastArg = theArgs[theArgs.length-1];
199
        if ((lastArg.endsWith(".gvp")) ||
200
                        (lastArg.endsWith(".GVP")))
201
        {
202
                PluginServices.getLogger().debug("Intentando cargar el proyecto " + lastArg);
203
                //File projectFile = new File(lastArg);
204
                setProject(readProject(lastArg));
205
                PluginServices.getMainFrame().setTitle(p.getName());
206
                projectPath = lastArg;
207
        }
208
        else
209
        {
210
                        setProject(ProjectFactory.createProject());
211
                        p.setName(PluginServices.getText(this, "untitled"));
212
                        p.setModified(false);
213
                        PluginServices.getMainFrame().setTitle(PluginServices.getText(this, "sin_titulo"));
214
        }
215
        }
216
        /**
217
         * @see com.iver.mdiApp.plugins.IExtension#postInitialize()
218
         */
219
        public void postInitialize() {
220
                loadInitialProject();
221
                getProjectFrame().setProject(p);
222
                p.restoreWindowProperties();
223
        }
224

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

    
249
        /**
250
         * Muestra la ventana con el gestor de proyectos, con las propiedades
251
         * de ventana especificadas.
252
         */
253
        public void showProjectWindow(WindowInfo wi) {
254
                seedProjectWindow = wi;
255
                showProjectWindow();
256
        }
257

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

    
277
        private boolean guardarDialogo(){
278
                boolean saved=false;
279

    
280
                if (lastSavePath == null)
281
                        lastSavePath = projectPath;
282

    
283

    
284
                Preferences prefs = Preferences.userRoot().node( "gvsig.foldering");
285
                JFileChooser jfc = new JFileChooser(PROJECT_FILE_CHOOSER_ID, prefs.get("ProjectsFolder", null));
286

    
287
                jfc.setDialogTitle(PluginServices.getText(this, "guardar_proyecto"));
288
                jfc.addChoosableFileFilter(new GenericFileFilter("gvp",
289
                                PluginServices.getText(this, "tipo_fichero_proyecto")));
290

    
291
                if (jfc.showSaveDialog((Component) PluginServices.getMainFrame()) == JFileChooser.APPROVE_OPTION) {
292
                        File file=jfc.getSelectedFile();
293
                        if (!(file.getPath().toLowerCase().endsWith(".gvp"))){
294
                                file=new File(file.getPath()+".gvp");
295
                        }
296
                        saved=writeProject(file, p);
297
                        String filePath = file.getAbsolutePath();
298
                        lastSavePath = filePath.substring(0, filePath.lastIndexOf(File.separatorChar));
299

    
300
                        getProjectFrame().refreshControls();
301
                }
302
                return saved;
303
        }
304

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

    
331
        /**
332
         * @see com.iver.mdiApp.plugins.IExtension#updateUI(java.lang.String)
333
         */
334
        public void execute(String actionCommand) {
335
                if (actionCommand.equals("NUEVO")) {
336
                        if (!askSave()) {
337
                                return;
338
                        }
339

    
340
                        projectPath=null;
341
                        ProjectDocument.initializeNUMS();
342
                        PluginServices.getMDIManager().closeAllWindows();
343
                        setProject(ProjectFactory.createProject());
344
                        getProjectFrame().setProject(p);
345
                        showProjectWindow();
346
                        PluginServices.getMainFrame().setTitle(PluginServices.getText(this, "sin_titulo"));
347
                } else if (actionCommand.equals("ABRIR")) {
348
                        if (!askSave())
349
                                return;
350

    
351
                        Preferences prefs = Preferences.userRoot().node( "gvsig.foldering" );
352
                        JFileChooser jfc = new JFileChooser(PROJECT_FILE_CHOOSER_ID, prefs.get("ProjectsFolder", null));
353
                        jfc.addChoosableFileFilter(new GenericFileFilter("gvp",
354
                                        PluginServices.getText(this, "tipo_fichero_proyecto")));
355

    
356
                        if (jfc.showOpenDialog((Component) PluginServices.getMainFrame()) == JFileChooser.APPROVE_OPTION) {
357
                                ProjectDocument.initializeNUMS();
358
                                PluginServices.getMDIManager().closeAllWindows();
359

    
360
                                File projectFile = jfc.getSelectedFile();
361
                                Project o = readProject(projectFile);
362
                                setPath(projectFile.getAbsolutePath());
363
                                lastPath = getPath();
364
                                if (o != null) {
365
                                        setProject(o);
366
                                }
367

    
368
                                getProjectFrame().setProject(p);
369
                                PluginServices.getMainFrame().setTitle(p.getName());
370
                                getProjectFrame().refreshControls();
371

    
372
//jaume                                p.setModified(true);
373
                                p.restoreWindowProperties();
374
                        }
375
                } else if (actionCommand.equals("GUARDAR")) {
376
                        guardar();
377
//jaume                        p.setModified(false);
378
                } else if (actionCommand.equals("GUARDAR_COMO")) {
379
                        guardarDialogo();
380
//jaume                        p.setModified(false);
381
                } else if (actionCommand.equals("SALIR")){
382
                        Launcher.closeApplication();
383
                } else if (actionCommand.compareTo("OPENTEMPLATE")==0){
384
                        openLayout();
385
//jaume                        p.setModified(true);
386
                }
387
        }
388
        public void openLayout() {
389
                //Project project = ((ProjectExtension) PluginServices.getExtension(ProjectExtension.class)).getProject();
390
                Layout layout=null;
391

    
392
                if (templatesPath == null) {
393
                        Preferences prefs = Preferences.userRoot().node( "gvsig.foldering" );
394
                        templatesPath = prefs.get("TemplatesFolder", null);
395
                }
396

    
397
                JFileChooser jfc = new JFileChooser(LAYOUT_TEMPLATE_FILECHOOSER_ID, templatesPath);
398
                jfc.addChoosableFileFilter(new GenericFileFilter("gvt",
399
                                PluginServices.getText(this, "plantilla")));
400

    
401
                if (jfc.showOpenDialog((Component) PluginServices.getMainFrame()) == JFileChooser.APPROVE_OPTION) {
402
                        File file=jfc.getSelectedFile();
403
                        if (!(file.getPath().endsWith(".gvt") || file.getPath().endsWith(".GVT"))){
404
                                file=new File(file.getPath()+".gvt");
405
                        }
406
                        try {
407
                                File xmlFile = new File(file.getAbsolutePath());
408
                                FileInputStream is = new FileInputStream(xmlFile);
409
                                Reader reader = XMLEncodingUtils.getReader(is);
410

    
411
                                XmlTag tag = (XmlTag) XmlTag.unmarshal(reader);
412
                                try {
413
                                        XMLEntity xml=new XMLEntity(tag);
414
                                        if (xml.contains("followHeaderEncoding")) {
415
                                                layout = Layout.createLayout(xml,p);
416
                                        }
417
                                        else {
418
                                                reader = new FileReader(xmlFile);
419
                                                tag = (XmlTag) XmlTag.unmarshal(reader);
420
                                                xml=new XMLEntity(tag);
421
                                                layout = Layout.createLayout(xml,p);
422
                                        }
423

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

    
441

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

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

    
488
                } catch (Exception e) {
489
                        NotificationManager.addError(PluginServices.getText(this,"error_writing_project")+ ": "+file.getName(), e);
490
                        return false;
491
                }
492
                NotificationManager.addInfo(PluginServices.getText(this,"wrote_project")+ ": "+file.getName());
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
                        NotificationManager.addInfo(PluginServices.getText(this,"openning_project")+ ": "+xml.getStringProperty("name"));
628

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

    
645
                        try {
646
                                // if ((VERSION!=null) && (VERSION.equals("0.5") || VERSION.equals("0.4") || (VERSION.indexOf("GISPLANET") != -1))){
647
                                if (VERSION != null) {
648
                                        proj = Project.createFromXML(xml);
649
                                }else{
650
                                        proj = Project.createFromXML03(new XMLEntity(tag));
651
                                }
652
                                NotificationManager.addInfo(PluginServices.getText(this,"opened_project")+ ": "+xml.getStringProperty("name"));
653

    
654
                                return proj;
655
                        } catch (OpenException e){
656
                                e.showError();
657
                                //NotificationManager.addInfo("Al leer el proyecto", e);
658
                        }
659
                }  catch (MarshalException e) {
660
                        PluginServices.getLogger().error(PluginServices.getText(this, "formato_incorrecto"),e);
661
                        JOptionPane.showMessageDialog((Component)PluginServices.getMainFrame(),PluginServices.getText(this, "formato_incorrecto"));
662
                        //NotificationManager.addError("Al leer el proyecto", e);
663
                } catch (ValidationException e) {
664
                        PluginServices.getLogger().error(PluginServices.getText(this, "formato_incorrecto"),e);
665
                        JOptionPane.showMessageDialog((Component)PluginServices.getMainFrame(),PluginServices.getText(this, "formato_incorrecto"));
666
                        //NotificationManager.addError("Al leer el proyecto", e);
667
                }
668
                NotificationManager.addInfo(PluginServices.getText(this,"error_openning_project"));
669

    
670
                return null;
671
        }
672

    
673
        /**
674
         * Devuelve el proyecto.
675
         *
676
         * @return Proyecto.
677
         */
678
        public Project getProject() {
679
                return p;
680
        }
681

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

    
689
        /**
690
         * @see com.iver.andami.plugins.IExtension#isVisible()
691
         */
692
        public boolean isVisible() {
693
                return true;
694
        }
695

    
696
        /**
697
         * Sets the project
698
         * @param p
699
         */
700
        public void setProject(Project p){
701
                getProjectFrame().setProject(p);
702
                this.p=p;
703
        }
704

    
705
        private void registerDocuments() {
706
                ProjectViewFactory.register();
707
                ProjectTableFactory.register();
708
                ProjectMapFactory.register();
709
        }
710

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

    
748
        public static String getPath() {
749
                return projectPath;
750
        }
751

    
752
        public static void setPath(String path) {
753
                projectPath = path;
754
        }
755

    
756
        public IWindow getProjectWindow() {
757
                return getProjectFrame();
758
        }
759

    
760

    
761
        public IExtensionStatus getStatus() {
762
                return this;
763
        }
764

    
765
        public boolean hasUnsavedData() {
766
                return p.hasChanged();
767
        }
768

    
769
        public IUnsavedData[] getUnsavedData() {
770
                if (hasUnsavedData()) {
771
                        UnsavedProject data = new UnsavedProject(this);
772
                        IUnsavedData[] dataArray = {data};
773
                        return dataArray;
774
                }
775
                else
776
                        return null;
777
        }
778

    
779
        /**
780
         * Implements the IUnsavedData interface to show unsaved projects
781
         * in the Unsavad Data dialog.
782
         *
783
         * @author Cesar Martinez Izquierdo <cesar.martinez@iver.es>
784
         */
785
        public class UnsavedProject  extends UnsavedData {
786

    
787
                public UnsavedProject(IExtension extension) {
788
                        super(extension);
789
                }
790

    
791
                public String getDescription() {
792
                        if (getPath()==null) {
793
                                return PluginServices.getText(ProjectExtension.this, "Unnamed_new_gvsig_project_");
794
                        }
795
                        else {
796
                                return PluginServices.getText(ProjectExtension.this, "Modified_project_");
797
                        }
798
                }
799

    
800
                public String getResourceName() {
801
                        if (getPath()==null) {
802
                                return PluginServices.getText(ProjectExtension.this, "Unnamed");
803
                        }
804
                        else {
805
                                return getPath();
806
                        }
807

    
808
                }
809

    
810
                public boolean saveData() {
811
                        return guardar();
812
                }
813

    
814
                public ImageIcon getIcon() {
815
                        try {
816
                                URL imagePath = PluginServices.getPluginServices(ProjectExtension.this).getClassLoader().getResource("images/logoGVA.gif");
817
                                return new ImageIcon(imagePath);
818
                        }
819
                        catch (Exception ex) {}
820
                        return null;
821
                }
822
        }
823

    
824
        public IMonitorableTask[] getRunningProcesses() {
825
                // TODO Auto-generated method stub
826
                return null;
827
        }
828
        public boolean hasRunningProcesses() {
829
                // TODO Auto-generated method stub
830
                return false;
831
        }
832

    
833
}