Revision 39136

View differences:

branches/v2_0_0_prep/applications/appgvSIG/src/org/gvsig/app/project/documents/view/toc/actions/CopyPasteLayersUtiles.java
1
package org.gvsig.app.project.documents.view.toc.actions;
2

  
3
import javax.help.UnsupportedOperationException;
4

  
5
import org.gvsig.fmap.mapcontext.layers.FLayer;
6
import org.gvsig.fmap.mapcontext.layers.FLayers;
7
import org.gvsig.utils.XMLEntity;
8

  
9

  
10
public class CopyPasteLayersUtiles {
11
	private static CopyPasteLayersUtiles theInstance = null;
12

  
13
	public static CopyPasteLayersUtiles getInstance() {
14
		if (theInstance == null) {
15
			theInstance = new CopyPasteLayersUtiles();
16
		}
17
		return theInstance;
18
	}
19

  
20
	public XMLEntity generateXMLCopyLayers(FLayer[] actives) {
21
		// FIXME: jjdc esta pendiente la implementacion del copy/paste
22
		throw new UnsupportedOperationException();
23
//
24
//		XMLEntity xml = this.newRootNode();
25
//		XMLEntity xmlLayers = this.newLayersNode();
26
//		XMLEntity xmlTables = this.newTablesNode();
27
//		XMLEntity xmlDataSources = this.newDataSourcesNode();
28
//
29
//		for (int i=0;i < actives.length; i++) {
30
//			if (!this.addToXMLLayer(actives[i],xmlLayers ,xmlTables,xmlDataSources)) {
31
//				return null;
32
//			}
33
//
34
//		}
35
//
36
//		if (xmlDataSources.getChildrenCount() > 0) {
37
//			xml.addChild(xmlDataSources);
38
//		}
39
//		if (xmlLayers.getChildrenCount() > 0) {
40
//			xml.addChild(xmlLayers);
41
//		}
42
//		if (xmlTables.getChildrenCount() > 0) {
43
//			xml.addChild(xmlTables);
44
//		}
45
//
46
//		return xml;
47
//
48
	}
49

  
50

  
51

  
52
	/*
53
	 *
54
	 *
55
	 *
56
	 * Funciones Publicas de carga de un XML (pegar)
57
	 *
58
	 *
59
	 *
60
	*/
61

  
62
	public boolean loadLayersFromXML(XMLEntity xml, FLayers root) {
63
		// FIXME: jjdc esta pendiente la implementacion del copy/paste
64
		throw new UnsupportedOperationException();
65
//		XMLEntity xmlLayers = xml.firstChild("type","layers");
66
//		XMLEntity xmlTables = xml.firstChild("type","tables");
67
//		XMLEntity xmlDataSources = xml.firstChild("type","dataSources");
68
//
69
//		if (xmlLayers == null ) {
70
//			return false;
71
//		}
72
//
73
//		// Se pegan las tablas igualmente
74
//		/*
75
//		Project project = this.getProject();
76
//
77
//		Hashtable tablesConfits = this.getConflicts(xmlTables,project.getTables());
78
//		*/
79
//
80
//
81
//		if (xmlDataSources != null)  {
82
//			if (!this.registerDataSources(xmlDataSources)) {
83
//				return false;
84
//			}
85
//		}
86
//
87
//		if (!this.addLayers(xmlLayers,root)) {
88
//			return false;
89
//		}
90
//
91
//		if (xmlTables != null)  {
92
//			if (!this.addTables(xmlTables)) {
93
//				return false;
94
//			}
95
//		}
96
//
97
//		return true;
98
//
99
	}
100

  
101
	public boolean loadTablesFromXML(XMLEntity xml) {
102
		// FIXME: jjdc esta pendiente la implementacion del copy/paste
103
		throw new UnsupportedOperationException();
104
//		XMLEntity xmlTables = xml.firstChild("type","tables");
105
//		XMLEntity xmlDataSources = xml.firstChild("type","dataSources");
106
//
107
//
108
//		if (xmlTables == null ) {
109
//			return false;
110
//		}
111
//
112
//		/*
113
//		Project project = this.getProject();
114
//
115
//		Hashtable tablesConfits = this.getConflicts(xmlTables,project.getTables());
116
//		*/
117
//
118
//		if (xmlDataSources != null)  {
119
//			if (!this.registerDataSources(xmlDataSources)) {
120
//				return false;
121
//			}
122
//		}
123
//
124
//
125
//
126
//		return this.addTables(xmlTables);
127
	}
128

  
129

  
130
	public boolean checkXMLRootNode(XMLEntity xml) {
131
		// FIXME: jjdc esta pendiente la implementacion del copy/paste
132
		throw new UnsupportedOperationException();
133
//		if (!xml.contains("applicationName")) {
134
//			return false;
135
//		}
136
//		if (!xml.getStringProperty("applicationName").equalsIgnoreCase("gvSIG")) {
137
//			return false;
138
//		}
139
//
140
//		if (!xml.contains("version")) {
141
//			return false;
142
//		}
143
//		if (!xml.getStringProperty("version").equalsIgnoreCase(Version.format())) {
144
//			return false;
145
//		}
146
//
147
//		return true;
148
	}
149

  
150
//	private void fillXMLRootNode(XMLEntity xml) {
151
//		xml.putProperty("applicationName","gvSIG");
152
//		xml.putProperty("version",Version.format());
153
//	}
154
//
155
//	private boolean registerDataSources(XMLEntity xmlDataSources) {
156
//		try {
157
//			int numDataSources = xmlDataSources.getChildrenCount();
158
//
159
//			if (numDataSources == 0) return true;
160
//			DataSourceFactory dsFactory = LayerFactory.getDataSourceFactory();
161
//
162
//			for (int i = 0; i < numDataSources; i++) {
163
//				XMLEntity child = xmlDataSources.getChild(i);
164
//				String name = child.getStringProperty("gdbmsname");
165
//
166
//				if (dsFactory.getDriverInfo(name) == null) {
167
//					if (child.getStringProperty("type").equals("otherDriverFile")) {
168
//						LayerFactory.getDataSourceFactory().addFileDataSource(
169
//								child.getStringProperty("driverName"),
170
//								name,
171
//								child.getStringProperty("file")
172
//						);
173
//
174
//
175
//					} else if (child.getStringProperty("type").equals("sameDriverFile")) {
176
//						/*                                String layerName = child.getStringProperty("layerName");
177
//						 ProjectView vista = project.getViewByName(child.getStringProperty(
178
//						 "viewName"));
179
//						 FLayer layer = vista.getMapContext().getLayers().getLayer(layerName);
180
//
181
//						 modelo = ((AlphanumericData) layer).getRecordset();
182
//						 associatedTable = (AlphanumericData) layer;
183
//						 */
184
//					} else if (child.getStringProperty("type").equals("db")) {
185
//						LayerFactory.getDataSourceFactory().addDBDataSourceByTable(
186
//								name,
187
//								child.getStringProperty("host"),
188
//								child.getIntProperty("port"),
189
//								child.getStringProperty("user"),
190
//								child.getStringProperty("password"),
191
//								child.getStringProperty("dbName"),
192
//								child.getStringProperty("tableName"),
193
//								child.getStringProperty("driverInfo")
194
//						);
195
//					}
196
//				}
197
//			}
198
//
199
//			return true;
200
//		} catch (Exception e) {
201
//			e.printStackTrace();
202
//			return false;
203
//		}
204
//		return false;
205
//	}
206
//
207
//	private boolean addTables(XMLEntity xmlTables) {
208
//		try {
209
//			int numTables = xmlTables.getChildrenCount();
210
//			if (numTables == 0) {
211
//				return true;
212
//			}
213
//
214
//			Project project = this.getProject();
215
//
216
//			for (int i = 0; i < numTables; i++) {
217
//				try{
218
//					FeatureTableDocument ptable = (FeatureTableDocument) FeatureTableDocument.createFromXML(xmlTables.getChild(i), project);
219
//					project.addDocument(ptable);
220
//					/*
221
//					if (ptable.getSeedViewInfo()!=null && ptable.getAndamiView()!=null) { // open the view, if it was open, and restore its dimensions
222
//						PluginServices.getMDIManager().addView(ptable.getAndamiView());
223
//						PluginServices.getMDIManager().changeViewInfo(ptable.getAndamiView(), ptable.getSeedViewInfo());
224
//					}
225
//					*/
226
//				}catch(OpenException e){
227
//					e.printStackTrace();
228
//					return false;
229
//				}
230
//			}
231
//
232
//			project.setLinkTable();
233
//
234
//			return true;
235
//		} catch (Exception e) {
236
//			e.printStackTrace();
237
//			return false;
238
//		}
239
//	}
240
//
241
//	private boolean addLayers(XMLEntity xmlLayers,FLayers root) {
242
//		try {
243
//			XMLEntity child;
244
//			int numLayers = xmlLayers.getChildrenCount();
245
//			for (int i = 0; i < numLayers; i++) {
246
//				child = xmlLayers.getChild(i);
247
//				if (!root.addLayerFromXMLEntity(child,null)) return false;
248
//			}
249
//			return true;
250
//		} catch (Exception e) {
251
//			e.printStackTrace();
252
//			return false;
253
//		}
254
//
255
//	}
256
//
257
//
258
//
259
//	private Project getProject() {
260
//		 return ((ProjectExtension)PluginServices.getExtension(ProjectExtension.class)).getProject();
261
//	}
262
//
263
//	private boolean addToXMLDataSource(SourceInfo source,XMLEntity xmlDataSources, Project project) {
264
//		if (project== null) {
265
//			project = this.getProject();
266
//		}
267
//  	  	xmlDataSources.addChild(project.getSourceInfoXMLEntity(source));
268
//
269
//  	  	return true;
270
//	}
271
//
272
//	private boolean addToXMLTable(FeatureTableDocument pt,XMLEntity xmlTables,XMLEntity xmlDataSources,Project project) {
273
//		if (project== null) {
274
//			project = this.getProject();
275
//		}
276
//		if (xmlTables.findChildren("name",pt.getName()) != null) return true;
277
//		XMLEntity xmlTable = null;
278
//		try {
279
//			xmlTable = pt.getXMLEntity();
280
//
281
//			xmlTables.addChild(xmlTable);
282
//
283
//			if (pt.getAssociatedTable() != null) {
284
//				this.addToXMLDataSource(pt.getAssociatedTable().getRecordset().getSourceInfo(),xmlDataSources,project);
285
//			}
286
//
287
//			if (pt.getLinkTable() != null) {
288
//				if (xmlTables.findChildren("name",pt.getLinkTable()) == null)  {
289
//					ProjectTable ptLink = (ProjectTable)project.getProjectDocumentByName(pt.getLinkTable(),ProjectTableFactory.registerName);
290
//					if (!this.addToXMLTable(ptLink,xmlTables,xmlDataSources,project)) return false;
291
//				}
292
//			}
293
//		} catch (SaveException e) {
294
//			e.printStackTrace();
295
//			return false;
296
//		} catch (ReadException e) {
297
//			e.printStackTrace();
298
//			return false;
299
//		}
300
//
301
//  	  	return true;
302
//	}
303
//
304
//	private boolean addToXMLLayerDependencies(FLayer lyr,XMLEntity xmlTables,XMLEntity xmlDataSources) {
305
//		try {
306
//			Project project = this.getProject();
307
//
308
//			if (lyr instanceof FLayers) {
309
//				FLayers lyrs = (FLayers)lyr;
310
//				int count = lyrs.getLayersCount();
311
//				for (int i=0;i < count;i++) {
312
//					FLayer subLyr = lyrs.getLayer(i);
313
//					this.addToXMLLayerDependencies(subLyr,xmlTables,xmlDataSources);
314
//				}
315
//
316
//		    } else if (lyr instanceof FLyrVect){
317
//            	if (!this.addToXMLDataSource(
318
//        			((FLyrVect)lyr).getRecordset().getSourceInfo(),
319
//        			xmlDataSources,
320
//        			project
321
//
322
//            	)) return false;
323
//
324
//                ProjectTable pt = project.getTable((FLyrVect) lyr);
325
//                if (pt != null) {
326
//                	if (!this.addToXMLTable(pt,xmlTables,xmlDataSources,project)) return false;
327
//                }
328
//
329
//            }
330
//
331
//		} catch (ReadException e) {
332
//			// TODO Auto-generated catch block
333
//			e.printStackTrace();
334
//			return false;
335
//		} catch (Exception e) {
336
//			e.printStackTrace();
337
//			return false;
338
//
339
//		}
340
//		return true;
341
//	}
342
//
343
//	private boolean addToXMLLayer(FLayer lyr,XMLEntity xmlLayers,XMLEntity xmlTables,XMLEntity xmlDataSources) {
344
//		try {
345
//			xmlLayers.addChild(lyr.getXMLEntity());
346
//
347
//			return this.addToXMLLayerDependencies(lyr,xmlTables,xmlDataSources);
348
//
349
//		} catch (XMLException e) {
350
//			e.printStackTrace();
351
//			return false;
352
//		} catch (Exception e) {
353
//			e.printStackTrace();
354
//			return false;
355
//		}
356
//	}
357
//
358
//	private XMLEntity newRootNode() {
359
//		XMLEntity xml = new XMLEntity();
360
//		fillXMLRootNode(xml);
361
//		return xml;
362
//	}
363
//
364
//	private XMLEntity newLayersNode() {
365
//		XMLEntity xmlLayers = new XMLEntity();
366
//		xmlLayers.putProperty("type","layers");
367
//		return xmlLayers;
368
//	}
369
//
370
//	private XMLEntity newDataSourcesNode() {
371
//		XMLEntity xmlDataSources = new XMLEntity();
372
//		xmlDataSources.putProperty("type","dataSources");
373
//		return xmlDataSources;
374
//	}
375
//
376
//	private XMLEntity newTablesNode() {
377
//		XMLEntity xmlTables = new XMLEntity();
378
//		xmlTables.putProperty("type","tables");
379
//		return xmlTables;
380
//	}
381
//
382
	public boolean removeLayers(FLayer[] actives) {
383
		// FIXME: jjdc esta pendiente la implementacion del copy/paste
384
		throw new UnsupportedOperationException();
385
//   	for (int i = actives.length-1; i>=0; i--){
386
//        	try {
387
//				//actives[i].getParentLayer().removeLayer(actives[i]);
388
//				//FLayers lyrs=getMapContext().getLayers();
389
//				//lyrs.addLayer(actives[i]);
390
//				actives[i].getParentLayer().removeLayer(actives[i]);
391
//
392
//                if (actives[i] instanceof FLyrVect){
393
//                    Project project = ((ProjectExtension)PluginServices.getExtension(ProjectExtension.class)).getProject();
394
//                    FeatureTableDocument pt = project.getTable((FLyrVect) actives[i]);
395
//
396
//                    List<IProjectDocument> tables = project.getDocuments(FeatureTableDocumentFactory.TYPENAME);
397
//                    for (int j = 0; j < tables.size(); j++) {
398
//                        if (tables.get(j) == pt){
399
//                            project.delDocument(tables.get(j));
400
//                            break;
401
//                        }
402
//                    }
403
//
404
//                    PluginServices.getMDIManager().closeSingletonWindow(pt);
405
//                }
406
//
407
//
408
//    		} catch (CancelationException e1) {
409
//    			e1.printStackTrace();
410
//    			return false;
411
//    		}
412
//    	}
413
//		return true;
414
	}
415

  
416
}
branches/v2_0_0_prep/applications/appgvSIG/src/org/gvsig/app/project/documents/view/toc/actions/CopyLayersTocMenuEntry.java
4 4

  
5 5
import javax.swing.JOptionPane;
6 6

  
7
import org.slf4j.Logger;
8
import org.slf4j.LoggerFactory;
9

  
7 10
import org.gvsig.andami.PluginServices;
8
import org.gvsig.app.extension.ProjectExtension;
9
import org.gvsig.app.project.Project;
10 11
import org.gvsig.app.project.documents.view.toc.AbstractTocContextMenuAction;
11 12
import org.gvsig.app.project.documents.view.toc.ITocItem;
12 13
import org.gvsig.fmap.mapcontext.layers.FLayer;
13
import org.gvsig.utils.XMLEntity;
14
import org.gvsig.i18n.Messages;
15
import org.gvsig.tools.persistence.PersistentState;
14 16

  
15 17

  
16 18
public class CopyLayersTocMenuEntry extends AbstractTocContextMenuAction {
17
	private CopyPasteLayersUtiles utiles = CopyPasteLayersUtiles.getInstance();
18

  
19
    
20
    private static Logger logger =
21
        LoggerFactory.getLogger(CopyLayersTocMenuEntry.class);
22
    
19 23
	public String getGroup() {
20 24
		return "copyPasteLayer";
21 25
	}
......
47 51

  
48 52

  
49 53
	public void execute(ITocItem item, FLayer[] selectedItems) {
50
		XMLEntity xml = this.utiles.generateXMLCopyLayers(selectedItems);
51
		if (xml == null) {
52
			JOptionPane.showMessageDialog(
53
					(Component)PluginServices.getMainFrame(),
54
					"<html>"+PluginServices.getText(this,"No_ha_sido_posible_realizar_la_operacion")+"</html>",//Mensaje
55
					PluginServices.getText(this,"copiar"),//titulo
56
					JOptionPane.ERROR_MESSAGE
57
					);
58
			return;
59
		}
60 54

  
61
		String data = xml.toString();
62
		if (data == null) {
63
			JOptionPane.showMessageDialog(
64
					(Component)PluginServices.getMainFrame(),
65
					"<html>"+PluginServices.getText(this,"No_ha_sido_posible_realizar_la_operacion")+"</html>",//Mensaje
66
					PluginServices.getText(this,"copiar"),//titulo
67
					JOptionPane.ERROR_MESSAGE
68
					);
69
			return;
70
		}
55
	       PersistentState lyrs_state = null;
56
	        
57
	        try {
58
	            lyrs_state = CopyPasteLayersUtils.getAsFLayersPersistentState(
59
	                selectedItems, this.getMapContext());
60
	            /*
61
	             * Saving layers data to clipboard.
62
	             * Files and URLs are not relativized
63
	             */
64
	            CopyPasteLayersUtils.saveToClipboard(lyrs_state);
65
	            
66
	            /*
67
	             * This code does not look right: why modified?
68
	             * 
69
	            Project project=((ProjectExtension)PluginServices.getExtension(ProjectExtension.class)).getProject();
70
	            project.setModified(true);
71
	            */
71 72

  
72
		PluginServices.putInClipboard(data);
73
		Project project=((ProjectExtension)PluginServices.getExtension(ProjectExtension.class)).getProject();
74
		project.setModified(true);
73
	        } catch (Exception e) {
74
	            
75
	            JOptionPane.showMessageDialog(
76
                    (Component)PluginServices.getMainFrame(),
77
                    Messages.getText("No_ha_sido_posible_realizar_la_operacion")
78
                    + "\n\n" + e.getMessage(),
79
                    Messages.getText("copiar"),
80
                    JOptionPane.ERROR_MESSAGE
81
                    );
82
	            logger.info("While copying layers.", e);
83
	            return;
84
	        }
75 85
	}
76 86

  
77 87

  
branches/v2_0_0_prep/applications/appgvSIG/src/org/gvsig/app/project/documents/view/toc/actions/CopyPasteLayersUtils.java
1
package org.gvsig.app.project.documents.view.toc.actions;
2

  
3
import java.awt.Component;
4
import java.io.File;
5
import java.io.FileInputStream;
6
import java.io.FileOutputStream;
7
import java.io.IOException;
8
import java.io.InputStream;
9
import java.io.OutputStream;
10

  
11
import javax.swing.JOptionPane;
12

  
13
import org.slf4j.Logger;
14
import org.slf4j.LoggerFactory;
15

  
16
import org.gvsig.andami.PluginServices;
17
import org.gvsig.andami.ui.mdiManager.IWindow;
18
import org.gvsig.app.extension.ProjectExtension;
19
import org.gvsig.app.project.Project;
20
import org.gvsig.fmap.mapcontext.MapContext;
21
import org.gvsig.fmap.mapcontext.layers.CancelationException;
22
import org.gvsig.fmap.mapcontext.layers.FLayer;
23
import org.gvsig.fmap.mapcontext.layers.FLayers;
24
import org.gvsig.i18n.Messages;
25
import org.gvsig.tools.ToolsLocator;
26
import org.gvsig.tools.persistence.PersistenceManager;
27
import org.gvsig.tools.persistence.PersistentState;
28
import org.gvsig.tools.persistence.exception.PersistenceException;
29
import org.gvsig.tools.persistence.impl.exception.ObjectNotFoundException;
30

  
31
/**
32
 * This class provides utility methods to manage the TOC clipboard
33
 * which will contain one or more layers for copy/cut/paste
34
 * operations. It is currently implemented using a persistence
35
 * file where an instance of FLayers is stored.
36
 * 
37
 * @author jldominguez
38
 * 
39
 */
40
public class CopyPasteLayersUtils {
41

  
42
    private static Logger logger = LoggerFactory
43
        .getLogger(CopyPasteLayersUtils.class);
44

  
45
    /**
46
     * The file which is used to save the layers
47
     */
48
    private static String CLIPBOARD_FILE_NAME = "gvSIG_clipboard.tmp";
49

  
50
    private static/* XML */PersistenceManager persManager = ToolsLocator
51
        .getPersistenceManager();
52

  
53
    private CopyPasteLayersUtils() {
54
    }
55

  
56
    /**
57
     * Gets the outputstream for writing contents to the
58
     * clipboard
59
     * 
60
     * @return
61
     * @throws IOException
62
     */
63
    private static OutputStream getClipboardOStream() throws IOException {
64
        String strf =
65
            System.getProperty("user.home") + File.separator + "gvSIG"
66
                + File.separator + CLIPBOARD_FILE_NAME;
67
        File f = new File(strf);
68
        if (f.exists()) {
69
            /*
70
             * If file exists, it is removed
71
             * (clipboard content overwritten)
72
             */
73
            f.delete();
74
        }
75
        /*
76
         * File will be removed on exit
77
         */
78
        f.deleteOnExit();
79
        return new FileOutputStream(f);
80
    }
81

  
82
    /**
83
     * Gets the input stream to read the clipboard
84
     * 
85
     * @return
86
     * @throws IOException
87
     */
88
    private static InputStream getClipboardIStream() throws IOException {
89
        String strf =
90
            System.getProperty("user.home") + File.separator + "gvSIG"
91
                + File.separator + CLIPBOARD_FILE_NAME;
92
        File f = new File(strf);
93
        if (f.exists()) {
94
            return new FileInputStream(f);
95
        } else {
96
            return null;
97
        }
98

  
99
    }
100

  
101
    /**
102
     * returns the content of the clipboard as an instance
103
     * of FLayers
104
     * @return
105
     * @throws PersistenceException
106
     */
107
    public static FLayers getClipboardAsFLayers() throws PersistenceException {
108

  
109
        InputStream is = null;
110

  
111
        try {
112
            is = getClipboardIStream();
113
            Object obj = persManager.getObject(is);
114
            is.close();
115
            if (obj instanceof FLayers) {
116
                return (FLayers) obj;
117
            } else {
118
                throw new ObjectNotFoundException();
119
            }
120
        } catch (Exception e) {
121
            logger.info("Clipboard file not found.", e);
122
            throw new PersistenceException(e);
123
        }
124

  
125
    }
126

  
127
    /**
128
     * Stores the given {@link PersistentState}
129
     * to clipboard
130
     * 
131
     * @param st
132
     * @throws PersistenceException
133
     */
134
    public static void saveToClipboard(PersistentState st)
135
        throws PersistenceException {
136

  
137
        OutputStream os = null;
138
        try {
139
            os = getClipboardOStream();
140
            persManager.saveState(st, os);
141
            os.close();
142
            if (st.getContext().getErrors() != null) {
143
                throw st.getContext().getErrors();
144
            }
145
        } catch (Exception ex) {
146
            throw new PersistenceException(ex);
147
        }
148
    }
149

  
150
    /**
151
     * Gets an array of layers as a {@link PersistentState}
152
     * of an instance of FLayers
153
     * 
154
     * @param actives
155
     * @param ctxt
156
     * @return
157
     * @throws PersistenceException
158
     */
159
    public static PersistentState getAsFLayersPersistentState(FLayer[] actives,
160
        MapContext ctxt) throws PersistenceException {
161

  
162
        FLayers lyrs = new FLayers();
163
        lyrs.setMapContext(ctxt);
164
        lyrs.setName("copy-paste-root");
165

  
166
        FLayer item = null;
167
        if (actives != null) {
168
            for (int i = 0; i < actives.length; i++) {
169
                item = actives[i];
170
                try {
171
                    item = item.cloneLayer();
172
                } catch (Exception ex) {
173
                    throw new PersistenceException(ex);
174
                }
175
                lyrs.addLayer(item);
176
            }
177
        }
178

  
179
        PersistentState state = null;
180
        state = persManager.getState(lyrs, true);
181

  
182
        if (state.getContext().getErrors() != null) {
183
            throw state.getContext().getErrors();
184
        }
185
        return state;
186
    }
187

  
188
    /**
189
     * Remosves the layers from the their parent
190
     * @param actives
191
     * @param mc
192
     * @return
193
     */
194
    public static boolean removeLayers(FLayer[] actives, MapContext mc) {
195

  
196
        if (actives == null || actives.length == 0) {
197
            return false;
198
        }
199

  
200
        for (int i = 0; i < actives.length; i++) {
201
            if (actives[i].isEditing() && actives[i].isAvailable()) {
202
                JOptionPane.showMessageDialog(
203
                    (Component) PluginServices.getMainFrame(),
204
                    Messages.getText("no_se_puede_borrar_una_capa_en_edicion"),
205
                    Messages.getText("eliminar_capa"),
206
                    JOptionPane.WARNING_MESSAGE);
207
                return false;
208
            }
209
        }
210

  
211
        mc.beginAtomicEvent();
212
        for (int i = actives.length - 1; i >= 0; i--) {
213
            try {
214
                // actives[i].getParentLayer().removeLayer(actives[i]);
215
                // FLayers lyrs=getMapContext().getLayers();
216
                // lyrs.addLayer(actives[i]);
217
                actives[i].getParentLayer().removeLayer(actives[i]);
218

  
219
                // Cierra todas las ventanas asociadas a la capa
220
                IWindow[] wList =
221
                    PluginServices.getMDIManager().getAllWindows();
222
                for (int j = 0; j < wList.length; j++) {
223
                    String name = wList[j].getWindowInfo().getAdditionalInfo();
224
                    for (int k = 0; k < actives.length; k++) {
225
                        if (name != null && actives != null
226
                            && actives[k] != null
227
                            && actives[k].getName() != null
228
                            && name.compareTo(actives[k].getName()) == 0)
229
                            PluginServices.getMDIManager()
230
                                .closeWindow(wList[j]);
231
                    }
232
                }
233

  
234
            } catch (CancelationException e1) {
235
                JOptionPane.showMessageDialog((Component) PluginServices
236
                    .getMainFrame(), Messages
237
                    .getText("No_ha_sido_posible_realizar_la_operacion"),
238
                    Messages.getText("eliminar_capa"),
239
                    JOptionPane.WARNING_MESSAGE);
240
                logger.info("Error while removing layers.", e1);
241
                return false;
242
            }
243
        }
244
        mc.endAtomicEvent();
245
        Project project =
246
            ((ProjectExtension) PluginServices
247
                .getExtension(ProjectExtension.class)).getProject();
248
        project.setModified(true);
249
        PluginServices.getMainFrame().enableControls();
250
        return true;
251

  
252
    }
253

  
254
    /**
255
     * Adds layers to target {@link FLayers}
256
     * 
257
     * @param clipboard_root
258
     * @param target_root
259
     * @return
260
     */
261
    public static boolean addLayers(FLayers clipboard_root, FLayers target_root) {
262

  
263
        if (clipboard_root == null || clipboard_root.getLayersCount() == 0) {
264
            return false;
265
        }
266

  
267
        int n = clipboard_root.getLayersCount();
268
        FLayer item = null;
269
        for (int i = 0; i < n; i++) {
270
            item = clipboard_root.getLayer(i);
271
            target_root.addLayer(item);
272
        }
273
        return true;
274
    }
275

  
276
}
0 277

  
branches/v2_0_0_prep/applications/appgvSIG/src/org/gvsig/app/project/documents/view/toc/actions/PasteLayersTocMenuEntry.java
1 1
package org.gvsig.app.project.documents.view.toc.actions;
2 2

  
3
import org.exolab.castor.xml.MarshalException;
4
import org.exolab.castor.xml.ValidationException;
3
import java.awt.Component;
4

  
5
import javax.swing.JOptionPane;
6

  
7
import org.slf4j.Logger;
8
import org.slf4j.LoggerFactory;
9

  
5 10
import org.gvsig.andami.PluginServices;
6 11
import org.gvsig.app.extension.ProjectExtension;
7 12
import org.gvsig.app.project.Project;
......
9 14
import org.gvsig.app.project.documents.view.toc.ITocItem;
10 15
import org.gvsig.fmap.mapcontext.layers.FLayer;
11 16
import org.gvsig.fmap.mapcontext.layers.FLayers;
12
import org.gvsig.utils.XMLEntity;
17
import org.gvsig.i18n.Messages;
18
import org.gvsig.tools.persistence.exception.PersistenceException;
13 19

  
14 20

  
15 21
public class PasteLayersTocMenuEntry extends AbstractTocContextMenuAction {
16
	private XMLEntity xml=null;
17
	private CopyPasteLayersUtiles utiles = CopyPasteLayersUtiles.getInstance();
22
    
23
    private static Logger logger =
24
        LoggerFactory.getLogger(PasteLayersTocMenuEntry.class);
18 25

  
19

  
20 26
	public String getGroup() {
21 27
		return "copyPasteLayer";
22 28
	}
......
37 43
		if (isTocItemBranch(item)) {
38 44
			FLayer lyr = getNodeLayer(item);
39 45
			if (lyr instanceof FLayers) {
40
				this.xml = this.getCheckedXMLFromClipboard();
41
				return true;
46
			    FLayers aux = this.getFLayersFromClipboard();
47
				return aux != null;
42 48
			}
43 49

  
44 50
		} else if (!isTocItemLeaf(item)) {
45 51
			if (getNodeLayer(item) == null) {
46
				this.xml = this.getCheckedXMLFromClipboard();
47
				return this.xml != null;
52
                FLayers aux = this.getFLayersFromClipboard();
53
                return aux != null;
48 54
			}
49 55
		}
50 56
		return false;
51 57
	}
52 58

  
53
	private XMLEntity getCheckedXMLFromClipboard() {
54
		String sourceString = PluginServices.getFromClipboard();
55
		if (sourceString == null) return null;
56

  
57
		XMLEntity xml;
58
		try {
59
			xml = XMLEntity.parse(sourceString);
60
		} catch (MarshalException e) {
61
			return null;
62
		} catch (ValidationException e) {
63
			return null;
64
		}
65

  
66

  
67
		if (!this.utiles.checkXMLRootNode(xml)) return null;
68

  
69
		if (xml.findChildren("type","layers") == null) return null;
70

  
71
		return  xml;
59
	private FLayers getFLayersFromClipboard() {
60
	    
61
		FLayers resp = null;
62
        try {
63
            resp = CopyPasteLayersUtils.getClipboardAsFLayers();
64
        } catch (PersistenceException e) {
65
            logger.info("While parsing clipboard data as FLayers.", e);
66
            resp = null;
67
        }
68
		return resp;
72 69
	}
73 70

  
74 71
	public void execute(ITocItem item, FLayer[] selectedItems) {
75
		FLayers root;
72
		FLayers target_root;
76 73

  
77
		if (this.xml == null) return;
74
        FLayers clipboard_root = this.getFLayersFromClipboard();
75
        if (clipboard_root == null) {
76
            JOptionPane.showMessageDialog(
77
                (Component)PluginServices.getMainFrame(),
78
                Messages.getText("No_ha_sido_posible_realizar_la_operacion"),
79
                Messages.getText("pegar"),
80
                JOptionPane.ERROR_MESSAGE
81
                );
82
            logger.info("Unable to parse clipboard as flayers");
83
            return;
84
        }
78 85

  
79 86
		if (isTocItemBranch(item)) {
80
			root = (FLayers)getNodeLayer(item);
87
		    target_root = (FLayers)getNodeLayer(item);
81 88
		} else if (getNodeLayer(item) == null){
82
			root = getMapContext().getLayers();
89
		    target_root = getMapContext().getLayers();
83 90
		} else {
84 91
			return;
85 92
		}
93
		
86 94
		getMapContext().beginAtomicEvent();
87 95

  
88
		boolean isOK = this.utiles.loadLayersFromXML(this.xml,root);
96
		boolean isOK = CopyPasteLayersUtils.addLayers(clipboard_root, target_root);
89 97

  
90 98
		getMapContext().endAtomicEvent();
91 99

  
branches/v2_0_0_prep/applications/appgvSIG/src/org/gvsig/app/project/documents/view/toc/actions/CutLayersTocMenuEntry.java
4 4

  
5 5
import javax.swing.JOptionPane;
6 6

  
7
import org.slf4j.Logger;
8
import org.slf4j.LoggerFactory;
9

  
7 10
import org.gvsig.andami.PluginServices;
8
import org.gvsig.app.extension.ProjectExtension;
9
import org.gvsig.app.project.Project;
10 11
import org.gvsig.app.project.documents.view.toc.AbstractTocContextMenuAction;
11 12
import org.gvsig.app.project.documents.view.toc.ITocItem;
12 13
import org.gvsig.fmap.mapcontext.layers.FLayer;
13
import org.gvsig.utils.XMLEntity;
14
import org.gvsig.i18n.Messages;
15
import org.gvsig.tools.persistence.PersistentState;
14 16

  
15 17

  
16 18
public class CutLayersTocMenuEntry extends AbstractTocContextMenuAction {
17
	private CopyPasteLayersUtiles utiles = CopyPasteLayersUtiles.getInstance();
18 19

  
20
    private static Logger logger =
21
        LoggerFactory.getLogger(CutLayersTocMenuEntry.class);
22

  
19 23
	public String getGroup() {
20 24
		return "copyPasteLayer";
21 25
	}
......
45 49

  
46 50

  
47 51
	public void execute(ITocItem item, FLayer[] selectedItems) {
48
		XMLEntity xml = this.utiles.generateXMLCopyLayers(selectedItems);
49
		if (xml == null) {
50
			JOptionPane.showMessageDialog(
51
					(Component)PluginServices.getMainFrame(),
52
					"<html>"+PluginServices.getText(this,"No_ha_sido_posible_realizar_la_operacion")+"</html>",//Mensaje
53
					PluginServices.getText(this,"cortar"),//titulo
54
					JOptionPane.ERROR_MESSAGE
55
					);
56
			return;
57
		}
52
	    
53
        PersistentState lyrs_state = null;
54
        
55
        try {
56
            lyrs_state = CopyPasteLayersUtils.getAsFLayersPersistentState(
57
                 selectedItems, this.getMapContext());
58
            /*
59
             * Saving layers data to clipboard.
60
             * Files and URLs are not relativized
61
             */
62
            CopyPasteLayersUtils.saveToClipboard(lyrs_state);
58 63

  
59
		String data = xml.toString();
60
		if (data == null) {
61
			JOptionPane.showMessageDialog(
62
					(Component)PluginServices.getMainFrame(),
63
					"<html>"+PluginServices.getText(this,"No_ha_sido_posible_realizar_la_operacion")+"</html>",//Mensaje
64
					PluginServices.getText(this,"cortar"),//titulo
65
					JOptionPane.ERROR_MESSAGE
66
					);
67
			return;
68
		}
64
            int option=JOptionPane.showConfirmDialog(
65
                (Component)PluginServices.getMainFrame(),
66
                PluginServices.getText(this,"desea_borrar_la_capa"));
67
            
68
            if (option == JOptionPane.OK_OPTION) {
69
                /*
70
                 * If user says no, this is like copy (not cut)
71
                 */
72
                CopyPasteLayersUtils.removeLayers(
73
                    selectedItems,
74
                    this.getMapContext());
75
            }
76
            
77
        } catch (Exception e) {
78
            
79
            JOptionPane.showMessageDialog(
80
                (Component)PluginServices.getMainFrame(),
81
                Messages.getText("No_ha_sido_posible_realizar_la_operacion")
82
                + "\n\n" + e.getMessage(),
83
                Messages.getText("cortar"),
84
                JOptionPane.ERROR_MESSAGE
85
                );
86
            logger.info("While cutting layers.", e);
87
            return;
88
        }
69 89

  
70 90

  
71
		PluginServices.putInClipboard(data);
72 91

  
73

  
74
    	int option=JOptionPane.showConfirmDialog((Component)PluginServices.getMainFrame(),PluginServices.getText(this,"desea_borrar_la_capa"));
75
    	if (option!=JOptionPane.OK_OPTION) {
76
    		return;
77
    	}
78
		getMapContext().beginAtomicEvent();
79

  
80

  
81
		boolean isOK =this.utiles.removeLayers(selectedItems);
82

  
83
		getMapContext().endAtomicEvent();
84

  
85
		if (isOK) {
86
			getMapContext().invalidate();
87
			Project project=((ProjectExtension)PluginServices.getExtension(ProjectExtension.class)).getProject();
88
			project.setModified(true);
89
			if (getMapContext().getLayers().getLayersCount()==0) {
90
				PluginServices.getMainFrame().enableControls();
91
			}
92
		}
93

  
94 92
	}
95 93

  
96 94
}

Also available in: Unified diff