Statistics
| Revision:

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

History | View | Annotate | Download (15.3 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.File;
45
import java.io.FileNotFoundException;
46
import java.io.FileReader;
47
import java.io.FileWriter;
48
import java.text.DateFormat;
49
import java.util.Date;
50

    
51
import javax.swing.JFileChooser;
52
import javax.swing.JOptionPane;
53

    
54
import org.exolab.castor.xml.MarshalException;
55
import org.exolab.castor.xml.Marshaller;
56
import org.exolab.castor.xml.ValidationException;
57

    
58
import com.iver.andami.Launcher;
59
import com.iver.andami.PluginServices;
60
import com.iver.andami.messages.Messages;
61
import com.iver.andami.messages.NotificationManager;
62
import com.iver.andami.plugins.Extension;
63
import com.iver.cit.gvsig.fmap.layers.LayerFactory;
64
import com.iver.cit.gvsig.gui.layout.Layout;
65
import com.iver.cit.gvsig.gui.project.OpenException;
66
import com.iver.cit.gvsig.gui.project.ProjectWindow;
67
import com.iver.cit.gvsig.project.Project;
68
import com.iver.cit.gvsig.project.ProjectFactory;
69
import com.iver.cit.gvsig.project.ProjectMap;
70
import com.iver.cit.gvsig.project.ProjectView;
71
import com.iver.utiles.GenericFileFilter;
72
import com.iver.utiles.XMLEntity;
73
import com.iver.utiles.extensionPoints.ExtensionPoint;
74
import com.iver.utiles.extensionPoints.ExtensionPoints;
75
import com.iver.utiles.extensionPoints.ExtensionPointsSingleton;
76
import com.iver.utiles.xmlEntity.generate.XmlTag;
77

    
78

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

    
99
                LayerFactory.setWritersPath(PluginServices.getPluginServices(this)
100
                                  .getPluginDirectory()
101
                                  .getAbsolutePath() +
102
                                  File.separator + "drivers");
103

    
104
        LayerFactory.setDriversPath(PluginServices.getPluginServices(this)
105
                                  .getPluginDirectory()
106
                                  .getAbsolutePath() +
107
                                  File.separator + "drivers");
108

    
109
        // Recuperamos el ?ltimo argumento, que se supone
110
        // que ser? el fichero .gvp que queremos abrir.
111
        // (por enmedio pueden venir o no otros argumentos,
112
        // por ejemplo el idioma)
113
        // TODO: Aqu? Jaume podr?a meter lo del backup del proyecto
114
        // que ha hecho para ValenciaUrban?stica
115

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

    
149
        /**
150
         * Muestra la ventana con el gestor de proyectos.
151
         */
152
        public void showProjectWindow() {
153
                PluginServices.getMDIManager().addView(projectFrame);
154
                if (Project.getSeedProjectWindow()!=null) {
155
                        PluginServices.getMDIManager().changeViewInfo(projectFrame, Project.getSeedProjectWindow());
156
                }
157
        }
158

    
159
        /**
160
         * Guarda el proyecto actual en disco.
161
         */
162
        private boolean guardar() {
163
                boolean saved=false;
164
                if (p.getPath() == null) {
165
                        saved=guardarDialogo();
166
                } else {
167
                        saved=writeProject(new File(p.getPath()), p);
168
                        projectFrame.refreshControls();
169
                }
170
                return saved;
171
        }
172
        private boolean guardarDialogo(){
173
                boolean saved=false;
174
                JFileChooser jfc = new JFileChooser();
175
                jfc.addChoosableFileFilter(new GenericFileFilter("gvp",
176
                                PluginServices.getText(this, "tipo_fichero_proyecto")));
177

    
178
                if (jfc.showSaveDialog((Component) PluginServices.getMainFrame()) == JFileChooser.APPROVE_OPTION) {
179
                        File file=jfc.getSelectedFile();
180
                        if (!(file.getPath().endsWith(".gvp") || file.getPath().endsWith(".GVP"))){
181
                                file=new File(file.getPath()+".gvp");
182
                        }
183
                        saved=writeProject(file, p);
184
                        projectFrame.refreshControls();
185
                }
186
                return saved;
187
        }
188
        /**
189
         * Guarda si el proyecto ha sido modificado.
190
         *
191
         * @return True si se ha guardado correctamente.
192
         */
193
        private boolean modificado() {
194
                if (p.isModified()) {
195
                ///if (true) {
196
                        //TODO de momento se queda como modificado siempre menos cuando est? totalmente vacio que se tomar? como no modificado,
197
                        //para poder controlar perfectamente cuando un proyecto ha sido modificado
198
                        //hay que recoger los eventos de cambio de leyenda, cambio de extent, a?adir una capa, etc que se encuentran en FMap.
199

    
200
                        int res = JOptionPane.showConfirmDialog((Component) PluginServices.getMainFrame(),
201
                                        PluginServices.getText(this, "guardar_cambios"),
202
                                        "gvSIG",
203
                                        JOptionPane.YES_NO_CANCEL_OPTION,
204
                                        JOptionPane.INFORMATION_MESSAGE);
205

    
206
                        if (res == JOptionPane.YES_OPTION) {
207
                                guardar();
208
                        } else if (res == JOptionPane.CANCEL_OPTION) {
209
                                return false;
210
                        }
211
                }
212

    
213
                return true;
214
        }
215

    
216
        /**
217
         * @see com.iver.mdiApp.plugins.IExtension#updateUI(java.lang.String)
218
         */
219
        public void execute(String actionCommand) {
220
                if (actionCommand.equals("NUEVO")) {
221
                        //Si est? modificado se pregunta si se quiere guardar el anterior
222
                        if (!modificado()) {
223
                                return;
224
                        }
225
                        ProjectView.numViews=0;
226
            ProjectMap.numMaps = 0;
227
                        PluginServices.getMDIManager().closeAllViews();
228
                        p = ProjectFactory.createProject();
229
                        p.setName(PluginServices.getText(this, "untitled"));
230
                        p.setModified(false);
231
                        projectFrame.setProject(p);
232
                        showProjectWindow();
233
                        PluginServices.getMainFrame().setTitle(PluginServices.getText(this, "sin_titulo"));
234
                } else if (actionCommand.equals("ABRIR")) {
235
                        //Si est? modificado se pregunta si se quiere guardar el anterior
236
                        if (!modificado()) {
237
                                ProjectView.numViews=0;
238
                ProjectMap.numMaps = 0;
239
                                return;
240
                        }
241

    
242
                        JFileChooser jfc = new JFileChooser();
243
                        jfc.addChoosableFileFilter(new GenericFileFilter("gvp",
244
                                        PluginServices.getText(this, "tipo_fichero_proyecto")));
245

    
246
                        if (jfc.showOpenDialog((Component) PluginServices.getMainFrame()) == JFileChooser.APPROVE_OPTION) {
247
                                ProjectView.numViews=0;
248
                ProjectMap.numMaps = 0;
249
                                PluginServices.getMDIManager().closeAllViews();
250
                                Project o = readProject(jfc.getSelectedFile());
251
                                if (o != null) {
252
                                        p = o;
253
                                }
254

    
255
                                projectFrame.setProject(p);
256
                                PluginServices.getMainFrame().setTitle(p.getName());
257
                                projectFrame.refreshControls();
258
                                showProjectWindow();
259
                        }
260
                } else if (actionCommand.equals("GUARDAR")) {
261
                        guardar();
262
                } else if (actionCommand.equals("GUARDAR_COMO")) {
263
                        guardarDialogo();
264
                } else if (actionCommand.equals("SALIR")){
265
                        int option = JOptionPane.showConfirmDialog((Component)PluginServices.getMainFrame(),
266
                                        Messages.getString("MDIFrame.quiere_salir"),
267
                                        Messages.getString("MDIFrame.salir"),
268
                                        JOptionPane.YES_NO_OPTION);
269

    
270
                        if (option == JOptionPane.YES_OPTION) {
271
                                Launcher.closeApplication();
272
                        }
273
                } else if (actionCommand.compareTo("OPENTEMPLATE")==0){
274
                        openLayout();
275
                }
276
        }
277
        public void openLayout() {
278
                //Project project = ((ProjectExtension) PluginServices.getExtension(ProjectExtension.class)).getProject();
279
                Layout layout=null;
280
                JFileChooser jfc = new JFileChooser();
281
                jfc.addChoosableFileFilter(new GenericFileFilter("gvt",
282
                                PluginServices.getText(this, "plantilla")));
283

    
284
                if (jfc.showOpenDialog((Component) PluginServices.getMainFrame()) == JFileChooser.APPROVE_OPTION) {
285
                        File file=jfc.getSelectedFile();
286
                        if (!(file.getPath().endsWith(".gvt") || file.getPath().endsWith(".GVT"))){
287
                                file=new File(file.getPath()+".gvt");
288
                        }
289
                        try {
290
                                File xmlFile = new File(file.getAbsolutePath());
291
                                FileReader reader;
292
                                reader = new FileReader(xmlFile);
293

    
294
                                XmlTag tag = (XmlTag) XmlTag.unmarshal(reader);
295
                                try {
296
                                        layout = Layout.createLayout(new XMLEntity(tag),p);
297
                                } catch (OpenException e) {
298
                                        e.showError();
299
                                }
300
                                //fPanelLegendManager.setRenderer(LegendFactory.createFromXML(new XMLEntity(tag)));
301
                        } catch (FileNotFoundException e) {
302
                                NotificationManager.addError(PluginServices.getText(this, "Al_leer_la_leyenda"), e);
303
                        } catch (MarshalException e) {
304
                                NotificationManager.addError(PluginServices.getText(this, "Al_leer_la_leyenda"), e);
305
                        } catch (ValidationException e) {
306
                                NotificationManager.addError(PluginServices.getText(this, "Al_leer_la_leyenda"), e);
307
                        }
308
                        ProjectMap pmap = ProjectFactory.createMap(file.getName());
309
                        pmap.setModel(layout);
310
                        pmap.getModel().setProjectMap(pmap);
311

    
312
                        p.addMap(pmap);
313
                        PluginServices.getMDIManager().addView(layout);
314

    
315

    
316
                }
317
        }
318
        /**
319
         * Escribe el proyecto en XML.
320
         *
321
         * @param file Fichero.
322
         * @param p Proyecto.
323
         */
324
        public boolean writeProject(File file, Project p) {
325
                if( file.exists()){
326
                        int resp = JOptionPane.showConfirmDialog(
327
                                        (Component) PluginServices.getMainFrame(),PluginServices.getText(this,"fichero_ya_existe_seguro_desea_guardarlo"),
328
                                        PluginServices.getText(this,"guardar"), JOptionPane.YES_NO_OPTION);
329
                        if (resp != JOptionPane.YES_OPTION) {
330
                                return false;
331
                        }
332
                }
333
                // write it out as XML
334
                try {
335
                        FileWriter writer = new FileWriter(file.getAbsolutePath());
336
                        Marshaller m = new Marshaller(writer);
337
                        m.setEncoding("ISO-8859-1");
338
                        p.setName(file.getName());
339
                        p.setPath(file.toString());
340
                        p.setModificationDate(DateFormat.getDateInstance().format(new Date()));
341
                        p.setModified(false);
342
                        m.marshal(p.getXMLEntity().getXmlTag());
343
                        PluginServices.getMainFrame().setTitle(file.getName());
344
                } catch (Exception e) {
345
                        NotificationManager.addError("Error guardando el proyecto", e);
346
                        return false;
347
                }
348
                return true;
349
        }
350

    
351
        /**
352
         * Lee del XML el proyecto.<br><br>
353
         *
354
         * Reads the XML of the project.<br>
355
         * 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
356
         * linked to the window you must to set this object to the extension:<br>
357
         *
358
         * <b>Example:</b><br>
359
         *
360
         * ...<br>
361
         * ...<br>
362
         * Project p = ProjectExtension.readProject(projectFile);<br>
363
         * ProjectExtension.setProject(p);
364
         * ...<br>
365
         * ...<br>
366
         * @param file Fichero.
367
         *
368
         * @return Project
369
         *
370
         */
371
        public Project readProject(File file) {
372
                Project proj = null;
373

    
374
                try {
375
                        File xmlFile = new File(file.getAbsolutePath());
376
                        FileReader reader;
377
                        reader = new FileReader(xmlFile);
378
                        XmlTag tag = (XmlTag) XmlTag.unmarshal(reader);
379
                        XMLEntity xml=new XMLEntity(tag);
380
                        String VERSION=xml.getStringProperty("VERSION");
381

    
382
                        try {
383
                                // if ((VERSION!=null) && (VERSION.equals("0.5") || VERSION.equals("0.4") || (VERSION.indexOf("GISPLANET") != -1))){
384
                                if (VERSION != null) {
385
                                        proj = Project.createFromXML(xml);
386
                                }else{
387
                                        proj = Project.createFromXML03(new XMLEntity(tag));
388
                                }
389
                                return proj;
390
                        } catch (OpenException e){
391
                                e.showError();
392
                                //NotificationManager.addInfo("Al leer el proyecto", e);
393
                        }
394
                } catch (FileNotFoundException e) {
395
                        JOptionPane.showMessageDialog((Component)PluginServices.getMainFrame(),PluginServices.getText(this, "fichero_incorrecto"));
396
                        //NotificationManager.addError("Al leer el proyecto", e);
397
                } catch (MarshalException e) {
398
                        JOptionPane.showMessageDialog((Component)PluginServices.getMainFrame(),PluginServices.getText(this, "formato_incorrecto"));
399
                        //NotificationManager.addError("Al leer el proyecto", e);
400
                } catch (ValidationException e) {
401
                        JOptionPane.showMessageDialog((Component)PluginServices.getMainFrame(),PluginServices.getText(this, "formato_incorrecto"));
402
                        //NotificationManager.addError("Al leer el proyecto", e);
403
                }
404

    
405
                return null;
406
        }
407

    
408
        /**
409
         * Devuelve el proyecto.
410
         *
411
         * @return Proyecto.
412
         */
413
        public Project getProject() {
414
                return p;
415
        }
416

    
417
        /**
418
         * @see com.iver.andami.plugins.IExtension#isEnabled()
419
         */
420
        public boolean isEnabled() {
421
                return true;
422
        }
423

    
424
        /**
425
         * @see com.iver.andami.plugins.IExtension#isVisible()
426
         */
427
        public boolean isVisible() {
428
                return true;
429
        }
430

    
431
        /**
432
         * Sets the project
433
         * @param p
434
         */
435
        public void setProject(Project p){
436
                projectFrame.setProject(p);
437
                this.p=p;
438
        }
439

    
440
        //Finalizar y preguntar si se quiere guardar el proyecto o cancelar.
441
        public void terminate() {
442
                int option = JOptionPane.showConfirmDialog((Component)PluginServices.getMainFrame(),PluginServices.getText(this,"guardar_cambios"),
443
                                PluginServices.getText(this,"guardar_proyecto"),
444
                                JOptionPane.YES_NO_OPTION);
445

    
446
                if (option == JOptionPane.YES_OPTION) {
447
                        if (!guardar())
448
                                terminate();
449
                }
450
        }
451
        
452
        private void initilizeDocumentActionsExtensionPoint() {
453
                ExtensionPoints extensionPoints = ExtensionPointsSingleton.getInstance();                
454
                if (!extensionPoints.containsKey("DocumentActions_View")) {
455
                        extensionPoints.put(
456
                                new ExtensionPoint(
457
                                        "DocumentActions_View",
458
                                        "Context menu options of the view document list" + 
459
                                                " in the project window "+ 
460
                                                "(register instances of " +
461
                                                "com.iver.cit.gvsig.project.AbstractDocumentContextMenuAction)"
462
                                )
463
                        );                        
464
                }
465
                if (!extensionPoints.containsKey("DocumentActions_Table")) {
466
                        extensionPoints.put(
467
                                new ExtensionPoint(
468
                                        "DocumentActions_Table",
469
                                        "Context menu options of the table document list" + 
470
                                                " in the project window "+ 
471
                                                "(register instances of " +
472
                                                "com.iver.cit.gvsig.project.AbstractDocumentContextMenuAction)"
473
                                )
474
                        );
475
                }
476
                if (!extensionPoints.containsKey("DocumentActions_Map")) {
477
                        extensionPoints.put(
478
                                new ExtensionPoint(
479
                                        "DocumentActions_Map",
480
                                        "Context menu options of the map document list" + 
481
                                                " in the project window "+ 
482
                                                "(register instances of " +
483
                                                "com.iver.cit.gvsig.project.AbstractDocumentContextMenuAction)"
484
                                )
485
                        );
486
                }
487
        }
488
}