Statistics
| Revision:

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

History | View | Annotate | Download (18 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.ProjectWindow2;
78
import com.iver.cit.gvsig.project.documents.layout.ProjectMap;
79
import com.iver.cit.gvsig.project.documents.table.ProjectTable;
80
import com.iver.cit.gvsig.project.documents.view.ProjectView;
81
import com.iver.utiles.GenericFileFilter;
82
import com.iver.utiles.XMLEntity;
83
import com.iver.utiles.extensionPoints.ExtensionPoint;
84
import com.iver.utiles.extensionPoints.ExtensionPoints;
85
import com.iver.utiles.extensionPoints.ExtensionPointsSingleton;
86
import com.iver.utiles.xmlEntity.generate.XmlTag;
87

    
88

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

    
112
                LayerFactory.setWritersPath(PluginServices.getPluginServices(this)
113
                                  .getPluginDirectory()
114
                                  .getAbsolutePath() +
115
                                  File.separator + "drivers");
116

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

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

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

    
156
        initilizeDocumentActionsExtensionPoint();
157
        registerDocuments();
158
            //projectFrame = new ProjectWindow(this);
159

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

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

    
194
        private boolean guardarDialogo(){
195
                boolean saved=false;
196
                JFileChooser jfc = new JFileChooser();
197
                jfc.addChoosableFileFilter(new GenericFileFilter("gvp",
198
                                PluginServices.getText(this, "tipo_fichero_proyecto")));
199

    
200
                if (jfc.showSaveDialog((Component) PluginServices.getMainFrame()) == JFileChooser.APPROVE_OPTION) {
201
                        File file=jfc.getSelectedFile();
202
                        if (!(file.getPath().toLowerCase().endsWith(".gvp"))){
203
                                file=new File(file.getPath()+".gvp");
204
                        }
205
                        saved=writeProject(file, p);
206
                        projectFrame.refreshControls();
207
                }
208
                return saved;
209
        }
210
        /**
211
         * Guarda si el proyecto ha sido modificado.
212
         *
213
         * @return True si se ha guardado correctamente.
214
         */
215
        private boolean modificado() {
216
                if (p.isModified()) {
217
                ///if (true) {
218
                        //TODO de momento se queda como modificado siempre menos cuando est? totalmente vacio que se tomar? como no modificado,
219
                        //para poder controlar perfectamente cuando un proyecto ha sido modificado
220
                        //hay que recoger los eventos de cambio de leyenda, cambio de extent, a?adir una capa, etc que se encuentran en FMap.
221

    
222
                        int res = JOptionPane.showConfirmDialog((Component) PluginServices.getMainFrame(),
223
                                        PluginServices.getText(this, "guardar_cambios"),
224
                                        "gvSIG",
225
                                        JOptionPane.YES_NO_CANCEL_OPTION,
226
                                        JOptionPane.INFORMATION_MESSAGE);
227

    
228
                        if (res == JOptionPane.YES_OPTION) {
229
                                guardar();
230
                        } else if (res == JOptionPane.CANCEL_OPTION) {
231
                                return false;
232
                        }
233
                }
234

    
235
                return true;
236
        }
237

    
238
        /**
239
         * @see com.iver.mdiApp.plugins.IExtension#updateUI(java.lang.String)
240
         */
241
        public void execute(String actionCommand) {
242
                if (actionCommand.equals("NUEVO")) {
243
                        //Si est? modificado se pregunta si se quiere guardar el anterior
244
                        if (!modificado()) {
245
                                return;
246
                        }
247
                        ProjectView.numViews=0;
248
            ProjectMap.numMaps = 0;
249
                        PluginServices.getMDIManager().closeAllWindows();
250
                        p = ProjectFactory.createProject();
251
                        p.setName(PluginServices.getText(this, "untitled"));
252
                        p.setModified(false);
253
                        projectFrame.setProject(p);
254
                        showProjectWindow();
255
                        PluginServices.getMainFrame().setTitle(PluginServices.getText(this, "sin_titulo"));
256
                } else if (actionCommand.equals("ABRIR")) {
257
                        //Si est? modificado se pregunta si se quiere guardar el anterior
258
                        if (!modificado()) {
259
                                ProjectView.numViews=0;
260
                ProjectMap.numMaps = 0;
261
                                return;
262
                        }
263

    
264
                        if (lastPath == null) {
265
                                Preferences prefs = Preferences.userRoot().node( "gvsig.foldering" );
266
                                lastPath = prefs.get("ProjectsFolder", null);
267
                        }
268

    
269
                        JFileChooser jfc = new JFileChooser(lastPath);
270
                        jfc.addChoosableFileFilter(new GenericFileFilter("gvp",
271
                                        PluginServices.getText(this, "tipo_fichero_proyecto")));
272

    
273
                        if (jfc.showOpenDialog((Component) PluginServices.getMainFrame()) == JFileChooser.APPROVE_OPTION) {
274
                                ProjectView.numViews=0;
275
                ProjectMap.numMaps = 0;
276
                                PluginServices.getMDIManager().closeAllWindows();
277

    
278
                                File projectFile = jfc.getSelectedFile();
279
                                Project o = readProject(projectFile);
280
                                setPath(projectFile.getAbsolutePath());
281
                                lastPath = getPath();
282
                                if (o != null) {
283
                                        p = o;
284
                                }
285

    
286
                                projectFrame.setProject(p);
287
                                PluginServices.getMainFrame().setTitle(p.getName());
288
                                projectFrame.refreshControls();
289
                                showProjectWindow();
290
                        }
291
                } else if (actionCommand.equals("GUARDAR")) {
292
                        guardar();
293
                } else if (actionCommand.equals("GUARDAR_COMO")) {
294
                        guardarDialogo();
295
                } else if (actionCommand.equals("SALIR")){
296
                        int option = JOptionPane.showConfirmDialog((Component)PluginServices.getMainFrame(),
297
                                        Messages.getString("MDIFrame.quiere_salir"),
298
                                        Messages.getString("MDIFrame.salir"),
299
                                        JOptionPane.YES_NO_OPTION);
300

    
301
                        if (option == JOptionPane.YES_OPTION) {
302
                                Launcher.closeApplication();
303
                        }
304
                } else if (actionCommand.compareTo("OPENTEMPLATE")==0){
305
                        openLayout();
306
                }
307
        }
308
        public void openLayout() {
309
                //Project project = ((ProjectExtension) PluginServices.getExtension(ProjectExtension.class)).getProject();
310
                Layout layout=null;
311
                JFileChooser jfc = new JFileChooser();
312
                jfc.addChoosableFileFilter(new GenericFileFilter("gvt",
313
                                PluginServices.getText(this, "plantilla")));
314

    
315
                if (jfc.showOpenDialog((Component) PluginServices.getMainFrame()) == JFileChooser.APPROVE_OPTION) {
316
                        File file=jfc.getSelectedFile();
317
                        if (!(file.getPath().endsWith(".gvt") || file.getPath().endsWith(".GVT"))){
318
                                file=new File(file.getPath()+".gvt");
319
                        }
320
                        try {
321
                                File xmlFile = new File(file.getAbsolutePath());
322
                                FileReader reader;
323
                                reader = new FileReader(xmlFile);
324

    
325
                                XmlTag tag = (XmlTag) XmlTag.unmarshal(reader);
326
                                try {
327
                                        layout = Layout.createLayout(new XMLEntity(tag),p);
328
                                } catch (OpenException e) {
329
                                        e.showError();
330
                                }
331
                                //fPanelLegendManager.setRenderer(LegendFactory.createFromXML(new XMLEntity(tag)));
332
                        } catch (FileNotFoundException e) {
333
                                NotificationManager.addError(PluginServices.getText(this, "Al_leer_la_leyenda"), e);
334
                        } catch (MarshalException e) {
335
                                NotificationManager.addError(PluginServices.getText(this, "Al_leer_la_leyenda"), e);
336
                        } catch (ValidationException e) {
337
                                NotificationManager.addError(PluginServices.getText(this, "Al_leer_la_leyenda"), e);
338
                        }
339
                        ProjectMap pmap = ProjectFactory.createMap(file.getName());
340
                        pmap.setModel(layout);
341
                        pmap.getModel().setProjectMap(pmap);
342
                        p.addDocument(pmap);
343
                        PluginServices.getMDIManager().addWindow(layout);
344

    
345

    
346
                }
347
        }
348
        /**
349
         * Escribe el proyecto en XML.
350
         *
351
         * @param file Fichero.
352
         * @param p Proyecto.
353
         */
354
        public boolean writeProject(File file, Project p) {
355
                if( file.exists()){
356
                        int resp = JOptionPane.showConfirmDialog(
357
                                        (Component) PluginServices.getMainFrame(),PluginServices.getText(this,"fichero_ya_existe_seguro_desea_guardarlo"),
358
                                        PluginServices.getText(this,"guardar"), JOptionPane.YES_NO_OPTION);
359
                        if (resp != JOptionPane.YES_OPTION) {
360
                                return false;
361
                        }
362
                }
363
                // write it out as XML
364
                try {
365
                        FileWriter writer = new FileWriter(file.getAbsolutePath());
366
                        Marshaller m = new Marshaller(writer);
367
                        m.setEncoding("ISO-8859-1");
368
                        p.setName(file.getName());
369
                        // p.setPath(file.toString());
370
                        p.setModificationDate(DateFormat.getDateInstance().format(new Date()));
371
                        p.setModified(false);
372
                        m.marshal(p.getXMLEntity().getXmlTag());
373
                        PluginServices.getMainFrame().setTitle(file.getName());
374
                        setPath(file.toString());
375

    
376
                } catch (Exception e) {
377
                        NotificationManager.addError("Error guardando el proyecto", e);
378
                        return false;
379
                }
380
                return true;
381
        }
382

    
383

    
384

    
385
        public Project readProject(String path) {
386
                BufferedReader reader =null;
387
                try {
388
                URL url=null;
389
                        url = new URL(path);
390
                        reader = new BufferedReader(new InputStreamReader(url
391
                        .openStream()));
392
                } catch (MalformedURLException e) {
393
                        File file=new File(path);
394
                        return readProject(file);
395
                } catch (IOException e) {
396
                        e.printStackTrace();
397
                }
398
                Project p=readProject(reader);
399
                ProjectExtension.setPath(path); //p.setPath(null);
400
                return p;
401
        }
402

    
403
        public Project readProject(File file) {
404
                File xmlFile = new File(file.getAbsolutePath());
405
                FileReader reader=null;
406
                try {
407
                        reader = new FileReader(xmlFile);
408
                } catch (FileNotFoundException e) {
409
                        JOptionPane.showMessageDialog((Component)PluginServices.getMainFrame(),PluginServices.getText(this, "fichero_incorrecto"));
410
                        return null;
411
                }
412
                return readProject(reader);
413
                }
414
        /**
415
         * Lee del XML el proyecto.<br><br>
416
         *
417
         * Reads the XML of the project.<br>
418
         * 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
419
         * linked to the window you must to set this object to the extension:<br>
420
         *
421
         * <b>Example:</b><br>
422
         *
423
         * ...<br>
424
         * ...<br>
425
         * Project p = ProjectExtension.readProject(projectFile);<br>
426
         * ProjectExtension.setProject(p);
427
         * ...<br>
428
         * ...<br>
429
         * @param file Fichero.
430
         *
431
         * @return Project
432
         *
433
         */
434
        public Project readProject(Reader reader) {
435
                Project proj = null;
436

    
437
                try {
438
//                        File xmlFile = new File(file.getAbsolutePath());
439
//                        FileReader reader;
440
//                        reader = new FileReader(xmlFile);
441

    
442

    
443
                        XmlTag tag = (XmlTag) XmlTag.unmarshal(reader);
444
                        XMLEntity xml=new XMLEntity(tag);
445
                        String VERSION=xml.getStringProperty("VERSION");
446

    
447
                        try {
448
                                // if ((VERSION!=null) && (VERSION.equals("0.5") || VERSION.equals("0.4") || (VERSION.indexOf("GISPLANET") != -1))){
449
                                if (VERSION != null) {
450
                                        proj = Project.createFromXML(xml);
451
                                }else{
452
                                        proj = Project.createFromXML03(new XMLEntity(tag));
453
                                }
454
                                return proj;
455
                        } catch (OpenException e){
456
                                e.showError();
457
                                //NotificationManager.addInfo("Al leer el proyecto", e);
458
                        }
459
                }  catch (MarshalException e) {
460
                        JOptionPane.showMessageDialog((Component)PluginServices.getMainFrame(),PluginServices.getText(this, "formato_incorrecto"));
461
                        //NotificationManager.addError("Al leer el proyecto", e);
462
                } catch (ValidationException e) {
463
                        JOptionPane.showMessageDialog((Component)PluginServices.getMainFrame(),PluginServices.getText(this, "formato_incorrecto"));
464
                        //NotificationManager.addError("Al leer el proyecto", e);
465
                }
466
                return null;
467
        }
468

    
469
        /**
470
         * Devuelve el proyecto.
471
         *
472
         * @return Proyecto.
473
         */
474
        public Project getProject() {
475
                return p;
476
        }
477

    
478
        /**
479
         * @see com.iver.andami.plugins.IExtension#isEnabled()
480
         */
481
        public boolean isEnabled() {
482
                return true;
483
        }
484

    
485
        /**
486
         * @see com.iver.andami.plugins.IExtension#isVisible()
487
         */
488
        public boolean isVisible() {
489
                return true;
490
        }
491

    
492
        /**
493
         * Sets the project
494
         * @param p
495
         */
496
        public void setProject(Project p){
497
                projectFrame.setProject(p);
498
                this.p=p;
499
        }
500

    
501
        //Finalizar y preguntar si se quiere guardar el proyecto o cancelar.
502
        public void terminate() {
503
                long t1,t2;
504
                t1 = System.currentTimeMillis();
505
                //if (getProject().hasChanged()) {
506
                        int option = JOptionPane.showConfirmDialog((Component)PluginServices.getMainFrame(),PluginServices.getText(this,"guardar_cambios"),
507
                                        PluginServices.getText(this,"guardar_proyecto"),
508
                                        JOptionPane.YES_NO_OPTION);
509

    
510
                        if (option == JOptionPane.YES_OPTION) {
511
                                if (!guardar())
512
                                        terminate();
513
                        }
514
                //}
515
                t2 = System.currentTimeMillis();
516
                System.err.println("ProjectExtension.terminate() " +  (t2-t1) + "milisecs");
517
        }
518

    
519
        private void registerDocuments() {
520
                ProjectDocument.register("ProjectView",
521
                                ProjectView.class);
522
                ProjectDocument.register("ProjectTable",
523
                                ProjectTable.class);
524
                ProjectDocument.register("ProjectMap",
525
                                ProjectMap.class);
526
                ExtensionPoints extensionPoints = ExtensionPointsSingleton.getInstance();
527
                ExtensionPoint extPoint=((ExtensionPoint)extensionPoints.get("Documents"));
528
                try {
529
                        extPoint.addAlias("ProjectView","com.iver.cit.gvsig.project.ProjectView");
530
                        extPoint.addAlias("ProjectTable","com.iver.cit.gvsig.project.ProjectTable");
531
                        extPoint.addAlias("ProjectMap","com.iver.cit.gvsig.project.ProjectMap");
532
                } catch (KeyException e) {
533
                        e.printStackTrace();
534
                }
535

    
536

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

    
575
        public static String getPath() {
576
                return projectPath;
577
        }
578

    
579
        public static void setPath(String path) {
580
                projectPath = path;
581
        }
582

    
583
}