Statistics
| Revision:

root / branches / v2_0_0_prep / applications / appgvSIG / src / com / iver / cit / gvsig / CopyPasteExtension.java @ 23176

History | View | Annotate | Download (43.3 KB)

1
package com.iver.cit.gvsig;
2

    
3
import java.awt.Component;
4
import java.awt.Toolkit;
5
import java.awt.datatransfer.DataFlavor;
6
import java.awt.datatransfer.StringSelection;
7
import java.awt.datatransfer.UnsupportedFlavorException;
8
import java.io.IOException;
9
import java.io.StringReader;
10
import java.io.StringWriter;
11
import java.util.ArrayList;
12
import java.util.Arrays;
13
import java.util.Comparator;
14
import java.util.Enumeration;
15
import java.util.Hashtable;
16
import java.util.Iterator;
17
import java.util.Map;
18

    
19
import javax.swing.JOptionPane;
20

    
21
import org.exolab.castor.xml.MarshalException;
22
import org.exolab.castor.xml.Marshaller;
23
import org.exolab.castor.xml.ValidationException;
24
import org.gvsig.fmap.data.ReadException;
25
import org.gvsig.fmap.mapcontext.layers.CancelationException;
26
import org.gvsig.fmap.mapcontext.layers.FLayer;
27
import org.gvsig.fmap.mapcontext.layers.FLayers;
28
import org.gvsig.fmap.mapcontext.layers.LayerFactory;
29
import org.gvsig.fmap.mapcontext.layers.vectorial.FLyrVect;
30

    
31
import com.iver.andami.PluginServices;
32
import com.iver.andami.plugins.Extension;
33
import com.iver.andami.ui.mdiManager.IWindow;
34
import com.iver.cit.gvsig.project.Project;
35
import com.iver.cit.gvsig.project.documents.ProjectDocument;
36
import com.iver.cit.gvsig.project.documents.contextMenu.AbstractDocumentContextMenuAction;
37
import com.iver.cit.gvsig.project.documents.exceptions.OpenException;
38
import com.iver.cit.gvsig.project.documents.exceptions.SaveException;
39
import com.iver.cit.gvsig.project.documents.layout.ProjectMap;
40
import com.iver.cit.gvsig.project.documents.layout.ProjectMapFactory;
41
import com.iver.cit.gvsig.project.documents.layout.fframes.FFrameView;
42
import com.iver.cit.gvsig.project.documents.layout.fframes.IFFrame;
43
import com.iver.cit.gvsig.project.documents.table.ProjectTable;
44
import com.iver.cit.gvsig.project.documents.table.ProjectTableFactory;
45
import com.iver.cit.gvsig.project.documents.view.ProjectView;
46
import com.iver.cit.gvsig.project.documents.view.ProjectViewFactory;
47
import com.iver.cit.gvsig.project.documents.view.gui.BaseView;
48
import com.iver.cit.gvsig.project.documents.view.toc.AbstractTocContextMenuAction;
49
import com.iver.cit.gvsig.project.documents.view.toc.ITocItem;
50
import com.iver.utiles.XMLEntity;
51
import com.iver.utiles.XMLException;
52
import com.iver.utiles.extensionPoints.IExtensionBuilder;
53
import com.iver.utiles.xmlEntity.generate.XmlTag;
54

    
55
public class CopyPasteExtension extends Extension {
56

    
57
        public void initialize() {
58
                /*
59
                ExtensionPoints extensionPoints = ExtensionPointsSingleton.getInstance();
60

61

62

63
                // TOC
64
                MyTocMenuEntry copy = new CopyTocMenuEntry();
65
                MyTocMenuEntry cut = new CutTocMenuEntry();
66
                MyTocMenuEntry paste = new PasteTocMenuEntry();
67
                Utiles utiles = new Utiles();
68
                copy.setUtiles(utiles);
69
                cut.setUtiles(utiles);
70
                paste.setUtiles(utiles);
71

72
                extensionPoints.add("View_TocActions","Copy","Copy selectes layers to system clipboard",copy);
73
                extensionPoints.add("View_TocActions","Cut","Cut selectes layers to system clipboard", cut);
74
                extensionPoints.add("View_TocActions","Paste","Paste layers from system clipboard",paste);
75

76

77
            //FPopupMenu.addEntry(copy);
78
            //FPopupMenu.addEntry(cut);
79
            //FPopupMenu.addEntry(paste);
80

81

82
            // ProjectWindow
83
                CopyProjectElement copyProjectElement = new CopyProjectElement();
84
                CutProjectElement cutProjectElement = new CutProjectElement();
85
                PasteProjectElement pasteProjectElementView = new PasteProjectElement();
86
                PasteProjectElement pasteProjectElementTable = new PasteProjectElement();
87
                PasteProjectElement pasteProjectElementMap = new PasteProjectElement();
88

89
                copyProjectElement.setUtiles(utiles);
90
                cutProjectElement.setUtiles(utiles);
91
                pasteProjectElementView.setUtiles(utiles);
92
                pasteProjectElementTable.setUtiles(utiles);
93
                pasteProjectElementMap.setUtiles(utiles);
94

95
                pasteProjectElementView.setType("views");
96
                pasteProjectElementTable.setType("tables");
97
                pasteProjectElementMap.setType("maps");
98

99

100
                extensionPoints.add("DocumentActions_View","Copy","Copy selectes documento to system clipboard",copyProjectElement);
101
                extensionPoints.add("DocumentActions_View","Cut","Cut selectes documento to system clipboard", cutProjectElement);
102
                extensionPoints.add("DocumentActions_View","Paste","Paste views from system clipboard",pasteProjectElementView);
103

104

105
                extensionPoints.add("DocumentActions_Table","Copy","Copy selectes documento to system clipboard",copyProjectElement);
106
                extensionPoints.add("DocumentActions_Table","Cut","Cut selectes documento to system clipboard", cutProjectElement);
107
                extensionPoints.add("DocumentActions_Table","Paste","Paste tables from system clipboard",pasteProjectElementTable);
108

109
                extensionPoints.add("DocumentActions_Map","Copy","Copy selectes documento to system clipboard",copyProjectElement);
110
                extensionPoints.add("DocumentActions_Map","Cut","Cut selectes documento to system clipboard", cutProjectElement);
111
                extensionPoints.add("DocumentActions_Map","Paste","Paste maps from system clipboard",pasteProjectElementMap);
112

113
                */
114
        }
115

    
116
        public void execute(String actionCommand) {
117
                // TODO Auto-generated method stub
118

    
119
        }
120

    
121
        public boolean isEnabled() {
122
                return false;
123
        }
124

    
125
        public boolean isVisible() {
126
                return false;
127
        }
128

    
129

    
130
}
131

    
132
abstract class MyDocumentAction extends AbstractDocumentContextMenuAction implements IExtensionBuilder {
133
        protected Utiles utiles;
134

    
135
        public void setUtiles(Utiles utiles) {
136
                this.utiles = utiles;
137
        }
138

    
139
        public String getGroup() {
140
                return "ClipboardActions";
141
        }
142

    
143

    
144
        public Object create() {
145
                return this;
146
        }
147

    
148
        public Object create(Object[] args) {
149
                // TODO Auto-generated method stub
150
                return this;
151
        }
152

    
153
        public Object create(Map args) {
154
                // TODO Auto-generated method stub
155
                return this;
156
        }
157
}
158

    
159

    
160
class CopyProjectElement extends MyDocumentAction{
161
        public String getDescription() {
162
                //FIXME: Falta claves
163
                //return PluginServices.getText(this,"tooltip_copiar_al_portapapeles");
164
                return null;
165
        }
166

    
167
        public int getOrder() {
168

    
169
                return 0;
170
        }
171

    
172
        public boolean isVisible(ProjectDocument item, ProjectDocument[] selectedItems) {
173
                return true;
174
        }
175

    
176
        public boolean isEnabled(ProjectDocument item, ProjectDocument[] selectedItems) {
177
                return selectedItems.length > 0;
178
        }
179

    
180

    
181
        public void execute(ProjectDocument item, ProjectDocument[] selectedItems) {
182
                XMLEntity xml = this.utiles.generateXMLCopyDocuments(selectedItems);
183
                if (xml == null) {
184
                        JOptionPane.showMessageDialog(
185
                                        (Component)PluginServices.getMainFrame(),
186
                                        "<html>"+PluginServices.getText(this,"No_ha_sido_posible_realizar_la_operacion")+"</html>",//Mensaje
187
                                        PluginServices.getText(this,"pegar"),//titulo
188
                                        JOptionPane.ERROR_MESSAGE
189
                                        );
190
                        return;
191
                }
192

    
193
                String data = this.utiles.marshallXMLEntity(xml);
194
                if (data == null) {
195
                        JOptionPane.showMessageDialog(
196
                                        (Component)PluginServices.getMainFrame(),
197
                                        "<html>"+PluginServices.getText(this,"No_ha_sido_posible_realizar_la_operacion")+"</html>",//Mensaje
198
                                        PluginServices.getText(this,"pegar"),//titulo
199
                                        JOptionPane.ERROR_MESSAGE
200
                                        );
201
                        return;
202
                }
203
                this.utiles.putInClipboard(data);
204
        }
205

    
206
        public String getText() {
207
                return PluginServices.getText(this, "copiar");
208
        }
209

    
210
}
211

    
212
class CutProjectElement extends MyDocumentAction {
213
        public String getDescription() {
214
                //FIXME: Falta claves
215
                //return PluginServices.getText(this,"tooltip_cortar_al_portapapeles");
216
                return null;
217
        }
218

    
219
        public int getOrder() {
220
                return 1;
221
        }
222

    
223
        public boolean isVisible(ProjectDocument item, ProjectDocument[] selectedItems) {
224
                return true;
225
        }
226

    
227
        public boolean isEnabled(ProjectDocument item, ProjectDocument[] selectedItems) {
228
                return selectedItems.length > 0;
229
        }
230

    
231

    
232
        public void execute(ProjectDocument item, ProjectDocument[] selectedItems) {
233
                XMLEntity xml = this.utiles.generateXMLCopyDocuments(selectedItems);
234
                if (xml == null) {
235
                        JOptionPane.showMessageDialog(
236
                                        (Component)PluginServices.getMainFrame(),
237
                                        "<html>"+PluginServices.getText(this,"No_ha_sido_posible_realizar_la_operacion")+"</html>",//Mensaje
238
                                        PluginServices.getText(this,"cortar"),//titulo
239
                                        JOptionPane.ERROR_MESSAGE
240
                                        );
241
                        return;
242
                }
243

    
244
                String data = this.utiles.marshallXMLEntity(xml);
245
                if (data == null) {
246
                        JOptionPane.showMessageDialog(
247
                                        (Component)PluginServices.getMainFrame(),
248
                                        "<html>"+PluginServices.getText(this,"No_ha_sido_posible_realizar_la_operacion")+"</html>",//Mensaje
249
                                        PluginServices.getText(this,"cortar"),//titulo
250
                                        JOptionPane.ERROR_MESSAGE
251
                                        );
252
                        return;
253
                }
254
                this.utiles.putInClipboard(data);
255

    
256

    
257
            int option=JOptionPane.showConfirmDialog((Component)PluginServices.getMainFrame(),PluginServices.getText(this,"desea_borrar_el_documento"));
258
            if (option!=JOptionPane.OK_OPTION) {
259
                    return;
260
            }
261

    
262

    
263
                this.utiles.removeDocuments(selectedItems);
264

    
265
        }
266

    
267
        public String getText() {
268
                return PluginServices.getText(this, "cortar");
269
        }
270

    
271
}
272

    
273
class PasteProjectElement extends MyDocumentAction {
274
        private String type;
275

    
276
        public String getDescription() {
277
                //FIXME: Falta claves
278
                //return PluginServices.getText(this,"tooltip_pegar_desde_el_portapapeles");
279
                return null;
280
        }
281

    
282
        public int getOrder() {
283
                return 2;
284
        }
285

    
286
        public void setType(String type) {
287
                this.type = type;
288
        }
289

    
290
        public String getType(String type) {
291
                return this.type;
292
        }
293

    
294
        public boolean isVisible(ProjectDocument item, ProjectDocument[] selectedItems) {
295
                return true;
296
        }
297

    
298
        public boolean isEnabled(ProjectDocument item, ProjectDocument[] selectedItems) {
299
                String sourceString = this.utiles.getFromClipboard();
300
                if (sourceString == null) return false;
301

    
302
                XMLEntity xml = this.utiles.unMarshallXMLEntity(sourceString);
303
                if (xml == null) return false;
304

    
305
                if (!this.utiles.checkXMLRootNode(xml)) return false;
306

    
307
                if (this.utiles.getXMLEntityChildOfType(xml,this.type) == null) return false;
308
                return true;
309
        }
310

    
311

    
312
        public void execute(ProjectDocument item, ProjectDocument[] selectedItems) {
313
                String sourceString = this.utiles.getFromClipboard();
314
                if (sourceString == null) return;
315

    
316
                XMLEntity xml = this.utiles.unMarshallXMLEntity(sourceString);
317
                if (xml == null) return;
318

    
319
                if (!this.utiles.checkXMLRootNode(xml)) return;
320

    
321
                if (this.type.equals("views")) {
322
                        this.utiles.loadViewsFromXML(xml);
323
                } else if (this.type.equals("tables")) {
324
                        this.utiles.loadTablesFromXML(xml);
325
                } else if (this.type.equals("maps")) {
326
                        this.utiles.loadMapsFromXML(xml);
327
                } else {
328
                        //TODO que hacer aqui??
329
                        return;
330
                }
331

    
332
        }
333

    
334
        public String getText() {
335
                return PluginServices.getText(this, "pegar");
336
        }
337

    
338
}
339

    
340

    
341

    
342
abstract class  MyTocMenuEntry extends AbstractTocContextMenuAction {
343
        protected Utiles utiles;
344

    
345
        public void setUtiles(Utiles utiles) {
346
                this.utiles = utiles;
347
        }
348

    
349
        public String getGroup() {
350
                return "copyPasteLayer";
351
        }
352

    
353
        public int getGroupOrder() {
354
                return 60;
355
        }
356

    
357
}
358

    
359
class CopyTocMenuEntry extends MyTocMenuEntry{
360
        public int getOrder() {
361
                return 0;
362
        }
363

    
364
        public String getText() {
365
                return PluginServices.getText(this, "copiar");
366
        }
367

    
368
        public boolean isEnabled(ITocItem item, FLayer[] selectedItems) {
369
                return selectedItems.length >= 1 && isTocItemBranch(item);
370
        }
371

    
372

    
373
        public void execute(ITocItem item, FLayer[] selectedItems) {
374
                XMLEntity xml = this.utiles.generateXMLCopyLayers(selectedItems);
375
                if (xml == null) {
376
                        JOptionPane.showMessageDialog(
377
                                        (Component)PluginServices.getMainFrame(),
378
                                        "<html>"+PluginServices.getText(this,"No_ha_sido_posible_realizar_la_operacion")+"</html>",//Mensaje
379
                                        PluginServices.getText(this,"copiar"),//titulo
380
                                        JOptionPane.ERROR_MESSAGE
381
                                        );
382
                        return;
383
                }
384

    
385
                String data = this.utiles.marshallXMLEntity(xml);
386
                if (data == null) {
387
                        JOptionPane.showMessageDialog(
388
                                        (Component)PluginServices.getMainFrame(),
389
                                        "<html>"+PluginServices.getText(this,"No_ha_sido_posible_realizar_la_operacion")+"</html>",//Mensaje
390
                                        PluginServices.getText(this,"copiar"),//titulo
391
                                        JOptionPane.ERROR_MESSAGE
392
                                        );
393
                        return;
394
                }
395

    
396
                this.utiles.putInClipboard(data);
397

    
398
        }
399

    
400

    
401
}
402

    
403
class CutTocMenuEntry extends MyTocMenuEntry{
404
        public int getOrder() {
405
                return 1;
406
        }
407

    
408
        public String getText() {
409
                return PluginServices.getText(this, "cortar");
410
        }
411

    
412
        public boolean isEnabled(ITocItem item, FLayer[] selectedItems) {
413
                return selectedItems.length >= 1 && isTocItemBranch(item);
414
        }
415

    
416

    
417
        public void execute(ITocItem item, FLayer[] selectedItems) {
418
                XMLEntity xml = this.utiles.generateXMLCopyLayers(selectedItems);
419
                if (xml == null) {
420
                        JOptionPane.showMessageDialog(
421
                                        (Component)PluginServices.getMainFrame(),
422
                                        "<html>"+PluginServices.getText(this,"No_ha_sido_posible_realizar_la_operacion")+"</html>",//Mensaje
423
                                        PluginServices.getText(this,"cortar"),//titulo
424
                                        JOptionPane.ERROR_MESSAGE
425
                                        );
426
                        return;
427
                }
428

    
429
                String data = this.utiles.marshallXMLEntity(xml);
430
                if (data == null) {
431
                        JOptionPane.showMessageDialog(
432
                                        (Component)PluginServices.getMainFrame(),
433
                                        "<html>"+PluginServices.getText(this,"No_ha_sido_posible_realizar_la_operacion")+"</html>",//Mensaje
434
                                        PluginServices.getText(this,"cortar"),//titulo
435
                                        JOptionPane.ERROR_MESSAGE
436
                                        );
437
                        return;
438
                }
439

    
440

    
441
                this.utiles.putInClipboard(data);
442

    
443

    
444
            int option=JOptionPane.showConfirmDialog((Component)PluginServices.getMainFrame(),PluginServices.getText(this,"desea_borrar_la_capa"));
445
            if (option!=JOptionPane.OK_OPTION) {
446
                    return;
447
            }
448
                getMapContext().beginAtomicEvent();
449

    
450

    
451
                boolean isOK =this.utiles.removeLayers(selectedItems);
452

    
453
                getMapContext().endAtomicEvent();
454

    
455
                if (isOK) {
456
                        getMapContext().invalidate();
457
                        if (getMapContext().getLayers().getLayersCount()==0) {
458
                                PluginServices.getMainFrame().enableControls();
459
                        }
460
                }
461

    
462
        }
463
}
464

    
465

    
466
class PasteTocMenuEntry extends MyTocMenuEntry{
467
        private XMLEntity xml=null;
468

    
469
        public int getOrder() {
470
                return 2;
471
        }
472

    
473
        public String getText() {
474
                return PluginServices.getText(this, "pegar");
475
        }
476

    
477
        public boolean isEnabled(ITocItem item, FLayer[] selectedItems) {
478
                if (isTocItemBranch(item)) {
479
                        FLayer lyr = getNodeLayer(item);
480
                        if (lyr instanceof FLayers) {
481
                                this.xml = this.getCheckedXMLFromClipboard();
482
                                return true;
483
                        }
484

    
485
                } else if (!isTocItemLeaf(item)) {
486
                        if (getNodeLayer(item) == null) {
487
                                this.xml = this.getCheckedXMLFromClipboard();
488
                                return this.xml != null;
489
                        }
490
                }
491
                return false;
492
        }
493

    
494
        private XMLEntity getCheckedXMLFromClipboard() {
495
                String sourceString = this.utiles.getFromClipboard();
496
                if (sourceString == null) return null;
497

    
498
                XMLEntity xml = this.utiles.unMarshallXMLEntity(sourceString);
499
                if (xml == null) return null;
500

    
501
                if (!this.utiles.checkXMLRootNode(xml)) return null;
502

    
503
                if (this.utiles.getXMLEntityChildOfType(xml,"layers") == null) return null;
504

    
505
                return  xml;
506
        }
507

    
508
        public void execute(ITocItem item, FLayer[] selectedItems) {
509
                FLayers root;
510

    
511
                if (this.xml == null) return;
512

    
513
                if (isTocItemBranch(item)) {
514
                        root = (FLayers)getNodeLayer(item);
515
                } else if (getNodeLayer(item) == null){
516
                        root = getMapContext().getLayers();
517
                } else {
518
                        return;
519
                }
520
                getMapContext().beginAtomicEvent();
521

    
522
                boolean isOK = this.utiles.loadLayersFromXML(this.xml,root);
523

    
524
                getMapContext().endAtomicEvent();
525

    
526
                if (isOK) {
527
                        getMapContext().invalidate();
528
                        IWindow view=PluginServices.getMDIManager().getActiveWindow();
529
                        if (view instanceof BaseView)
530
                                ((ProjectDocument)((BaseView)view).getModel()).setModified(true);
531
                }
532
        }
533

    
534
}
535

    
536

    
537
class Utiles {
538

    
539
        /*
540
         *
541
======================================
542
 Comportamiento del Pegar documentos:
543
======================================
544

545
?Pegar vista.
546
        Si ya existe una vista en el proyecto con el mismo nombre.
547
                1. Abortar
548
                2. Pedir nuevo nombre.
549
                        Que hacemos con las tablas asociadas.
550
                                No se pegan
551
        Si alguna de las tablas a pegar de las que van en
552
        el portapapeles ya existen en el proyecto.
553
                1. abortamos
554
                2. Informamos al usuario y no se pegan las tablas.
555

556
Pegar tabla.
557
        Si alguna de las tablas existe.
558
                Se pega igualmente (apareceran tablas duplicadas)
559

560
Pegar mapa.
561
        Si el mapa ya existe en el proyecto.
562
                1. Abortar
563
                2. renombrar el mapa
564
        Si alguna vista ya existe en el proyecto.
565
                1. Abortar
566
                2. Usar la vista que ya existe en el proyecto y no
567
                   pegar la nueva vista.
568
        Si alguna de las tablas a pegar de las que van en
569
                el portapapeles ya existen en el proyecto.
570
                        1. abortamos
571
                        2. Informamos al usuario y no se pegan las tablas.
572

573

574
         */
575

    
576

    
577
        /*
578
         *
579
         *
580
         *
581
         * Funciones Publicas para generar XML (copiar)
582
         *
583
         *
584
        */
585

    
586
        /**
587
         * Genera un XMLEntity con la informacion necesaria
588
         * para copiar los elementos de selectedItems en
589
         * otro proyecto
590
         */
591
        public XMLEntity generateXMLCopyDocuments(ProjectDocument[] selectedItems) {
592
                if (selectedItems.length == 0) return null;
593

    
594
                if (selectedItems[0] instanceof ProjectView) {
595
                        ProjectView[] views = new ProjectView[selectedItems.length];
596
                        System.arraycopy(selectedItems,0,views,0,selectedItems.length);
597
                        return this.generateXMLCopyViews(views);
598
                } else if (selectedItems[0] instanceof ProjectMap) {
599
                        ProjectMap[] maps = new ProjectMap[selectedItems.length];
600
                        System.arraycopy(selectedItems,0,maps,0,selectedItems.length);
601
                        return this.generateXMLCopyMaps(maps);
602
                } else if (selectedItems[0] instanceof ProjectTable) {
603
                        ProjectTable[] tables = new ProjectTable[selectedItems.length];
604
                        System.arraycopy(selectedItems,0,tables,0,selectedItems.length);
605
                        return this.generateXMLCopyTables(tables);
606
                } else {
607
                        //FIXME:????
608
                        return null;
609
                }
610
        }
611

    
612
        public XMLEntity generateXMLCopyViews(ProjectView[] selectedItems) {
613
                XMLEntity xml = this.newRootNode();
614

    
615
                XMLEntity xmlTables = this.newTablesNode();
616
                XMLEntity xmlDataSources = this.newDataSourcesNode();
617
                XMLEntity xmlViews = this.newViewsNode();
618

    
619
                for (int i=0;i < selectedItems.length; i++) {
620
                        if (!this.addToXMLView(selectedItems[i],xmlViews,xmlTables,xmlDataSources)) return null;
621

    
622
                }
623

    
624

    
625
                if (xmlDataSources.getChildrenCount() > 0) {
626
                        xml.addChild(xmlDataSources);
627
                }
628
                if (xmlViews.getChildrenCount() > 0) {
629
                        xml.addChild(xmlViews);
630
                }
631
                if (xmlTables.getChildrenCount() > 0) {
632
                        xml.addChild(xmlTables);
633
                }
634

    
635
                return xml;
636

    
637
        }
638

    
639

    
640
        public XMLEntity generateXMLCopyMaps(ProjectMap[] selectedItems) {
641
                XMLEntity xml = this.newRootNode();
642

    
643
                XMLEntity xmlTables = this.newTablesNode();
644
                XMLEntity xmlDataSources = this.newDataSourcesNode();
645
                XMLEntity xmlViews = this.newViewsNode();
646
                XMLEntity xmlMaps = this.newMapsNode();
647

    
648
                for (int i=0;i < selectedItems.length; i++) {
649
                        if (!this.addToXMLMap(selectedItems[i],xmlMaps,xmlViews,xmlTables,xmlDataSources)) return null;
650

    
651
                }
652

    
653

    
654
                if (xmlDataSources.getChildrenCount() > 0) {
655
                        xml.addChild(xmlDataSources);
656
                }
657
                if (xmlViews.getChildrenCount() > 0) {
658
                        xml.addChild(xmlViews);
659
                }
660
                if (xmlTables.getChildrenCount() > 0) {
661
                        xml.addChild(xmlTables);
662
                }
663
                if (xmlMaps.getChildrenCount() > 0) {
664
                        xml.addChild(xmlMaps);
665
                }
666

    
667

    
668
                return xml;
669
        }
670

    
671
        public XMLEntity generateXMLCopyTables(ProjectTable[] selectedItems) {
672
                XMLEntity xml = this.newRootNode();
673

    
674
                XMLEntity xmlTables = this.newTablesNode();
675
                XMLEntity xmlDataSources = this.newDataSourcesNode();
676

    
677
                for (int i=0;i < selectedItems.length; i++) {
678
                        if (!this.addToXMLTable(selectedItems[i],xmlTables,xmlDataSources,null)) return null;
679
                }
680

    
681

    
682
                if (xmlDataSources.getChildrenCount() > 0) {
683
                        xml.addChild(xmlDataSources);
684
                }
685
                if (xmlTables.getChildrenCount() > 0) {
686
                        xml.addChild(xmlTables);
687
                }
688

    
689
                return xml;
690
        }
691

    
692

    
693
        public XMLEntity generateXMLCopyLayers(FLayer[] actives) {
694

    
695
                XMLEntity xml = this.newRootNode();
696
                XMLEntity xmlLayers = this.newLayersNode();
697
                XMLEntity xmlTables = this.newTablesNode();
698
                XMLEntity xmlDataSources = this.newDataSourcesNode();
699

    
700
                for (int i=0;i < actives.length; i++) {
701
                        if (!this.addToXMLLayer(actives[i],xmlLayers ,xmlTables,xmlDataSources)) return null;
702

    
703
                }
704

    
705
                if (xmlDataSources.getChildrenCount() > 0) {
706
                        xml.addChild(xmlDataSources);
707
                }
708
                if (xmlLayers.getChildrenCount() > 0) {
709
                        xml.addChild(xmlLayers);
710
                }
711
                if (xmlTables.getChildrenCount() > 0) {
712
                        xml.addChild(xmlTables);
713
                }
714

    
715
                return xml;
716

    
717
        }
718

    
719

    
720

    
721
        /*
722
         *
723
         *
724
         *
725
         * Funciones Publicas de carga de un XML (pegar)
726
         *
727
         *
728
         *
729
        */
730

    
731
        public boolean loadLayersFromXML(XMLEntity xml, FLayers root) {
732
                XMLEntity xmlLayers = this.getXMLEntityChildOfType(xml,"layers");
733
                XMLEntity xmlTables = this.getXMLEntityChildOfType(xml,"tables");
734
                XMLEntity xmlDataSources = this.getXMLEntityChildOfType(xml,"dataSources");
735

    
736
                if (xmlLayers == null ) return false;
737

    
738
                // Se pegan las tablas igualmente
739
                /*
740
                Project project = this.getProject();
741

742
                Hashtable tablesConfits = this.getConflicts(xmlTables,project.getTables());
743
                */
744

    
745

    
746
                if (xmlDataSources != null)  {
747
                        if (!this.registerDataSources(xmlDataSources)) return false;
748
                }
749

    
750
                if (!this.addLayers(xmlLayers,root)) return false;
751

    
752
                if (xmlTables != null)  {
753
                        if (!this.addTables(xmlTables)) return false;
754
                }
755

    
756
                return true;
757

    
758
        }
759

    
760

    
761
        public boolean loadViewsFromXML(XMLEntity xml) {
762
                XMLEntity xmlViews = this.getXMLEntityChildOfType(xml,"views");
763
                XMLEntity xmlTables = this.getXMLEntityChildOfType(xml,"tables");
764
                XMLEntity xmlDataSources = this.getXMLEntityChildOfType(xml,"dataSources");
765

    
766
                if (xmlViews == null ) return false;
767

    
768
                Project project = this.getProject();
769

    
770
                Hashtable viewsConflits = this.getConflicts(xmlViews,project.getDocumentsByType(ProjectViewFactory.registerName));
771

    
772
                Hashtable tablesConflits = this.getConflicts(xmlTables,project.getDocumentsByType(ProjectTableFactory.registerName));
773

    
774
                if (viewsConflits != null && viewsConflits.size() > 0) {
775
                        int option = JOptionPane.showConfirmDialog(
776
                                        (Component)PluginServices.getMainFrame(),
777
                                        "<html>"+
778
                                                PluginServices.getText(this,"conflicto_de_nombres_de_vistas_al_pegar") + "<br>" +
779
                                                PluginServices.getText(this,"debera_introducir_nombres_para_las_vistas_a_pegar") + "<br>" +
780
                                                PluginServices.getText(this,"no_se_pegaran_las_tablas") + "<br>" +
781
                                                PluginServices.getText(this,"desea_continuar") +
782
                                        "</html>",
783
                                        PluginServices.getText(this,"pegar_vistas"),
784
                                        JOptionPane.YES_NO_OPTION
785
                                        );
786
                        if (option != JOptionPane.YES_OPTION) {
787
                                return false;
788
                        }
789
                        Enumeration en = viewsConflits.elements();
790
                        while (en.hasMoreElements()) {
791
                                XMLEntity view = (XMLEntity)en.nextElement();
792
                                String newName = JOptionPane.showInputDialog(
793
                                                (Component)PluginServices.getMainFrame(),
794
                                                "<html>"+
795
                                                        PluginServices.getText(this,"introduzca_nuevo_nombre_para_la_vista") +" "+  view.getStringProperty("name") + ":" +
796
                                                "</html>", //Mensaje
797
                                                view.getStringProperty("name") //Valor por defecto
798
                                                );
799
                                if (newName == null) {
800
                                        JOptionPane.showMessageDialog(
801
                                                        (Component)PluginServices.getMainFrame(),
802
                                                        "<html>"+PluginServices.getText(this,"operacion_cancelada")+"</html>",//Mensaje
803
                                                        PluginServices.getText(this,"pegar_vistas"),//titulo
804
                                                        JOptionPane.ERROR_MESSAGE
805
                                                        );
806
                                } else if (newName.equalsIgnoreCase(view.getStringProperty("name")) ) {
807
                                        JOptionPane.showMessageDialog(
808
                                                        (Component)PluginServices.getMainFrame(),
809
                                                        "<html>"+
810
                                                                PluginServices.getText(this,"operacion_cancelada") +":<br>" +
811
                                                                PluginServices.getText(this,"nombre_no_valido")+
812
                                                        "</html>",//Mensaje
813
                                                        PluginServices.getText(this,"pegar_vistas"),//FIXME: getText
814
                                                        JOptionPane.ERROR_MESSAGE
815
                                                        );
816
                                        return false;
817
                                }
818
                                view.setName(newName);
819
                        }
820
                        if (xmlTables != null) xmlTables.removeAllChildren();
821
                        tablesConflits = null;
822
                }
823

    
824
                if (tablesConflits != null && tablesConflits.size() > 0) {
825
                        int option = JOptionPane.showConfirmDialog(
826
                                        (Component)PluginServices.getMainFrame(),
827
                                        "<html>" +
828
                                                PluginServices.getText(this,"conflicto_de_nombres_de_tablas_al_pegar") + "<br>" +
829
                                                PluginServices.getText(this,"no_se_pegaran_las_tablas") + "<br>" +
830
                                                PluginServices.getText(this,"desea_continuar") +
831
                                        "</html>", //Mensaje
832
                                        PluginServices.getText(this,"pegar_vistas"),//FIXME: getText
833
                                        JOptionPane.YES_NO_OPTION
834
                                        );
835
                        if (option != JOptionPane.YES_OPTION) {
836
                                return false;
837
                        }
838
                        xmlTables.removeAllChildren();
839
                }
840

    
841

    
842
                if (xmlDataSources != null)  {
843
                        if (!this.registerDataSources(xmlDataSources)) return false;
844
                }
845

    
846
                if (!this.addViews(xmlViews)) return false;
847

    
848
                if (xmlTables != null)  {
849
                        if (!this.addTables(xmlTables)) return false;
850
                }
851

    
852
                return true;
853
        }
854

    
855
        public boolean loadTablesFromXML(XMLEntity xml) {
856
                XMLEntity xmlTables = this.getXMLEntityChildOfType(xml,"tables");
857
                XMLEntity xmlDataSources = this.getXMLEntityChildOfType(xml,"dataSources");
858

    
859

    
860
                if (xmlTables == null ) return false;
861

    
862
                /*
863
                Project project = this.getProject();
864

865
                Hashtable tablesConfits = this.getConflicts(xmlTables,project.getTables());
866
                */
867

    
868
                if (xmlDataSources != null)  {
869
                        if (!this.registerDataSources(xmlDataSources)) return false;
870
                }
871

    
872

    
873

    
874
                return this.addTables(xmlTables);
875
        }
876

    
877
        public boolean loadMapsFromXML(XMLEntity xml) {
878
                XMLEntity xmlMaps = this.getXMLEntityChildOfType(xml,"Maps");
879
                XMLEntity xmlViews = this.getXMLEntityChildOfType(xml,"views");
880
                XMLEntity xmlTables = this.getXMLEntityChildOfType(xml,"tables");
881
                XMLEntity xmlDataSources = this.getXMLEntityChildOfType(xml,"dataSources");
882

    
883
                if (xmlMaps == null ) return false;
884

    
885
                Project project = this.getProject();
886

    
887
                Hashtable mapsConflits = this.getConflicts(xmlMaps,project.getDocumentsByType(ProjectMapFactory.registerName));
888

    
889
                Hashtable viewsConflits = this.getConflicts(xmlViews,project.getDocumentsByType(ProjectViewFactory.registerName));
890

    
891
                Hashtable tablesConflits = this.getConflicts(xmlTables,project.getDocumentsByType(ProjectTableFactory.registerName));
892

    
893

    
894
                if (mapsConflits != null && mapsConflits.size() > 0) {
895
                        int option = JOptionPane.showConfirmDialog(
896
                                        (Component)PluginServices.getMainFrame(),
897
                                        "<html>"+
898
                                                PluginServices.getText(this,"conflicto_de_nombres_de_mapas_al_pegar") + "<br>" +
899
                                                PluginServices.getText(this,"debera_introducir_nombres_para_los_mapas_a_pegar") + "<br>" +
900
                                        "</html>", //Mensaje
901
                                        PluginServices.getText(this,"pegar_mapas"),//titulo
902
                                        JOptionPane.YES_NO_OPTION
903
                                        );
904
                        if (option != JOptionPane.YES_OPTION) {
905
                                return false;
906
                        }
907
                        Enumeration en = mapsConflits.elements();
908
                        while (en.hasMoreElements()) {
909
                                XMLEntity map = (XMLEntity)en.nextElement();
910
                                String newName = JOptionPane.showInputDialog(
911
                                                (Component)PluginServices.getMainFrame(),
912
                                                "<html>"+
913
                                                        PluginServices.getText(this,"nuevo_nombre_para_el_mapa") +" "+  map.getStringProperty("name") + ":" +
914
                                            "</html>", //Mensaje
915
                                                map.getStringProperty("name") //Valor por defecto
916
                                                );
917
                                if (newName == null) {
918
                                        JOptionPane.showMessageDialog(
919
                                                        (Component)PluginServices.getMainFrame(),
920
                                                        "<html>"+PluginServices.getText(this,"operacion_cancelada")+"</html>",//Mensaje
921
                                                        PluginServices.getText(this,"pegar_mapas"),//titulo
922
                                                        JOptionPane.ERROR_MESSAGE
923
                                                        );
924
                                } else if (newName.equalsIgnoreCase(map.getStringProperty("name")) ) {
925
                                        JOptionPane.showMessageDialog(
926
                                                        (Component)PluginServices.getMainFrame(),
927
                                                        "<html>"+
928
                                                                PluginServices.getText(this,"operacion_cancelada") +":<br>" +
929
                                                                PluginServices.getText(this,"nombre_no_valido")+
930
                                                        "</html>",//Mensaje
931
                                                        PluginServices.getText(this,"pegar_mapas"),//titulo
932
                                                        JOptionPane.ERROR_MESSAGE
933
                                                        );
934
                                        return false;
935
                                }
936
                                map.setName(newName);
937
                        }
938
                }
939

    
940
                if (viewsConflits != null && viewsConflits.size() > 0) {
941
                        int option = JOptionPane.showConfirmDialog(
942
                                        (Component)PluginServices.getMainFrame(),
943
                                        "<html>"+
944
                                                PluginServices.getText(this,"conflicto_de_nombres_de_vistas_al_pegar") + "<br>" +
945
                                                PluginServices.getText(this,"no_se_pegaran_las_vistas_del_conflicto") + "<br>" +
946
                                                PluginServices.getText(this,"desea_continuar") +
947
                                        "</html>",
948
                                        PluginServices.getText(this,"pegar_mapas"),//titulo
949
                                        JOptionPane.YES_NO_OPTION
950
                                        );
951
                        if (option != JOptionPane.YES_OPTION) {
952
                                return false;
953
                        }
954
                        // Eliminamos las vistas del xml que no vamos a importar
955

    
956
                        // Esto me devuelve los indices en orden inverso
957
                        int[] indexes = this.getIndexOfConflict(viewsConflits);
958
                        for (int i=0;i < indexes.length;i++) {
959
                                xmlViews.removeChild(indexes[i]);
960
                        }
961
                        viewsConflits = null;
962

    
963
                }
964

    
965

    
966
                if (tablesConflits != null && tablesConflits.size() > 0) {
967
                        int option = JOptionPane.showConfirmDialog(
968
                                        (Component)PluginServices.getMainFrame(),
969
                                        "<html>" +
970
                                                PluginServices.getText(this,"conflito_de_nombres_de_tablas_al_pegar") + "<br>" +
971
                                                PluginServices.getText(this,"no_se_pegaran_las_tablas") + "<br>" +
972
                                                PluginServices.getText(this,"desea_continuar") +
973
                                        "</html>", //Mensaje
974
                                        PluginServices.getText(this,"pegar_mapas"),
975
                                        JOptionPane.YES_NO_OPTION
976
                                        );
977
                        if (option != JOptionPane.YES_OPTION) {
978
                                return false;
979
                        }
980
                        xmlTables.removeAllChildren();
981
                }
982

    
983

    
984
                if (xmlDataSources != null)  {
985
                        if (!this.registerDataSources(xmlDataSources)) return false;
986
                }
987

    
988
                if (xmlViews != null)  {
989
                        if (!this.addViews(xmlViews)) return false;
990
                }
991

    
992
                if (xmlTables != null)  {
993
                        if (!this.addTables(xmlTables)) return false;
994
                }
995

    
996
                return this.addMaps(xmlMaps);
997

    
998
        }
999

    
1000

    
1001

    
1002

    
1003

    
1004

    
1005

    
1006

    
1007

    
1008

    
1009

    
1010
        /**
1011
         * Devuelve las claves de conflits ordenados
1012
         * en orden inverso. Las claves se esperan que
1013
         * sean instancias de Integer
1014
         */
1015
        private int[] getIndexOfConflict(Hashtable conflits) {
1016
                Object[] tmpArray = conflits.keySet().toArray();
1017
                Arrays.sort(tmpArray,new Comparator() {
1018
                        public int compare(Object o1, Object o2) {
1019
                                return ((Integer)o2).intValue() - ((Integer)o1).intValue();
1020
                        }
1021
                }
1022
                );
1023
                int[] indexes = new int[] {tmpArray.length};
1024
                for (int i = 0;i< tmpArray.length;i++) {
1025
                        indexes[i] = ((Integer)tmpArray[i]).intValue();
1026
                }
1027
                return indexes;
1028

    
1029

    
1030
        }
1031

    
1032

    
1033
        private boolean addToXMLMapDependencies(ProjectMap map, XMLEntity xmlViews,XMLEntity xmlTables, XMLEntity xmlDataSources) {
1034
                IFFrame[] components = map.getModel().getLayoutContext().getFFrames();
1035
                for (int i=0; i < components.length; i++) {
1036
                        if (components[i] instanceof FFrameView) {
1037
                                ProjectView view = ((FFrameView)components[i]).getView();
1038
                                if (findChildInXML(xmlViews,"name",view.getName())==null) {
1039
                                        if (!this.addToXMLView(view,xmlViews,xmlTables,xmlDataSources)) return false;
1040
                                }
1041
                        }
1042
                }
1043

    
1044
                return true;
1045
        }
1046

    
1047
        private boolean addToXMLMap(ProjectMap map,XMLEntity xmlMaps,XMLEntity xmlViews,XMLEntity xmlTables,XMLEntity xmlDataSources) {
1048
                try {
1049
                        xmlMaps.addChild(map.getXMLEntity());
1050

    
1051
                        return this.addToXMLMapDependencies(map,xmlViews,xmlTables,xmlDataSources);
1052

    
1053
                } catch (SaveException e) {
1054
                        // TODO Auto-generated catch block
1055
                        e.printStackTrace();
1056
                        return false;
1057
                }
1058
        }
1059

    
1060
        private boolean addToXMLView(ProjectView view,XMLEntity xmlViews,XMLEntity xmlTables,XMLEntity xmlDataSources) {
1061
                try {
1062
                        xmlViews.addChild(view.getXMLEntity());
1063

    
1064
                        if (!this.addToXMLLayerDependencies(view.getMapContext().getLayers(),xmlTables,xmlDataSources)) return false;
1065

    
1066
                        if (view.getMapOverViewContext() != null) {
1067
                                return this.addToXMLLayerDependencies(view.getMapOverViewContext().getLayers(),xmlTables,xmlDataSources);
1068
                        } else {
1069
                                return true;
1070
                        }
1071

    
1072

    
1073

    
1074
                } catch (SaveException e) {
1075
                        // TODO Auto-generated catch block
1076
                        e.printStackTrace();
1077
                        return false;
1078
                }
1079
        }
1080

    
1081

    
1082

    
1083
        public boolean checkXMLRootNode(XMLEntity xml) {
1084
                if (!xml.contains("applicationName")) return false;
1085
                if (!xml.getStringProperty("applicationName").equalsIgnoreCase("gvSIG")) return false;
1086

    
1087
                if (!xml.contains("version")) return false;
1088
                if (!xml.getStringProperty("version").equalsIgnoreCase(Version.format())) return false;
1089

    
1090
                return true;
1091
        }
1092

    
1093
        private void fillXMLRootNode(XMLEntity xml) {
1094
                xml.putProperty("applicationName","gvSIG");
1095
                xml.putProperty("version",Version.format());
1096
        }
1097

    
1098
        public XMLEntity getXMLEntityChildOfType(XMLEntity xml,String type) {
1099
                int childCount = xml.getChildrenCount();
1100
                XMLEntity child;
1101
                for (int i=0; i < childCount; i++  ) {
1102
                        child = xml.getChild(i);
1103
                        if (child.contains("type")) {
1104
                                if (child.getStringProperty("type").equalsIgnoreCase(type)) {
1105
                                        return child;
1106
                                }
1107
                        }
1108
                }
1109
                return null;
1110

    
1111
        }
1112

    
1113
        private Hashtable getConflicts(XMLEntity xml,ArrayList elements) {
1114
                if (xml == null || xml.getChildrenCount() < 1) return null;
1115
                Hashtable conflits = new Hashtable();
1116
                for (int iXML=0;iXML < xml.getChildrenCount();iXML++) {
1117
                        XMLEntity child = xml.getChild(iXML);
1118
                        Iterator iter = elements.iterator();
1119
                        while (iter.hasNext()) {
1120
                                ProjectDocument element = (ProjectDocument)iter.next();
1121
                                if (element.getName().equalsIgnoreCase(child.getStringProperty("name"))) {
1122
                                        conflits.put(new Integer(iXML),child);
1123
                                        break;
1124
                                }
1125

    
1126
                        }
1127
                }
1128
                return conflits;
1129
        }
1130

    
1131

    
1132

    
1133
        private boolean registerDataSources(XMLEntity xmlDataSources) {
1134
                try {
1135
                        int numDataSources = xmlDataSources.getChildrenCount();
1136

    
1137
                        if (numDataSources == 0) return true;
1138
                        DataSourceFactory dsFactory = LayerFactory.getDataSourceFactory();
1139

    
1140
                        for (int i = 0; i < numDataSources; i++) {
1141
                                XMLEntity child = xmlDataSources.getChild(i);
1142
                                String name = child.getStringProperty("gdbmsname");
1143

    
1144
                                if (dsFactory.getDriverInfo(name) == null) {
1145
                                        if (child.getStringProperty("type").equals("otherDriverFile")) {
1146
                                                LayerFactory.getDataSourceFactory().addFileDataSource(
1147
                                                                child.getStringProperty("driverName"),
1148
                                                                name,
1149
                                                                child.getStringProperty("file")
1150
                                                );
1151

    
1152

    
1153
                                        } else if (child.getStringProperty("type").equals("sameDriverFile")) {
1154
                                                /*                                String layerName = child.getStringProperty("layerName");
1155
                                                 ProjectView vista = project.getViewByName(child.getStringProperty(
1156
                                                 "viewName"));
1157
                                                 FLayer layer = vista.getMapContext().getLayers().getLayer(layerName);
1158

1159
                                                 modelo = ((AlphanumericData) layer).getRecordset();
1160
                                                 associatedTable = (AlphanumericData) layer;
1161
                                                 */
1162
                                        } else if (child.getStringProperty("type").equals("db")) {
1163
                                                LayerFactory.getDataSourceFactory().addDBDataSourceByTable(
1164
                                                                name,
1165
                                                                child.getStringProperty("host"),
1166
                                                                child.getIntProperty("port"),
1167
                                                                child.getStringProperty("user"),
1168
                                                                child.getStringProperty("password"),
1169
                                                                child.getStringProperty("dbName"),
1170
                                                                child.getStringProperty("tableName"),
1171
                                                                child.getStringProperty("driverInfo")
1172
                                                );
1173
                                        }
1174
                                }
1175
                        }
1176

    
1177
                        return true;
1178
                } catch (Exception e) {
1179
                        e.printStackTrace();
1180
                        return false;
1181
                }
1182
        }
1183

    
1184
        private boolean addTables(XMLEntity xmlTables) {
1185
                try {
1186
                        int numTables = xmlTables.getChildrenCount();
1187
                        if (numTables == 0) return true;
1188

    
1189
                        Project project = this.getProject();
1190

    
1191
                        for (int i = 0; i < numTables; i++) {
1192
                                try{
1193
                                        ProjectTable ptable = (ProjectTable) ProjectTable.createFromXML(xmlTables.getChild(i), project);
1194
                                        project.addDocument(ptable);
1195
                                        /*
1196
                                        if (ptable.getSeedViewInfo()!=null && ptable.getAndamiView()!=null) { // open the view, if it was open, and restore its dimensions
1197
                                                PluginServices.getMDIManager().addView(ptable.getAndamiView());
1198
                                                PluginServices.getMDIManager().changeViewInfo(ptable.getAndamiView(), ptable.getSeedViewInfo());
1199
                                        }
1200
                                        */
1201
                                }catch(OpenException e){
1202
                                        e.printStackTrace();
1203
                                        return false;
1204
                                }
1205
                        }
1206

    
1207
                        project.setLinkTable();
1208

    
1209
                        return true;
1210
                } catch (Exception e) {
1211
                        e.printStackTrace();
1212
                        return false;
1213
                }
1214
        }
1215

    
1216
        public XMLEntity findChildInXML(XMLEntity xml,String propName,String value) {
1217
                int num = xml.getChildrenCount();
1218
                XMLEntity child;
1219
                for (int i=0;i < num; i++) {
1220
                        child = xml.getChild(i);
1221
                        if (child.getStringProperty(propName).equals(value)) {
1222
                                return child;
1223
                        }
1224
                }
1225
                return null;
1226
        }
1227

    
1228
        private boolean addLayers(XMLEntity xmlLayers,FLayers root) {
1229
                try {
1230
                        XMLEntity child;
1231
                        int numLayers = xmlLayers.getChildrenCount();
1232
                        for (int i = 0; i < numLayers; i++) {
1233
                                child = xmlLayers.getChild(i);
1234
                                if (!root.addLayerFromXMLEntity(child,null)) return false;
1235
                        }
1236
                        return true;
1237
                } catch (Exception e) {
1238
                        e.printStackTrace();
1239
                        return false;
1240
                }
1241

    
1242
        }
1243

    
1244

    
1245
        private boolean addViews(XMLEntity xmlViews) {
1246
                try {
1247
                        Project project = this.getProject();
1248
                        XMLEntity child;
1249
                        int numLayers = xmlViews.getChildrenCount();
1250
                        for (int i = 0; i < numLayers; i++) {
1251
                                child = xmlViews.getChild(i);
1252

    
1253
                                ProjectView pv = (ProjectView) ProjectView.createFromXML(child, project);
1254
                                project.addDocument(pv);
1255

    
1256
                        }
1257
                        return true;
1258
                } catch (Exception e) {
1259
                        e.printStackTrace();
1260
                        return false;
1261
                }
1262

    
1263
        }
1264

    
1265
        private boolean addMaps(XMLEntity xmlMaps) {
1266
                try {
1267
                        Project project = this.getProject();
1268
                        XMLEntity child;
1269
                        int numLayers = xmlMaps.getChildrenCount();
1270
                        for (int i = 0; i < numLayers; i++) {
1271
                                child = xmlMaps.getChild(i);
1272

    
1273
                                ProjectMap pm = (ProjectMap) ProjectMap.createFromXML(child, project);
1274
                                project.addDocument(pm);
1275

    
1276
                        }
1277
                        return true;
1278
                } catch (Exception e) {
1279
                        e.printStackTrace();
1280
                        return false;
1281
                }
1282

    
1283
        }
1284

    
1285
        private Project getProject() {
1286
                 return ((ProjectExtension)PluginServices.getExtension(ProjectExtension.class)).getProject();
1287
        }
1288

    
1289
        private boolean addToXMLDataSource(SourceInfo source,XMLEntity xmlDataSources, Project project) {
1290
                if (project== null) {
1291
                        project = this.getProject();
1292
                }
1293
                    xmlDataSources.addChild(project.getSourceInfoXMLEntity(source));
1294

    
1295
                    return true;
1296
        }
1297

    
1298
        private boolean addToXMLTable(ProjectTable pt,XMLEntity xmlTables,XMLEntity xmlDataSources,Project project) {
1299
                if (project== null) {
1300
                        project = this.getProject();
1301
                }
1302
                if (findChildInXML(xmlTables,"name",pt.getName()) != null) return true;
1303
                XMLEntity xmlTable = null;
1304
                try {
1305
                        xmlTable = pt.getXMLEntity();
1306

    
1307
                        xmlTables.addChild(xmlTable);
1308

    
1309
                        if (pt.getAssociatedTable() != null) {
1310
                                this.addToXMLDataSource(pt.getAssociatedTable().getRecordset().getSourceInfo(),xmlDataSources,project);
1311
                        }
1312

    
1313
                        if (pt.getLinkTable() != null) {
1314
                                if (findChildInXML(xmlTables,"name",pt.getLinkTable()) == null)  {
1315
                                        ProjectTable ptLink = project.getTable(pt.getLinkTable());
1316
                                        if (!this.addToXMLTable(ptLink,xmlTables,xmlDataSources,project)) return false;
1317
                                }
1318
                        }
1319
                } catch (SaveException e) {
1320
                        e.printStackTrace();
1321
                        return false;
1322
                } catch (ReadException e) {
1323
                        e.printStackTrace();
1324
                        return false;
1325
                }
1326

    
1327
                    return true;
1328
        }
1329

    
1330
        private boolean addToXMLLayerDependencies(FLayer lyr,XMLEntity xmlTables,XMLEntity xmlDataSources) {
1331
                try {
1332
                        Project project = this.getProject();
1333

    
1334
                        if (lyr instanceof FLayers) {
1335
                                FLayers lyrs = (FLayers)lyr;
1336
                                int count = lyrs.getLayersCount();
1337
                                for (int i=0;i < count;i++) {
1338
                                        FLayer subLyr = lyrs.getLayer(i);
1339
                                        this.addToXMLLayerDependencies(subLyr,xmlTables,xmlDataSources);
1340
                                }
1341

    
1342
                    } else if (lyr instanceof FLyrVect){
1343
                    if (!this.addToXMLDataSource(
1344
                                ((FLyrVect)lyr).getRecordset().getSourceInfo(),
1345
                                xmlDataSources,
1346
                                project
1347

    
1348
                    )) return false;
1349

    
1350
                ProjectTable pt = project.getTable((FLyrVect) lyr);
1351
                if (pt != null) {
1352
                        if (!this.addToXMLTable(pt,xmlTables,xmlDataSources,project)) return false;
1353
                }
1354

    
1355
            }
1356

    
1357
                } catch (ReadException e) {
1358
                        e.printStackTrace();
1359
                        return false;
1360
                } catch (Exception e) {
1361
                        e.printStackTrace();
1362
                        return false;
1363

    
1364
                }
1365
                return true;
1366

    
1367
        }
1368

    
1369
        private boolean addToXMLLayer(FLayer lyr,XMLEntity xmlLayers,XMLEntity xmlTables,XMLEntity xmlDataSources) {
1370
                try {
1371
                        xmlLayers.addChild(lyr.getXMLEntity());
1372

    
1373
                        return this.addToXMLLayerDependencies(lyr,xmlTables,xmlDataSources);
1374

    
1375
                } catch (XMLException e) {
1376
                        e.printStackTrace();
1377
                        return false;
1378
                } catch (Exception e) {
1379
                        e.printStackTrace();
1380
                        return false;
1381
                }
1382
        }
1383

    
1384
        private XMLEntity newRootNode() {
1385
                XMLEntity xml = new XMLEntity();
1386
                fillXMLRootNode(xml);
1387
                return xml;
1388
        }
1389

    
1390
        private XMLEntity newLayersNode() {
1391
                XMLEntity xmlLayers = new XMLEntity();
1392
                xmlLayers.putProperty("type","layers");
1393
                return xmlLayers;
1394
        }
1395

    
1396
        private XMLEntity newDataSourcesNode() {
1397
                XMLEntity xmlDataSources = new XMLEntity();
1398
                xmlDataSources.putProperty("type","dataSources");
1399
                return xmlDataSources;
1400
        }
1401

    
1402
        private XMLEntity newTablesNode() {
1403
                XMLEntity xmlTables = new XMLEntity();
1404
                xmlTables.putProperty("type","tables");
1405
                return xmlTables;
1406
        }
1407

    
1408
        private XMLEntity newViewsNode() {
1409
                XMLEntity xmlTables = new XMLEntity();
1410
                xmlTables.putProperty("type","views");
1411
                return xmlTables;
1412
        }
1413

    
1414
        private XMLEntity newMapsNode() {
1415
                XMLEntity xmlTables = new XMLEntity();
1416
                xmlTables.putProperty("type","maps");
1417
                return xmlTables;
1418
        }
1419

    
1420

    
1421
        public void putInClipboard(String data) {
1422
                StringSelection ss = new StringSelection(data);
1423

    
1424
                Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss,ss);
1425
        }
1426

    
1427
        public String marshallXMLEntity(XMLEntity xml) {
1428
                StringWriter buffer = new StringWriter();
1429

    
1430
                Marshaller m;
1431
                try {
1432
                        m = new Marshaller(buffer);
1433
                } catch (IOException e4) {
1434
                        // TODO Auto-generated catch block
1435
                        e4.printStackTrace();
1436
                        return null;
1437
                }
1438
                m.setEncoding(ProjectExtension.PROJECTENCODING);
1439

    
1440
                try {
1441
                        m.marshal(xml.getXmlTag());
1442
                        //if (i < actives.length-1) buffer.write("\n##layer-separator##\n");
1443
                } catch (MarshalException e2) {
1444
                        // TODO Auto-generated catch block
1445
                        e2.printStackTrace();
1446
                        return null;
1447
                } catch (ValidationException e3) {
1448
                        // TODO Auto-generated catch block
1449
                        e3.printStackTrace();
1450
                        return null;
1451
                }
1452

    
1453
                return buffer.toString();
1454

    
1455
        }
1456

    
1457
        public XMLEntity unMarshallXMLEntity(String data) {
1458
                StringReader reader = new StringReader(data);
1459

    
1460
                XmlTag tag;
1461
                try {
1462
                        tag = (XmlTag) XmlTag.unmarshal(reader);
1463
                } catch (MarshalException e) {
1464
                        return null;
1465
                } catch (ValidationException e) {
1466
                        return null;
1467
                }
1468
                XMLEntity xml=new XMLEntity(tag);
1469

    
1470
                return xml;
1471
        }
1472

    
1473
        public String getFromClipboard() {
1474

    
1475
                 try {
1476
                        return (String)Toolkit.getDefaultToolkit().getSystemClipboard().getContents(null).getTransferData(DataFlavor.stringFlavor);
1477
                } catch (UnsupportedFlavorException e) {
1478
                        return null;
1479
                } catch (IOException e) {
1480
                        // TODO Auto-generated catch block
1481
                        return null;
1482
                }
1483
        }
1484

    
1485
        public boolean removeLayers(FLayer[] actives) {
1486
            for (int i = actives.length-1; i>=0; i--){
1487
                try {
1488
                                //actives[i].getParentLayer().removeLayer(actives[i]);
1489
                                //FLayers lyrs=getMapContext().getLayers();
1490
                                //lyrs.addLayer(actives[i]);
1491
                                actives[i].getParentLayer().removeLayer(actives[i]);
1492

    
1493
                if (actives[i] instanceof FLyrVect){
1494
                    Project project = ((ProjectExtension)PluginServices.getExtension(ProjectExtension.class)).getProject();
1495
                    ProjectTable pt = project.getTable((FLyrVect) actives[i]);
1496

    
1497
                    ArrayList tables = project.getDocumentsByType(ProjectTableFactory.registerName);
1498
                    for (int j = 0; j < tables.size(); j++) {
1499
                        if (tables.get(j) == pt){
1500
                            project.delDocument((ProjectDocument)tables.get(j));
1501
                            break;
1502
                        }
1503
                    }
1504

    
1505
                    PluginServices.getMDIManager().closeSingletonWindow(pt);
1506
                }
1507

    
1508

    
1509
                    } catch (CancelationException e1) {
1510
                            e1.printStackTrace();
1511
                            return false;
1512
                    }
1513
            }
1514
                return true;
1515
        }
1516

    
1517
        public boolean removeDocuments(ProjectDocument[] selectedItems) {
1518
                Project p = this.getProject();
1519
                ProjectDocument element;
1520
                int index;
1521
                for (int i=selectedItems.length-1;i>=0;i--) {
1522

    
1523
                        element = selectedItems[i];
1524

    
1525
                        if (element instanceof ProjectMap) {
1526

    
1527
                                if (element.isLocked()) {
1528
                                        JOptionPane.showMessageDialog(
1529
                                                (Component)PluginServices.getMainFrame(),
1530
                                                PluginServices.getText(this, "locked_element_it_cannot_be_deleted") + ": " +element.getName()
1531
                                        );
1532
                                        //return false;
1533
                                } else {
1534
                                        PluginServices.getMDIManager().closeSingletonWindow(element);
1535
                                        p.delDocument(element);
1536
                                }
1537
                        } else if (element instanceof ProjectTable) {
1538
                                if (element.isLocked()) {
1539
                                        JOptionPane.showMessageDialog(
1540
                                                (Component)PluginServices.getMainFrame(),
1541
                                                PluginServices.getText(this, "locked_element_it_cannot_be_deleted") + ": " +element.getName()
1542
                                        );
1543

    
1544
                                        //return false;
1545
                                } else {
1546
                                        PluginServices.getMDIManager().closeSingletonWindow(element);
1547
                                        p.delDocument(element);
1548
                                }
1549
                        } else {
1550
                                if (element.isLocked()) {
1551
                                        JOptionPane.showMessageDialog(
1552
                                                (Component)PluginServices.getMainFrame(),
1553
                                                PluginServices.getText(this, "locked_element_it_cannot_be_deleted") + ": " +element.getName()
1554
                                        );
1555
                                        //return false;
1556
                                } else {
1557
                                        PluginServices.getMDIManager().closeSingletonWindow(element);
1558
                                        p.delDocument(element);
1559
                                }
1560
                        }
1561
                }
1562
                return true;
1563
        }
1564

    
1565
}