Statistics
| Revision:

svn-gvsig-desktop / trunk / applications / appgvSIG / src / com / iver / cit / gvsig / CopyPasteExtension.java @ 9532

History | View | Annotate | Download (43.5 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

    
25
import com.hardcode.gdbms.engine.data.DataSourceFactory;
26
import com.hardcode.gdbms.engine.data.SourceInfo;
27
import com.iver.andami.PluginServices;
28
import com.iver.andami.plugins.Extension;
29
import com.iver.andami.ui.mdiManager.IWindow;
30
import com.iver.cit.gvsig.fmap.DriverException;
31
import com.iver.cit.gvsig.fmap.layers.CancelationException;
32
import com.iver.cit.gvsig.fmap.layers.FLayer;
33
import com.iver.cit.gvsig.fmap.layers.FLayers;
34
import com.iver.cit.gvsig.fmap.layers.LayerFactory;
35
import com.iver.cit.gvsig.fmap.layers.XMLException;
36
import com.iver.cit.gvsig.fmap.layers.layerOperations.AlphanumericData;
37
import com.iver.cit.gvsig.project.Project;
38
import com.iver.cit.gvsig.project.documents.ProjectDocument;
39
import com.iver.cit.gvsig.project.documents.contextMenu.AbstractDocumentContextMenuAction;
40
import com.iver.cit.gvsig.project.documents.exceptions.OpenException;
41
import com.iver.cit.gvsig.project.documents.exceptions.SaveException;
42
import com.iver.cit.gvsig.project.documents.layout.ProjectMap;
43
import com.iver.cit.gvsig.project.documents.layout.ProjectMapFactory;
44
import com.iver.cit.gvsig.project.documents.layout.fframes.FFrameView;
45
import com.iver.cit.gvsig.project.documents.layout.fframes.IFFrame;
46
import com.iver.cit.gvsig.project.documents.table.ProjectTable;
47
import com.iver.cit.gvsig.project.documents.table.ProjectTableFactory;
48
import com.iver.cit.gvsig.project.documents.view.ProjectView;
49
import com.iver.cit.gvsig.project.documents.view.ProjectViewFactory;
50
import com.iver.cit.gvsig.project.documents.view.gui.BaseView;
51
import com.iver.cit.gvsig.project.documents.view.toc.AbstractTocContextMenuAction;
52
import com.iver.cit.gvsig.project.documents.view.toc.ITocItem;
53
import com.iver.utiles.XMLEntity;
54
import com.iver.utiles.extensionPoints.IExtensionBuilder;
55
import com.iver.utiles.xmlEntity.generate.XmlTag;
56

    
57
public class CopyPasteExtension extends Extension {
58

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

63

64

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

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

78

79
            //FPopupMenu.addEntry(copy);
80
            //FPopupMenu.addEntry(cut);
81
            //FPopupMenu.addEntry(paste);
82

83

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

91
                copyProjectElement.setUtiles(utiles);
92
                cutProjectElement.setUtiles(utiles);
93
                pasteProjectElementView.setUtiles(utiles);
94
                pasteProjectElementTable.setUtiles(utiles);
95
                pasteProjectElementMap.setUtiles(utiles);
96

97
                pasteProjectElementView.setType("views");
98
                pasteProjectElementTable.setType("tables");
99
                pasteProjectElementMap.setType("maps");
100

101

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

106

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

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

115
                */
116
        }
117

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

    
121
        }
122

    
123
        public boolean isEnabled() {
124
                return false;
125
        }
126

    
127
        public boolean isVisible() {
128
                return false;
129
        }
130

    
131

    
132
}
133

    
134
abstract class MyDocumentAction extends AbstractDocumentContextMenuAction implements IExtensionBuilder {
135
        protected Utiles utiles;
136

    
137
        public void setUtiles(Utiles utiles) {
138
                this.utiles = utiles;
139
        }
140

    
141
        public String getGroup() {
142
                return "ClipboardActions";
143
        }
144

    
145

    
146
        public Object create() {
147
                return this;
148
        }
149

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

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

    
161

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

    
169
        public int getOrder() {
170

    
171
                return 0;
172
        }
173

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

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

    
182

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

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

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

    
212
}
213

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

    
221
        public int getOrder() {
222
                return 1;
223
        }
224

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

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

    
233

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

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

    
258

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

    
264

    
265
                this.utiles.removeDocuments(selectedItems);
266

    
267
        }
268

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

    
273
}
274

    
275
class PasteProjectElement extends MyDocumentAction {
276
        private String type;
277

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

    
284
        public int getOrder() {
285
                return 2;
286
        }
287

    
288
        public void setType(String type) {
289
                this.type = type;
290
        }
291

    
292
        public String getType(String type) {
293
                return this.type;
294
        }
295

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

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

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

    
307
                if (!this.utiles.checkXMLRootNode(xml)) return false;
308

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

    
313

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

    
318
                XMLEntity xml = this.utiles.unMarshallXMLEntity(sourceString);
319
                if (xml == null) return;
320

    
321
                if (!this.utiles.checkXMLRootNode(xml)) return;
322

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

    
334
        }
335

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

    
340
}
341

    
342

    
343

    
344
abstract class  MyTocMenuEntry extends AbstractTocContextMenuAction {
345
        protected Utiles utiles;
346

    
347
        public void setUtiles(Utiles utiles) {
348
                this.utiles = utiles;
349
        }
350

    
351
        public String getGroup() {
352
                return "copyPasteLayer";
353
        }
354

    
355
        public int getGroupOrder() {
356
                return 60;
357
        }
358

    
359
}
360

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

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

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

    
374

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

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

    
398
                this.utiles.putInClipboard(data);
399

    
400
        }
401

    
402

    
403
}
404

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

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

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

    
418

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

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

    
442

    
443
                this.utiles.putInClipboard(data);
444

    
445

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

    
452

    
453
                boolean isOK =this.utiles.removeLayers(selectedItems);
454

    
455
                getMapContext().endAtomicEvent();
456

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

    
464
        }
465
}
466

    
467

    
468
class PasteTocMenuEntry extends MyTocMenuEntry{
469
        private XMLEntity xml=null;
470

    
471
        public int getOrder() {
472
                return 2;
473
        }
474

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

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

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

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

    
500
                XMLEntity xml = this.utiles.unMarshallXMLEntity(sourceString);
501
                if (xml == null) return null;
502

    
503
                if (!this.utiles.checkXMLRootNode(xml)) return null;
504

    
505
                if (this.utiles.getXMLEntityChildOfType(xml,"layers") == null) return null;
506

    
507
                return  xml;
508
        }
509

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

    
513
                if (this.xml == null) return;
514

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

    
524
                boolean isOK = this.utiles.loadLayersFromXML(this.xml,root);
525

    
526
                getMapContext().endAtomicEvent();
527

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

    
536
}
537

    
538

    
539
class Utiles {
540

    
541
        /*
542
         *
543
======================================
544
 Comportamiento del Pegar documentos:
545
======================================
546

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

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

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

575

576
         */
577

    
578

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

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

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

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

    
617
                XMLEntity xmlTables = this.newTablesNode();
618
                XMLEntity xmlDataSources = this.newDataSourcesNode();
619
                XMLEntity xmlViews = this.newViewsNode();
620

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

    
624
                }
625

    
626

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

    
637
                return xml;
638

    
639
        }
640

    
641

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

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

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

    
653
                }
654

    
655

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

    
669

    
670
                return xml;
671
        }
672

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

    
676
                XMLEntity xmlTables = this.newTablesNode();
677
                XMLEntity xmlDataSources = this.newDataSourcesNode();
678

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

    
683

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

    
691
                return xml;
692
        }
693

    
694

    
695
        public XMLEntity generateXMLCopyLayers(FLayer[] actives) {
696

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

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

    
705
                }
706

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

    
717
                return xml;
718

    
719
        }
720

    
721

    
722

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

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

    
738
                if (xmlLayers == null ) return false;
739

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

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

    
747

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

    
752
                if (!this.addLayers(xmlLayers,root)) return false;
753

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

    
758
                return true;
759

    
760
        }
761

    
762

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

    
768
                if (xmlViews == null ) return false;
769

    
770
                Project project = this.getProject();
771

    
772
                Hashtable viewsConflits = this.getConflicts(xmlViews,project.getDocumentsByType(ProjectViewFactory.registerName));
773

    
774
                Hashtable tablesConflits = this.getConflicts(xmlTables,project.getDocumentsByType(ProjectTableFactory.registerName));
775

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

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

    
843

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

    
848
                if (!this.addViews(xmlViews)) return false;
849

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

    
854
                return true;
855
        }
856

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

    
861

    
862
                if (xmlTables == null ) return false;
863

    
864
                /*
865
                Project project = this.getProject();
866

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

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

    
874

    
875

    
876
                return this.addTables(xmlTables);
877
        }
878

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

    
885
                if (xmlMaps == null ) return false;
886

    
887
                Project project = this.getProject();
888

    
889
                Hashtable mapsConflits = this.getConflicts(xmlMaps,project.getDocumentsByType(ProjectMapFactory.registerName));
890

    
891
                Hashtable viewsConflits = this.getConflicts(xmlViews,project.getDocumentsByType(ProjectViewFactory.registerName));
892

    
893
                Hashtable tablesConflits = this.getConflicts(xmlTables,project.getDocumentsByType(ProjectTableFactory.registerName));
894

    
895

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

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

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

    
965
                }
966

    
967

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

    
985

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

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

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

    
998
                return this.addMaps(xmlMaps);
999

    
1000
        }
1001

    
1002

    
1003

    
1004

    
1005

    
1006

    
1007

    
1008

    
1009

    
1010

    
1011

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

    
1031

    
1032
        }
1033

    
1034

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

    
1046
                return true;
1047
        }
1048

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

    
1053
                        return this.addToXMLMapDependencies(map,xmlViews,xmlTables,xmlDataSources);
1054

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

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

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

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

    
1074

    
1075

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

    
1083

    
1084

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

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

    
1092
                return true;
1093
        }
1094

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

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

    
1113
        }
1114

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

    
1128
                        }
1129
                }
1130
                return conflits;
1131
        }
1132

    
1133

    
1134

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

    
1139
                        if (numDataSources == 0) return true;
1140
                        DataSourceFactory dsFactory = LayerFactory.getDataSourceFactory();
1141

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

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

    
1154

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

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

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

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

    
1191
                        Project project = this.getProject();
1192

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

    
1209
                        project.setLinkTable();
1210

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

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

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

    
1244
        }
1245

    
1246

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

    
1255
                                ProjectView pv = (ProjectView) ProjectView.createFromXML(child, project);
1256
                                project.addDocument(pv);
1257

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

    
1265
        }
1266

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

    
1275
                                ProjectMap pm = (ProjectMap) ProjectMap.createFromXML(child, project);
1276
                                project.addDocument(pm);
1277

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

    
1285
        }
1286

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

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

    
1297
                    return true;
1298
        }
1299

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

    
1309
                        xmlTables.addChild(xmlTable);
1310

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

    
1315
                        if (pt.getLinkTable() != null) {
1316
                                if (findChildInXML(xmlTables,"name",pt.getLinkTable()) == null)  {
1317
                                        ProjectTable ptLink = project.getTable(pt.getLinkTable());
1318
                                        if (!this.addToXMLTable(ptLink,xmlTables,xmlDataSources,project)) return false;
1319
                                }
1320
                        }
1321
                } catch (SaveException e) {
1322
                        // TODO Auto-generated catch block
1323
                        e.printStackTrace();
1324
                        return false;
1325
                } catch (DriverException e) {
1326
                        // TODO Auto-generated catch block
1327
                        e.printStackTrace();
1328
                        return false;
1329
                }
1330

    
1331
                    return true;
1332
        }
1333

    
1334
        private boolean addToXMLLayerDependencies(FLayer lyr,XMLEntity xmlTables,XMLEntity xmlDataSources) {
1335
                try {
1336
                        Project project = this.getProject();
1337

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

    
1346
                    } else if (lyr instanceof AlphanumericData){
1347
                    if (!this.addToXMLDataSource(
1348
                                ((AlphanumericData)lyr).getRecordset().getSourceInfo(),
1349
                                xmlDataSources,
1350
                                project
1351

    
1352
                    )) return false;
1353

    
1354
                ProjectTable pt = project.getTable((AlphanumericData) lyr);
1355
                if (pt != null) {
1356
                        if (!this.addToXMLTable(pt,xmlTables,xmlDataSources,project)) return false;
1357
                }
1358

    
1359
            }
1360

    
1361
                } catch (DriverException e) {
1362
                        // TODO Auto-generated catch block
1363
                        e.printStackTrace();
1364
                        return false;
1365
                } catch (Exception e) {
1366
                        e.printStackTrace();
1367
                        return false;
1368

    
1369
                }
1370
                return true;
1371

    
1372
        }
1373

    
1374
        private boolean addToXMLLayer(FLayer lyr,XMLEntity xmlLayers,XMLEntity xmlTables,XMLEntity xmlDataSources) {
1375
                try {
1376
                        xmlLayers.addChild(lyr.getXMLEntity());
1377

    
1378
                        return this.addToXMLLayerDependencies(lyr,xmlTables,xmlDataSources);
1379

    
1380
                } catch (XMLException e) {
1381
                        e.printStackTrace();
1382
                        return false;
1383
                } catch (Exception e) {
1384
                        e.printStackTrace();
1385
                        return false;
1386
                }
1387
        }
1388

    
1389
        private XMLEntity newRootNode() {
1390
                XMLEntity xml = new XMLEntity();
1391
                fillXMLRootNode(xml);
1392
                return xml;
1393
        }
1394

    
1395
        private XMLEntity newLayersNode() {
1396
                XMLEntity xmlLayers = new XMLEntity();
1397
                xmlLayers.putProperty("type","layers");
1398
                return xmlLayers;
1399
        }
1400

    
1401
        private XMLEntity newDataSourcesNode() {
1402
                XMLEntity xmlDataSources = new XMLEntity();
1403
                xmlDataSources.putProperty("type","dataSources");
1404
                return xmlDataSources;
1405
        }
1406

    
1407
        private XMLEntity newTablesNode() {
1408
                XMLEntity xmlTables = new XMLEntity();
1409
                xmlTables.putProperty("type","tables");
1410
                return xmlTables;
1411
        }
1412

    
1413
        private XMLEntity newViewsNode() {
1414
                XMLEntity xmlTables = new XMLEntity();
1415
                xmlTables.putProperty("type","views");
1416
                return xmlTables;
1417
        }
1418

    
1419
        private XMLEntity newMapsNode() {
1420
                XMLEntity xmlTables = new XMLEntity();
1421
                xmlTables.putProperty("type","maps");
1422
                return xmlTables;
1423
        }
1424

    
1425

    
1426
        public void putInClipboard(String data) {
1427
                StringSelection ss = new StringSelection(data);
1428

    
1429
                Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss,ss);
1430
        }
1431

    
1432
        public String marshallXMLEntity(XMLEntity xml) {
1433
                StringWriter buffer = new StringWriter();
1434

    
1435
                Marshaller m;
1436
                try {
1437
                        m = new Marshaller(buffer);
1438
                } catch (IOException e4) {
1439
                        // TODO Auto-generated catch block
1440
                        e4.printStackTrace();
1441
                        return null;
1442
                }
1443
                m.setEncoding("ISO-8859-1");
1444

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

    
1458
                return buffer.toString();
1459

    
1460
        }
1461

    
1462
        public XMLEntity unMarshallXMLEntity(String data) {
1463
                StringReader reader = new StringReader(data);
1464

    
1465
                XmlTag tag;
1466
                try {
1467
                        tag = (XmlTag) XmlTag.unmarshal(reader);
1468
                } catch (MarshalException e) {
1469
                        return null;
1470
                } catch (ValidationException e) {
1471
                        return null;
1472
                }
1473
                XMLEntity xml=new XMLEntity(tag);
1474

    
1475
                return xml;
1476
        }
1477

    
1478
        public String getFromClipboard() {
1479

    
1480
                 try {
1481
                        return (String)Toolkit.getDefaultToolkit().getSystemClipboard().getContents(null).getTransferData(DataFlavor.stringFlavor);
1482
                } catch (UnsupportedFlavorException e) {
1483
                        return null;
1484
                } catch (IOException e) {
1485
                        // TODO Auto-generated catch block
1486
                        return null;
1487
                }
1488
        }
1489

    
1490
        public boolean removeLayers(FLayer[] actives) {
1491
            for (int i = actives.length-1; i>=0; i--){
1492
                try {
1493
                                //actives[i].getParentLayer().removeLayer(actives[i]);
1494
                                //FLayers lyrs=getMapContext().getLayers();
1495
                                //lyrs.addLayer(actives[i]);
1496
                                actives[i].getParentLayer().removeLayer(actives[i]);
1497

    
1498
                if (actives[i] instanceof AlphanumericData){
1499
                    Project project = ((ProjectExtension)PluginServices.getExtension(ProjectExtension.class)).getProject();
1500
                    ProjectTable pt = project.getTable((AlphanumericData) actives[i]);
1501

    
1502
                    ArrayList tables = project.getDocumentsByType(ProjectTableFactory.registerName);
1503
                    for (int j = 0; j < tables.size(); j++) {
1504
                        if (tables.get(j) == pt){
1505
                            project.delDocument((ProjectDocument)tables.get(j));
1506
                            break;
1507
                        }
1508
                    }
1509

    
1510
                    PluginServices.getMDIManager().closeSingletonWindow(pt);
1511
                }
1512

    
1513

    
1514
                    } catch (CancelationException e1) {
1515
                            e1.printStackTrace();
1516
                            return false;
1517
                    }
1518
            }
1519
                return true;
1520
        }
1521

    
1522
        public boolean removeDocuments(ProjectDocument[] selectedItems) {
1523
                Project p = this.getProject();
1524
                ProjectDocument element;
1525
                int index;
1526
                for (int i=selectedItems.length-1;i>=0;i--) {
1527

    
1528
                        element = selectedItems[i];
1529

    
1530
                        if (element instanceof ProjectMap) {
1531

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

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

    
1570
}