Statistics
| Revision:

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

History | View | Annotate | Download (17.9 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 String lastPath;
101
        private static String projectPath = null;
102
        //private ProjectWindow projectFrame;
103
        private ProjectWindow projectFrame;
104
        private Project p;
105
        private String lastSavePath;
106
        /**
107
         * @see com.iver.mdiApp.plugins.IExtension#initialize()
108
         */
109
        public void initialize() {
110
            try {
111
            Class.forName("javax.media.jai.EnumeratedParameter");
112
        } catch (ClassNotFoundException e) {
113
            NotificationManager.addError("La m?quina virtual con la que se ejecuta gvSIG no tiene JAI instalado", e);
114
        }
115

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

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

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

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

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

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

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

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

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

    
204
                JFileChooser jfc = new JFileChooser(lastSavePath);
205
                jfc.addChoosableFileFilter(new GenericFileFilter("gvp",
206
                                PluginServices.getText(this, "tipo_fichero_proyecto")));
207

    
208
                if (jfc.showSaveDialog((Component) PluginServices.getMainFrame()) == JFileChooser.APPROVE_OPTION) {
209
                        File file=jfc.getSelectedFile();
210
                        if (!(file.getPath().toLowerCase().endsWith(".gvp"))){
211
                                file=new File(file.getPath()+".gvp");
212
                        }
213
                        saved=writeProject(file, p);
214
                        String filePath = file.getAbsolutePath();
215
                        lastSavePath = filePath.substring(0, filePath.lastIndexOf(File.separatorChar));
216

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

    
233
                        int res = JOptionPane.showConfirmDialog((Component) PluginServices.getMainFrame(),
234
                                        PluginServices.getText(this, "guardar_cambios"),
235
                                        "gvSIG",
236
                                        JOptionPane.YES_NO_CANCEL_OPTION,
237
                                        JOptionPane.INFORMATION_MESSAGE);
238

    
239
                        if (res == JOptionPane.YES_OPTION) {
240
                                guardar();
241
                        } else if (res == JOptionPane.CANCEL_OPTION) {
242
                                return false;
243
                        }
244
                }
245

    
246
                return true;
247
        }
248

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

    
275
                        if (lastPath == null) {
276
                                Preferences prefs = Preferences.userRoot().node( "gvsig.foldering" );
277
                                lastPath = prefs.get("ProjectsFolder", null);
278
                        }
279

    
280
                        JFileChooser jfc = new JFileChooser(lastPath);
281
                        jfc.addChoosableFileFilter(new GenericFileFilter("gvp",
282
                                        PluginServices.getText(this, "tipo_fichero_proyecto")));
283

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

    
289
                                File projectFile = jfc.getSelectedFile();
290
                                Project o = readProject(projectFile);
291
                                setPath(projectFile.getAbsolutePath());
292
                                lastPath = getPath();
293
                                if (o != null) {
294
                                        p = o;
295
                                }
296

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

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

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

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

    
356

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

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

    
394

    
395

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

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

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

    
453

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

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

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

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

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

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

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

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

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

    
572
        public static String getPath() {
573
                return projectPath;
574
        }
575

    
576
        public static void setPath(String path) {
577
                projectPath = path;
578
        }
579

    
580
}