Statistics
| Revision:

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

History | View | Annotate | Download (24.4 KB)

1 1103 fjp
/* 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 312 fernando
package com.iver.cit.gvsig;
42
43 2242 jaume
import java.awt.Component;
44 6730 caballero
import java.io.BufferedReader;
45 2242 jaume
import java.io.File;
46 8455 cesar
import java.io.FileInputStream;
47 2242 jaume
import java.io.FileNotFoundException;
48 8455 cesar
import java.io.FileOutputStream;
49 2242 jaume
import java.io.FileReader;
50 6730 caballero
import java.io.IOException;
51 8455 cesar
import java.io.InputStream;
52 6730 caballero
import java.io.InputStreamReader;
53 8455 cesar
import java.io.OutputStreamWriter;
54 6730 caballero
import java.io.Reader;
55 8455 cesar
import java.io.UnsupportedEncodingException;
56 6730 caballero
import java.net.MalformedURLException;
57
import java.net.URL;
58 2242 jaume
import java.text.DateFormat;
59
import java.util.Date;
60 7222 jaume
import java.util.prefs.Preferences;
61 2242 jaume
62
import javax.swing.JFileChooser;
63
import javax.swing.JOptionPane;
64
65
import org.exolab.castor.xml.MarshalException;
66
import org.exolab.castor.xml.Marshaller;
67
import org.exolab.castor.xml.ValidationException;
68
69
import com.iver.andami.Launcher;
70 596 fernando
import com.iver.andami.PluginServices;
71 2242 jaume
import com.iver.andami.messages.Messages;
72 692 fernando
import com.iver.andami.messages.NotificationManager;
73 596 fernando
import com.iver.andami.plugins.Extension;
74 7621 fjp
import com.iver.andami.ui.mdiManager.IWindow;
75 7689 cesar
import com.iver.andami.ui.mdiManager.WindowInfo;
76 701 fernando
import com.iver.cit.gvsig.fmap.layers.LayerFactory;
77 1221 fernando
import com.iver.cit.gvsig.project.Project;
78 312 fernando
import com.iver.cit.gvsig.project.ProjectFactory;
79 9690 caballero
import com.iver.cit.gvsig.project.documents.ProjectDocument;
80 7304 caballero
import com.iver.cit.gvsig.project.documents.exceptions.OpenException;
81 7343 caballero
import com.iver.cit.gvsig.project.documents.gui.ProjectWindow;
82 7304 caballero
import com.iver.cit.gvsig.project.documents.layout.ProjectMap;
83 7343 caballero
import com.iver.cit.gvsig.project.documents.layout.ProjectMapFactory;
84 9392 caballero
import com.iver.cit.gvsig.project.documents.layout.gui.Layout;
85 7343 caballero
import com.iver.cit.gvsig.project.documents.table.ProjectTableFactory;
86
import com.iver.cit.gvsig.project.documents.view.ProjectViewFactory;
87 596 fernando
import com.iver.utiles.GenericFileFilter;
88 436 vcaballero
import com.iver.utiles.XMLEntity;
89 6635 jmvivo
import com.iver.utiles.extensionPoints.ExtensionPoint;
90
import com.iver.utiles.extensionPoints.ExtensionPoints;
91
import com.iver.utiles.extensionPoints.ExtensionPointsSingleton;
92 8455 cesar
import com.iver.utiles.xml.XMLEncodingUtils;
93 436 vcaballero
import com.iver.utiles.xmlEntity.generate.XmlTag;
94 312 fernando
95 1219 vcaballero
96 312 fernando
/**
97
 * Extension que proporciona controles para crear proyectos nuevos, abrirlos y
98
 * guardarlos. Adem?s los tipos de tabla que soporta el proyecto son a?adidos
99
 * en esta clase.
100
 *
101
 * @author Fernando Gonz?lez Cort?s
102
 */
103 5005 jorpiell
public class ProjectExtension extends Extension {
104 6876 jaume
        private static String projectPath = null;
105 7304 caballero
        //private ProjectWindow projectFrame;
106 7343 caballero
        private ProjectWindow projectFrame;
107 1219 vcaballero
        private Project p;
108 7426 jaume
        private String lastPath;
109 7385 jaume
        private String lastSavePath;
110 7426 jaume
        private String templatesPath;
111 7689 cesar
        private WindowInfo seedProjectWindow;
112 8455 cesar
        /**
113
         * Use UTF-8 for encoding, as it can represent characters from
114
         * any language.
115 8536 jaume
         *
116
         * Another sensible option would be
117 8455 cesar
         * encoding = System.getProperty("file.encoding");
118
         * but this would need some extra testing.
119
         */
120 10365 caballero
        public static String PROJECTENCODING = "UTF-8";
121 8536 jaume
122 1219 vcaballero
        /**
123 5005 jorpiell
         * @see com.iver.mdiApp.plugins.IExtension#initialize()
124 1219 vcaballero
         */
125 5005 jorpiell
        public void initialize() {
126 2183 fernando
            try {
127
            Class.forName("javax.media.jai.EnumeratedParameter");
128
        } catch (ClassNotFoundException e) {
129
            NotificationManager.addError("La m?quina virtual con la que se ejecuta gvSIG no tiene JAI instalado", e);
130
        }
131 4748 fjp
132
                LayerFactory.setWritersPath(PluginServices.getPluginServices(this)
133 3666 fjp
                                  .getPluginDirectory()
134
                                  .getAbsolutePath() +
135
                                  File.separator + "drivers");
136 6153 caballero
137 4748 fjp
        LayerFactory.setDriversPath(PluginServices.getPluginServices(this)
138 4140 caballero
                                  .getPluginDirectory()
139
                                  .getAbsolutePath() +
140 4748 fjp
                                  File.separator + "drivers");
141 8536 jaume
142 7699 cesar
        initializeDocumentActionsExtensionPoint();
143 7689 cesar
        registerDocuments();
144 4140 caballero
145 3666 fjp
        // Recuperamos el ?ltimo argumento, que se supone
146
        // que ser? el fichero .gvp que queremos abrir.
147 4140 caballero
        // (por enmedio pueden venir o no otros argumentos,
148 3666 fjp
        // por ejemplo el idioma)
149
        // TODO: Aqu? Jaume podr?a meter lo del backup del proyecto
150
        // que ha hecho para ValenciaUrban?stica
151 4140 caballero
152 3666 fjp
                /*
153
                pe = (ProjectExtension) PluginServices.getExtension(com.iver.cit.gvsig.ProjectExtension.class);
154
                if (projectFile.length()!=0){
155 4140 caballero
                        p=pe.readProject(projectFile);
156 3666 fjp
                }
157
                else
158
                        p = restorePreviousProject();
159
                pe.setProject(p); */
160 4140 caballero
        String[] theArgs = PluginServices.getArguments();
161 3666 fjp
        String lastArg = theArgs[theArgs.length-1];
162
        if ((lastArg.endsWith(".gvp")) ||
163
                        (lastArg.endsWith(".GVP")))
164
        {
165
                PluginServices.getLogger().debug("Intentando cargar el proyecto " + lastArg);
166 6730 caballero
                //File projectFile = new File(lastArg);
167 10679 jaume
                setProject(readProject(lastArg));
168 3666 fjp
                PluginServices.getMainFrame().setTitle(p.getName());
169 7239 jmvivo
                projectPath = lastArg;
170 3666 fjp
        }
171
        else
172
        {
173 10679 jaume
                        setProject(ProjectFactory.createProject());
174 3666 fjp
                        p.setName(PluginServices.getText(this, "untitled"));
175
                        p.setModified(false);
176
                        PluginServices.getMainFrame().setTitle(PluginServices.getText(this, "sin_titulo"));
177
        }
178 7304 caballero
        }
179
        /**
180
         * @see com.iver.mdiApp.plugins.IExtension#postInitialize()
181
         */
182
        public void postInitialize() {
183 8536 jaume
                getProjectFrame().setProject(p);
184 7689 cesar
                p.restoreWindowProperties();
185 1219 vcaballero
        }
186 8536 jaume
187 9248 jjdelcerro
        public ProjectWindow getProjectFrame() {
188 8536 jaume
                if (projectFrame==null)
189
                                projectFrame = new ProjectWindow();
190
                return projectFrame;
191
        }
192 1219 vcaballero
        /**
193
         * Muestra la ventana con el gestor de proyectos.
194
         */
195
        public void showProjectWindow() {
196 7689 cesar
                if (seedProjectWindow!=null) {
197
                        if (seedProjectWindow.isClosed()) {
198
                                // if it was closed, we just don't open the window now
199
                                seedProjectWindow.setClosed(false);
200
                                return;
201
                        }
202
                        WindowInfo winProps = seedProjectWindow;
203
                        seedProjectWindow = null;
204 8536 jaume
                        PluginServices.getMDIManager().addWindow(getProjectFrame());
205
                        PluginServices.getMDIManager().changeWindowInfo(getProjectFrame(), winProps);
206 7689 cesar
                }
207
                else
208 8536 jaume
                        PluginServices.getMDIManager().addWindow(getProjectFrame());
209 312 fernando
        }
210 8536 jaume
211 7689 cesar
        /**
212
         * Muestra la ventana con el gestor de proyectos, con las propiedades
213
         * de ventana especificadas.
214
         */
215
        public void showProjectWindow(WindowInfo wi) {
216
                seedProjectWindow = wi;
217
                showProjectWindow();
218
        }
219 312 fernando
220 1219 vcaballero
        /**
221
         * Guarda el proyecto actual en disco.
222
         */
223 6190 caballero
        private boolean guardar() {
224
                boolean saved=false;
225 6876 jaume
//                if (p.getPath() == null) {
226
                if (projectPath == null) {
227 6190 caballero
                        saved=guardarDialogo();
228 312 fernando
                } else {
229 6876 jaume
                        saved=writeProject(new File(projectPath), p); //new File(p.getPath()), p);
230 8536 jaume
                        getProjectFrame().refreshControls();
231 312 fernando
                }
232 6190 caballero
                return saved;
233 312 fernando
        }
234 6876 jaume
235 6190 caballero
        private boolean guardarDialogo(){
236
                boolean saved=false;
237 7385 jaume
238
                if (lastSavePath == null)
239
                        lastSavePath = projectPath;
240
241 7444 jaume
                if (lastSavePath == null) {
242
                        Preferences prefs = Preferences.userRoot().node( "gvsig.foldering" );
243
                        lastSavePath = prefs.get("ProjectsFolder", null);
244
                }
245
246 7385 jaume
                JFileChooser jfc = new JFileChooser(lastSavePath);
247 1271 vcaballero
                jfc.addChoosableFileFilter(new GenericFileFilter("gvp",
248 1226 vcaballero
                                PluginServices.getText(this, "tipo_fichero_proyecto")));
249 1219 vcaballero
250 1226 vcaballero
                if (jfc.showSaveDialog((Component) PluginServices.getMainFrame()) == JFileChooser.APPROVE_OPTION) {
251 1254 vcaballero
                        File file=jfc.getSelectedFile();
252 6876 jaume
                        if (!(file.getPath().toLowerCase().endsWith(".gvp"))){
253 1271 vcaballero
                                file=new File(file.getPath()+".gvp");
254 1254 vcaballero
                        }
255 6190 caballero
                        saved=writeProject(file, p);
256 7385 jaume
                        String filePath = file.getAbsolutePath();
257
                        lastSavePath = filePath.substring(0, filePath.lastIndexOf(File.separatorChar));
258
259 8536 jaume
                        getProjectFrame().refreshControls();
260 1226 vcaballero
                }
261 6190 caballero
                return saved;
262 1226 vcaballero
        }
263 1219 vcaballero
        /**
264
         * Guarda si el proyecto ha sido modificado.
265
         *
266
         * @return True si se ha guardado correctamente.
267
         */
268 10679 jaume
        private int askSave() {
269
                if (p.hasChanged()) {
270 3586 caballero
                ///if (true) {
271 4140 caballero
                        //TODO de momento se queda como modificado siempre menos cuando est? totalmente vacio que se tomar? como no modificado,
272
                        //para poder controlar perfectamente cuando un proyecto ha sido modificado
273 2785 caballero
                        //hay que recoger los eventos de cambio de leyenda, cambio de extent, a?adir una capa, etc que se encuentran en FMap.
274 4140 caballero
275 10679 jaume
                        return JOptionPane.showConfirmDialog((Component) PluginServices.getMainFrame(),
276 596 fernando
                                        PluginServices.getText(this, "guardar_cambios"),
277 2419 caballero
                                        "gvSIG",
278 312 fernando
                                        JOptionPane.YES_NO_CANCEL_OPTION,
279
                                        JOptionPane.INFORMATION_MESSAGE);
280
281
                }
282 1219 vcaballero
283 10679 jaume
                return JOptionPane.NO_OPTION;
284 312 fernando
        }
285
286 1219 vcaballero
        /**
287 5005 jorpiell
         * @see com.iver.mdiApp.plugins.IExtension#updateUI(java.lang.String)
288 1219 vcaballero
         */
289
        public void execute(String actionCommand) {
290
                if (actionCommand.equals("NUEVO")) {
291
                        //Si est? modificado se pregunta si se quiere guardar el anterior
292 10679 jaume
                        int answer = askSave();
293
                        if (answer == JOptionPane.CANCEL_OPTION) {
294
                                // then do nothing
295 1219 vcaballero
                                return;
296 10679 jaume
                        } else if (answer == JOptionPane.YES_OPTION) {
297
                                execute("GUARDAR");
298 1219 vcaballero
                        }
299 9690 caballero
                        ProjectDocument.initializeNUMS();
300 6880 cesar
                        PluginServices.getMDIManager().closeAllWindows();
301 10679 jaume
                        setProject(ProjectFactory.createProject());
302
303
//                        p.setModified(true);
304 8536 jaume
                        getProjectFrame().setProject(p);
305 1219 vcaballero
                        showProjectWindow();
306 1412 fernando
                        PluginServices.getMainFrame().setTitle(PluginServices.getText(this, "sin_titulo"));
307 1219 vcaballero
                } else if (actionCommand.equals("ABRIR")) {
308
                        //Si est? modificado se pregunta si se quiere guardar el anterior
309 10679 jaume
                        int answer = askSave();
310
311
                        if (answer == JOptionPane.CANCEL_OPTION) { // ? don't ask me why
312 9690 caballero
                                ProjectDocument.initializeNUMS();
313 1219 vcaballero
                                return;
314
                        }
315 4140 caballero
316 7222 jaume
                        if (lastPath == null) {
317
                                Preferences prefs = Preferences.userRoot().node( "gvsig.foldering" );
318
                                lastPath = prefs.get("ProjectsFolder", null);
319
                        }
320
321
                        JFileChooser jfc = new JFileChooser(lastPath);
322 1271 vcaballero
                        jfc.addChoosableFileFilter(new GenericFileFilter("gvp",
323 1219 vcaballero
                                        PluginServices.getText(this, "tipo_fichero_proyecto")));
324
325
                        if (jfc.showOpenDialog((Component) PluginServices.getMainFrame()) == JFileChooser.APPROVE_OPTION) {
326 9690 caballero
                                ProjectDocument.initializeNUMS();
327 6880 cesar
                                PluginServices.getMDIManager().closeAllWindows();
328 6876 jaume
329
                                File projectFile = jfc.getSelectedFile();
330
                                Project o = readProject(projectFile);
331
                                setPath(projectFile.getAbsolutePath());
332 7222 jaume
                                lastPath = getPath();
333 1219 vcaballero
                                if (o != null) {
334 10679 jaume
                                        setProject(o);
335 596 fernando
                                }
336 312 fernando
337 8536 jaume
                                getProjectFrame().setProject(p);
338 1412 fernando
                                PluginServices.getMainFrame().setTitle(p.getName());
339 8536 jaume
                                getProjectFrame().refreshControls();
340 10679 jaume
341
//jaume                                p.setModified(true);
342 7689 cesar
                                p.restoreWindowProperties();
343 1219 vcaballero
                        }
344
                } else if (actionCommand.equals("GUARDAR")) {
345
                        guardar();
346 10679 jaume
//jaume                        p.setModified(false);
347 1226 vcaballero
                } else if (actionCommand.equals("GUARDAR_COMO")) {
348
                        guardarDialogo();
349 10679 jaume
//jaume                        p.setModified(false);
350 2242 jaume
                } else if (actionCommand.equals("SALIR")){
351 6190 caballero
                        int option = JOptionPane.showConfirmDialog((Component)PluginServices.getMainFrame(),
352 2242 jaume
                                        Messages.getString("MDIFrame.quiere_salir"),
353
                                        Messages.getString("MDIFrame.salir"),
354
                                        JOptionPane.YES_NO_OPTION);
355
356
                        if (option == JOptionPane.YES_OPTION) {
357
                                Launcher.closeApplication();
358
                        }
359 3115 caballero
                } else if (actionCommand.compareTo("OPENTEMPLATE")==0){
360
                        openLayout();
361 10679 jaume
//jaume                        p.setModified(true);
362 1219 vcaballero
                }
363
        }
364 3115 caballero
        public void openLayout() {
365 3135 caballero
                //Project project = ((ProjectExtension) PluginServices.getExtension(ProjectExtension.class)).getProject();
366 3115 caballero
                Layout layout=null;
367 7426 jaume
368
                if (templatesPath == null) {
369
                        Preferences prefs = Preferences.userRoot().node( "gvsig.foldering" );
370
                        templatesPath = prefs.get("TemplatesFolder", null);
371
                }
372
373
                JFileChooser jfc = new JFileChooser(templatesPath);
374 3115 caballero
                jfc.addChoosableFileFilter(new GenericFileFilter("gvt",
375
                                PluginServices.getText(this, "plantilla")));
376 312 fernando
377 3115 caballero
                if (jfc.showOpenDialog((Component) PluginServices.getMainFrame()) == JFileChooser.APPROVE_OPTION) {
378
                        File file=jfc.getSelectedFile();
379
                        if (!(file.getPath().endsWith(".gvt") || file.getPath().endsWith(".GVT"))){
380
                                file=new File(file.getPath()+".gvt");
381
                        }
382
                        try {
383
                                File xmlFile = new File(file.getAbsolutePath());
384
                                FileReader reader;
385
                                reader = new FileReader(xmlFile);
386
387
                                XmlTag tag = (XmlTag) XmlTag.unmarshal(reader);
388 3185 caballero
                                try {
389
                                        layout = Layout.createLayout(new XMLEntity(tag),p);
390
                                } catch (OpenException e) {
391
                                        e.showError();
392
                                }
393 3115 caballero
                                //fPanelLegendManager.setRenderer(LegendFactory.createFromXML(new XMLEntity(tag)));
394
                        } catch (FileNotFoundException e) {
395
                                NotificationManager.addError(PluginServices.getText(this, "Al_leer_la_leyenda"), e);
396
                        } catch (MarshalException e) {
397 5503 cesar
                                NotificationManager.addError(PluginServices.getText(this, "Al_leer_la_leyenda"), e);
398 3115 caballero
                        } catch (ValidationException e) {
399 5503 cesar
                                NotificationManager.addError(PluginServices.getText(this, "Al_leer_la_leyenda"), e);
400 3115 caballero
                        }
401
                        ProjectMap pmap = ProjectFactory.createMap(file.getName());
402
                        pmap.setModel(layout);
403
                        pmap.getModel().setProjectMap(pmap);
404 7304 caballero
                        p.addDocument(pmap);
405 6880 cesar
                        PluginServices.getMDIManager().addWindow(layout);
406 4140 caballero
407
408 3115 caballero
                }
409
        }
410 1219 vcaballero
        /**
411
         * Escribe el proyecto en XML.
412
         *
413
         * @param file Fichero.
414
         * @param p Proyecto.
415
         */
416 6190 caballero
        public boolean writeProject(File file, Project p) {
417 8801 jaume
                return writeProject(file, p, true);
418
        }
419
420 8803 jaume
        /**
421
         * Escribe el proyecto en XML. Pero permite decidir si se
422
         * pide confirmaci?n para sobreescribir
423
         *
424
         * @param file Fichero.
425
         * @param p Proyecto.
426
         * @param askConfirmation boolean
427
         */
428 8802 jaume
        public boolean writeProject(File file, Project p, boolean askConfirmation) {
429
                if( askConfirmation && file.exists()){
430 6153 caballero
                        int resp = JOptionPane.showConfirmDialog(
431
                                        (Component) PluginServices.getMainFrame(),PluginServices.getText(this,"fichero_ya_existe_seguro_desea_guardarlo"),
432
                                        PluginServices.getText(this,"guardar"), JOptionPane.YES_NO_OPTION);
433
                        if (resp != JOptionPane.YES_OPTION) {
434 6190 caballero
                                return false;
435 6153 caballero
                        }
436
                }
437 1219 vcaballero
                // write it out as XML
438 596 fernando
                try {
439 8455 cesar
            FileOutputStream fos = new FileOutputStream(file.getAbsolutePath());
440 10365 caballero
            OutputStreamWriter writer = new OutputStreamWriter(fos, PROJECTENCODING);
441 1219 vcaballero
                        Marshaller m = new Marshaller(writer);
442 10365 caballero
                        m.setEncoding(PROJECTENCODING);
443 1254 vcaballero
                        p.setName(file.getName());
444 6876 jaume
                        // p.setPath(file.toString());
445 1219 vcaballero
                        p.setModificationDate(DateFormat.getDateInstance().format(new Date()));
446
                        p.setModified(false);
447 8455 cesar
                        XMLEntity xml = p.getXMLEntity();
448 10679 jaume
                        xml.putProperty("followHeaderEncoding", true, false);
449 8455 cesar
                        m.marshal(xml.getXmlTag());
450 1412 fernando
                        PluginServices.getMainFrame().setTitle(file.getName());
451 6876 jaume
                        setPath(file.toString());
452
453 1219 vcaballero
                } catch (Exception e) {
454
                        NotificationManager.addError("Error guardando el proyecto", e);
455 6190 caballero
                        return false;
456 1219 vcaballero
                }
457 6190 caballero
                return true;
458 1219 vcaballero
        }
459
460 6730 caballero
        public Project readProject(String path) {
461
                BufferedReader reader =null;
462
                try {
463
                URL url=null;
464
                        url = new URL(path);
465 8455 cesar
                        String encoding = XMLEncodingUtils.getEncoding(url.openStream());
466
                        InputStream is = url.openStream();
467
                        if (encoding!=null) {
468
                                Project proj=null;
469
                                try {
470
                                        reader = new BufferedReader(new InputStreamReader(is, encoding));
471
                                        proj=readProject(reader, true);
472
                                } catch (UnsupportedEncodingException e) {
473
                                        reader = new BufferedReader(new InputStreamReader(is));
474
                                        try {
475
                                                Project p=readProject(reader, false);
476
                                        } catch (UnsupportedEncodingException e1) {
477
                                                JOptionPane.showMessageDialog((Component)PluginServices.getMainFrame(),PluginServices.getText(this, e1.getLocalizedMessage()));
478 8536 jaume
                                                return null;
479 8455 cesar
                                        }
480
                                }
481
                                ProjectExtension.setPath(path);
482
                                return proj;
483
                        }
484
                        else {
485
                                reader = new BufferedReader(new InputStreamReader(is));
486
                                Project p;
487
                                try {
488
                                        p = readProject(reader, false);
489
                                } catch (UnsupportedEncodingException e) {
490
                                        JOptionPane.showMessageDialog((Component)PluginServices.getMainFrame(),PluginServices.getText(this, e.getLocalizedMessage()));
491
                                        return null;
492
                                }
493
                                ProjectExtension.setPath(path); //p.setPath(null);
494
                                return p;
495
                        }
496 6730 caballero
                } catch (MalformedURLException e) {
497
                        File file=new File(path);
498
                        return readProject(file);
499
                } catch (IOException e) {
500
                        e.printStackTrace();
501 8455 cesar
                        return null;
502 6730 caballero
                }
503
        }
504
505 8455 cesar
        /**
506
         * Lee del XML el proyecto.<br><br>
507
         *
508
         * Reads the XML of the project.<br>
509
         * It returns a project object holding all needed info that is not linked to the Project Dialog. <br>In case you want the project to be
510
         * linked to the window you must set this object to the extension:<br>
511
         *
512
         * <b>Example:</b><br>
513
         *
514
         * ...<br>
515
         * ...<br>
516
         * Project p = ProjectExtension.readProject(projectFile);<br>
517
         * ProjectExtension.setProject(p);
518
         * ...<br>
519
         * ...<br>
520
         * @param file Fichero.
521
         *
522
         * @return Project
523
         *
524
         */
525 6730 caballero
        public Project readProject(File file) {
526
                File xmlFile = new File(file.getAbsolutePath());
527
                try {
528 8455 cesar
                        String encoding = XMLEncodingUtils.getEncoding(new FileInputStream(xmlFile));
529
                        InputStreamReader reader=null;
530
                        if (encoding!=null) {
531
                                try {
532
                                        reader = new InputStreamReader(new FileInputStream(xmlFile), encoding);
533
                                        return readProject(reader, true);
534
                                } catch (UnsupportedEncodingException e) {
535
                                        reader = new InputStreamReader(new FileInputStream(xmlFile));
536
                                        try {
537
                                                return readProject(reader, false);
538
                                        } catch (UnsupportedEncodingException e1) {
539
                                                JOptionPane.showMessageDialog((Component)PluginServices.getMainFrame(),PluginServices.getText(this, e1.getLocalizedMessage()));
540
                                                return null;
541
                                        }
542
                                }
543
                        }
544
                        else {
545
                                reader = new InputStreamReader(new FileInputStream(xmlFile));
546
                                try {
547
                                        return readProject(reader, false);
548
                                } catch (UnsupportedEncodingException e1) {
549
                                        JOptionPane.showMessageDialog((Component)PluginServices.getMainFrame(),PluginServices.getText(this, e1.getLocalizedMessage()));
550
                                        return null;
551
                                }
552
                        }
553 6730 caballero
                } catch (FileNotFoundException e) {
554
                        JOptionPane.showMessageDialog((Component)PluginServices.getMainFrame(),PluginServices.getText(this, "fichero_incorrecto"));
555
                        return null;
556
                }
557 8455 cesar
        }
558 8536 jaume
559 1219 vcaballero
        /**
560 2922 jaume
         * Lee del XML el proyecto.<br><br>
561 4140 caballero
         *
562 2922 jaume
         * Reads the XML of the project.<br>
563 8455 cesar
         * It returns a project object holding all needed info that is not linked to the Project Dialog. <br>In case you want the project to be
564
         * linked to the window you must set this object to the extension:<br>
565 4140 caballero
         *
566 2922 jaume
         * <b>Example:</b><br>
567 4140 caballero
         *
568 2922 jaume
         * ...<br>
569
         * ...<br>
570 3666 fjp
         * Project p = ProjectExtension.readProject(projectFile);<br>
571 2922 jaume
         * ProjectExtension.setProject(p);
572
         * ...<br>
573
         * ...<br>
574 8455 cesar
         * @param reader File reader
575
         * @param encodingFollowed Whether the encoded specified in the xml header was followed
576
         * when creating the reader. If the property followHeaderEncoding is false or not set,
577
         * then the encoding should have not been used when creating the reader, so it must be
578
         * recreated.
579 8536 jaume
         *
580 2922 jaume
         * @return Project
581 8536 jaume
         * @throws UnsupportedEncodingException
582 4140 caballero
         *
583 312 fernando
         */
584 9213 fdiaz
        public Project readProject(Reader reader, boolean encodingFollowed) throws UnsupportedEncodingException {
585 1219 vcaballero
                Project proj = null;
586
587
                try {
588 2183 fernando
                        XmlTag tag = (XmlTag) XmlTag.unmarshal(reader);
589 3167 caballero
                        XMLEntity xml=new XMLEntity(tag);
590
                        String VERSION=xml.getStringProperty("VERSION");
591 8536 jaume
592 8455 cesar
                        if (encodingFollowed) {
593
                                if (xml.contains("followHeaderEncoding")) {
594
                                        boolean useEncoding = xml.getBooleanProperty("followHeaderEncoding");
595
                                        if (!useEncoding) {
596
                                                throw new UnsupportedEncodingException("the encoding specified in the xml header is not safe");
597
                                        }
598
                                }
599
                                else {
600
                                        // Old projects didn't contain followHeaderEncoding and they were
601
                                        // not correctly encoded. We throw an exception now, and we'll try
602
                                        // to reopen the project
603 8536 jaume
                                        // using the default system encoding.
604 8455 cesar
                                        throw new UnsupportedEncodingException("the encoding specified in the xml header is not safe");
605
                                }
606
                        }
607 8536 jaume
608 2183 fernando
                        try {
609 3810 fjp
                                // if ((VERSION!=null) && (VERSION.equals("0.5") || VERSION.equals("0.4") || (VERSION.indexOf("GISPLANET") != -1))){
610
                                if (VERSION != null) {
611 3167 caballero
                                        proj = Project.createFromXML(xml);
612
                                }else{
613
                                        proj = Project.createFromXML03(new XMLEntity(tag));
614
                                }
615 2183 fernando
                                return proj;
616 3185 caballero
                        } catch (OpenException e){
617
                                e.showError();
618
                                //NotificationManager.addInfo("Al leer el proyecto", e);
619 3167 caballero
                        }
620 6730 caballero
                }  catch (MarshalException e) {
621 9237 caballero
                        PluginServices.getLogger().error(PluginServices.getText(this, "formato_incorrecto"),e);
622 2695 nacho
                        JOptionPane.showMessageDialog((Component)PluginServices.getMainFrame(),PluginServices.getText(this, "formato_incorrecto"));
623 2419 caballero
                        //NotificationManager.addError("Al leer el proyecto", e);
624 1219 vcaballero
                } catch (ValidationException e) {
625 9213 fdiaz
                        PluginServices.getLogger().error(PluginServices.getText(this, "formato_incorrecto"),e);
626 2695 nacho
                        JOptionPane.showMessageDialog((Component)PluginServices.getMainFrame(),PluginServices.getText(this, "formato_incorrecto"));
627 2419 caballero
                        //NotificationManager.addError("Al leer el proyecto", e);
628 4140 caballero
                }
629 2183 fernando
                return null;
630 1219 vcaballero
        }
631
632
        /**
633
         * Devuelve el proyecto.
634
         *
635
         * @return Proyecto.
636
         */
637 312 fernando
        public Project getProject() {
638
                return p;
639
        }
640
641 596 fernando
        /**
642 5005 jorpiell
         * @see com.iver.andami.plugins.IExtension#isEnabled()
643 596 fernando
         */
644
        public boolean isEnabled() {
645
                return true;
646
        }
647
648
        /**
649 5005 jorpiell
         * @see com.iver.andami.plugins.IExtension#isVisible()
650 596 fernando
         */
651
        public boolean isVisible() {
652
                return true;
653
        }
654 4140 caballero
655 2879 jaume
        /**
656 2922 jaume
         * Sets the project
657 2879 jaume
         * @param p
658
         */
659 2922 jaume
        public void setProject(Project p){
660 8536 jaume
                getProjectFrame().setProject(p);
661 10679 jaume
                p.setSignature(p.getXMLEntity().hash());
662 2922 jaume
                this.p=p;
663 2879 jaume
        }
664 6190 caballero
665 10679 jaume
        public boolean isReadyToTerminate() {
666
                int answer = askSave();
667
668
                if (answer == JOptionPane.CANCEL_OPTION) {
669
                        // the user doesn't want to close the application
670
                        // so quit will be canceled.
671
                        return false;
672
                } else if (answer == JOptionPane.YES_OPTION) {
673
                        // the user wants to save the project before exit
674
                        boolean ready = guardar();
675
                        if (!ready) {
676
                                int sel = JOptionPane.showConfirmDialog((Component) PluginServices.getMainFrame(),
677
                                                PluginServices.getText(this, "the_project_could_not_be_saved.Continue_exiting_anyway"),
678
                                                PluginServices.getText(this, "warning"),
679
                                                JOptionPane.YES_NO_OPTION);
680
                                ready = (sel == JOptionPane.YES_OPTION);
681
                        }
682
683
                        return ready;
684
                } else if (answer == JOptionPane.NO_OPTION) {
685
                        // the user doesn't care about the current state of the project
686
                        return true;
687
                } else {
688
                        NotificationManager.addWarning("Reached what should be unreachable code", new IllegalArgumentException());
689
                        return false;
690
                }
691
        }
692
693 6190 caballero
        //Finalizar y preguntar si se quiere guardar el proyecto o cancelar.
694 6639 caballero
        public void terminate() {
695 10679 jaume
//                long t1,t2;
696
//                t1 = System.currentTimeMillis();
697
//                if (askSave()){
698
//                        int option = JOptionPane.showConfirmDialog((Component)PluginServices.getMainFrame(),PluginServices.getText(this,"guardar_cambios"),
699
//                                        PluginServices.getText(this,"guardar_proyecto"),
700
//                                        JOptionPane.YES_NO_OPTION);
701
//
702
//                        if (option == JOptionPane.YES_OPTION) {
703
//                                if (!guardar())
704
//                                        terminate();
705
//                        }
706
//                }
707
//                t2 = System.currentTimeMillis();
708
//                System.err.println("ProjectExtension.terminate() " +  (t2-t1) + "milisecs");
709 6190 caballero
        }
710 6730 caballero
711 7304 caballero
        private void registerDocuments() {
712 7343 caballero
                ProjectViewFactory.register();
713
                ProjectTableFactory.register();
714
                ProjectMapFactory.register();
715 7304 caballero
        }
716 10679 jaume
717 7699 cesar
        private void initializeDocumentActionsExtensionPoint() {
718 6730 caballero
                ExtensionPoints extensionPoints = ExtensionPointsSingleton.getInstance();
719 6672 jmvivo
                if (!extensionPoints.containsKey("DocumentActions_View")) {
720
                        extensionPoints.put(
721
                                new ExtensionPoint(
722
                                        "DocumentActions_View",
723 6730 caballero
                                        "Context menu options of the view document list" +
724
                                                " in the project window "+
725 6672 jmvivo
                                                "(register instances of " +
726
                                                "com.iver.cit.gvsig.project.AbstractDocumentContextMenuAction)"
727
                                )
728 6730 caballero
                        );
729 6672 jmvivo
                }
730
                if (!extensionPoints.containsKey("DocumentActions_Table")) {
731
                        extensionPoints.put(
732
                                new ExtensionPoint(
733
                                        "DocumentActions_Table",
734 6730 caballero
                                        "Context menu options of the table document list" +
735
                                                " in the project window "+
736 6672 jmvivo
                                                "(register instances of " +
737
                                                "com.iver.cit.gvsig.project.AbstractDocumentContextMenuAction)"
738
                                )
739
                        );
740
                }
741
                if (!extensionPoints.containsKey("DocumentActions_Map")) {
742
                        extensionPoints.put(
743
                                new ExtensionPoint(
744
                                        "DocumentActions_Map",
745 6730 caballero
                                        "Context menu options of the map document list" +
746
                                                " in the project window "+
747 6672 jmvivo
                                                "(register instances of " +
748
                                                "com.iver.cit.gvsig.project.AbstractDocumentContextMenuAction)"
749
                                )
750
                        );
751
                }
752 6635 jmvivo
        }
753 6876 jaume
754
        public static String getPath() {
755
                return projectPath;
756
        }
757
758
        public static void setPath(String path) {
759
                projectPath = path;
760
        }
761
762 7608 cesar
        public IWindow getProjectWindow() {
763 8536 jaume
                return getProjectFrame();
764 7608 cesar
        }
765 312 fernando
}