Statistics
| Revision:

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

History | View | Annotate | Download (16.7 KB)

1
package com.iver.cit.gvsig;
2

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

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

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

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

    
59
        /**
60
         * @see com.iver.andami.plugins.IExtension#initialize()
61
         */
62
        public void initialize() {
63
        }
64

    
65
        /**
66
         * @see com.iver.andami.plugins.IExtension#execute(java.lang.String)
67
         */
68
        public void execute(String s) {
69
                com.iver.andami.ui.mdiManager.IWindow f = PluginServices.getMDIManager()
70
                                .getActiveWindow();
71

    
72
                vista = (View) f;
73
                boolean isStop=false;
74
                IProjectView model = vista.getModel();
75
                MapContext mapa = model.getMapContext();
76
                FLayers layers = mapa.getLayers();
77
                EditionManager edMan = CADExtension.getEditionManager();
78
                if (s.equals("STOPEDITING")) {
79
                        vista.getMapControl().getCanceldraw().setCanceled(true);
80
                        FLayer[] actives = layers.getActives();
81
                        // TODO: Comprobar que solo hay una activa, o al menos
82
                        // que solo hay una en edici?n que est? activa, etc, etc
83
                        for (int i = 0; i < actives.length; i++) {
84
                                if (actives[i] instanceof FLyrVect && actives[i].isEditing()) {
85
                                        FLyrVect lv = (FLyrVect) actives[i];
86
                                        MapControl mapControl = vista.getMapControl();
87
                                        VectorialLayerEdited lyrEd = (VectorialLayerEdited)        edMan.getActiveLayerEdited();
88
                                        try {
89
                                                lv.getRecordset().removeSelectionListener(lyrEd);
90
                                        } catch (ReadDriverException e) {
91
                                                NotificationManager.addError("Remove Selection Listener",e);
92
                                        }
93
                                        isStop=stopEditing(lv, mapControl);
94
                                        if (isStop){
95
                                                lv.removeLayerListener(edMan);
96
                                                if (lv instanceof FLyrAnnotation){
97
                                                        FLyrAnnotation lva=(FLyrAnnotation)lv;
98
                                            lva.setMapping(lva.getMapping());
99
                                                }
100
                                        }
101
                                }
102
                        }
103
                        if (isStop) {
104
                                vista.getMapControl().setTool("zoomIn");
105
                                vista.hideConsole();
106
                                vista.repaintMap();
107
                                CADExtension.clearView();
108

    
109
                        }
110
                }
111
                PluginServices.getMainFrame().enableControls();
112
        }
113

    
114
        /**
115
         * @see com.iver.andami.plugins.IExtension#isEnabled()
116
         */
117
        public boolean isEnabled() {
118
                FLayer[] lyrs = EditionUtilities.getActiveAndEditedLayers();
119
                if (lyrs == null)
120
                        return false;
121
                FLyrVect lyrVect = (FLyrVect) lyrs[0];
122
                if (lyrVect.getSource() instanceof VectorialEditableAdapter) {
123
                        return true;
124
                }
125
                return false;
126
        }
127
        /**
128
         * DOCUMENT ME!
129
         */
130
        public boolean stopEditing(FLyrVect layer, MapControl mapControl) {
131
                VectorialEditableAdapter vea = (VectorialEditableAdapter) layer
132
                                .getSource();
133
                int resp = JOptionPane.NO_OPTION;
134

    
135
                try {
136
                        if (layer.isWritable()) {
137
                                resp = JOptionPane.showConfirmDialog((Component) PluginServices
138
                                                .getMainFrame(), PluginServices.getText(this,
139
                                                "realmente_desea_guardar_la_capa")
140
                                                + " : " + layer.getName()+"?", PluginServices.getText(this,
141
                                                "guardar"), JOptionPane.YES_NO_OPTION);
142
                                if (resp == JOptionPane.YES_OPTION) { // GUARDAMOS EL TEMA
143
                                        saveLayer(layer);
144

    
145
                                } else if (resp == JOptionPane.NO_OPTION){ // CANCEL EDITING
146
                                        cancelEdition(layer);
147
                                } else {
148
                                        return false;
149
                                }
150

    
151
                                vea.getCommandRecord().removeCommandListener(mapControl);
152
                                layer.setEditing(false);
153
                                if (layer.isSpatiallyIndexed())
154
                    {
155
                            if(vea.getSpatialIndex() != null)
156
                        {
157
                                    layer.setISpatialIndex(vea.getSpatialIndex());
158
                                    if(layer.getISpatialIndex() instanceof IPersistentSpatialIndex)
159
                                ((IPersistentSpatialIndex) layer.getISpatialIndex()).flush();
160
                                    PluginServices.
161
                                                                cancelableBackgroundExecution(new CreateSpatialIndexMonitorableTask(layer));
162

    
163
                        }
164
                    }
165

    
166
                                return true;
167
                        }
168
                        // Si no existe writer para la capa que tenemos en edici?n
169
                                resp = JOptionPane
170
                                                .showConfirmDialog(
171
                                                                (Component) PluginServices.getMainFrame(),
172
                                                                PluginServices
173
                                                                                .getText(
174
                                                                                                this,
175
                                                                                                "no_existe_writer_para_este_formato_de_capa_o_no_tiene_permisos_de_escritura_los_datos_no_se_guardaran_desea_continuar")
176
                                                                                + " : " + layer.getName(),
177
                                                                PluginServices.getText(this, "cancelar_edicion"),
178
                                                                JOptionPane.YES_NO_OPTION);
179
                                if (resp == JOptionPane.YES_OPTION) { // CANCEL EDITING
180
                                        cancelEdition(layer);
181

    
182
                                        vea.getCommandRecord().removeCommandListener(mapControl);
183
                                        if (!(layer.getSource().getDriver() instanceof IndexedShpDriver)){
184
                                                VectorialLayerEdited vle=(VectorialLayerEdited)CADExtension.getEditionManager().getLayerEdited(layer);
185
                                                layer.setLegend((IVectorLegend)vle.getLegend());
186
                                        }
187
                                        layer.setEditing(false);
188
                                        return true;
189
                                }
190

    
191
                } catch (LegendLayerException e) {
192
                        NotificationManager.addError(e);
193
                } catch (StartEditionLayerException e) {
194
                        NotificationManager.addError(e);
195
                } catch (ReadDriverException e) {
196
                        NotificationManager.addError(e);
197
                } catch (InitializeWriterException e) {
198
                        NotificationManager.addError(e);
199
                } catch (CancelEditingTableException e) {
200
                        NotificationManager.addError(e);
201
                } catch (StopWriterVisitorException e) {
202
                        NotificationManager.addError(e);
203
                } catch (CancelEditingLayerException e) {
204
                        NotificationManager.addError(e);
205
                }
206
                return false;
207

    
208
        }
209

    
210

    
211
        private void saveLayer(FLyrVect layer) throws ReadDriverException, InitializeWriterException, StopWriterVisitorException{
212
                layer.setProperty("stoppingEditing",new Boolean(true));
213
                VectorialEditableAdapter vea = (VectorialEditableAdapter) layer
214
                                .getSource();
215

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

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

    
272
        }
273
        public IExtensionStatus getStatus() {
274
                return new StopEditingStatus();
275
        }
276
        /**
277
         * Show the dialogs to save the layer without ask if don't like to save.
278
         * @param layer Layer to save.
279
         */
280
        public boolean executeSaveLayer(FLyrVect layer ) {
281
//                EditionManager edMan = CADExtension.getEditionManager();
282
                CADToolAdapter cadtoolAdapter=CADExtension.getCADToolAdapter(layer);
283
                EditionManager edMan =cadtoolAdapter.getEditionManager();
284
                VectorialLayerEdited lyrEd = (VectorialLayerEdited)        edMan.getLayerEdited(layer);
285
                boolean isStop=false;
286
                try {
287
                        lyrEd.clearSelection(false);
288

    
289

    
290
                if (layer.isWritable()) {
291
                                saveLayer(layer);
292
                                layer.setEditing(false);
293
                                if (layer.isSpatiallyIndexed())
294
                            {
295
                                    if(layer.getISpatialIndex() != null)
296
                                {
297
                                        PluginServices.
298
                                                                        cancelableBackgroundExecution(new CreateSpatialIndexMonitorableTask((FLyrVect)layer));
299
                                                }
300
                            }
301

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

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

    
376
        private class UnsavedLayer extends UnsavedData{
377

    
378
                private FLayer layer;
379

    
380
                public UnsavedLayer(IExtension extension) {
381
                        super(extension);
382
                }
383

    
384
                public String getDescription() {
385
                        return PluginServices.getText(this,"editing_layer_unsaved");
386
                }
387

    
388
                public String getResourceName() {
389
                        return layer.getName();
390
                }
391

    
392

    
393

    
394
                public boolean saveData() {
395
                        return executeSaveLayer((FLyrVect)layer);
396
                }
397

    
398
                public void setLayer(FLayer layer) {
399
                        this.layer=layer;
400

    
401
                }
402

    
403
                public ImageIcon getIcon() {
404
                        return layer.getTocImageIcon();
405
                }
406

    
407
        }
408

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