Statistics
| Revision:

root / trunk / applications / appgvSIG / src / com / iver / cit / gvsig / CopyPasteExtension.java @ 33261

History | View | Annotate | Download (43.6 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.tools.file.PathGenerator;
25

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

    
58
public class CopyPasteExtension extends Extension {
59

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

64

65

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

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

79

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

84

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

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

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

102

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

107

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

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

116
                */
117
        }
118

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

    
122
        }
123

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

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

    
132

    
133
}
134

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

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

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

    
146

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

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

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

    
162

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

    
170
        public int getOrder() {
171

    
172
                return 0;
173
        }
174

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

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

    
183

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

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

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

    
213
}
214

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

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

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

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

    
234

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

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

    
259

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

    
265

    
266
                this.utiles.removeDocuments(selectedItems);
267

    
268
        }
269

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

    
274
}
275

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

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

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

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

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

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

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

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

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

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

    
314

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

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

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

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

    
335
        }
336

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

    
341
}
342

    
343

    
344

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

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

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

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

    
360
}
361

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

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

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

    
375

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

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

    
399
                this.utiles.putInClipboard(data);
400

    
401
        }
402

    
403

    
404
}
405

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

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

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

    
419

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

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

    
443

    
444
                this.utiles.putInClipboard(data);
445

    
446

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

    
453

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

    
456
                getMapContext().endAtomicEvent();
457

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

    
465
        }
466
}
467

    
468

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

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

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

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

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

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

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

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

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

    
508
                return  xml;
509
        }
510

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

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

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

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

    
527
                getMapContext().endAtomicEvent();
528

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

    
537
}
538

    
539

    
540
class Utiles {
541

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

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

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

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

576

577
         */
578

    
579

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

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

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

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

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

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

    
625
                }
626

    
627

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

    
638
                return xml;
639

    
640
        }
641

    
642

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

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

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

    
654
                }
655

    
656

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

    
670

    
671
                return xml;
672
        }
673

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

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

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

    
684

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

    
692
                return xml;
693
        }
694

    
695

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

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

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

    
706
                }
707

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

    
718
                return xml;
719

    
720
        }
721

    
722

    
723

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

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

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

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

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

    
748

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

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

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

    
759
                return true;
760

    
761
        }
762

    
763

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

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

    
771
                Project project = this.getProject();
772

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

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

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

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

    
844

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

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

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

    
855
                return true;
856
        }
857

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

    
862

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

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

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

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

    
875

    
876

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

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

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

    
888
                Project project = this.getProject();
889

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

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

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

    
896

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

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

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

    
966
                }
967

    
968

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

    
986

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

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

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

    
999
                return this.addMaps(xmlMaps);
1000

    
1001
        }
1002

    
1003

    
1004

    
1005

    
1006

    
1007

    
1008

    
1009

    
1010

    
1011

    
1012

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

    
1032

    
1033
        }
1034

    
1035

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

    
1047
                return true;
1048
        }
1049

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

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

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

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

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

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

    
1075

    
1076

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

    
1084

    
1085

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

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

    
1093
                return true;
1094
        }
1095

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

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

    
1114
        }
1115

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

    
1129
                        }
1130
                }
1131
                return conflits;
1132
        }
1133

    
1134

    
1135

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

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

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

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

    
1155

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

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

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

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

    
1192
                        Project project = this.getProject();
1193

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

    
1210
                        project.setLinkTable();
1211

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

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

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

    
1245
        }
1246

    
1247

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

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

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

    
1266
        }
1267

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

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

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

    
1286
        }
1287

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

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

    
1298
                    return true;
1299
        }
1300

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

    
1310
                        xmlTables.addChild(xmlTable);
1311

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

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

    
1330
                    return true;
1331
        }
1332

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

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

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

    
1351
                    )) return false;
1352

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

    
1358
            }
1359

    
1360
                } catch (ReadDriverException e) {
1361
                        e.printStackTrace();
1362
                        return false;
1363
                } catch (Exception e) {
1364
                        e.printStackTrace();
1365
                        return false;
1366

    
1367
                }
1368
                return true;
1369

    
1370
        }
1371

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

    
1376
                        return this.addToXMLLayerDependencies(lyr,xmlTables,xmlDataSources);
1377

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

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

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

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

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

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

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

    
1423

    
1424
        public void putInClipboard(String data) {
1425
                StringSelection ss = new StringSelection(data);
1426

    
1427
                Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss,ss);
1428
        }
1429

    
1430
        public String marshallXMLEntity(XMLEntity xml) {
1431
                StringWriter buffer = new StringWriter();
1432

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

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

    
1456
                return buffer.toString();
1457

    
1458
        }
1459

    
1460
        public XMLEntity unMarshallXMLEntity(String data) {
1461
                StringReader reader = new StringReader(data);
1462

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

    
1473
                return xml;
1474
        }
1475

    
1476
        public String getFromClipboard() {
1477

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

    
1488
        public boolean removeLayers(FLayer[] actives) {
1489
            for (int i = actives.length-1; i>=0; i--){
1490
                try {
1491
                                //actives[i].getParentLayer().removeLayer(actives[i]);
1492
                                //FLayers lyrs=getMapContext().getLayers();
1493
                                //lyrs.addLayer(actives[i]);
1494
                                actives[i].getParentLayer().removeLayer(actives[i]);
1495
                                PluginServices.getMainFrame().enableControls();
1496
                if (actives[i] instanceof AlphanumericData){
1497
                    Project project = ((ProjectExtension)PluginServices.getExtension(ProjectExtension.class)).getProject();
1498
                    ProjectTable pt = project.getTable((AlphanumericData) actives[i]);
1499

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

    
1508
                    PluginServices.getMDIManager().closeSingletonWindow(pt);
1509
                }
1510

    
1511

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

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

    
1526
                        element = selectedItems[i];
1527

    
1528
                        if (element instanceof ProjectMap) {
1529

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

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

    
1568
}