Statistics
| Revision:

svn-gvsig-desktop / branches / v10 / applications / appgvSIG / src / com / iver / cit / gvsig / ProjectExtension.java @ 7444

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

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

    
157
        initilizeDocumentActionsExtensionPoint();
158

    
159
            projectFrame = new ProjectWindow(this);
160
                projectFrame.setProject(p);
161
                showProjectWindow();
162
        }
163

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

    
183
        public IWindow getProjectWindow() {
184
                return projectFrame;
185
        }
186

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

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

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

    
208
                if (lastSavePath == null) {
209
                        Preferences prefs = Preferences.userRoot().node( "gvsig.foldering" );
210
                        lastSavePath = prefs.get("ProjectsFolder", null);
211
                }
212

    
213
                JFileChooser jfc = new JFileChooser(lastSavePath);
214
                jfc.addChoosableFileFilter(new GenericFileFilter("gvp",
215
                                PluginServices.getText(this, "tipo_fichero_proyecto")));
216

    
217
                if (jfc.showSaveDialog((Component) PluginServices.getMainFrame()) == JFileChooser.APPROVE_OPTION) {
218
                        File file=jfc.getSelectedFile();
219
                        if (!(file.getPath().toLowerCase().endsWith(".gvp"))){
220
                                file=new File(file.getPath()+".gvp");
221
                        }
222
                        saved=writeProject(file, p);
223

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

    
242
                        int res = JOptionPane.showConfirmDialog((Component) PluginServices.getMainFrame(),
243
                                        PluginServices.getText(this, "guardar_cambios"),
244
                                        "gvSIG",
245
                                        JOptionPane.YES_NO_CANCEL_OPTION,
246
                                        JOptionPane.INFORMATION_MESSAGE);
247

    
248
                        if (res == JOptionPane.YES_OPTION) {
249
                                guardar();
250
                        } else if (res == JOptionPane.CANCEL_OPTION) {
251
                                return false;
252
                        }
253
                }
254

    
255
                return true;
256
        }
257

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

    
284
                        if (lastPath == null) {
285
                                Preferences prefs = Preferences.userRoot().node( "gvsig.foldering" );
286
                                lastPath = prefs.get("ProjectsFolder", null);
287
                        }
288

    
289
                        JFileChooser jfc = new JFileChooser(lastPath);
290
                        jfc.addChoosableFileFilter(new GenericFileFilter("gvp",
291
                                        PluginServices.getText(this, "tipo_fichero_proyecto")));
292

    
293
                        if (jfc.showOpenDialog((Component) PluginServices.getMainFrame()) == JFileChooser.APPROVE_OPTION) {
294
                                ProjectView.numViews=0;
295
                ProjectMap.numMaps = 0;
296
                                PluginServices.getMDIManager().closeAllWindows();
297

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

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

    
321
                        if (option == JOptionPane.YES_OPTION) {
322
                                Launcher.closeApplication();
323
                        }
324
                } else if (actionCommand.compareTo("OPENTEMPLATE")==0){
325
                        openLayout();
326
                }
327
        }
328

    
329
        public void openLayout() {
330
                //Project project = ((ProjectExtension) PluginServices.getExtension(ProjectExtension.class)).getProject();
331
                Layout layout=null;
332

    
333
                if (templatesPath == null) {
334
                        Preferences prefs = Preferences.userRoot().node( "gvsig.foldering" );
335
                        templatesPath = prefs.get("TemplatesFolder", null);
336
                }
337

    
338
                JFileChooser jfc = new JFileChooser(templatesPath);
339

    
340
                jfc.addChoosableFileFilter(new GenericFileFilter("gvt",
341
                                PluginServices.getText(this, "plantilla")));
342

    
343
                if (jfc.showOpenDialog((Component) PluginServices.getMainFrame()) == JFileChooser.APPROVE_OPTION) {
344
                        File file=jfc.getSelectedFile();
345
                        if (!(file.getPath().endsWith(".gvt") || file.getPath().endsWith(".GVT"))){
346
                                file=new File(file.getPath()+".gvt");
347
                        }
348
                        try {
349
                                File xmlFile = new File(file.getAbsolutePath());
350
                                FileReader reader;
351
                                reader = new FileReader(xmlFile);
352

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

    
371
                        p.addMap(pmap);
372
                        PluginServices.getMDIManager().addWindow(layout);
373

    
374

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

    
405
                } catch (Exception e) {
406
                        NotificationManager.addError("Error guardando el proyecto", e);
407
                        return false;
408
                }
409
                return true;
410
        }
411

    
412

    
413

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

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

    
466
                try {
467
//                        File xmlFile = new File(file.getAbsolutePath());
468
//                        FileReader reader;
469
//                        reader = new FileReader(xmlFile);
470

    
471

    
472
                        XmlTag tag = (XmlTag) XmlTag.unmarshal(reader);
473
                        XMLEntity xml=new XMLEntity(tag);
474
                        String VERSION=xml.getStringProperty("VERSION");
475

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

    
498
        /**
499
         * Devuelve el proyecto.
500
         *
501
         * @return Proyecto.
502
         */
503
        public Project getProject() {
504
                return p;
505
        }
506

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

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

    
521
        /**
522
         * Sets the project
523
         * @param p
524
         */
525
        public void setProject(Project p){
526
                projectFrame.setProject(p);
527
                this.p=p;
528
        }
529

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

    
539
                        if (option == JOptionPane.YES_OPTION) {
540
                                if (!guardar())
541
                                        terminate();
542
                        }
543
                //}
544
                t2 = System.currentTimeMillis();
545
                System.err.println("ProjectExtension.terminate() " +  (t2-t1) + "milisecs");
546
        }
547

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

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

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

    
593
}