Statistics
| Revision:

svn-gvsig-desktop / branches / v2_0_0_prep / applications / appgvSIG / src / org / gvsig / app / extension / ProjectExtension.java @ 33639

History | View | Annotate | Download (32.1 KB)

1
/* gvSIG. Sistema de Informaci?n Geogr?fica de la Generalitat Valenciana
2
 *
3
 * Copyright (C) 2004-2007 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 org.gvsig.app.extension;
42

    
43
import java.awt.Component;
44
import java.io.File;
45
import java.io.FileInputStream;
46
import java.io.FileNotFoundException;
47
import java.util.ArrayList;
48
import java.util.Iterator;
49
import java.util.List;
50
import java.util.prefs.Preferences;
51

    
52
import javax.swing.JOptionPane;
53

    
54
import org.gvsig.andami.Launcher;
55
import org.gvsig.andami.PluginServices;
56
import org.gvsig.andami.Launcher.TerminationProcess;
57
import org.gvsig.andami.messages.NotificationManager;
58
import org.gvsig.andami.plugins.Extension;
59
import org.gvsig.andami.plugins.IExtension;
60
import org.gvsig.andami.plugins.status.IExtensionStatus;
61
import org.gvsig.andami.plugins.status.IUnsavedData;
62
import org.gvsig.andami.plugins.status.UnsavedData;
63
import org.gvsig.andami.ui.mdiManager.IWindow;
64
import org.gvsig.andami.ui.mdiManager.WindowInfo;
65
import org.gvsig.andami.ui.wizard.UnsavedDataPanel;
66
import org.gvsig.app.project.Project;
67
import org.gvsig.app.project.ProjectManager;
68
import org.gvsig.app.project.documents.gui.ProjectWindow;
69
import org.gvsig.app.project.documents.layout.LayoutDocument;
70
import org.gvsig.app.project.documents.layout.LayoutManager;
71
import org.gvsig.app.project.documents.layout.gui.LayoutPanel;
72
import org.gvsig.app.project.documents.table.TableManager;
73
import org.gvsig.app.project.documents.view.ViewManager;
74
import org.gvsig.gui.beans.swing.JFileChooser;
75
import org.gvsig.tools.ToolsLocator;
76
import org.gvsig.tools.extensionpoint.ExtensionPointManager;
77
import org.gvsig.tools.persistence.PersistenceManager;
78
import org.gvsig.tools.persistence.PersistentState;
79
import org.gvsig.tools.persistence.exception.PersistenceException;
80
import org.gvsig.utils.GenericFileFilter;
81
import org.gvsig.utils.save.AfterSavingListener;
82
import org.gvsig.utils.save.BeforeSavingListener;
83
import org.gvsig.utils.save.SaveEvent;
84
import org.gvsig.utils.swing.threads.IMonitorableTask;
85

    
86

    
87

    
88
/**
89
 * Extension que proporciona controles para crear proyectos nuevos, abrirlos y
90
 * guardarlos. Adem?s los tipos de tabla que soporta el proyecto son a?adidos
91
 * en esta clase.
92
 *
93
 * @author Fernando Gonz?lez Cort?s
94
 */
95
public class ProjectExtension extends Extension implements IExtensionStatus {
96
        private static String projectPath = null;
97
        //private ProjectWindow projectFrame;
98
        private ProjectWindow projectFrame;
99
        private Project p;
100
//        private String lastPath;
101
        private String lastSavePath;
102
        private String templatesPath;
103
        private WindowInfo seedProjectWindow;
104
        public static final String LAYOUT_TEMPLATE_FILECHOOSER_ID = "LAYOUT_TEMPLATE_FILECHOOSER_ID";
105
        public static final String PROJECT_FILE_CHOOSER_ID = "PROJECT_FILECHOOSER_ID";
106
        /**
107
         * Use UTF-8 for encoding, as it can represent characters from
108
         * any language.
109
         *
110
         * Another sensible option would be
111
         * encoding = System.getProperty("file.encoding");
112
         * but this would need some extra testing.
113
         * @deprecated see PersistentManager
114
         */
115
        public static String PROJECTENCODING = "UTF-8";
116

    
117
        private List<BeforeSavingListener> beforeSavingListeners = new ArrayList<BeforeSavingListener>();
118
        //        /**
119
        //         * <p>Identifier of the extension point used by <code>ProjectExtension</code> to manage {@link BeforeSavingListener BeforeSavingListener}s.</p>
120
        //         */
121
        //        public static final String BEFORE_SAVING_ID = "Before_Saving_PrjExt";
122

    
123
        private List<AfterSavingListener> afterSavingListeners = new ArrayList<AfterSavingListener>();
124

    
125
        //        /**
126
        //         * <p>Identifier of the extension point used by <code>ProjectExtension</code> to manage {@link BeforeSavingListener BeforeSavingListener}s.</p>
127
        //         */
128
        //        public static final String AFTER_SAVING_ID = "After_Saving_PrjExt";
129

    
130
        /**
131
         * @see com.iver.mdiApp.plugins.IExtension#initialize()
132
         */
133
        public void initialize() {
134
            try {
135
            Class.forName("javax.media.jai.EnumeratedParameter");
136
        } catch (ClassNotFoundException e) {
137
            NotificationManager.addError("La m?quina virtual con la que se ejecuta gvSIG no tiene JAI instalado", e);
138
        }
139

    
140
        initializeDocumentActionsExtensionPoint();
141
        registerDocuments();
142

    
143
            registerIcons();
144

    
145
        }
146

    
147
        private void registerIcons(){
148
                PluginServices.getIconTheme().registerDefault(
149
                                "project-new",
150
                                this.getClass().getClassLoader().getResource("images/new.png")
151
                        );
152

    
153
                PluginServices.getIconTheme().registerDefault(
154
                                "project-open",
155
                                this.getClass().getClassLoader().getResource("images/open.png")
156
                        );
157

    
158
                PluginServices.getIconTheme().registerDefault(
159
                                "project-save",
160
                                this.getClass().getClassLoader().getResource("images/save.png")
161
                        );
162

    
163
                PluginServices.getIconTheme().registerDefault(
164
                                "project-save-as",
165
                                this.getClass().getClassLoader().getResource("images/save.png")
166
                        );
167

    
168
                PluginServices.getIconTheme().registerDefault(
169
                                "layout-template-open",
170
                                this.getClass().getClassLoader().getResource("images/opentemplate.png")
171
                        );
172

    
173
                PluginServices.getIconTheme().registerDefault(
174
                                "application-exit",
175
                                this.getClass().getClassLoader().getResource("images/salir.png")
176
                        );
177
        }
178

    
179
        private void loadInitialProject(){
180
                String[] theArgs = PluginServices.getArguments();
181
        String lastArg = theArgs[theArgs.length-1];
182
        if ((lastArg.toLowerCase().endsWith(".gvp")) ) {
183
                PluginServices.getLogger().debug("Intentando cargar el proyecto " + lastArg);
184
                //File projectFile = new File(lastArg);
185
                setProject(readProject(lastArg));
186
                PluginServices.getMainFrame().setTitle(p.getName());
187
                projectPath = lastArg;
188
        }
189
        else
190
        {
191
                        setProject(ProjectManager.getInstance().createProject());
192
                        p.setName(PluginServices.getText(this, "untitled"));
193
                        p.setModified(false);
194
                        PluginServices.getMainFrame().setTitle(PluginServices.getText(this, "sin_titulo"));
195
        }
196
       
197
        }
198

    
199
        /**
200
         * @see com.iver.mdiApp.plugins.IExtension#postInitialize()
201
         */
202
        public void postInitialize() {
203
                loadInitialProject();
204
                getProjectFrame().setProject(p);
205
                showProjectWindow();
206
        }
207

    
208
        public ProjectWindow getProjectFrame() {
209
                if (projectFrame==null) {
210
                        projectFrame = new ProjectWindow();
211
                }
212
                return projectFrame;
213
        }
214
        /**
215
         * Muestra la ventana con el gestor de proyectos.
216
         */
217
        public void showProjectWindow() {
218
                if (seedProjectWindow!=null) {
219
                        if (seedProjectWindow.isClosed()) {
220
                                // if it was closed, we just don't open the window now
221
                                seedProjectWindow.setClosed(false);
222
                                return;
223
                        }
224
                        WindowInfo winProps = seedProjectWindow;
225
                        seedProjectWindow = null;
226
                        PluginServices.getMDIManager().addWindow(getProjectFrame());
227
                        PluginServices.getMDIManager().changeWindowInfo(getProjectFrame(), winProps);
228
                } else {
229
                        PluginServices.getMDIManager().addWindow(getProjectFrame());
230
                }
231
        }
232

    
233
        /**
234
         * Muestra la ventana con el gestor de proyectos, con las propiedades
235
         * de ventana especificadas.
236
         */
237
        public void showProjectWindow(WindowInfo wi) {
238
                seedProjectWindow = wi;
239
                showProjectWindow();
240
        }
241

    
242
        /**
243
         * Guarda el proyecto actual en disco.
244
         */
245
        private boolean guardar() {
246
                boolean saved=false;
247
//                if (p.getPath() == null) {
248
                if (projectPath == null) {
249
                        saved=guardarDialogo();
250
                } else {
251
                        long t1,t2;
252
                        t1 = System.currentTimeMillis();
253
                        saved=writeProject(new File(projectPath), p, false);
254
                        t2 = System.currentTimeMillis();
255
                        PluginServices.getLogger().info("Project saved. " +  (t2-t1) + " miliseconds");
256
                        getProjectFrame().refreshControls();
257
                }
258
                return saved;
259
        }
260

    
261
        private boolean guardarDialogo(){
262
                boolean saved=false;
263

    
264
                if (lastSavePath == null) {
265
                        lastSavePath = projectPath;
266
                }
267

    
268

    
269
                Preferences prefs = Preferences.userRoot().node( "gvsig.foldering");
270
                JFileChooser jfc = new JFileChooser(PROJECT_FILE_CHOOSER_ID, prefs.get("ProjectsFolder", null));
271

    
272
                jfc.setDialogTitle(PluginServices.getText(this, "guardar_proyecto"));
273
                jfc.addChoosableFileFilter(new GenericFileFilter("gvp",
274
                                PluginServices.getText(this, "tipo_fichero_proyecto")));
275

    
276
                if (jfc.showSaveDialog((Component) PluginServices.getMainFrame()) == JFileChooser.APPROVE_OPTION) {
277
                        File file=jfc.getSelectedFile();
278
                        if (!(file.getPath().toLowerCase().endsWith(".gvp"))){
279
                                file=new File(file.getPath()+".gvp");
280
                        }
281
                        saved=writeProject(file, p);
282
                        String filePath = file.getAbsolutePath();
283
                        lastSavePath = filePath.substring(0, filePath.lastIndexOf(File.separatorChar));
284

    
285
                        getProjectFrame().refreshControls();
286
                }
287
                return saved;
288
        }
289

    
290
        /**
291
         * Checks whether the project and related unsaved data is modified,
292
         *  and allows the user to save it.
293
         *
294
         * @return true if the data has been correctly saved, false otherwise
295
         */
296
        private boolean askSave() {
297
                if (p != null && p.hasChanged()) {
298
                        TerminationProcess process = Launcher.getTerminationProcess();
299
                        UnsavedDataPanel panel = process.getUnsavedDataPanel();
300
                        panel.setHeaderText(PluginServices.getText(this, "Select_resources_to_save_before_closing_current_project"));
301
                        panel.setAcceptText(
302
                                        PluginServices.getText(this, "save_resources"),
303
                                        PluginServices.getText(this, "Save_the_selected_resources_and_close_current_project"));
304
                        panel.setCancelText(
305
                                        PluginServices.getText(this, "Dont_close"),
306
                                        PluginServices.getText(this, "Return_to_current_project"));
307
                        int closeCurrProj = process.manageUnsavedData();
308
                        if (closeCurrProj==JOptionPane.NO_OPTION) {
309
                                // the user chose to return to current project
310
                                return false;
311
                        }
312
                }
313
                return true;
314
        }
315

    
316
        /**
317
         * @see com.iver.mdiApp.plugins.IExtension#updateUI(java.lang.String)
318
         */
319
        public void execute(String actionCommand) {
320
                if (actionCommand.equals("NUEVO")) {
321
                        if (!askSave()) {
322
                                return;
323
                        }
324

    
325
                        projectPath=null;
326
                        //ProjectDocument.initializeNUMS();
327
                        PluginServices.getMDIManager().closeAllWindows();
328
                        setProject(ProjectManager.getInstance().createProject());
329
                        getProjectFrame().setProject(p);
330
                        showProjectWindow();
331
                        PluginServices.getMainFrame().setTitle(PluginServices.getText(this, "sin_titulo"));
332
                } else if (actionCommand.equals("ABRIR")) {
333
                        if (!askSave()) {
334
                                return;
335
                        }
336

    
337
                        Preferences prefs = Preferences.userRoot().node( "gvsig.foldering" );
338
                        JFileChooser jfc = new JFileChooser(PROJECT_FILE_CHOOSER_ID, prefs.get("ProjectsFolder", null));
339
                        jfc.addChoosableFileFilter(new GenericFileFilter("gvp",
340
                                        PluginServices.getText(this, "tipo_fichero_proyecto")));
341

    
342
                        if (jfc.showOpenDialog((Component) PluginServices.getMainFrame()) == JFileChooser.APPROVE_OPTION) {
343
                                //ProjectDocument.initializeNUMS();
344
                                PluginServices.getMDIManager().closeAllWindows();
345

    
346
                                File projectFile = jfc.getSelectedFile();
347
                                Project o = readProject(projectFile);
348
                                setPath(projectFile.getAbsolutePath());
349
//                                lastPath = getPath();
350
                                if (o != null) {
351
                                        setProject(o);
352
                                }
353

    
354
                                getProjectFrame().setProject(p);
355
                                PluginServices.getMainFrame().setTitle(p.getName());
356
                                getProjectFrame().refreshControls();
357

    
358
                                //p.restoreWindowProperties();
359
                        }
360
                } else if (actionCommand.equals("GUARDAR")) {
361
                        guardar();
362
                } else if (actionCommand.equals("GUARDAR_COMO")) {
363
                        guardarDialogo();
364
                } else if (actionCommand.equals("SALIR")){
365
                        Launcher.closeApplication();
366
                } else if (actionCommand.compareTo("OPENTEMPLATE")==0){
367
                        openLayout();
368
                }
369
        }
370
        private void openLayout() {
371
                //Project project = ((ProjectExtension) PluginServices.getExtension(ProjectExtension.class)).getProject();
372
                LayoutPanel layout=null;
373

    
374
                if (templatesPath == null) {
375
                        Preferences prefs = Preferences.userRoot().node( "gvsig.foldering" );
376
                        templatesPath = prefs.get("TemplatesFolder", null);
377
                }
378

    
379
                JFileChooser jfc = new JFileChooser(LAYOUT_TEMPLATE_FILECHOOSER_ID, templatesPath);
380
                jfc.addChoosableFileFilter(new GenericFileFilter("gvt",
381
                                PluginServices.getText(this, "plantilla")));
382

    
383
                if (jfc.showOpenDialog((Component) PluginServices.getMainFrame()) == JFileChooser.APPROVE_OPTION) {
384
                        File file=jfc.getSelectedFile();
385
                        if (!(file.getPath().endsWith(".gvt") || file.getPath().endsWith(".GVT"))){
386
                                file=new File(file.getPath()+".gvt");
387
                        }
388
                        try {
389
                                File xmlFile = new File(file.getAbsolutePath());
390
                                FileInputStream is = new FileInputStream(xmlFile);
391
                                
392
                                PersistenceManager persistenceManager = ToolsLocator.getPersistenceManager();
393
                                PersistentState persistentState = persistenceManager.loadState(is);
394
                                layout = (LayoutPanel)persistenceManager.create(persistentState);
395

    
396
                        } catch (FileNotFoundException e) {
397
                                NotificationManager.addError(PluginServices.getText(this, "Al_leer_la_leyenda"), e);
398
                        } catch (PersistenceException e) {
399
                            NotificationManager.addError(PluginServices.getText(this, "Al_leer_la_leyenda"), e);
400
            }
401

    
402
                        LayoutDocument layoutDocument = (LayoutDocument) ProjectManager.getInstance().createDocument(LayoutManager.TYPENAME, file.getName());
403
                        p.add(layoutDocument);
404
                        PluginServices.getMDIManager().addWindow(layout);
405

    
406

    
407
                }
408
        }
409
        /**
410
         * Escribe el proyecto en XML.
411
         *
412
         * @param file Fichero.
413
         * @param p Proyecto.
414
         */
415
        public boolean writeProject(File file, Project p) {
416
                return writeProject(file, p, true);
417
        }
418

    
419
        /**
420
         * Escribe el proyecto en XML. Pero permite decidir si se
421
         * pide confirmaci?n para sobreescribir
422
         *
423
         * @param file Fichero.
424
         * @param p Proyecto.
425
         * @param askConfirmation boolean
426
         */
427
        public boolean writeProject(File file, Project p, boolean askConfirmation) {
428
                if( askConfirmation && file.exists()){
429
                        int resp = JOptionPane.showConfirmDialog(
430
                                        (Component) PluginServices.getMainFrame(),PluginServices.getText(this,"fichero_ya_existe_seguro_desea_guardarlo"),
431
                                        PluginServices.getText(this,"guardar"), JOptionPane.YES_NO_OPTION);
432
                        if (resp != JOptionPane.YES_OPTION) {
433
                                return false;
434
                        }
435
                }
436
                NotificationManager.addInfo(PluginServices.getText(this,"writinng_project")+ ": "+file.getName());
437
                
438
                // write it out as XML
439
                try {
440
                        fireBeforeSavingFileEvent(new SaveEvent(this, SaveEvent.BEFORE_SAVING, file));
441
                        p.saveState(file);
442
                        fireAfterSavingFileEvent(new SaveEvent(this, SaveEvent.AFTER_SAVING, file));
443
                        PluginServices.getMainFrame().setTitle(file.getName());
444
                        setPath(file.toString());
445

    
446
                } catch (PersistenceException e) {
447
                        String messagestack = e.getLocalizedMessageStack(); 
448
                        NotificationManager.addError(
449
                                PluginServices.getText(this,
450
                                        "error_writing_project")+ 
451
                                        ": "+
452
                                        file.getName()+
453
                                        "\n"+
454
                                        messagestack,
455
                                e
456
                        );
457
                        return false;
458
                } catch (Exception e) {
459
                        NotificationManager.addError(PluginServices.getText(this,"error_writing_project")+ ": "+file.getName(), e);
460
                        return false;
461
                }
462
                NotificationManager.addInfo(PluginServices.getText(this,"wrote_project")+ ": "+file.getName());
463
                return true;
464
        }
465

    
466
        public Project readProject(String path) {
467
                Project project = ProjectManager.getInstance().createProject();
468
                
469
                project.loadState(new File(path));
470
                return (Project) project;
471
                
472
//                BufferedReader reader =null;
473
//                try {
474
//                URL url=null;
475
//                        url = new URL(path);
476
//                        String encoding = XMLEncodingUtils.getEncoding(url.openStream());
477
//                        InputStream is = url.openStream();
478
//                        if (encoding!=null) {
479
//                                Project proj=null;
480
//                                try {
481
//                                        reader = new BufferedReader(new InputStreamReader(is, encoding));
482
//                                        proj=readProject(reader, true);
483
//                                } catch (UnsupportedEncodingException e) {
484
//                                        reader = new BufferedReader(new InputStreamReader(is));
485
//                                        try {
486
//                                                proj = readProject(reader, false);
487
//                                        } catch (UnsupportedEncodingException e1) {
488
//                                                JOptionPane.showMessageDialog((Component)PluginServices.getMainFrame(),PluginServices.getText(this, e1.getLocalizedMessage()));
489
//                                                return null;
490
//                                        }
491
//                                }
492
//                                ProjectExtension.setPath(path);
493
//                                return proj;
494
//                        }
495
//                        else {
496
//                                reader = new BufferedReader(new InputStreamReader(is));
497
//                                Project p;
498
//                                try {
499
//                                        p = readProject(reader, false);
500
//                                } catch (UnsupportedEncodingException e) {
501
//                                        JOptionPane.showMessageDialog((Component)PluginServices.getMainFrame(),PluginServices.getText(this, e.getLocalizedMessage()));
502
//                                        return null;
503
//                                }
504
//                                ProjectExtension.setPath(path); //p.setPath(null);
505
//                                return p;
506
//                        }
507
//                } catch (MalformedURLException e) {
508
//                        File file=new File(path);
509
//                        return readProject(file);
510
//                } catch (IOException e) {
511
//                        e.printStackTrace();
512
//                        return null;
513
//                }
514
        }
515

    
516
        /**
517
         * Lee del XML el proyecto.<br><br>
518
         *
519
         * Reads the XML of the project.<br>
520
         * 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
521
         * linked to the window you must set this object to the extension:<br>
522
         *
523
         * <b>Example:</b><br>
524
         *
525
         * ...<br>
526
         * ...<br>
527
         * Project p = ProjectExtension.readProject(projectFile);<br>
528
         * ProjectExtension.setProject(p);
529
         * ...<br>
530
         * ...<br>
531
         * @param file Fichero.
532
         *
533
         * @return Project
534
         *
535
         */
536
        public Project readProject(File file) {
537
                Project project = ProjectManager.getInstance().createProject();
538
                
539
                project.loadState(file);
540
                return (Project) project;
541
//                
542
//                File xmlFile = new File(file.getAbsolutePath());
543
//                try {
544
//                        String encoding = XMLEncodingUtils.getEncoding(new FileInputStream(xmlFile));
545
//                        InputStreamReader reader=null;
546
//                        if (encoding!=null) {
547
//                                try {
548
//                                        reader = new InputStreamReader(new FileInputStream(xmlFile), encoding);
549
//                                        return readProject(reader, true);
550
//                                } catch (UnsupportedEncodingException e) {
551
//                                        reader = new InputStreamReader(new FileInputStream(xmlFile));
552
//                                        try {
553
//                                                return readProject(reader, false);
554
//                                        } catch (UnsupportedEncodingException e1) {
555
//                                                JOptionPane.showMessageDialog((Component)PluginServices.getMainFrame(),PluginServices.getText(this, e1.getLocalizedMessage()));
556
//                                                return null;
557
//                                        }
558
//                                }
559
//                        }
560
//                        else {
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
//                } catch (FileNotFoundException e) {
570
//                        JOptionPane.showMessageDialog((Component)PluginServices.getMainFrame(),PluginServices.getText(this, "fichero_incorrecto"));
571
//                        return null;
572
//                }
573
        }
574

    
575
//        /**
576
//         * Lee del XML el proyecto.<br><br>
577
//         *
578
//         * Reads the XML of the project.<br>
579
//         * 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
580
//         * linked to the window you must set this object to the extension:<br>
581
//         *
582
//         * <b>Example:</b><br>
583
//         *
584
//         * ...<br>
585
//         * ...<br>
586
//         * Project p = ProjectExtension.readProject(projectFile);<br>
587
//         * ProjectExtension.setProject(p);
588
//         * ...<br>
589
//         * ...<br>
590
//         * @param reader File reader
591
//         * @param encodingFollowed Whether the encoded specified in the xml header was followed
592
//         * when creating the reader. If the property followHeaderEncoding is false or not set,
593
//         * then the encoding should have not been used when creating the reader, so it must be
594
//         * recreated.
595
//         *
596
//         * @return Project
597
//         * @throws UnsupportedEncodingException
598
//         *
599
//         */
600
//        public Project readProject(Reader reader, boolean encodingFollowed) throws UnsupportedEncodingException {
601
//                Project proj = null;
602
//
603
//                try {
604
//                        XmlTag tag = (XmlTag) XmlTag.unmarshal(reader);
605
//                        XMLEntity xml=new XMLEntity(tag);
606
//                        String VERSION=xml.getStringProperty("VERSION");
607
//                        NotificationManager.addInfo(PluginServices.getText(this,"openning_project")+ ": "+xml.getStringProperty("name"));
608
//
609
//                        if (encodingFollowed) {
610
//                                if (xml.contains("followHeaderEncoding")) {
611
//                                        boolean useEncoding = xml.getBooleanProperty("followHeaderEncoding");
612
//                                        if (!useEncoding) {
613
//                                                throw new UnsupportedEncodingException("the encoding specified in the xml header is not safe");
614
//                                        }
615
//                                }
616
//                                else {
617
//                                        // Old projects didn't contain followHeaderEncoding and they were
618
//                                        // not correctly encoded. We throw an exception now, and we'll try
619
//                                        // to reopen the project
620
//                                        // using the default system encoding.
621
//                                        throw new UnsupportedEncodingException("the encoding specified in the xml header is not safe");
622
//                                }
623
//                        }
624
//
625
//                        try {
626
//                                proj = Project.createFromXML(xml);
627
//                                NotificationManager.addInfo(PluginServices.getText(this,"opened_project")+ ": "+xml.getStringProperty("name"));
628
//
629
//                                return proj;
630
//                        } catch (OpenException e){
631
//                                e.showError();
632
//                                //NotificationManager.addInfo("Al leer el proyecto", e);
633
//                        }
634
//                }  catch (MarshalException e) {
635
//                        PluginServices.getLogger().error(PluginServices.getText(this, "formato_incorrecto"),e);
636
//                        JOptionPane.showMessageDialog((Component)PluginServices.getMainFrame(),PluginServices.getText(this, "formato_incorrecto"));
637
//                        //NotificationManager.addError("Al leer el proyecto", e);
638
//                } catch (ValidationException e) {
639
//                        PluginServices.getLogger().error(PluginServices.getText(this, "formato_incorrecto"),e);
640
//                        JOptionPane.showMessageDialog((Component)PluginServices.getMainFrame(),PluginServices.getText(this, "formato_incorrecto"));
641
//                        //NotificationManager.addError("Al leer el proyecto", e);
642
//                }
643
//                NotificationManager.addInfo(PluginServices.getText(this,"error_openning_project"));
644
//
645
//                return null;
646
//        }
647

    
648
        /**
649
         * Devuelve el proyecto.
650
         *
651
         * @return Proyecto.
652
         */
653
        public Project getProject() {
654
                return p;
655
        }
656

    
657
        /**
658
         * @see org.gvsig.andami.plugins.IExtension#isEnabled()
659
         */
660
        public boolean isEnabled() {
661
                return true;
662
        }
663

    
664
        /**
665
         * @see org.gvsig.andami.plugins.IExtension#isVisible()
666
         */
667
        public boolean isVisible() {
668
                return true;
669
        }
670

    
671
        /**
672
         * Sets the project
673
         * @param p
674
         */
675
        public void setProject(Project p){
676
                getProjectFrame().setProject(p);
677
                this.p=p;
678
        }
679

    
680
        private void registerDocuments() {
681
                ViewManager.register();
682
                TableManager.register();
683
                LayoutManager.register();
684
        }
685

    
686
        private void initializeDocumentActionsExtensionPoint() {
687
                ExtensionPointManager epMan = ToolsLocator.getExtensionPointManager();
688
                epMan.add(
689
                        "DocumentActions_View",
690
                        "Context menu options of the view document list"
691
                                + " in the project window "
692
                                + "(register instances of "
693
                                + "org.gvsig.app.project.AbstractDocumentContextMenuAction)");
694
                epMan.add(
695
                        "DocumentActions_Table",
696
                        "Context menu options of the table document list"
697
                                + " in the project window "
698
                                + "(register instances of "
699
                                + "org.gvsig.app.project.AbstractDocumentContextMenuAction)");
700
                epMan.add(
701
                        "DocumentActions_Map",
702
                        "Context menu options of the map document list"
703
                                + " in the project window "
704
                                + "(register instances of "
705
                                + "org.gvsig.app.project.AbstractDocumentContextMenuAction)");
706
        }
707

    
708
        public static String getPath() {
709
                return projectPath;
710
        }
711

    
712
        public static void setPath(String path) {
713
                projectPath = path;
714
        }
715

    
716
        public IWindow getProjectWindow() {
717
                return getProjectFrame();
718
        }
719

    
720

    
721
        public IExtensionStatus getStatus() {
722
                return this;
723
        }
724

    
725
        public boolean hasUnsavedData() {
726
                return p.hasChanged();
727
        }
728

    
729
        public IUnsavedData[] getUnsavedData() {
730
                if (hasUnsavedData()) {
731
                        UnsavedProject data = new UnsavedProject(this);
732
                        IUnsavedData[] dataArray = {data};
733
                        return dataArray;
734
                } else {
735
                        return null;
736
                }
737
        }
738

    
739
        /**
740
         * Implements the IUnsavedData interface to show unsaved projects
741
         * in the Unsavad Data dialog.
742
         *
743
         * @author Cesar Martinez Izquierdo <cesar.martinez@iver.es>
744
         */
745
        public class UnsavedProject  extends UnsavedData {
746

    
747
                public UnsavedProject(IExtension extension) {
748
                        super(extension);
749
                }
750

    
751
                public String getDescription() {
752
                        if (getPath()==null) {
753
                                return PluginServices.getText(ProjectExtension.this, "Unnamed_new_gvsig_project_");
754
                        }
755
                        else {
756
                                return PluginServices.getText(ProjectExtension.this, "Modified_project_");
757
                        }
758
                }
759

    
760
                public String getResourceName() {
761
                        if (getPath()==null) {
762
                                return PluginServices.getText(ProjectExtension.this, "Unnamed");
763
                        }
764
                        else {
765
                                return getPath();
766
                        }
767

    
768
                }
769

    
770
                public boolean saveData() {
771
                        return guardar();
772
                }
773

    
774
                public String getIcon() {
775
                                return "images/logoGVA.gif"; 
776
                }
777
        }
778

    
779
        public IMonitorableTask[] getRunningProcesses() {
780
                // TODO Auto-generated method stub
781
                return null;
782
        }
783
        public boolean hasRunningProcesses() {
784
                // TODO Auto-generated method stub
785
                return false;
786
        }
787

    
788
    /**
789
     * Adds the specified before saving listener to receive "before saving file events" from
790
     * this component.
791
     * If l is null, no exception is thrown and no action is performed.
792
     *
793
     * @author Pablo Piqueras Bartolom? <pablo.piqueras@iver.es>
794
     *
795
     * @param    l the before saving listener.
796
     * @see      SaveEvent
797
     * @see      BeforeSavingListener
798
     * @see      #removeListener(BeforeSavingListener)
799
     * @see      #getBeforeSavingListeners
800
     */
801
    public synchronized void addListener(BeforeSavingListener l) {
802
            if (l == null) {
803
                        return;
804
                }
805
                //
806
                //        ExtensionPoints ePs = (ExtensionPointsSingleton.getInstance());
807
                //
808
                //        if (ePs.get(BEFORE_SAVING_ID) == null) {
809
                //                ArrayList aL = new ArrayList();
810
                //                aL.add(l);
811
                //
812
                //                ePs.add(BEFORE_SAVING_ID, "", aL);
813
                //                return;
814
                //        }
815
                //
816
                //        ((ArrayList)((ExtensionPoint)ePs.get(BEFORE_SAVING_ID)).get("")).add(l);
817
                if (!this.beforeSavingListeners.contains(l)) {
818
                        this.beforeSavingListeners.add(l);
819
                }
820
    }
821

    
822
    /**
823
     * Adds the specified after saving listener to receive "after saving file events" from
824
     * this component.
825
     * If l is null, no exception is thrown and no action is performed.
826
     *
827
     * @author Pablo Piqueras Bartolom? <pablo.piqueras@iver.es>
828
     *
829
     * @param    l the after saving listener.
830
     * @see      SaveEvent
831
     * @see      AfterSavingListener
832
     * @see      #removeListener(AfterSavingListener)
833
     * @see      #getAfterSavingListeners()
834
     */
835
    public synchronized void addListener(AfterSavingListener l) {
836
        if (l == null) {
837
            return;
838
        }
839

    
840
                //        ExtensionPoints ePs = (ExtensionPointsSingleton.getInstance());
841
                //
842
                //        if (ePs.get(AFTER_SAVING_ID) == null) {
843
                //                ArrayList aL = new ArrayList();
844
                //                aL.add(l);
845
                //
846
                //                ePs.add(AFTER_SAVING_ID, "", aL);
847
                //                return;
848
                //        }
849
                //
850
                //        ((ArrayList)((ExtensionPoint)ePs.get(AFTER_SAVING_ID)).get("")).add(l);
851
                if (!this.afterSavingListeners.contains(l)) {
852
                        this.afterSavingListeners.add(l);
853
                }
854

    
855
    }
856

    
857
    /**
858
     * Returns an array of all the before saving listeners
859
     * registered on this component.
860
     *
861
     * @author Pablo Piqueras Bartolom? <pablo.piqueras@iver.es>
862
     *
863
     * @return all of this component's <code>BeforeSavingListener</code>s
864
     *         or an empty array if no key
865
     *         listeners are currently registered
866
     *
867
     * @see      #addBeforeSavingListener(BeforeSavingListener)
868
     * @see      #removeBeforeSavingListener(BeforeSavingListener)
869
     */
870
    public synchronized BeforeSavingListener[] getBeforeSavingListeners() {
871
                //            ExtensionPoint eP = (ExtensionPoint)(ExtensionPointsSingleton.getInstance()).get(BEFORE_SAVING_ID);
872
                //
873
                //            if (eP == null) {
874
                //                        return null;
875
                //                }
876
                //
877
                //            return eP.get("") == null ? null : (BeforeSavingListener[]) ((ArrayList)eP.get("")).toArray(new BeforeSavingListener[0]);
878
            return this.beforeSavingListeners
879
                                .toArray(new BeforeSavingListener[] {});
880
    }
881

    
882
    /**
883
     * Returns an array of all the after saving listeners
884
     * registered on this component.
885
     *
886
     * @author Pablo Piqueras Bartolom? <pablo.piqueras@iver.es>
887
     *
888
     * @return all of this component's <code>AfterSavingListener</code>s
889
     *         or an empty array if no key
890
     *         listeners are currently registered
891
     *
892
     * @see      #addAfterSavingListener(AfterSavingListener)
893
     * @see      #removeAfterSavingListener
894
     */
895
    public synchronized AfterSavingListener[] getAfterSavingListeners() {
896
                //            ExtensionPoint eP = (ExtensionPoint)(ExtensionPointsSingleton.getInstance()).get(AFTER_SAVING_ID);
897
                //
898
                //            if (eP == null) {
899
                //                        return null;
900
                //                }
901
                //
902
                //            return eP.get("") == null ? null : (AfterSavingListener[]) ((ArrayList)eP.get("")).toArray(new AfterSavingListener[0]);
903
                return this.afterSavingListeners.toArray(new AfterSavingListener[] {});
904

    
905
    }
906

    
907
    /**
908
     * Removes the specified before saving listener so that it no longer
909
     * receives save file events from this component. This method performs
910
     * no function, nor does it throw an exception, if the listener
911
     * specified by the argument was not previously added to this component.
912
     * If listener <code>l</code> is <code>null</code>,
913
     * no exception is thrown and no action is performed.
914
     *
915
     * @author Pablo Piqueras Bartolom? <pablo.piqueras@iver.es>
916
     *
917
     * @param    l   the before saving listener
918
     * @see      SaveEvent
919
     * @see      BeforeSavingListener
920
     * @see      #addListener(BeforeSavingListener)
921
     * @see      #getBeforeSavingListeners()
922
     */
923
    public synchronized void removeListener(BeforeSavingListener l) {
924
        if (l == null) {
925
            return;
926
        }
927

    
928
                //        ExtensionPoint eP = (ExtensionPoint)(ExtensionPointsSingleton.getInstance()).get(BEFORE_SAVING_ID);
929
                //
930
                //        if (eP != null) {
931
                //                ((ArrayList)eP.get("")).remove(l);
932
                //        }
933
                this.beforeSavingListeners.remove(l);
934
    }
935

    
936
    /**
937
     * Removes the specified after saving listener so that it no longer
938
     * receives save file events from this component. This method performs
939
     * no function, nor does it throw an exception, if the listener
940
     * specified by the argument was not previously added to this component.
941
     * If listener <code>l</code> is <code>null</code>,
942
     * no exception is thrown and no action is performed.
943
     *
944
     * @author Pablo Piqueras Bartolom? <pablo.piqueras@iver.es>
945
     *
946
     * @param    l   the after saving listener
947
     * @see      SaveEvent
948
     * @see      AfterSavingListener
949
     * @see      #addListener(AfterSavingListener)
950
     * @see      #getAfterSavingListeners()
951
     */
952
    public synchronized void removeListener(AfterSavingListener l) {
953
        if (l == null) {
954
            return;
955
        }
956

    
957
                //        ExtensionPoint eP = (ExtensionPoint)(ExtensionPointsSingleton.getInstance()).get(AFTER_SAVING_ID);
958
                //
959
                //        if (eP != null) {
960
                //                ((ArrayList)eP.get("")).remove(l);
961
                //        }
962
                this.afterSavingListeners.remove(l);
963
    }
964

    
965
    /**
966
     * Reports a before saving file event.
967
     *
968
     * @author Pablo Piqueras Bartolom? <pablo.piqueras@iver.es>
969
     *
970
     * @param evt the before saving file event
971
     */
972
    protected void fireBeforeSavingFileEvent(SaveEvent evt) {
973
        if ((evt.getID() != SaveEvent.BEFORE_SAVING) || (evt.getFile() == null)) {
974
            return;
975
        }
976

    
977
                //        ExtensionPoint eP = (ExtensionPoint)(ExtensionPointsSingleton.getInstance()).get(BEFORE_SAVING_ID);
978

    
979
                        //                ArrayList listeners = ((ArrayList)eP.get(""));
980
        Iterator<BeforeSavingListener> iter = this.beforeSavingListeners
981
                                .iterator();
982

    
983
        while (iter.hasNext()) {
984
                        iter.next().beforeSaving(evt);
985
        }
986
    }
987

    
988
    /**
989
     * Reports a after saving file event.
990
     *
991
     * @author Pablo Piqueras Bartolom? <pablo.piqueras@iver.es>
992
     *
993
     * @param evt the after saving file event
994
     */
995
    protected void fireAfterSavingFileEvent(SaveEvent evt) {
996
        if ((evt.getID() != SaveEvent.AFTER_SAVING) || (evt.getFile() == null)) {
997
            return;
998
        }
999
        Iterator<AfterSavingListener> iter = this.afterSavingListeners
1000
                                .iterator();
1001

    
1002
        while (iter.hasNext()) {
1003
                        iter.next().afterSaving(evt);
1004
                }
1005

    
1006
    }
1007
}