Statistics
| Revision:

svn-gvsig-desktop / trunk / applications / appgvSIG / src / com / iver / cit / gvsig / ProjectExtension.java @ 7239

History | View | Annotate | Download (16.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.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.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 String lastPath;
95
        private static String projectPath = null;
96
        private ProjectWindow projectFrame;
97
        private Project p;
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
                PluginServices.getMDIManager().addWindow(projectFrame);
164
                if (Project.getSeedProjectWindow()!=null) {
165
                        PluginServices.getMDIManager().changeWindowInfo(projectFrame, Project.getSeedProjectWindow());
166
                }
167
        }
168

    
169
        /**
170
         * Guarda el proyecto actual en disco.
171
         */
172
        private boolean guardar() {
173
                boolean saved=false;
174
//                if (p.getPath() == null) {
175
                if (projectPath == null) {
176
                        saved=guardarDialogo();
177
                } else {
178
                        saved=writeProject(new File(projectPath), p); //new File(p.getPath()), p);
179
                        projectFrame.refreshControls();
180
                }
181
                return saved;
182
        }
183

    
184
        private boolean guardarDialogo(){
185
                boolean saved=false;
186
                JFileChooser jfc = new JFileChooser();
187
                jfc.addChoosableFileFilter(new GenericFileFilter("gvp",
188
                                PluginServices.getText(this, "tipo_fichero_proyecto")));
189

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

    
212
                        int res = JOptionPane.showConfirmDialog((Component) PluginServices.getMainFrame(),
213
                                        PluginServices.getText(this, "guardar_cambios"),
214
                                        "gvSIG",
215
                                        JOptionPane.YES_NO_CANCEL_OPTION,
216
                                        JOptionPane.INFORMATION_MESSAGE);
217

    
218
                        if (res == JOptionPane.YES_OPTION) {
219
                                guardar();
220
                        } else if (res == JOptionPane.CANCEL_OPTION) {
221
                                return false;
222
                        }
223
                }
224

    
225
                return true;
226
        }
227

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

    
254
                        if (lastPath == null) {
255
                                Preferences prefs = Preferences.userRoot().node( "gvsig.foldering" );
256
                                lastPath = prefs.get("ProjectsFolder", null);
257
                        }
258

    
259
                        JFileChooser jfc = new JFileChooser(lastPath);
260
                        jfc.addChoosableFileFilter(new GenericFileFilter("gvp",
261
                                        PluginServices.getText(this, "tipo_fichero_proyecto")));
262

    
263
                        if (jfc.showOpenDialog((Component) PluginServices.getMainFrame()) == JFileChooser.APPROVE_OPTION) {
264
                                ProjectView.numViews=0;
265
                ProjectMap.numMaps = 0;
266
                                PluginServices.getMDIManager().closeAllWindows();
267

    
268
                                File projectFile = jfc.getSelectedFile();
269
                                Project o = readProject(projectFile);
270
                                setPath(projectFile.getAbsolutePath());
271
                                lastPath = getPath();
272
                                if (o != null) {
273
                                        p = o;
274
                                }
275

    
276
                                projectFrame.setProject(p);
277
                                PluginServices.getMainFrame().setTitle(p.getName());
278
                                projectFrame.refreshControls();
279
                                showProjectWindow();
280
                        }
281
                } else if (actionCommand.equals("GUARDAR")) {
282
                        guardar();
283
                } else if (actionCommand.equals("GUARDAR_COMO")) {
284
                        guardarDialogo();
285
                } else if (actionCommand.equals("SALIR")){
286
                        int option = JOptionPane.showConfirmDialog((Component)PluginServices.getMainFrame(),
287
                                        Messages.getString("MDIFrame.quiere_salir"),
288
                                        Messages.getString("MDIFrame.salir"),
289
                                        JOptionPane.YES_NO_OPTION);
290

    
291
                        if (option == JOptionPane.YES_OPTION) {
292
                                Launcher.closeApplication();
293
                        }
294
                } else if (actionCommand.compareTo("OPENTEMPLATE")==0){
295
                        openLayout();
296
                }
297
        }
298
        public void openLayout() {
299
                //Project project = ((ProjectExtension) PluginServices.getExtension(ProjectExtension.class)).getProject();
300
                Layout layout=null;
301
                JFileChooser jfc = new JFileChooser();
302
                jfc.addChoosableFileFilter(new GenericFileFilter("gvt",
303
                                PluginServices.getText(this, "plantilla")));
304

    
305
                if (jfc.showOpenDialog((Component) PluginServices.getMainFrame()) == JFileChooser.APPROVE_OPTION) {
306
                        File file=jfc.getSelectedFile();
307
                        if (!(file.getPath().endsWith(".gvt") || file.getPath().endsWith(".GVT"))){
308
                                file=new File(file.getPath()+".gvt");
309
                        }
310
                        try {
311
                                File xmlFile = new File(file.getAbsolutePath());
312
                                FileReader reader;
313
                                reader = new FileReader(xmlFile);
314

    
315
                                XmlTag tag = (XmlTag) XmlTag.unmarshal(reader);
316
                                try {
317
                                        layout = Layout.createLayout(new XMLEntity(tag),p);
318
                                } catch (OpenException e) {
319
                                        e.showError();
320
                                }
321
                                //fPanelLegendManager.setRenderer(LegendFactory.createFromXML(new XMLEntity(tag)));
322
                        } catch (FileNotFoundException e) {
323
                                NotificationManager.addError(PluginServices.getText(this, "Al_leer_la_leyenda"), e);
324
                        } catch (MarshalException e) {
325
                                NotificationManager.addError(PluginServices.getText(this, "Al_leer_la_leyenda"), e);
326
                        } catch (ValidationException e) {
327
                                NotificationManager.addError(PluginServices.getText(this, "Al_leer_la_leyenda"), e);
328
                        }
329
                        ProjectMap pmap = ProjectFactory.createMap(file.getName());
330
                        pmap.setModel(layout);
331
                        pmap.getModel().setProjectMap(pmap);
332

    
333
                        p.addMap(pmap);
334
                        PluginServices.getMDIManager().addWindow(layout);
335

    
336

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

    
367
                } catch (Exception e) {
368
                        NotificationManager.addError("Error guardando el proyecto", e);
369
                        return false;
370
                }
371
                return true;
372
        }
373

    
374

    
375

    
376
        public Project readProject(String path) {
377
                BufferedReader reader =null;
378
                try {
379
                URL url=null;
380
                        url = new URL(path);
381
                        reader = new BufferedReader(new InputStreamReader(url
382
                        .openStream()));
383
                } catch (MalformedURLException e) {
384
                        File file=new File(path);
385
                        return readProject(file);
386
                } catch (IOException e) {
387
                        e.printStackTrace();
388
                }
389
                Project p=readProject(reader);
390
                ProjectExtension.setPath(path); //p.setPath(null);
391
                return p;
392
        }
393

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

    
428
                try {
429
//                        File xmlFile = new File(file.getAbsolutePath());
430
//                        FileReader reader;
431
//                        reader = new FileReader(xmlFile);
432

    
433

    
434
                        XmlTag tag = (XmlTag) XmlTag.unmarshal(reader);
435
                        XMLEntity xml=new XMLEntity(tag);
436
                        String VERSION=xml.getStringProperty("VERSION");
437

    
438
                        try {
439
                                // if ((VERSION!=null) && (VERSION.equals("0.5") || VERSION.equals("0.4") || (VERSION.indexOf("GISPLANET") != -1))){
440
                                if (VERSION != null) {
441
                                        proj = Project.createFromXML(xml);
442
                                }else{
443
                                        proj = Project.createFromXML03(new XMLEntity(tag));
444
                                }
445
                                return proj;
446
                        } catch (OpenException e){
447
                                e.showError();
448
                                //NotificationManager.addInfo("Al leer el proyecto", e);
449
                        }
450
                }  catch (MarshalException e) {
451
                        JOptionPane.showMessageDialog((Component)PluginServices.getMainFrame(),PluginServices.getText(this, "formato_incorrecto"));
452
                        //NotificationManager.addError("Al leer el proyecto", e);
453
                } catch (ValidationException e) {
454
                        JOptionPane.showMessageDialog((Component)PluginServices.getMainFrame(),PluginServices.getText(this, "formato_incorrecto"));
455
                        //NotificationManager.addError("Al leer el proyecto", e);
456
                }
457
                return null;
458
        }
459

    
460
        /**
461
         * Devuelve el proyecto.
462
         *
463
         * @return Proyecto.
464
         */
465
        public Project getProject() {
466
                return p;
467
        }
468

    
469
        /**
470
         * @see com.iver.andami.plugins.IExtension#isEnabled()
471
         */
472
        public boolean isEnabled() {
473
                return true;
474
        }
475

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

    
483
        /**
484
         * Sets the project
485
         * @param p
486
         */
487
        public void setProject(Project p){
488
                projectFrame.setProject(p);
489
                this.p=p;
490
        }
491

    
492
        //Finalizar y preguntar si se quiere guardar el proyecto o cancelar.
493
        public void terminate() {
494
                long t1,t2;
495
                t1 = System.currentTimeMillis();
496
                //if (getProject().hasChanged()) {
497
                        int option = JOptionPane.showConfirmDialog((Component)PluginServices.getMainFrame(),PluginServices.getText(this,"guardar_cambios"),
498
                                        PluginServices.getText(this,"guardar_proyecto"),
499
                                        JOptionPane.YES_NO_OPTION);
500

    
501
                        if (option == JOptionPane.YES_OPTION) {
502
                                if (!guardar())
503
                                        terminate();
504
                        }
505
                //}
506
                t2 = System.currentTimeMillis();
507
                System.err.println("ProjectExtension.terminate() " +  (t2-t1) + "milisecs");
508
        }
509

    
510
        private void initilizeDocumentActionsExtensionPoint() {
511
                ExtensionPoints extensionPoints = ExtensionPointsSingleton.getInstance();
512
                if (!extensionPoints.containsKey("DocumentActions_View")) {
513
                        extensionPoints.put(
514
                                new ExtensionPoint(
515
                                        "DocumentActions_View",
516
                                        "Context menu options of the view document list" +
517
                                                " in the project window "+
518
                                                "(register instances of " +
519
                                                "com.iver.cit.gvsig.project.AbstractDocumentContextMenuAction)"
520
                                )
521
                        );
522
                }
523
                if (!extensionPoints.containsKey("DocumentActions_Table")) {
524
                        extensionPoints.put(
525
                                new ExtensionPoint(
526
                                        "DocumentActions_Table",
527
                                        "Context menu options of the table document list" +
528
                                                " in the project window "+
529
                                                "(register instances of " +
530
                                                "com.iver.cit.gvsig.project.AbstractDocumentContextMenuAction)"
531
                                )
532
                        );
533
                }
534
                if (!extensionPoints.containsKey("DocumentActions_Map")) {
535
                        extensionPoints.put(
536
                                new ExtensionPoint(
537
                                        "DocumentActions_Map",
538
                                        "Context menu options of the map document list" +
539
                                                " in the project window "+
540
                                                "(register instances of " +
541
                                                "com.iver.cit.gvsig.project.AbstractDocumentContextMenuAction)"
542
                                )
543
                        );
544
                }
545
        }
546

    
547
        public static String getPath() {
548
                return projectPath;
549
        }
550

    
551
        public static void setPath(String path) {
552
                projectPath = path;
553
        }
554

    
555
}