Statistics
| Revision:

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

History | View | Annotate | Download (17.4 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.text.DateFormat;
55
import java.util.Date;
56

    
57
import javax.swing.JFileChooser;
58
import javax.swing.JOptionPane;
59

    
60
import org.exolab.castor.xml.MarshalException;
61
import org.exolab.castor.xml.Marshaller;
62
import org.exolab.castor.xml.ValidationException;
63

    
64
import com.iver.andami.Launcher;
65
import com.iver.andami.PluginServices;
66
import com.iver.andami.messages.Messages;
67
import com.iver.andami.messages.NotificationManager;
68
import com.iver.andami.plugins.Extension;
69
import com.iver.andami.ui.mdiManager.WindowInfo;
70
import com.iver.cit.gvsig.fmap.layers.LayerFactory;
71
import com.iver.cit.gvsig.gui.layout.Layout;
72
import com.iver.cit.gvsig.gui.project.OpenException;
73
import com.iver.cit.gvsig.gui.project.ProjectWindow;
74
import com.iver.cit.gvsig.project.Project;
75
import com.iver.cit.gvsig.project.ProjectFactory;
76
import com.iver.cit.gvsig.project.ProjectMap;
77
import com.iver.cit.gvsig.project.ProjectView;
78
import com.iver.utiles.GenericFileFilter;
79
import com.iver.utiles.XMLEntity;
80
import com.iver.utiles.extensionPoints.ExtensionPoint;
81
import com.iver.utiles.extensionPoints.ExtensionPoints;
82
import com.iver.utiles.extensionPoints.ExtensionPointsSingleton;
83
import com.iver.utiles.xmlEntity.generate.XmlTag;
84

    
85

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

    
108
                LayerFactory.setWritersPath(PluginServices.getPluginServices(this)
109
                                  .getPluginDirectory()
110
                                  .getAbsolutePath() +
111
                                  File.separator + "drivers");
112

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

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

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

    
152
        initilizeDocumentActionsExtensionPoint();
153

    
154
            projectFrame = new ProjectWindow(this);
155
                projectFrame.setProject(p);
156
                showProjectWindow();
157
        }
158

    
159
        /**
160
         * Muestra la ventana con el gestor de proyectos.
161
         */
162
        public void showProjectWindow() {
163
                WindowInfo seedWindowInfo = Project.getSeedProjectWindow();
164
                if (seedWindowInfo!=null) {
165
                        Project.setSeedProjectWindow(null);
166
                        if (!seedWindowInfo.isClosed()) {
167
                                PluginServices.getMDIManager().addWindow(projectFrame);
168
                                PluginServices.getMDIManager().changeWindowInfo(projectFrame, seedWindowInfo);
169
                        }
170
                }
171
                else
172
                        PluginServices.getMDIManager().addWindow(projectFrame);
173
        }
174

    
175
        public XMLEntity getProjectWindowXMLEntity() {
176
                WindowInfo wi = PluginServices.getMDIManager().getWindowInfo(projectFrame);
177
                if (wi!=null) {
178
                        if (wi.checkPersistence())
179
                                return wi.getXMLEntity();
180
                        else // if the window was marked as not persistent, return null (we don't want to save it)
181
                                return null;
182
                }
183
                return null;
184
        }
185

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

    
201
        private boolean guardarDialogo(){
202
                boolean saved=false;
203

    
204
                if (lastSavePath == null)
205
                        lastSavePath = projectPath;
206

    
207
                JFileChooser jfc = new JFileChooser(lastSavePath);
208
                jfc.addChoosableFileFilter(new GenericFileFilter("gvp",
209
                                PluginServices.getText(this, "tipo_fichero_proyecto")));
210

    
211
                if (jfc.showSaveDialog((Component) PluginServices.getMainFrame()) == JFileChooser.APPROVE_OPTION) {
212
                        File file=jfc.getSelectedFile();
213
                        if (!(file.getPath().toLowerCase().endsWith(".gvp"))){
214
                                file=new File(file.getPath()+".gvp");
215
                        }
216
                        saved=writeProject(file, p);
217

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

    
236
                        int res = JOptionPane.showConfirmDialog((Component) PluginServices.getMainFrame(),
237
                                        PluginServices.getText(this, "guardar_cambios"),
238
                                        "gvSIG",
239
                                        JOptionPane.YES_NO_CANCEL_OPTION,
240
                                        JOptionPane.INFORMATION_MESSAGE);
241

    
242
                        if (res == JOptionPane.YES_OPTION) {
243
                                guardar();
244
                        } else if (res == JOptionPane.CANCEL_OPTION) {
245
                                return false;
246
                        }
247
                }
248

    
249
                return true;
250
        }
251

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

    
278
                        JFileChooser jfc = new JFileChooser();
279
                        jfc.addChoosableFileFilter(new GenericFileFilter("gvp",
280
                                        PluginServices.getText(this, "tipo_fichero_proyecto")));
281

    
282
                        if (jfc.showOpenDialog((Component) PluginServices.getMainFrame()) == JFileChooser.APPROVE_OPTION) {
283
                                ProjectView.numViews=0;
284
                ProjectMap.numMaps = 0;
285
                                PluginServices.getMDIManager().closeAllWindows();
286

    
287
                                File projectFile = jfc.getSelectedFile();
288
                                Project o = readProject(projectFile);
289
                                setPath(projectFile.getAbsolutePath());
290
                                if (o != null) {
291
                                        p = o;
292
                                }
293

    
294
                                projectFrame.setProject(p);
295
                                PluginServices.getMainFrame().setTitle(p.getName());
296
                                projectFrame.refreshControls();
297
                                showProjectWindow();
298
                        }
299
                } else if (actionCommand.equals("GUARDAR")) {
300
                        guardar();
301
                } else if (actionCommand.equals("GUARDAR_COMO")) {
302
                        guardarDialogo();
303
                } else if (actionCommand.equals("SALIR")){
304
                        int option = JOptionPane.showConfirmDialog((Component)PluginServices.getMainFrame(),
305
                                        Messages.getString("MDIFrame.quiere_salir"),
306
                                        Messages.getString("MDIFrame.salir"),
307
                                        JOptionPane.YES_NO_OPTION);
308

    
309
                        if (option == JOptionPane.YES_OPTION) {
310
                                Launcher.closeApplication();
311
                        }
312
                } else if (actionCommand.compareTo("OPENTEMPLATE")==0){
313
                        openLayout();
314
                }
315
        }
316
        public void openLayout() {
317
                //Project project = ((ProjectExtension) PluginServices.getExtension(ProjectExtension.class)).getProject();
318
                Layout layout=null;
319
                JFileChooser jfc = new JFileChooser();
320
                jfc.addChoosableFileFilter(new GenericFileFilter("gvt",
321
                                PluginServices.getText(this, "plantilla")));
322

    
323
                if (jfc.showOpenDialog((Component) PluginServices.getMainFrame()) == JFileChooser.APPROVE_OPTION) {
324
                        File file=jfc.getSelectedFile();
325
                        if (!(file.getPath().endsWith(".gvt") || file.getPath().endsWith(".GVT"))){
326
                                file=new File(file.getPath()+".gvt");
327
                        }
328
                        try {
329
                                File xmlFile = new File(file.getAbsolutePath());
330
                                FileReader reader;
331
                                reader = new FileReader(xmlFile);
332

    
333
                                XmlTag tag = (XmlTag) XmlTag.unmarshal(reader);
334
                                try {
335
                                        layout = Layout.createLayout(new XMLEntity(tag),p);
336
                                } catch (OpenException e) {
337
                                        e.showError();
338
                                }
339
                                //fPanelLegendManager.setRenderer(LegendFactory.createFromXML(new XMLEntity(tag)));
340
                        } catch (FileNotFoundException e) {
341
                                NotificationManager.addError(PluginServices.getText(this, "Al_leer_la_leyenda"), e);
342
                        } catch (MarshalException e) {
343
                                NotificationManager.addError(PluginServices.getText(this, "Al_leer_la_leyenda"), e);
344
                        } catch (ValidationException e) {
345
                                NotificationManager.addError(PluginServices.getText(this, "Al_leer_la_leyenda"), e);
346
                        }
347
                        ProjectMap pmap = ProjectFactory.createMap(file.getName());
348
                        pmap.setModel(layout);
349
                        pmap.getModel().setProjectMap(pmap);
350

    
351
                        p.addMap(pmap);
352
                        PluginServices.getMDIManager().addWindow(layout);
353

    
354

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

    
385
                } catch (Exception e) {
386
                        NotificationManager.addError("Error guardando el proyecto", e);
387
                        return false;
388
                }
389
                return true;
390
        }
391

    
392

    
393

    
394
        public Project readProject(String path) {
395
                BufferedReader reader =null;
396
                try {
397
                URL url=null;
398
                        url = new URL(path);
399
                        reader = new BufferedReader(new InputStreamReader(url
400
                        .openStream()));
401
                } catch (MalformedURLException e) {
402
                        File file=new File(path);
403
                        return readProject(file);
404
                } catch (IOException e) {
405
                        e.printStackTrace();
406
                }
407
                Project p=readProject(reader);
408
                ProjectExtension.setPath(path); //p.setPath(null);
409
                return p;
410
        }
411

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

    
446
                try {
447
//                        File xmlFile = new File(file.getAbsolutePath());
448
//                        FileReader reader;
449
//                        reader = new FileReader(xmlFile);
450

    
451

    
452
                        XmlTag tag = (XmlTag) XmlTag.unmarshal(reader);
453
                        XMLEntity xml=new XMLEntity(tag);
454
                        String VERSION=xml.getStringProperty("VERSION");
455

    
456
                        try {
457
                                // if ((VERSION!=null) && (VERSION.equals("0.5") || VERSION.equals("0.4") || (VERSION.indexOf("GISPLANET") != -1))){
458
                                if (VERSION != null) {
459
                                        proj = Project.createFromXML(xml);
460
                                }else{
461
                                        proj = Project.createFromXML03(new XMLEntity(tag));
462
                                }
463
                                return proj;
464
                        } catch (OpenException e){
465
                                e.showError();
466
                                //NotificationManager.addInfo("Al leer el proyecto", e);
467
                        }
468
                }  catch (MarshalException e) {
469
                        JOptionPane.showMessageDialog((Component)PluginServices.getMainFrame(),PluginServices.getText(this, "formato_incorrecto"));
470
                        //NotificationManager.addError("Al leer el proyecto", e);
471
                } catch (ValidationException e) {
472
                        JOptionPane.showMessageDialog((Component)PluginServices.getMainFrame(),PluginServices.getText(this, "formato_incorrecto"));
473
                        //NotificationManager.addError("Al leer el proyecto", e);
474
                }
475
                return null;
476
        }
477

    
478
        /**
479
         * Devuelve el proyecto.
480
         *
481
         * @return Proyecto.
482
         */
483
        public Project getProject() {
484
                return p;
485
        }
486

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

    
494
        /**
495
         * @see com.iver.andami.plugins.IExtension#isVisible()
496
         */
497
        public boolean isVisible() {
498
                return true;
499
        }
500

    
501
        /**
502
         * Sets the project
503
         * @param p
504
         */
505
        public void setProject(Project p){
506
                projectFrame.setProject(p);
507
                this.p=p;
508
        }
509

    
510
        //Finalizar y preguntar si se quiere guardar el proyecto o cancelar.
511
        public void terminate() {
512
                long t1,t2;
513
                t1 = System.currentTimeMillis();
514
                //if (getProject().hasChanged()) {
515
                        int option = JOptionPane.showConfirmDialog((Component)PluginServices.getMainFrame(),PluginServices.getText(this,"guardar_cambios"),
516
                                        PluginServices.getText(this,"guardar_proyecto"),
517
                                        JOptionPane.YES_NO_OPTION);
518

    
519
                        if (option == JOptionPane.YES_OPTION) {
520
                                if (!guardar())
521
                                        terminate();
522
                        }
523
                //}
524
                t2 = System.currentTimeMillis();
525
                System.err.println("ProjectExtension.terminate() " +  (t2-t1) + "milisecs");
526
        }
527

    
528
        private void initilizeDocumentActionsExtensionPoint() {
529
                ExtensionPoints extensionPoints = ExtensionPointsSingleton.getInstance();
530
                if (!extensionPoints.containsKey("DocumentActions_View")) {
531
                        extensionPoints.put(
532
                                new ExtensionPoint(
533
                                        "DocumentActions_View",
534
                                        "Context menu options of the view document list" +
535
                                                " in the project window "+
536
                                                "(register instances of " +
537
                                                "com.iver.cit.gvsig.project.AbstractDocumentContextMenuAction)"
538
                                )
539
                        );
540
                }
541
                if (!extensionPoints.containsKey("DocumentActions_Table")) {
542
                        extensionPoints.put(
543
                                new ExtensionPoint(
544
                                        "DocumentActions_Table",
545
                                        "Context menu options of the table document list" +
546
                                                " in the project window "+
547
                                                "(register instances of " +
548
                                                "com.iver.cit.gvsig.project.AbstractDocumentContextMenuAction)"
549
                                )
550
                        );
551
                }
552
                if (!extensionPoints.containsKey("DocumentActions_Map")) {
553
                        extensionPoints.put(
554
                                new ExtensionPoint(
555
                                        "DocumentActions_Map",
556
                                        "Context menu options of the map document list" +
557
                                                " in the project window "+
558
                                                "(register instances of " +
559
                                                "com.iver.cit.gvsig.project.AbstractDocumentContextMenuAction)"
560
                                )
561
                        );
562
                }
563
        }
564

    
565
        public static String getPath() {
566
                return projectPath;
567
        }
568

    
569
        public static void setPath(String path) {
570
                projectPath = path;
571
        }
572

    
573
}