Statistics
| Revision:

root / trunk / extensions / extCAD / src / com / iver / cit / gvsig / StopEditing.java @ 31385

History | View | Annotate | Download (16.9 KB)

1
package com.iver.cit.gvsig;
2

    
3
import java.awt.Component;
4
import java.util.ArrayList;
5
import java.util.HashMap;
6

    
7
import javax.swing.ImageIcon;
8
import javax.swing.JOptionPane;
9

    
10
import com.hardcode.gdbms.driver.exceptions.InitializeWriterException;
11
import com.hardcode.gdbms.driver.exceptions.ReadDriverException;
12
import com.iver.andami.PluginServices;
13
import com.iver.andami.messages.NotificationManager;
14
import com.iver.andami.plugins.Extension;
15
import com.iver.andami.plugins.IExtension;
16
import com.iver.andami.plugins.status.IExtensionStatus;
17
import com.iver.andami.plugins.status.IUnsavedData;
18
import com.iver.andami.plugins.status.UnsavedData;
19
import com.iver.cit.gvsig.exceptions.layers.CancelEditingLayerException;
20
import com.iver.cit.gvsig.exceptions.layers.LegendLayerException;
21
import com.iver.cit.gvsig.exceptions.layers.StartEditionLayerException;
22
import com.iver.cit.gvsig.exceptions.table.CancelEditingTableException;
23
import com.iver.cit.gvsig.exceptions.visitors.StopWriterVisitorException;
24
import com.iver.cit.gvsig.fmap.MapContext;
25
import com.iver.cit.gvsig.fmap.MapControl;
26
import com.iver.cit.gvsig.fmap.drivers.FieldDescription;
27
import com.iver.cit.gvsig.fmap.drivers.ILayerDefinition;
28
import com.iver.cit.gvsig.fmap.drivers.shp.IndexedShpDriver;
29
import com.iver.cit.gvsig.fmap.edition.EditionEvent;
30
import com.iver.cit.gvsig.fmap.edition.ISpatialWriter;
31
import com.iver.cit.gvsig.fmap.edition.VectorialEditableAdapter;
32
import com.iver.cit.gvsig.fmap.layers.FLayer;
33
import com.iver.cit.gvsig.fmap.layers.FLayers;
34
import com.iver.cit.gvsig.fmap.layers.FLyrAnnotation;
35
import com.iver.cit.gvsig.fmap.layers.FLyrVect;
36
import com.iver.cit.gvsig.fmap.layers.LayersIterator;
37
import com.iver.cit.gvsig.fmap.rendering.IVectorLegend;
38
import com.iver.cit.gvsig.fmap.spatialindex.IPersistentSpatialIndex;
39
import com.iver.cit.gvsig.gui.cad.CADToolAdapter;
40
import com.iver.cit.gvsig.gui.cad.panels.StopEditingPanel;
41
import com.iver.cit.gvsig.layers.VectorialLayerEdited;
42
import com.iver.cit.gvsig.project.documents.table.gui.Table;
43
import com.iver.cit.gvsig.project.documents.view.IProjectView;
44
import com.iver.cit.gvsig.project.documents.view.ProjectView;
45
import com.iver.cit.gvsig.project.documents.view.ProjectViewFactory;
46
import com.iver.cit.gvsig.project.documents.view.gui.View;
47
import com.iver.cit.gvsig.project.documents.view.legend.CreateSpatialIndexMonitorableTask;
48
import com.iver.utiles.swing.threads.IMonitorableTask;
49

    
50
/**
51
 * @author Francisco Jos?
52
 *
53
 * Cuando un tema se pone en edici?n, puede que su driver implemente
54
 * ISpatialWriter. En ese caso, es capaz de guardarse sobre s? mismo. Si no lo
55
 * implementa, esta opci?n estar? deshabilitada y la ?nica posibilidad de
56
 * guardar este tema ser? "Guardando como..."
57
 */
58
public class StopEditing extends Extension {
59
        private View vista;
60
        private static HashMap<String, Class> supportedFormats = new HashMap<String,  Class>();
61

    
62
        /**
63
         * Add a format to export the edited layer.
64
         * @param name
65
         * The name of the format
66
         * @param extension
67
         * The extension that can export this format.
68
         */
69
        public static void addExportFormat(String name, Class extension){
70
                supportedFormats.put(name, extension);
71
        }
72

    
73
        /**
74
         * Returns all the formats that can be used to export
75
         * an edited layer.
76
         * @return
77
         * A map of formats and extensions.
78
         */
79
        public static HashMap<String, Class> getSupportedFormats(){
80
                return supportedFormats;
81
        }
82

    
83
        /**
84
         * @see com.iver.andami.plugins.IExtension#initialize()
85
         */
86
        public void initialize() {
87
                addExportFormat("SHP", ExportTo.class);
88
                addExportFormat("DXF", ExportTo.class);
89
                addExportFormat("POSTGIS", ExportTo.class);
90
        }
91

    
92
        /**
93
         * @see com.iver.andami.plugins.IExtension#execute(java.lang.String)
94
         */
95
        public void execute(String s) {
96
                com.iver.andami.ui.mdiManager.IWindow f = PluginServices.getMDIManager()
97
                                .getActiveWindow();
98

    
99
                vista = (View) f;
100
                boolean isStop=false;
101
                IProjectView model = vista.getModel();
102
                MapContext mapa = model.getMapContext();
103
                FLayers layers = mapa.getLayers();
104
                EditionManager edMan = CADExtension.getEditionManager();
105
                if (s.equals("STOPEDITING")) {
106
                        vista.getMapControl().getCanceldraw().setCanceled(true);
107
                        FLayer[] actives = layers.getActives();
108
                        // TODO: Comprobar que solo hay una activa, o al menos
109
                        // que solo hay una en edici?n que est? activa, etc, etc
110
                        for (int i = 0; i < actives.length; i++) {
111
                                if (actives[i] instanceof FLyrVect && actives[i].isEditing()) {
112
                                        FLyrVect lv = (FLyrVect) actives[i];
113
                                        MapControl mapControl = vista.getMapControl();
114
                                        VectorialLayerEdited lyrEd = (VectorialLayerEdited)        edMan.getActiveLayerEdited();
115
                                        try {
116
                                                lv.getRecordset().removeSelectionListener(lyrEd);
117
                                        } catch (ReadDriverException e) {
118
                                                NotificationManager.addError("Remove Selection Listener",e);
119
                                        }
120
                                        isStop=stopEditing(lv, mapControl);
121
                                        if (isStop){
122
                                                lv.removeLayerListener(edMan);
123
                                                if (lv instanceof FLyrAnnotation){
124
                                                        FLyrAnnotation lva=(FLyrAnnotation)lv;
125
                                            lva.setMapping(lva.getMapping());
126
                                                }
127
                                        }
128
                                }
129
                        }
130
                        if (isStop) {
131
                                vista.getMapControl().setTool("zoomIn");
132
                                vista.hideConsole();
133
                                vista.repaintMap();
134
                                CADExtension.clearView();
135

    
136
                        }
137
                }
138
                PluginServices.getMainFrame().enableControls();
139
        }
140

    
141
        /**
142
         * @see com.iver.andami.plugins.IExtension#isEnabled()
143
         */
144
        public boolean isEnabled() {
145
                FLayer[] lyrs = EditionUtilities.getActiveAndEditedLayers();
146
                if (lyrs == null)
147
                        return false;
148
                FLyrVect lyrVect = (FLyrVect) lyrs[0];
149
                if (lyrVect.getSource() instanceof VectorialEditableAdapter) {
150
                        return true;
151
                }
152
                return false;
153
        }
154
        /**
155
         * DOCUMENT ME!
156
         */
157
        public boolean stopEditing(FLyrVect layer, MapControl mapControl) {
158
                VectorialEditableAdapter vea = (VectorialEditableAdapter) layer
159
                                .getSource();
160
                int resp = JOptionPane.NO_OPTION;
161

    
162
                try {
163
                        if (layer.isWritable()) {
164
                                resp = JOptionPane.showConfirmDialog((Component) PluginServices
165
                                                .getMainFrame(), PluginServices.getText(this,
166
                                                "realmente_desea_guardar_la_capa")
167
                                                + " : " + layer.getName()+"?", PluginServices.getText(this,
168
                                                "guardar"), JOptionPane.YES_NO_OPTION);
169
                                if (resp == JOptionPane.YES_OPTION) { // GUARDAMOS EL TEMA
170
                                        saveLayer(layer);
171

    
172
                                } else if (resp == JOptionPane.NO_OPTION){ // CANCEL EDITING
173
                                        cancelEdition(layer);
174
                                } else {
175
                                        return false;
176
                                }
177

    
178
                                vea.getCommandRecord().removeCommandListener(mapControl);
179
                                layer.setEditing(false);
180
                                if (layer.isSpatiallyIndexed())
181
                    {
182
                            if(vea.getSpatialIndex() != null)
183
                        {
184
                                    layer.setISpatialIndex(vea.getSpatialIndex());
185
                                    if(layer.getISpatialIndex() instanceof IPersistentSpatialIndex)
186
                                ((IPersistentSpatialIndex) layer.getISpatialIndex()).flush();
187
                                    PluginServices.
188
                                                                cancelableBackgroundExecution(new CreateSpatialIndexMonitorableTask(layer));
189

    
190
                        }
191
                    }
192

    
193
                                return true;
194
                        }
195
                        // Si no existe writer para la capa que tenemos en edici?n
196
                        PluginServices.getMDIManager().addCentredWindow(new StopEditingPanel(this, layer, mapControl));
197
                        return false;
198
                } catch (StartEditionLayerException e) {
199
                        NotificationManager.addError(e);
200
                } catch (ReadDriverException e) {
201
                        NotificationManager.addError(e);
202
                } catch (InitializeWriterException e) {
203
                        NotificationManager.addError(e);
204
                } catch (CancelEditingTableException e) {
205
                        NotificationManager.addError(e);
206
                } catch (StopWriterVisitorException e) {
207
                        NotificationManager.addError(e);
208
                } catch (CancelEditingLayerException e) {
209
                        NotificationManager.addError(e);
210
                }
211
                return false;
212

    
213
        }
214

    
215

    
216
        private void saveLayer(FLyrVect layer) throws ReadDriverException, InitializeWriterException, StopWriterVisitorException{
217
                layer.setWaitTodraw(true);
218
                vista.getMapControl().cancelDrawing();
219
                layer.setProperty("stoppingEditing",new Boolean(true));
220
                VectorialEditableAdapter vea = (VectorialEditableAdapter) layer
221
                                .getSource();
222

    
223
                ISpatialWriter writer = (ISpatialWriter) vea.getWriter();
224
                com.iver.andami.ui.mdiManager.IWindow[] views = PluginServices
225
                                .getMDIManager().getAllWindows();
226
                for (int j = 0; j < views.length; j++) {
227
                        if (views[j] instanceof Table) {
228
                                Table table = (Table) views[j];
229
                                if (table.getModel().getAssociatedTable() != null
230
                                                && table.getModel().getAssociatedTable().equals(layer)) {
231
                                        table.stopEditingCell();
232
                                }
233
                        }
234
                }
235
                vea.cleanSelectableDatasource();
236
                layer.setRecordset(vea.getRecordset()); // Queremos que el recordset del layer
237
                // refleje los cambios en los campos.
238
                ILayerDefinition lyrDef = EditionUtilities.createLayerDefinition(layer);
239
                String aux="FIELDS:";
240
                FieldDescription[] flds = lyrDef.getFieldsDesc();
241
                for (int i=0; i < flds.length; i++)
242
                {
243
                        aux = aux + ", " + flds[i].getFieldAlias();
244
                }
245
                System.err.println("Escribiendo la capa " + lyrDef.getName() +
246
                                " con los campos " + aux);
247
                lyrDef.setShapeType(layer.getShapeType());
248
                writer.initialize(lyrDef);
249
                vea.stopEdition(writer, EditionEvent.GRAPHIC);
250
                layer.setProperty("stoppingEditing",new Boolean(false));
251
                layer.setWaitTodraw(false);
252
                vista.getMapControl().drawMap(false);
253
        }
254

    
255
        public void cancelEdition(FLyrVect layer) throws CancelEditingTableException, CancelEditingLayerException {
256
                layer.setProperty("stoppingEditing",new Boolean(true));
257
                com.iver.andami.ui.mdiManager.IWindow[] views = PluginServices
258
                                .getMDIManager().getAllWindows();
259
                VectorialEditableAdapter vea = (VectorialEditableAdapter) layer
260
                                .getSource();
261
                vea.cancelEdition(EditionEvent.GRAPHIC);
262
                for (int j = 0; j < views.length; j++) {
263
                        if (views[j] instanceof Table) {
264
                                Table table = (Table) views[j];
265
                                if (table.getModel().getAssociatedTable() != null
266
                                                && table.getModel().getAssociatedTable().equals(layer)) {
267
                                        table.cancelEditing();
268
                                }
269
                        }
270
                }
271
                layer.setProperty("stoppingEditing",new Boolean(false));
272
        }
273
        /**
274
         * @see com.iver.andami.plugins.IExtension#isVisible()
275
         */
276
        public boolean isVisible() {
277
                if (EditionUtilities.getEditionStatus() == EditionUtilities.EDITION_STATUS_ONE_VECTORIAL_LAYER_ACTIVE_AND_EDITABLE)
278
                        return true;
279
                return false;
280

    
281
        }
282
        public IExtensionStatus getStatus() {
283
                return new StopEditingStatus();
284
        }
285
        /**
286
         * Show the dialogs to save the layer without ask if don't like to save.
287
         * @param layer Layer to save.
288
         */
289
        public boolean executeSaveLayer(FLyrVect layer ) {
290
//                EditionManager edMan = CADExtension.getEditionManager();
291
                CADToolAdapter cadtoolAdapter=CADExtension.getCADToolAdapter(layer);
292
                EditionManager edMan =cadtoolAdapter.getEditionManager();
293
                VectorialLayerEdited lyrEd = (VectorialLayerEdited)        edMan.getLayerEdited(layer);
294
                boolean isStop=false;
295
                try {
296
                        lyrEd.clearSelection(false);
297

    
298

    
299
                if (layer.isWritable()) {
300
                                saveLayer(layer);
301
                                layer.setEditing(false);
302
                                if (layer.isSpatiallyIndexed())
303
                            {
304
                                    if(layer.getISpatialIndex() != null)
305
                                {
306
                                        PluginServices.
307
                                                                        cancelableBackgroundExecution(new CreateSpatialIndexMonitorableTask((FLyrVect)layer));
308
                                                }
309
                            }
310

    
311
                        isStop=true;
312
                }else {
313
//                         Si no existe writer para la capa que tenemos en edici?n
314
                        int resp = JOptionPane
315
                                        .showConfirmDialog(
316
                                                        (Component) PluginServices.getMainFrame(),
317
                                                        PluginServices
318
                                                                        .getText(
319
                                                                                        this,
320
                                                                                        "no_existe_writer_para_este_formato_de_capa_o_no_tiene_permisos_de_escritura_los_datos_no_se_guardaran_desea_continuar")
321
                                                                        + " : " + layer.getName(),
322
                                                        PluginServices.getText(this, "cancelar_edicion"),
323
                                                        JOptionPane.YES_NO_OPTION);
324
                        if (resp == JOptionPane.YES_OPTION) { // CANCEL EDITING
325
                                try {
326
                                        cancelEdition(layer);
327
                                        layer.setEditing(false);
328
                                if (!(layer.getSource().getDriver() instanceof IndexedShpDriver)){
329
                                        VectorialLayerEdited vle=(VectorialLayerEdited)CADExtension.getEditionManager().getLayerEdited(layer);
330
                                        layer.setLegend((IVectorLegend)vle.getLegend());
331
                                }
332
                                } catch (CancelEditingTableException e) {
333
                                        PluginServices.getLogger().error(e.getMessage(),e);
334
//                                        NotificationManager.addError(e.getMessage(),e);
335
                                        return isStop;
336
                                } catch (CancelEditingLayerException e) {
337
                                        PluginServices.getLogger().error(e.getMessage(),e);
338
//                                        NotificationManager.addError(e.getMessage(),e);
339
                                        return isStop;
340
                                } catch (LegendLayerException e) {
341
                                        PluginServices.getLogger().error(e.getMessage(),e);
342
//                                        NotificationManager.addError(e.getMessage(),e);
343
                                        return isStop;
344
                                }
345
                                isStop=true;
346
                        }
347

    
348
                }
349
//                boolean isStop=stopEditing((FLyrVect)layer, null);
350
                if (isStop){
351
                        layer.removeLayerListener(edMan);
352
                        if (layer instanceof FLyrAnnotation){
353
                                FLyrAnnotation lva=(FLyrAnnotation)layer;
354
                    lva.setMapping(lva.getMapping());
355
                        }
356
                        com.iver.andami.ui.mdiManager.IWindow f = PluginServices.getMDIManager()
357
                        .getActiveWindow();
358
                        if (f instanceof View) {
359
                                vista = (View) f;
360
                                FLayer auxLayer=vista.getMapControl().getMapContext().getLayers().getLayer(layer.getName());
361
                                if (auxLayer!=null && auxLayer.equals(layer)) {
362
                                        vista.getMapControl().setTool("zoomIn");
363
                                        vista.hideConsole();
364
                                        vista.repaintMap();
365
                                        CADExtension.clearView();
366
                                }
367
                        }
368
                }
369
                } catch (ReadDriverException e1) {
370
                        PluginServices.getLogger().error(e1.getMessage(),e1);
371
//                        NotificationManager.addError(e.getMessage(),e);
372
                } catch (StartEditionLayerException e) {
373
                        PluginServices.getLogger().error(e.getMessage(),e);
374
//                        NotificationManager.addError(e.getMessage(),e);
375
                } catch (StopWriterVisitorException e) {
376
                        PluginServices.getLogger().error(e.getMessage(),e);
377
//                        NotificationManager.addError(e.getMessage(),e);
378
                } catch (InitializeWriterException e) {
379
                        PluginServices.getLogger().error(e.getMessage(),e);
380
//                        NotificationManager.addError(e.getMessage(),e);
381
                }
382
                return isStop;
383
        }
384

    
385
        private class UnsavedLayer extends UnsavedData{
386

    
387
                private FLayer layer;
388

    
389
                public UnsavedLayer(IExtension extension) {
390
                        super(extension);
391
                }
392

    
393
                public String getDescription() {
394
                        return PluginServices.getText(this,"editing_layer_unsaved");
395
                }
396

    
397
                public String getResourceName() {
398
                        return layer.getName();
399
                }
400

    
401

    
402

    
403
                public boolean saveData() {
404
                        return executeSaveLayer((FLyrVect)layer);
405
                }
406

    
407
                public void setLayer(FLayer layer) {
408
                        this.layer=layer;
409

    
410
                }
411

    
412
                public ImageIcon getIcon() {
413
                        return layer.getTocImageIcon();
414
                }
415

    
416
        }
417

    
418
        /**
419
         * <p>This class provides the status of extensions.
420
         * If this extension has some unsaved editing layer (and save them), and methods
421
         * to check if the extension has some associated background tasks.
422
         *
423
         * @author Vicente Caballero Navarro
424
         *
425
         */
426
        private class StopEditingStatus implements IExtensionStatus {
427
                /**
428
             * This method is used to check if this extension has some unsaved editing layer.
429
             *
430
             * @return true if the extension has some unsaved editing layer, false otherwise.
431
             */
432
                public boolean hasUnsavedData() {
433
                        ProjectExtension pe=(ProjectExtension)PluginServices.getExtension(ProjectExtension.class);
434
                        ProjectView[] views=(ProjectView[])pe.getProject().getDocumentsByType(ProjectViewFactory.registerName).toArray(new ProjectView[0]);
435
                        for (int i=0;i<views.length;i++) {
436
                                FLayers layers=views[i].getMapContext().getLayers();
437
                                LayersIterator iter = getEditingLayer(layers);
438
                                if (iter.hasNext()) {
439
                                        return true;
440
                                }
441
                        }
442
                        return false;
443
                }
444
                /**
445
             * This method is used to check if the extension has some associated
446
             * background process which is currently running.
447
             *
448
             * @return true if the extension has some associated background process,
449
             * false otherwise.
450
             */
451
                public boolean hasRunningProcesses() {
452
                        return false;
453
                }
454
                 /**
455
             * <p>Gets an array of the traceable background tasks associated with this
456
             * extension. These tasks may be tracked, canceled, etc.</p>
457
             *
458
             * @return An array of the associated background tasks, or null in case there is
459
             * no associated background tasks.
460
             */
461
                public IMonitorableTask[] getRunningProcesses() {
462
                        return null;
463
                }
464
                /**
465
             * <p>Gets an array of the UnsavedData objects, which contain information about
466
             * the unsaved editing layers and allows to save it.</p>
467
             *
468
             * @return An array of the associated unsaved editing layers, or null in case the extension
469
             * has not unsaved editing layers.
470
             */
471
                public IUnsavedData[] getUnsavedData() {
472
                        ProjectExtension pe=(ProjectExtension)PluginServices.getExtension(ProjectExtension.class);
473
                        ProjectView[] views=(ProjectView[])pe.getProject().getDocumentsByType(ProjectViewFactory.registerName).toArray(new ProjectView[0]);
474
                        ArrayList unsavedLayers=new ArrayList();
475
                        for (int i=0;i<views.length;i++) {
476
                                FLayers layers = views[i].getMapContext().getLayers();
477
                                LayersIterator iter = getEditingLayer(layers);
478
                                while (iter.hasNext()){
479
                                        UnsavedLayer ul=new UnsavedLayer(StopEditing.this);
480
                                        ul.setLayer(iter.nextLayer());
481
                                        unsavedLayers.add(ul);
482
                                }
483
                        }
484
                        return (IUnsavedData[])unsavedLayers.toArray(new IUnsavedData[0]);
485
                }
486
        }
487
        private LayersIterator getEditingLayer(FLayers layers){
488
                return new LayersIterator(layers){
489
                        public boolean evaluate(FLayer layer) {
490
                                return layer.isEditing();
491
                        }
492
                };
493
        }
494
}
495