Statistics
| Revision:

svn-gvsig-desktop / tags / v10_RC2c / applications / appgvSIG / src / com / iver / cit / gvsig / ProjectExtension.java @ 8745

History | View | Annotate | Download (18.1 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
import java.util.prefs.Preferences;
57

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

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

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

    
87

    
88
/**
89
 * Extension que proporciona controles para crear proyectos nuevos, abrirlos y
90
 * guardarlos. Adem?s los tipos de tabla que soporta el proyecto son a?adidos
91
 * en esta clase.
92
 *
93
 * @author Fernando Gonz?lez Cort?s
94
 */
95
public class ProjectExtension extends Extension {
96
        private static String projectPath = null;
97
        private ProjectWindow projectFrame;
98
        private Project p;
99
        private String lastPath;
100
        private String lastSavePath;
101
        private String templatesPath;
102

    
103
        /**
104
         * @see com.iver.mdiApp.plugins.IExtension#initialize()
105
         */
106
        public void initialize() {
107
            try {
108
            Class.forName("javax.media.jai.EnumeratedParameter");
109
        } catch (ClassNotFoundException e) {
110
            NotificationManager.addError("La m?quina virtual con la que se ejecuta gvSIG no tiene JAI instalado", e);
111
        }
112

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

    
118
        LayerFactory.setDriversPath(PluginServices.getPluginServices(this)
119
                                  .getPluginDirectory()
120
                                  .getAbsolutePath() +
121
                                  File.separator + "drivers");
122
        
123
            projectFrame = new ProjectWindow(this);
124

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

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

    
159
        initilizeDocumentActionsExtensionPoint();
160
                projectFrame.setProject(p);
161
                
162
        if (!(lastArg.endsWith(".gvp") || // if we are not opening a project, show the project manager window
163
                        lastArg.endsWith(".GVP")))
164
        {
165
                showProjectWindow();
166
        }
167
        }
168

    
169
        /**
170
         * Muestra la ventana con el gestor de proyectos.
171
         */
172
        public void showProjectWindow() {
173
                WindowInfo seedWindowInfo = p.getSeedProjectWindow();
174
                if (seedWindowInfo!=null) {
175
                        if (seedWindowInfo.isClosed()) {
176
                                // if it was closed, we just don't open the window now
177
                                seedWindowInfo.setClosed(false);
178
                                return;
179
                        }
180
                        p.setSeedProjectWindow(null);
181
                        PluginServices.getMDIManager().addWindow(projectFrame);
182
                        PluginServices.getMDIManager().changeWindowInfo(projectFrame, seedWindowInfo);
183
                }
184
                else
185
                        PluginServices.getMDIManager().addWindow(projectFrame);
186
        }
187

    
188
        public IWindow getProjectWindow() {
189
                return projectFrame;
190
        }
191

    
192
        /**
193
         * Guarda el proyecto actual en disco.
194
         */
195
        private boolean guardar() {
196
                boolean saved=false;
197
//                if (p.getPath() == null) {
198
                if (projectPath == null) {
199
                        saved=guardarDialogo();
200
                } else {
201
                        saved=writeProject(new File(projectPath), p); //new File(p.getPath()), p);
202
                        projectFrame.refreshControls();
203
                }
204
                return saved;
205
        }
206

    
207
        private boolean guardarDialogo(){
208
                boolean saved=false;
209

    
210
                if (lastSavePath == null)
211
                        lastSavePath = projectPath;
212

    
213
                if (lastSavePath == null) {
214
                        Preferences prefs = Preferences.userRoot().node( "gvsig.foldering" );
215
                        lastSavePath = prefs.get("ProjectsFolder", null);
216
                }
217

    
218
                JFileChooser jfc = new JFileChooser(lastSavePath);
219
                jfc.addChoosableFileFilter(new GenericFileFilter("gvp",
220
                                PluginServices.getText(this, "tipo_fichero_proyecto")));
221

    
222
                if (jfc.showSaveDialog((Component) PluginServices.getMainFrame()) == JFileChooser.APPROVE_OPTION) {
223
                        File file=jfc.getSelectedFile();
224
                        if (!(file.getPath().toLowerCase().endsWith(".gvp"))){
225
                                file=new File(file.getPath()+".gvp");
226
                        }
227
                        saved=writeProject(file, p);
228

    
229
                        String filePath = file.getAbsolutePath();
230
                        lastSavePath = filePath.substring(0, filePath.lastIndexOf(File.separatorChar));
231
                        projectFrame.refreshControls();
232
                }
233
                return saved;
234
        }
235
        /**
236
         * Guarda si el proyecto ha sido modificado.
237
         *
238
         * @return True si se ha guardado correctamente.
239
         */
240
        private boolean modificado() {
241
                if (p.isModified()) {
242
                ///if (true) {
243
                        //TODO de momento se queda como modificado siempre menos cuando est? totalmente vacio que se tomar? como no modificado,
244
                        //para poder controlar perfectamente cuando un proyecto ha sido modificado
245
                        //hay que recoger los eventos de cambio de leyenda, cambio de extent, a?adir una capa, etc que se encuentran en FMap.
246

    
247
                        int res = JOptionPane.showConfirmDialog((Component) PluginServices.getMainFrame(),
248
                                        PluginServices.getText(this, "guardar_cambios"),
249
                                        "gvSIG",
250
                                        JOptionPane.YES_NO_CANCEL_OPTION,
251
                                        JOptionPane.INFORMATION_MESSAGE);
252

    
253
                        if (res == JOptionPane.YES_OPTION) {
254
                                guardar();
255
                        } else if (res == JOptionPane.CANCEL_OPTION) {
256
                                return false;
257
                        }
258
                }
259

    
260
                return true;
261
        }
262

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

    
289
                        if (lastPath == null) {
290
                                Preferences prefs = Preferences.userRoot().node( "gvsig.foldering" );
291
                                lastPath = prefs.get("ProjectsFolder", null);
292
                        }
293

    
294
                        JFileChooser jfc = new JFileChooser(lastPath);
295
                        jfc.addChoosableFileFilter(new GenericFileFilter("gvp",
296
                                        PluginServices.getText(this, "tipo_fichero_proyecto")));
297

    
298
                        if (jfc.showOpenDialog((Component) PluginServices.getMainFrame()) == JFileChooser.APPROVE_OPTION) {
299
                                ProjectView.numViews=0;
300
                ProjectMap.numMaps = 0;
301
                                PluginServices.getMDIManager().closeAllWindows();
302

    
303
                                File projectFile = jfc.getSelectedFile();
304
                                Project o = readProject(projectFile);
305
                                setPath(projectFile.getAbsolutePath());
306
                                lastPath = getPath();
307
                                if (o != null) {
308
                                        p = o;
309
                                }
310

    
311
                                projectFrame.setProject(p);
312
                                PluginServices.getMainFrame().setTitle(p.getName());
313
                                projectFrame.refreshControls();
314
                                //showProjectWindow(); don't show it now; it will be called in the right order
315
                        }
316
                } else if (actionCommand.equals("GUARDAR")) {
317
                        guardar();
318
                } else if (actionCommand.equals("GUARDAR_COMO")) {
319
                        guardarDialogo();
320
                } else if (actionCommand.equals("SALIR")){
321
                        int option = JOptionPane.showConfirmDialog((Component)PluginServices.getMainFrame(),
322
                                        Messages.getString("MDIFrame.quiere_salir"),
323
                                        Messages.getString("MDIFrame.salir"),
324
                                        JOptionPane.YES_NO_OPTION);
325

    
326
                        if (option == JOptionPane.YES_OPTION) {
327
                                Launcher.closeApplication();
328
                        }
329
                } else if (actionCommand.compareTo("OPENTEMPLATE")==0){
330
                        openLayout();
331
                }
332
        }
333

    
334
        public void openLayout() {
335
                //Project project = ((ProjectExtension) PluginServices.getExtension(ProjectExtension.class)).getProject();
336
                Layout layout=null;
337

    
338
                if (templatesPath == null) {
339
                        Preferences prefs = Preferences.userRoot().node( "gvsig.foldering" );
340
                        templatesPath = prefs.get("TemplatesFolder", null);
341
                }
342

    
343
                JFileChooser jfc = new JFileChooser(templatesPath);
344

    
345
                jfc.addChoosableFileFilter(new GenericFileFilter("gvt",
346
                                PluginServices.getText(this, "plantilla")));
347

    
348
                if (jfc.showOpenDialog((Component) PluginServices.getMainFrame()) == JFileChooser.APPROVE_OPTION) {
349
                        File file=jfc.getSelectedFile();
350
                        if (!(file.getPath().endsWith(".gvt") || file.getPath().endsWith(".GVT"))){
351
                                file=new File(file.getPath()+".gvt");
352
                        }
353
                        try {
354
                                File xmlFile = new File(file.getAbsolutePath());
355
                                FileReader reader;
356
                                reader = new FileReader(xmlFile);
357

    
358
                                XmlTag tag = (XmlTag) XmlTag.unmarshal(reader);
359
                                try {
360
                                        layout = Layout.createLayout(new XMLEntity(tag),p);
361
                                } catch (OpenException e) {
362
                                        e.showError();
363
                                }
364
                                //fPanelLegendManager.setRenderer(LegendFactory.createFromXML(new XMLEntity(tag)));
365
                        } catch (FileNotFoundException e) {
366
                                NotificationManager.addError(PluginServices.getText(this, "Al_leer_la_leyenda"), e);
367
                        } catch (MarshalException e) {
368
                                NotificationManager.addError(PluginServices.getText(this, "Al_leer_la_leyenda"), e);
369
                        } catch (ValidationException e) {
370
                                NotificationManager.addError(PluginServices.getText(this, "Al_leer_la_leyenda"), e);
371
                        }
372
                        ProjectMap pmap = ProjectFactory.createMap(file.getName());
373
                        pmap.setModel(layout);
374
                        pmap.getModel().setProjectMap(pmap);
375

    
376
                        p.addMap(pmap);
377
                        PluginServices.getMDIManager().addWindow(layout);
378

    
379

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

    
410
                } catch (Exception e) {
411
                        NotificationManager.addError("Error guardando el proyecto", e);
412
                        return false;
413
                }
414
                return true;
415
        }
416

    
417

    
418

    
419
        public Project readProject(String path) {
420
                BufferedReader reader =null;
421
                try {
422
                URL url=null;
423
                        url = new URL(path);
424
                        reader = new BufferedReader(new InputStreamReader(url
425
                        .openStream()));
426
                } catch (MalformedURLException e) {
427
                        File file=new File(path);
428
                        return readProject(file);
429
                } catch (IOException e) {
430
                        e.printStackTrace();
431
                }
432
                Project p=readProject(reader);
433
                ProjectExtension.setPath(path); //p.setPath(null);
434
                return p;
435
        }
436

    
437
        public Project readProject(File file) {
438
                File xmlFile = new File(file.getAbsolutePath());
439
                FileReader reader=null;
440
                try {
441
                        reader = new FileReader(xmlFile);
442
                } catch (FileNotFoundException e) {
443
                        JOptionPane.showMessageDialog((Component)PluginServices.getMainFrame(),PluginServices.getText(this, "fichero_incorrecto"));
444
                        return null;
445
                }
446
                return readProject(reader);
447
                }
448
        /**
449
         * Lee del XML el proyecto.<br><br>
450
         *
451
         * Reads the XML of the project.<br>
452
         * 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
453
         * linked to the window you must to set this object to the extension:<br>
454
         *
455
         * <b>Example:</b><br>
456
         *
457
         * ...<br>
458
         * ...<br>
459
         * Project p = ProjectExtension.readProject(projectFile);<br>
460
         * ProjectExtension.setProject(p);
461
         * ...<br>
462
         * ...<br>
463
         * @param file Fichero.
464
         *
465
         * @return Project
466
         *
467
         */
468
        public Project readProject(Reader reader) {
469
                Project proj = null;
470

    
471
                try {
472
//                        File xmlFile = new File(file.getAbsolutePath());
473
//                        FileReader reader;
474
//                        reader = new FileReader(xmlFile);
475

    
476

    
477
                        XmlTag tag = (XmlTag) XmlTag.unmarshal(reader);
478
                        XMLEntity xml=new XMLEntity(tag);
479
                        String VERSION=xml.getStringProperty("VERSION");
480

    
481
                        try {
482
                                // if ((VERSION!=null) && (VERSION.equals("0.5") || VERSION.equals("0.4") || (VERSION.indexOf("GISPLANET") != -1))){
483
                                if (VERSION != null) {
484
                                        proj = Project.createFromXML(xml);
485
                                }else{
486
                                        proj = Project.createFromXML03(new XMLEntity(tag));
487
                                }
488
                                return proj;
489
                        } catch (OpenException e){
490
                                e.showError();
491
                                //NotificationManager.addInfo("Al leer el proyecto", e);
492
                        }
493
                }  catch (MarshalException e) {
494
                        JOptionPane.showMessageDialog((Component)PluginServices.getMainFrame(),PluginServices.getText(this, "formato_incorrecto"));
495
                        //NotificationManager.addError("Al leer el proyecto", e);
496
                } catch (ValidationException e) {
497
                        JOptionPane.showMessageDialog((Component)PluginServices.getMainFrame(),PluginServices.getText(this, "formato_incorrecto"));
498
                        //NotificationManager.addError("Al leer el proyecto", e);
499
                }
500
                return null;
501
        }
502

    
503
        /**
504
         * Devuelve el proyecto.
505
         *
506
         * @return Proyecto.
507
         */
508
        public Project getProject() {
509
                return p;
510
        }
511

    
512
        /**
513
         * @see com.iver.andami.plugins.IExtension#isEnabled()
514
         */
515
        public boolean isEnabled() {
516
                return true;
517
        }
518

    
519
        /**
520
         * @see com.iver.andami.plugins.IExtension#isVisible()
521
         */
522
        public boolean isVisible() {
523
                return true;
524
        }
525

    
526
        /**
527
         * Sets the project
528
         * @param p
529
         */
530
        public void setProject(Project p){
531
                projectFrame.setProject(p);
532
                this.p=p;
533
        }
534

    
535
        //Finalizar y preguntar si se quiere guardar el proyecto o cancelar.
536
        public void terminate() {
537
                long t1,t2;
538
                t1 = System.currentTimeMillis();
539
                //if (getProject().hasChanged()) {
540
                        int option = JOptionPane.showConfirmDialog((Component)PluginServices.getMainFrame(),PluginServices.getText(this,"guardar_cambios"),
541
                                        PluginServices.getText(this,"guardar_proyecto"),
542
                                        JOptionPane.YES_NO_OPTION);
543

    
544
                        if (option == JOptionPane.YES_OPTION) {
545
                                if (!guardar())
546
                                        terminate();
547
                        }
548
                //}
549
                t2 = System.currentTimeMillis();
550
                System.err.println("ProjectExtension.terminate() " +  (t2-t1) + "milisecs");
551
        }
552

    
553
        private void initilizeDocumentActionsExtensionPoint() {
554
                ExtensionPoints extensionPoints = ExtensionPointsSingleton.getInstance();
555
                if (!extensionPoints.containsKey("DocumentActions_View")) {
556
                        extensionPoints.put(
557
                                new ExtensionPoint(
558
                                        "DocumentActions_View",
559
                                        "Context menu options of the view document list" +
560
                                                " in the project window "+
561
                                                "(register instances of " +
562
                                                "com.iver.cit.gvsig.project.AbstractDocumentContextMenuAction)"
563
                                )
564
                        );
565
                }
566
                if (!extensionPoints.containsKey("DocumentActions_Table")) {
567
                        extensionPoints.put(
568
                                new ExtensionPoint(
569
                                        "DocumentActions_Table",
570
                                        "Context menu options of the table document list" +
571
                                                " in the project window "+
572
                                                "(register instances of " +
573
                                                "com.iver.cit.gvsig.project.AbstractDocumentContextMenuAction)"
574
                                )
575
                        );
576
                }
577
                if (!extensionPoints.containsKey("DocumentActions_Map")) {
578
                        extensionPoints.put(
579
                                new ExtensionPoint(
580
                                        "DocumentActions_Map",
581
                                        "Context menu options of the map document list" +
582
                                                " in the project window "+
583
                                                "(register instances of " +
584
                                                "com.iver.cit.gvsig.project.AbstractDocumentContextMenuAction)"
585
                                )
586
                        );
587
                }
588
        }
589

    
590
        public static String getPath() {
591
                return projectPath;
592
        }
593

    
594
        public static void setPath(String path) {
595
                projectPath = path;
596
        }
597

    
598
}