Statistics
| Revision:

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

History | View | Annotate | Download (18.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.FileNotFoundException;
47
import java.io.FileReader;
48
import java.io.FileWriter;
49
import java.io.IOException;
50
import java.io.InputStreamReader;
51
import java.io.Reader;
52
import java.net.MalformedURLException;
53
import java.net.URL;
54
import java.security.KeyException;
55
import java.text.DateFormat;
56
import java.util.Date;
57
import java.util.prefs.Preferences;
58

    
59
import javax.swing.JFileChooser;
60
import javax.swing.JOptionPane;
61

    
62
import org.exolab.castor.xml.MarshalException;
63
import org.exolab.castor.xml.Marshaller;
64
import org.exolab.castor.xml.ValidationException;
65

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

    
91

    
92
/**
93
 * Extension que proporciona controles para crear proyectos nuevos, abrirlos y
94
 * guardarlos. Adem?s los tipos de tabla que soporta el proyecto son a?adidos
95
 * en esta clase.
96
 *
97
 * @author Fernando Gonz?lez Cort?s
98
 */
99
public class ProjectExtension extends Extension {
100
        private static String projectPath = null;
101
        //private ProjectWindow projectFrame;
102
        private ProjectWindow projectFrame;
103
        private Project p;
104
        private String lastPath;
105
        private String lastSavePath;
106
        private String templatesPath;
107
        /**
108
         * @see com.iver.mdiApp.plugins.IExtension#initialize()
109
         */
110
        public void initialize() {
111
            try {
112
            Class.forName("javax.media.jai.EnumeratedParameter");
113
        } catch (ClassNotFoundException e) {
114
            NotificationManager.addError("La m?quina virtual con la que se ejecuta gvSIG no tiene JAI instalado", e);
115
        }
116

    
117
                LayerFactory.setWritersPath(PluginServices.getPluginServices(this)
118
                                  .getPluginDirectory()
119
                                  .getAbsolutePath() +
120
                                  File.separator + "drivers");
121

    
122
        LayerFactory.setDriversPath(PluginServices.getPluginServices(this)
123
                                  .getPluginDirectory()
124
                                  .getAbsolutePath() +
125
                                  File.separator + "drivers");
126

    
127
        // Recuperamos el ?ltimo argumento, que se supone
128
        // que ser? el fichero .gvp que queremos abrir.
129
        // (por enmedio pueden venir o no otros argumentos,
130
        // por ejemplo el idioma)
131
        // TODO: Aqu? Jaume podr?a meter lo del backup del proyecto
132
        // que ha hecho para ValenciaUrban?stica
133

    
134
                /*
135
                pe = (ProjectExtension) PluginServices.getExtension(com.iver.cit.gvsig.ProjectExtension.class);
136
                if (projectFile.length()!=0){
137
                        p=pe.readProject(projectFile);
138
                }
139
                else
140
                        p = restorePreviousProject();
141
                pe.setProject(p); */
142
        String[] theArgs = PluginServices.getArguments();
143
        String lastArg = theArgs[theArgs.length-1];
144
        if ((lastArg.endsWith(".gvp")) ||
145
                        (lastArg.endsWith(".GVP")))
146
        {
147
                PluginServices.getLogger().debug("Intentando cargar el proyecto " + lastArg);
148
                //File projectFile = new File(lastArg);
149
                p = readProject(lastArg);
150
                PluginServices.getMainFrame().setTitle(p.getName());
151
                projectPath = lastArg;
152
        }
153
        else
154
        {
155
                        p = ProjectFactory.createProject();
156
                        p.setName(PluginServices.getText(this, "untitled"));
157
                        p.setModified(false);
158
                        PluginServices.getMainFrame().setTitle(PluginServices.getText(this, "sin_titulo"));
159
        }
160

    
161
        initilizeDocumentActionsExtensionPoint();
162
        registerDocuments();
163
            //projectFrame = new ProjectWindow(this);
164

    
165
        }
166
        /**
167
         * @see com.iver.mdiApp.plugins.IExtension#postInitialize()
168
         */
169
        public void postInitialize() {
170
                projectFrame = new ProjectWindow();
171
                projectFrame.setProject(p);
172
                showProjectWindow();
173
        }
174
        /**
175
         * Muestra la ventana con el gestor de proyectos.
176
         */
177
        public void showProjectWindow() {
178
                PluginServices.getMDIManager().addWindow(projectFrame);
179
                if (Project.getSeedProjectWindow()!=null) {
180
                        PluginServices.getMDIManager().changeWindowInfo(projectFrame, Project.getSeedProjectWindow());
181
                }
182
        }
183

    
184
        /**
185
         * Guarda el proyecto actual en disco.
186
         */
187
        private boolean guardar() {
188
                boolean saved=false;
189
//                if (p.getPath() == null) {
190
                if (projectPath == null) {
191
                        saved=guardarDialogo();
192
                } else {
193
                        saved=writeProject(new File(projectPath), p); //new File(p.getPath()), p);
194
                        projectFrame.refreshControls();
195
                }
196
                return saved;
197
        }
198

    
199
        private boolean guardarDialogo(){
200
                boolean saved=false;
201

    
202
                if (lastSavePath == null)
203
                        lastSavePath = projectPath;
204

    
205
                if (lastSavePath == null) {
206
                        Preferences prefs = Preferences.userRoot().node( "gvsig.foldering" );
207
                        lastSavePath = prefs.get("ProjectsFolder", null);
208
                }
209

    
210
                JFileChooser jfc = new JFileChooser(lastSavePath);
211
                jfc.addChoosableFileFilter(new GenericFileFilter("gvp",
212
                                PluginServices.getText(this, "tipo_fichero_proyecto")));
213

    
214
                if (jfc.showSaveDialog((Component) PluginServices.getMainFrame()) == JFileChooser.APPROVE_OPTION) {
215
                        File file=jfc.getSelectedFile();
216
                        if (!(file.getPath().toLowerCase().endsWith(".gvp"))){
217
                                file=new File(file.getPath()+".gvp");
218
                        }
219
                        saved=writeProject(file, p);
220
                        String filePath = file.getAbsolutePath();
221
                        lastSavePath = filePath.substring(0, filePath.lastIndexOf(File.separatorChar));
222

    
223
                        projectFrame.refreshControls();
224
                }
225
                return saved;
226
        }
227
        /**
228
         * Guarda si el proyecto ha sido modificado.
229
         *
230
         * @return True si se ha guardado correctamente.
231
         */
232
        private boolean modificado() {
233
                if (p.isModified()) {
234
                ///if (true) {
235
                        //TODO de momento se queda como modificado siempre menos cuando est? totalmente vacio que se tomar? como no modificado,
236
                        //para poder controlar perfectamente cuando un proyecto ha sido modificado
237
                        //hay que recoger los eventos de cambio de leyenda, cambio de extent, a?adir una capa, etc que se encuentran en FMap.
238

    
239
                        int res = JOptionPane.showConfirmDialog((Component) PluginServices.getMainFrame(),
240
                                        PluginServices.getText(this, "guardar_cambios"),
241
                                        "gvSIG",
242
                                        JOptionPane.YES_NO_CANCEL_OPTION,
243
                                        JOptionPane.INFORMATION_MESSAGE);
244

    
245
                        if (res == JOptionPane.YES_OPTION) {
246
                                guardar();
247
                        } else if (res == JOptionPane.CANCEL_OPTION) {
248
                                return false;
249
                        }
250
                }
251

    
252
                return true;
253
        }
254

    
255
        /**
256
         * @see com.iver.mdiApp.plugins.IExtension#updateUI(java.lang.String)
257
         */
258
        public void execute(String actionCommand) {
259
                if (actionCommand.equals("NUEVO")) {
260
                        //Si est? modificado se pregunta si se quiere guardar el anterior
261
                        if (!modificado()) {
262
                                return;
263
                        }
264
                        ProjectView.numViews=0;
265
            ProjectMap.numMaps = 0;
266
                        PluginServices.getMDIManager().closeAllWindows();
267
                        p = ProjectFactory.createProject();
268
                        p.setName(PluginServices.getText(this, "untitled"));
269
                        p.setModified(false);
270
                        projectFrame.setProject(p);
271
                        showProjectWindow();
272
                        PluginServices.getMainFrame().setTitle(PluginServices.getText(this, "sin_titulo"));
273
                } else if (actionCommand.equals("ABRIR")) {
274
                        //Si est? modificado se pregunta si se quiere guardar el anterior
275
                        if (!modificado()) {
276
                                ProjectView.numViews=0;
277
                ProjectMap.numMaps = 0;
278
                                return;
279
                        }
280

    
281
                        if (lastPath == null) {
282
                                Preferences prefs = Preferences.userRoot().node( "gvsig.foldering" );
283
                                lastPath = prefs.get("ProjectsFolder", null);
284
                        }
285

    
286
                        JFileChooser jfc = new JFileChooser(lastPath);
287
                        jfc.addChoosableFileFilter(new GenericFileFilter("gvp",
288
                                        PluginServices.getText(this, "tipo_fichero_proyecto")));
289

    
290
                        if (jfc.showOpenDialog((Component) PluginServices.getMainFrame()) == JFileChooser.APPROVE_OPTION) {
291
                                ProjectView.numViews=0;
292
                ProjectMap.numMaps = 0;
293
                                PluginServices.getMDIManager().closeAllWindows();
294

    
295
                                File projectFile = jfc.getSelectedFile();
296
                                Project o = readProject(projectFile);
297
                                setPath(projectFile.getAbsolutePath());
298
                                lastPath = getPath();
299
                                if (o != null) {
300
                                        p = o;
301
                                }
302

    
303
                                projectFrame.setProject(p);
304
                                PluginServices.getMainFrame().setTitle(p.getName());
305
                                projectFrame.refreshControls();
306
                                showProjectWindow();
307
                        }
308
                } else if (actionCommand.equals("GUARDAR")) {
309
                        guardar();
310
                } else if (actionCommand.equals("GUARDAR_COMO")) {
311
                        guardarDialogo();
312
                } else if (actionCommand.equals("SALIR")){
313
                        int option = JOptionPane.showConfirmDialog((Component)PluginServices.getMainFrame(),
314
                                        Messages.getString("MDIFrame.quiere_salir"),
315
                                        Messages.getString("MDIFrame.salir"),
316
                                        JOptionPane.YES_NO_OPTION);
317

    
318
                        if (option == JOptionPane.YES_OPTION) {
319
                                Launcher.closeApplication();
320
                        }
321
                } else if (actionCommand.compareTo("OPENTEMPLATE")==0){
322
                        openLayout();
323
                }
324
        }
325
        public void openLayout() {
326
                //Project project = ((ProjectExtension) PluginServices.getExtension(ProjectExtension.class)).getProject();
327
                Layout layout=null;
328

    
329
                if (templatesPath == null) {
330
                        Preferences prefs = Preferences.userRoot().node( "gvsig.foldering" );
331
                        templatesPath = prefs.get("TemplatesFolder", null);
332
                }
333

    
334
                JFileChooser jfc = new JFileChooser(templatesPath);
335
                jfc.addChoosableFileFilter(new GenericFileFilter("gvt",
336
                                PluginServices.getText(this, "plantilla")));
337

    
338
                if (jfc.showOpenDialog((Component) PluginServices.getMainFrame()) == JFileChooser.APPROVE_OPTION) {
339
                        File file=jfc.getSelectedFile();
340
                        if (!(file.getPath().endsWith(".gvt") || file.getPath().endsWith(".GVT"))){
341
                                file=new File(file.getPath()+".gvt");
342
                        }
343
                        try {
344
                                File xmlFile = new File(file.getAbsolutePath());
345
                                FileReader reader;
346
                                reader = new FileReader(xmlFile);
347

    
348
                                XmlTag tag = (XmlTag) XmlTag.unmarshal(reader);
349
                                try {
350
                                        layout = Layout.createLayout(new XMLEntity(tag),p);
351
                                } catch (OpenException e) {
352
                                        e.showError();
353
                                }
354
                                //fPanelLegendManager.setRenderer(LegendFactory.createFromXML(new XMLEntity(tag)));
355
                        } catch (FileNotFoundException e) {
356
                                NotificationManager.addError(PluginServices.getText(this, "Al_leer_la_leyenda"), e);
357
                        } catch (MarshalException e) {
358
                                NotificationManager.addError(PluginServices.getText(this, "Al_leer_la_leyenda"), e);
359
                        } catch (ValidationException e) {
360
                                NotificationManager.addError(PluginServices.getText(this, "Al_leer_la_leyenda"), e);
361
                        }
362
                        ProjectMap pmap = ProjectFactory.createMap(file.getName());
363
                        pmap.setModel(layout);
364
                        pmap.getModel().setProjectMap(pmap);
365
                        p.addDocument(pmap);
366
                        PluginServices.getMDIManager().addWindow(layout);
367

    
368

    
369
                }
370
        }
371
        /**
372
         * Escribe el proyecto en XML.
373
         *
374
         * @param file Fichero.
375
         * @param p Proyecto.
376
         */
377
        public boolean writeProject(File file, Project p) {
378
                if( file.exists()){
379
                        int resp = JOptionPane.showConfirmDialog(
380
                                        (Component) PluginServices.getMainFrame(),PluginServices.getText(this,"fichero_ya_existe_seguro_desea_guardarlo"),
381
                                        PluginServices.getText(this,"guardar"), JOptionPane.YES_NO_OPTION);
382
                        if (resp != JOptionPane.YES_OPTION) {
383
                                return false;
384
                        }
385
                }
386
                // write it out as XML
387
                try {
388
                        FileWriter writer = new FileWriter(file.getAbsolutePath());
389
                        Marshaller m = new Marshaller(writer);
390
                        m.setEncoding("ISO-8859-1");
391
                        p.setName(file.getName());
392
                        // p.setPath(file.toString());
393
                        p.setModificationDate(DateFormat.getDateInstance().format(new Date()));
394
                        p.setModified(false);
395
                        m.marshal(p.getXMLEntity().getXmlTag());
396
                        PluginServices.getMainFrame().setTitle(file.getName());
397
                        setPath(file.toString());
398

    
399
                } catch (Exception e) {
400
                        NotificationManager.addError("Error guardando el proyecto", e);
401
                        return false;
402
                }
403
                return true;
404
        }
405

    
406

    
407

    
408
        public Project readProject(String path) {
409
                BufferedReader reader =null;
410
                try {
411
                URL url=null;
412
                        url = new URL(path);
413
                        reader = new BufferedReader(new InputStreamReader(url
414
                        .openStream()));
415
                } catch (MalformedURLException e) {
416
                        File file=new File(path);
417
                        return readProject(file);
418
                } catch (IOException e) {
419
                        e.printStackTrace();
420
                }
421
                Project p=readProject(reader);
422
                ProjectExtension.setPath(path); //p.setPath(null);
423
                return p;
424
        }
425

    
426
        public Project readProject(File file) {
427
                File xmlFile = new File(file.getAbsolutePath());
428
                FileReader reader=null;
429
                try {
430
                        reader = new FileReader(xmlFile);
431
                } catch (FileNotFoundException e) {
432
                        JOptionPane.showMessageDialog((Component)PluginServices.getMainFrame(),PluginServices.getText(this, "fichero_incorrecto"));
433
                        return null;
434
                }
435
                return readProject(reader);
436
                }
437
        /**
438
         * Lee del XML el proyecto.<br><br>
439
         *
440
         * Reads the XML of the project.<br>
441
         * It returns n project object holding all needed info that is not linked to the Project Dialog. <br>In case you want the project to be
442
         * linked to the window you must to set this object to the extension:<br>
443
         *
444
         * <b>Example:</b><br>
445
         *
446
         * ...<br>
447
         * ...<br>
448
         * Project p = ProjectExtension.readProject(projectFile);<br>
449
         * ProjectExtension.setProject(p);
450
         * ...<br>
451
         * ...<br>
452
         * @param file Fichero.
453
         *
454
         * @return Project
455
         *
456
         */
457
        public Project readProject(Reader reader) {
458
                Project proj = null;
459

    
460
                try {
461
//                        File xmlFile = new File(file.getAbsolutePath());
462
//                        FileReader reader;
463
//                        reader = new FileReader(xmlFile);
464

    
465

    
466
                        XmlTag tag = (XmlTag) XmlTag.unmarshal(reader);
467
                        XMLEntity xml=new XMLEntity(tag);
468
                        String VERSION=xml.getStringProperty("VERSION");
469

    
470
                        try {
471
                                // if ((VERSION!=null) && (VERSION.equals("0.5") || VERSION.equals("0.4") || (VERSION.indexOf("GISPLANET") != -1))){
472
                                if (VERSION != null) {
473
                                        proj = Project.createFromXML(xml);
474
                                }else{
475
                                        proj = Project.createFromXML03(new XMLEntity(tag));
476
                                }
477
                                return proj;
478
                        } catch (OpenException e){
479
                                e.showError();
480
                                //NotificationManager.addInfo("Al leer el proyecto", e);
481
                        }
482
                }  catch (MarshalException e) {
483
                        JOptionPane.showMessageDialog((Component)PluginServices.getMainFrame(),PluginServices.getText(this, "formato_incorrecto"));
484
                        //NotificationManager.addError("Al leer el proyecto", e);
485
                } catch (ValidationException e) {
486
                        JOptionPane.showMessageDialog((Component)PluginServices.getMainFrame(),PluginServices.getText(this, "formato_incorrecto"));
487
                        //NotificationManager.addError("Al leer el proyecto", e);
488
                }
489
                return null;
490
        }
491

    
492
        /**
493
         * Devuelve el proyecto.
494
         *
495
         * @return Proyecto.
496
         */
497
        public Project getProject() {
498
                return p;
499
        }
500

    
501
        /**
502
         * @see com.iver.andami.plugins.IExtension#isEnabled()
503
         */
504
        public boolean isEnabled() {
505
                return true;
506
        }
507

    
508
        /**
509
         * @see com.iver.andami.plugins.IExtension#isVisible()
510
         */
511
        public boolean isVisible() {
512
                return true;
513
        }
514

    
515
        /**
516
         * Sets the project
517
         * @param p
518
         */
519
        public void setProject(Project p){
520
                projectFrame.setProject(p);
521
                this.p=p;
522
        }
523

    
524
        //Finalizar y preguntar si se quiere guardar el proyecto o cancelar.
525
        public void terminate() {
526
                long t1,t2;
527
                t1 = System.currentTimeMillis();
528
                //if (getProject().hasChanged()) {
529
                        int option = JOptionPane.showConfirmDialog((Component)PluginServices.getMainFrame(),PluginServices.getText(this,"guardar_cambios"),
530
                                        PluginServices.getText(this,"guardar_proyecto"),
531
                                        JOptionPane.YES_NO_OPTION);
532

    
533
                        if (option == JOptionPane.YES_OPTION) {
534
                                if (!guardar())
535
                                        terminate();
536
                        }
537
                //}
538
                t2 = System.currentTimeMillis();
539
                System.err.println("ProjectExtension.terminate() " +  (t2-t1) + "milisecs");
540
        }
541

    
542
        private void registerDocuments() {
543
                ProjectViewFactory.register();
544
                ProjectTableFactory.register();
545
                ProjectMapFactory.register();
546
        }
547
        private void initilizeDocumentActionsExtensionPoint() {
548
                ExtensionPoints extensionPoints = ExtensionPointsSingleton.getInstance();
549
                if (!extensionPoints.containsKey("DocumentActions_View")) {
550
                        extensionPoints.put(
551
                                new ExtensionPoint(
552
                                        "DocumentActions_View",
553
                                        "Context menu options of the view document list" +
554
                                                " in the project window "+
555
                                                "(register instances of " +
556
                                                "com.iver.cit.gvsig.project.AbstractDocumentContextMenuAction)"
557
                                )
558
                        );
559
                }
560
                if (!extensionPoints.containsKey("DocumentActions_Table")) {
561
                        extensionPoints.put(
562
                                new ExtensionPoint(
563
                                        "DocumentActions_Table",
564
                                        "Context menu options of the table document list" +
565
                                                " in the project window "+
566
                                                "(register instances of " +
567
                                                "com.iver.cit.gvsig.project.AbstractDocumentContextMenuAction)"
568
                                )
569
                        );
570
                }
571
                if (!extensionPoints.containsKey("DocumentActions_Map")) {
572
                        extensionPoints.put(
573
                                new ExtensionPoint(
574
                                        "DocumentActions_Map",
575
                                        "Context menu options of the map document list" +
576
                                                " in the project window "+
577
                                                "(register instances of " +
578
                                                "com.iver.cit.gvsig.project.AbstractDocumentContextMenuAction)"
579
                                )
580
                        );
581
                }
582
        }
583

    
584
        public static String getPath() {
585
                return projectPath;
586
        }
587

    
588
        public static void setPath(String path) {
589
                projectPath = path;
590
        }
591

    
592
}