Statistics
| Revision:

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

History | View | Annotate | Download (25.9 KB)

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