Statistics
| Revision:

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

History | View | Annotate | Download (25.9 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.gui.beans.swing.JFileChooser;
69

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

    
102

    
103
/**
104
 * Extension que proporciona controles para crear proyectos nuevos, abrirlos y
105
 * guardarlos. Adem?s los tipos de tabla que soporta el proyecto son a?adidos
106
 * en esta clase.
107
 *
108
 * @author Fernando Gonz?lez Cort?s
109
 */
110
public class ProjectExtension extends Extension implements IExtensionStatus {
111
        private static String projectPath = null;
112
        //private ProjectWindow projectFrame;
113
        private ProjectWindow projectFrame;
114
        private Project p;
115
        private String lastPath;
116
        private String lastSavePath;
117
        private String templatesPath;
118
        private WindowInfo seedProjectWindow;
119
        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
                                FileReader reader;
409
                                reader = new FileReader(xmlFile);
410

    
411
                                XmlTag tag = (XmlTag) XmlTag.unmarshal(reader);
412
                                try {
413
                                        layout = Layout.createLayout(new XMLEntity(tag),p);
414
                                } catch (OpenException e) {
415
                                        e.showError();
416
                                }
417
                                //fPanelLegendManager.setRenderer(LegendFactory.createFromXML(new XMLEntity(tag)));
418
                        } catch (FileNotFoundException e) {
419
                                NotificationManager.addError(PluginServices.getText(this, "Al_leer_la_leyenda"), e);
420
                        } catch (MarshalException e) {
421
                                NotificationManager.addError(PluginServices.getText(this, "Al_leer_la_leyenda"), e);
422
                        } catch (ValidationException e) {
423
                                NotificationManager.addError(PluginServices.getText(this, "Al_leer_la_leyenda"), e);
424
                        }
425
                        ProjectMap pmap = ProjectFactory.createMap(file.getName());
426
                        pmap.setModel(layout);
427
                        pmap.getModel().setProjectMap(pmap);
428
                        p.addDocument(pmap);
429
                        PluginServices.getMDIManager().addWindow(layout);
430

    
431

    
432
                }
433
        }
434
        /**
435
         * Escribe el proyecto en XML.
436
         *
437
         * @param file Fichero.
438
         * @param p Proyecto.
439
         */
440
        public boolean writeProject(File file, Project p) {
441
                return writeProject(file, p, true);
442
        }
443

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

    
478
                } catch (Exception e) {
479
                        NotificationManager.addError(PluginServices.getText(this,"error_writing_project")+ ": "+file.getName(), e);
480
                        return false;
481
                }
482
                NotificationManager.addInfo(PluginServices.getText(this,"wrote_project")+ ": "+file.getName());
483
                return true;
484
        }
485

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

    
531
        /**
532
         * Lee del XML el proyecto.<br><br>
533
         *
534
         * Reads the XML of the project.<br>
535
         * 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
536
         * linked to the window you must set this object to the extension:<br>
537
         *
538
         * <b>Example:</b><br>
539
         *
540
         * ...<br>
541
         * ...<br>
542
         * Project p = ProjectExtension.readProject(projectFile);<br>
543
         * ProjectExtension.setProject(p);
544
         * ...<br>
545
         * ...<br>
546
         * @param file Fichero.
547
         *
548
         * @return Project
549
         *
550
         */
551
        public Project readProject(File file) {
552
                File xmlFile = new File(file.getAbsolutePath());
553
                try {
554
                        String encoding = XMLEncodingUtils.getEncoding(new FileInputStream(xmlFile));
555
                        InputStreamReader reader=null;
556
                        if (encoding!=null) {
557
                                try {
558
                                        reader = new InputStreamReader(new FileInputStream(xmlFile), encoding);
559
                                        return readProject(reader, true);
560
                                } catch (UnsupportedEncodingException e) {
561
                                        reader = new InputStreamReader(new FileInputStream(xmlFile));
562
                                        try {
563
                                                return readProject(reader, false);
564
                                        } catch (UnsupportedEncodingException e1) {
565
                                                JOptionPane.showMessageDialog((Component)PluginServices.getMainFrame(),PluginServices.getText(this, e1.getLocalizedMessage()));
566
                                                return null;
567
                                        }
568
                                }
569
                        }
570
                        else {
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
                } catch (FileNotFoundException e) {
580
                        JOptionPane.showMessageDialog((Component)PluginServices.getMainFrame(),PluginServices.getText(this, "fichero_incorrecto"));
581
                        return null;
582
                }
583
        }
584

    
585
        /**
586
         * Lee del XML el proyecto.<br><br>
587
         *
588
         * Reads the XML of the project.<br>
589
         * 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
590
         * linked to the window you must set this object to the extension:<br>
591
         *
592
         * <b>Example:</b><br>
593
         *
594
         * ...<br>
595
         * ...<br>
596
         * Project p = ProjectExtension.readProject(projectFile);<br>
597
         * ProjectExtension.setProject(p);
598
         * ...<br>
599
         * ...<br>
600
         * @param reader File reader
601
         * @param encodingFollowed Whether the encoded specified in the xml header was followed
602
         * when creating the reader. If the property followHeaderEncoding is false or not set,
603
         * then the encoding should have not been used when creating the reader, so it must be
604
         * recreated.
605
         *
606
         * @return Project
607
         * @throws UnsupportedEncodingException
608
         *
609
         */
610
        public Project readProject(Reader reader, boolean encodingFollowed) throws UnsupportedEncodingException {
611
                Project proj = null;
612

    
613
                try {
614
                        XmlTag tag = (XmlTag) XmlTag.unmarshal(reader);
615
                        XMLEntity xml=new XMLEntity(tag);
616
                        String VERSION=xml.getStringProperty("VERSION");
617
                        NotificationManager.addInfo(PluginServices.getText(this,"openning_project")+ ": "+xml.getStringProperty("name"));
618

    
619
                        if (encodingFollowed) {
620
                                if (xml.contains("followHeaderEncoding")) {
621
                                        boolean useEncoding = xml.getBooleanProperty("followHeaderEncoding");
622
                                        if (!useEncoding) {
623
                                                throw new UnsupportedEncodingException("the encoding specified in the xml header is not safe");
624
                                        }
625
                                }
626
                                else {
627
                                        // Old projects didn't contain followHeaderEncoding and they were
628
                                        // not correctly encoded. We throw an exception now, and we'll try
629
                                        // to reopen the project
630
                                        // using the default system encoding.
631
                                        throw new UnsupportedEncodingException("the encoding specified in the xml header is not safe");
632
                                }
633
                        }
634

    
635
                        try {
636
                                // if ((VERSION!=null) && (VERSION.equals("0.5") || VERSION.equals("0.4") || (VERSION.indexOf("GISPLANET") != -1))){
637
                                if (VERSION != null) {
638
                                        proj = Project.createFromXML(xml);
639
                                }else{
640
                                        proj = Project.createFromXML03(new XMLEntity(tag));
641
                                }
642
                                NotificationManager.addInfo(PluginServices.getText(this,"opened_project")+ ": "+xml.getStringProperty("name"));
643

    
644
                                return proj;
645
                        } catch (OpenException e){
646
                                e.showError();
647
                                //NotificationManager.addInfo("Al leer el proyecto", e);
648
                        }
649
                }  catch (MarshalException e) {
650
                        PluginServices.getLogger().error(PluginServices.getText(this, "formato_incorrecto"),e);
651
                        JOptionPane.showMessageDialog((Component)PluginServices.getMainFrame(),PluginServices.getText(this, "formato_incorrecto"));
652
                        //NotificationManager.addError("Al leer el proyecto", e);
653
                } catch (ValidationException e) {
654
                        PluginServices.getLogger().error(PluginServices.getText(this, "formato_incorrecto"),e);
655
                        JOptionPane.showMessageDialog((Component)PluginServices.getMainFrame(),PluginServices.getText(this, "formato_incorrecto"));
656
                        //NotificationManager.addError("Al leer el proyecto", e);
657
                }
658
                NotificationManager.addInfo(PluginServices.getText(this,"error_openning_project"));
659

    
660
                return null;
661
        }
662

    
663
        /**
664
         * Devuelve el proyecto.
665
         *
666
         * @return Proyecto.
667
         */
668
        public Project getProject() {
669
                return p;
670
        }
671

    
672
        /**
673
         * @see com.iver.andami.plugins.IExtension#isEnabled()
674
         */
675
        public boolean isEnabled() {
676
                return true;
677
        }
678

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

    
686
        /**
687
         * Sets the project
688
         * @param p
689
         */
690
        public void setProject(Project p){
691
                getProjectFrame().setProject(p);
692
                this.p=p;
693
        }
694

    
695
        private void registerDocuments() {
696
                ProjectViewFactory.register();
697
                ProjectTableFactory.register();
698
                ProjectMapFactory.register();
699
        }
700

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

    
738
        public static String getPath() {
739
                return projectPath;
740
        }
741

    
742
        public static void setPath(String path) {
743
                projectPath = path;
744
        }
745

    
746
        public IWindow getProjectWindow() {
747
                return getProjectFrame();
748
        }
749

    
750

    
751
        public IExtensionStatus getStatus() {
752
                return this;
753
        }
754

    
755
        public boolean hasUnsavedData() {
756
                return p.hasChanged();
757
        }
758

    
759
        public IUnsavedData[] getUnsavedData() {
760
                if (hasUnsavedData()) {
761
                        UnsavedProject data = new UnsavedProject(this);
762
                        IUnsavedData[] dataArray = {data};
763
                        return dataArray;
764
                }
765
                else
766
                        return null;
767
        }
768

    
769
        /**
770
         * Implements the IUnsavedData interface to show unsaved projects
771
         * in the Unsavad Data dialog.
772
         *
773
         * @author Cesar Martinez Izquierdo <cesar.martinez@iver.es>
774
         */
775
        public class UnsavedProject  extends UnsavedData {
776

    
777
                public UnsavedProject(IExtension extension) {
778
                        super(extension);
779
                }
780

    
781
                public String getDescription() {
782
                        if (getPath()==null) {
783
                                return PluginServices.getText(ProjectExtension.this, "Unnamed_new_gvsig_project_");
784
                        }
785
                        else {
786
                                return PluginServices.getText(ProjectExtension.this, "Modified_project_");
787
                        }
788
                }
789

    
790
                public String getResourceName() {
791
                        if (getPath()==null) {
792
                                return PluginServices.getText(ProjectExtension.this, "Unnamed");
793
                        }
794
                        else {
795
                                return getPath();
796
                        }
797

    
798
                }
799

    
800
                public boolean saveData() {
801
                        return guardar();
802
                }
803

    
804
                public ImageIcon getIcon() {
805
                        try {
806
                                URL imagePath = PluginServices.getPluginServices(ProjectExtension.this).getClassLoader().getResource("images/logoGVA.gif");
807
                                return new ImageIcon(imagePath);
808
                        }
809
                        catch (Exception ex) {}
810
                        return null;
811
                }
812
        }
813

    
814
        public IMonitorableTask[] getRunningProcesses() {
815
                // TODO Auto-generated method stub
816
                return null;
817
        }
818
        public boolean hasRunningProcesses() {
819
                // TODO Auto-generated method stub
820
                return false;
821
        }
822

    
823
}