Statistics
| Revision:

root / branches / v2_0_0_prep / extensions / extEditing / src / org / gvsig / editing / StopEditing.java @ 29685

History | View | Annotate | Download (16.5 KB)

1
package org.gvsig.editing;
2

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

    
6
import javax.swing.JOptionPane;
7

    
8
import org.gvsig.andami.PluginServices;
9
import org.gvsig.andami.messages.NotificationManager;
10
import org.gvsig.andami.plugins.Extension;
11
import org.gvsig.andami.plugins.IExtension;
12
import org.gvsig.andami.plugins.status.IExtensionStatus;
13
import org.gvsig.andami.plugins.status.IUnsavedData;
14
import org.gvsig.andami.plugins.status.UnsavedData;
15
import org.gvsig.app.extension.ProjectExtension;
16
import org.gvsig.app.project.documents.table.exceptions.CancelEditingTableException;
17
import org.gvsig.app.project.documents.table.gui.FeatureTableDocumentPanel;
18
import org.gvsig.app.project.documents.view.IProjectView;
19
import org.gvsig.app.project.documents.view.ProjectView;
20
import org.gvsig.app.project.documents.view.ProjectViewFactory;
21
import org.gvsig.app.project.documents.view.gui.View;
22
import org.gvsig.editing.gui.cad.CADToolAdapter;
23
import org.gvsig.editing.layers.VectorialLayerEdited;
24
import org.gvsig.fmap.dal.exception.DataException;
25
import org.gvsig.fmap.dal.exception.ReadException;
26
import org.gvsig.fmap.dal.exception.WriteException;
27
import org.gvsig.fmap.dal.feature.FeatureStore;
28
import org.gvsig.fmap.mapcontext.MapContext;
29
import org.gvsig.fmap.mapcontext.exceptions.CancelEditingLayerException;
30
import org.gvsig.fmap.mapcontext.exceptions.StartEditionLayerException;
31
import org.gvsig.fmap.mapcontext.layers.FLayer;
32
import org.gvsig.fmap.mapcontext.layers.FLayers;
33
import org.gvsig.fmap.mapcontext.layers.LayersIterator;
34
import org.gvsig.fmap.mapcontext.layers.vectorial.FLyrVect;
35
import org.gvsig.fmap.mapcontrol.MapControl;
36
import org.gvsig.utils.swing.threads.IMonitorableTask;
37

    
38

    
39
/**
40
 * @author Francisco Jos?
41
 *
42
 * Cuando un tema se pone en edici?n, puede que su driver implemente
43
 * ISpatialWriter. En ese caso, es capaz de guardarse sobre s? mismo. Si no lo
44
 * implementa, esta opci?n estar? deshabilitada y la ?nica posibilidad de
45
 * guardar este tema ser? "Guardando como..."
46
 */
47
public class StopEditing extends Extension {
48
        private View vista;
49

    
50
        /**
51
         * @see org.gvsig.andami.plugins.IExtension#initialize()
52
         */
53
        public void initialize() {
54
        }
55

    
56
        /**
57
         * @see org.gvsig.andami.plugins.IExtension#execute(java.lang.String)
58
         */
59
        public void execute(String s) {
60
                org.gvsig.andami.ui.mdiManager.IWindow f = PluginServices.getMDIManager()
61
                                .getActiveWindow();
62

    
63
                vista = (View) f;
64
                boolean isStop=false;
65
                IProjectView model = vista.getModel();
66
                MapContext mapa = model.getMapContext();
67
                FLayers layers = mapa.getLayers();
68
                EditionManager edMan = CADExtension.getEditionManager();
69
                if (s.equals("STOPEDITING")) {
70
                        vista.getMapControl().getCanceldraw().setCanceled(true);
71
                        FLayer[] actives = layers.getActives();
72
                        // TODO: Comprobar que solo hay una activa, o al menos
73
                        // que solo hay una en edici?n que est? activa, etc, etc
74
                        for (int i = 0; i < actives.length; i++) {
75
                                if (actives[i] instanceof FLyrVect && actives[i].isEditing()) {
76
                                        FLyrVect lv = (FLyrVect) actives[i];
77
                                        MapControl mapControl = vista.getMapControl();
78
                                        VectorialLayerEdited lyrEd = (VectorialLayerEdited)        edMan.getActiveLayerEdited();
79
                                        try {
80
                                                lv.getFeatureStore().deleteObserver(lyrEd);
81
                                        } catch (ReadException e) {
82
                                                NotificationManager.addError("Remove Selection Listener",e);
83
                                        }
84
                                        isStop=stopEditing(lv, mapControl);
85
                                        if (isStop){
86
                                                lv.removeLayerListener(edMan);
87
                                                mapControl.getMapContext().removeLayerDrawListener(
88
                                                                lyrEd);
89
//                                                if (lv instanceof FLyrAnnotation){
90
//                                                        FLyrAnnotation lva=(FLyrAnnotation)lv;
91
//                                            lva.setMapping(lva.getMapping());
92
//                                                }
93
                                        } else {
94
                                                try {
95
                                                        lv.getFeatureStore().addObserver(lyrEd);
96
                                                } catch (ReadException e) {
97
                                                        NotificationManager.addError(
98
                                                                        "Remove Selection Listener", e);
99
                                                }
100

    
101
                                        }
102
                                }
103
                        }
104
                        if (isStop) {
105
                                vista.getMapControl().setTool("zoomIn");
106
                                vista.hideConsole();
107
                                vista.repaintMap();
108
                                CADExtension.clearView();
109

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

    
115
        /**
116
         * @see org.gvsig.andami.plugins.IExtension#isEnabled()
117
         */
118
        public boolean isEnabled() {
119
                FLayer[] lyrs = EditionUtilities.getActiveAndEditedLayers();
120
                if (lyrs == null) {
121
                        return false;
122
                }
123
                FLyrVect lyrVect = (FLyrVect) lyrs[0];
124
                if (lyrVect.isEditing()) {
125
                        return true;
126
                }
127
                return false;
128
        }
129
        /**
130
         * DOCUMENT ME!
131
         */
132
        public boolean stopEditing(FLyrVect layer, MapControl mapControl) {
133
//                FeatureStore featureStore=null;
134
//                try {
135
//                        featureStore = layer.getFeatureStore();
136
//                } catch (ReadException e1) {
137
//                        // TODO Auto-generated catch block
138
//                        e1.printStackTrace();
139
//                }
140
                int resp = JOptionPane.NO_OPTION;
141

    
142
                try {
143
                        if (layer.isWritable()) {
144
                                resp = JOptionPane.showConfirmDialog((Component) PluginServices
145
                                                .getMainFrame(), PluginServices.getText(this,
146
                                                "realmente_desea_guardar_la_capa")
147
                                                + " : " + layer.getName()+"?", PluginServices.getText(this,
148
                                                "guardar"), JOptionPane.YES_NO_OPTION);
149
                                if (resp == JOptionPane.YES_OPTION) { // GUARDAMOS EL TEMA
150
                                        saveLayer(layer);
151

    
152
                                } else if (resp == JOptionPane.NO_OPTION){ // CANCEL EDITING
153
                                        cancelEdition(layer);
154
                                } else {
155
                                        return false;
156
                                }
157

    
158
//                                featureStore.deleteObservers();
159
                                layer.setEditing(false);
160
//                                if (layer.isSpatiallyIndexed())
161
//                    {
162
//                            if(vea.getSpatialIndex() != null)
163
//                        {
164
//                                    layer.setISpatialIndex(vea.getSpatialIndex());
165
//                                    if(layer.getISpatialIndex() instanceof IPersistentSpatialIndex)
166
//                                ((IPersistentSpatialIndex) layer.getISpatialIndex()).flush();
167
//                                    PluginServices.
168
//                                                                cancelableBackgroundExecution(new CreateSpatialIndexMonitorableTask(layer));
169
//
170
//                        }
171
//                    }
172

    
173
                                return true;
174
                        }
175
                        // Si no existe writer para la capa que tenemos en edici?n
176
                                resp = JOptionPane
177
                                                .showConfirmDialog(
178
                                                                (Component) PluginServices.getMainFrame(),
179
                                                                PluginServices
180
                                                                                .getText(
181
                                                                                                this,
182
                                                                                                "no_existe_writer_para_este_formato_de_capa_o_no_tiene_permisos_de_escritura_los_datos_no_se_guardaran_desea_continuar")
183
                                                                                + " : " + layer.getName(),
184
                                                                PluginServices.getText(this, "cancelar_edicion"),
185
                                                                JOptionPane.YES_NO_OPTION);
186
                                if (resp == JOptionPane.YES_OPTION) { // CANCEL EDITING
187
                                        cancelEdition(layer);
188

    
189
//                                        featureStore.deleteObservers();
190
//                                        if (!(layer.getSource().getDriver() instanceof IndexedShpDriver)){
191
//                                                VectorialLayerEdited vle=(VectorialLayerEdited)CADExtension.getEditionManager().getLayerEdited(layer);
192
//                                                layer.setLegend((IVectorLegend)vle.getLegend());
193
//                                        }
194
                                        layer.setEditing(false);
195
                                        return true;
196
                                }
197

    
198
                } catch (StartEditionLayerException e) {
199
                        NotificationManager.addError(e);
200
                } catch (ReadException e) {
201
                        NotificationManager.addError(e);
202
                } catch (CancelEditingTableException e) {
203
                        NotificationManager.addError(e);
204
                } catch (CancelEditingLayerException e) {
205
                        NotificationManager.addError(e);
206
                }
207
                return false;
208

    
209
        }
210

    
211

    
212
        private void saveLayer(FLyrVect layer) throws ReadException{
213
                layer.setProperty("stoppingEditing",new Boolean(true));
214
                FeatureStore featureStore=layer.getFeatureStore();
215
//                VectorialEditableAdapter vea = (VectorialEditableAdapter) layer
216
//                                .getSource();
217

    
218
//                ISpatialWriter writer = (ISpatialWriter) vea.getWriter();
219
                org.gvsig.andami.ui.mdiManager.IWindow[] views = PluginServices
220
                                .getMDIManager().getAllWindows();
221
                for (int j = 0; j < views.length; j++) {
222
                        if (views[j] instanceof FeatureTableDocumentPanel) {
223
                                FeatureTableDocumentPanel table = (FeatureTableDocumentPanel) views[j];
224
                                if (table.getModel().getAssociatedLayer() != null
225
                                                && table.getModel().getAssociatedLayer().equals(layer)) {
226
//                                        table.stopEditing();
227
                                }
228
                        }
229
                }
230
//                vea.cleanSelectableDatasource();
231
//                layer.setRecordset(vea.getRecordset()); // Queremos que el recordset del layer
232
                // refleje los cambios en los campos.
233
//                ILayerDefinition lyrDef = EditionUtilities.createLayerDefinition(layer);
234
//                String aux="FIELDS:";
235
//                FieldDescription[] flds = lyrDef.getFieldsDesc();
236
//                for (int i=0; i < flds.length; i++){
237
//                        aux = aux + ", " + flds[i].getFieldAlias();
238
//                }
239
//                System.err.println("Escribiendo la capa " + lyrDef.getName() +
240
//                                " con los campos " + aux);
241
//                lyrDef.setShapeType(layer.getShapeType());
242
//                writer.initialize(lyrDef);
243
//                vea.stopEdition(writer, EditionEvent.GRAPHIC);
244
                try {
245
                        featureStore.finishEditing();
246
                } catch (WriteException e) {
247
                        // TODO Auto-generated catch block
248
                        e.printStackTrace();
249
                } catch (DataException e) {
250
                        // TODO Auto-generated catch block
251
                        e.printStackTrace();
252
                }
253
                layer.setProperty("stoppingEditing",new Boolean(false));
254
        }
255

    
256
        private void cancelEdition(FLyrVect layer) throws CancelEditingTableException, CancelEditingLayerException {
257
                layer.setProperty("stoppingEditing",new Boolean(true));
258
                org.gvsig.andami.ui.mdiManager.IWindow[] views = PluginServices
259
                        .getMDIManager().getAllWindows();
260
                FeatureStore featureStore=null;
261
                try {
262
                        featureStore = layer.getFeatureStore();
263

    
264
                        featureStore.cancelEditing();
265
//                        VectorialEditableAdapter vea = (VectorialEditableAdapter) layer
266
//                        .getSource();
267
//                        vea.cancelEdition(EditionEvent.GRAPHIC);
268
                        for (int j = 0; j < views.length; j++) {
269
                                if (views[j] instanceof FeatureTableDocumentPanel) {
270
                                        FeatureTableDocumentPanel table = (FeatureTableDocumentPanel) views[j];
271
                                        if (table.getModel().getAssociatedLayer() != null
272
                                                        && table.getModel().getAssociatedLayer().equals(layer)) {
273
//                                                table.stopEditing();
274
                                        }
275
                                }
276
                        }
277
                        layer.setProperty("stoppingEditing",new Boolean(false));
278
                } catch (ReadException e) {
279
                        // TODO Auto-generated catch block
280
                        e.printStackTrace();
281
                } catch (DataException e) {
282
                        // TODO Auto-generated catch block
283
                        e.printStackTrace();
284
                }
285
        }
286
        /**
287
         * @see org.gvsig.andami.plugins.IExtension#isVisible()
288
         */
289
        public boolean isVisible() {
290
                if (EditionUtilities.getEditionStatus() == EditionUtilities.EDITION_STATUS_ONE_VECTORIAL_LAYER_ACTIVE_AND_EDITABLE) {
291
                        return true;
292
                }
293
                return false;
294

    
295
        }
296
        public IExtensionStatus getStatus() {
297
                return new StopEditingStatus();
298
        }
299
        /**
300
         * Show the dialogs to save the layer without ask if don't like to save.
301
         * @param layer Layer to save.
302
         */
303
        public boolean executeSaveLayer(FLyrVect layer ) {
304
//                EditionManager edMan = CADExtension.getEditionManager();
305
                CADToolAdapter cadtoolAdapter=CADExtension.getCADToolAdapter(layer);
306
                EditionManager edMan =cadtoolAdapter.getEditionManager();
307
                VectorialLayerEdited lyrEd = (VectorialLayerEdited)        edMan.getLayerEdited(layer);
308
                boolean isStop=false;
309
                try {
310
                        lyrEd.clearSelection();
311

    
312

    
313
                if (layer.isWritable()) {
314
                                saveLayer(layer);
315
                                layer.setEditing(false);
316
//                                if (layer.isSpatiallyIndexed())
317
//                            {
318
//                                    if(layer.getISpatialIndex() != null)
319
//                                {
320
//                                        PluginServices.
321
//                                                                        cancelableBackgroundExecution(new CreateSpatialIndexMonitorableTask((FLyrVect)layer));
322
//                                                }
323
//                            }
324

    
325
                        isStop=true;
326
                }else {
327
//                         Si no existe writer para la capa que tenemos en edici?n
328
                        int resp = JOptionPane
329
                                        .showConfirmDialog(
330
                                                        (Component) PluginServices.getMainFrame(),
331
                                                        PluginServices
332
                                                                        .getText(
333
                                                                                        this,
334
                                                                                        "no_existe_writer_para_este_formato_de_capa_o_no_tiene_permisos_de_escritura_los_datos_no_se_guardaran_desea_continuar")
335
                                                                        + " : " + layer.getName(),
336
                                                        PluginServices.getText(this, "cancelar_edicion"),
337
                                                        JOptionPane.YES_NO_OPTION);
338
                        if (resp == JOptionPane.YES_OPTION) { // CANCEL EDITING
339
                                try {
340
                                        cancelEdition(layer);
341
                                        layer.setEditing(false);
342
//                                if (!(layer.getSource().getDriver() instanceof IndexedShpDriver)){
343
//                                        VectorialLayerEdited vle=(VectorialLayerEdited)CADExtension.getEditionManager().getLayerEdited(layer);
344
//                                        layer.setLegend((IVectorLegend)vle.getLegend());
345
//                                }
346
                                } catch (CancelEditingTableException e) {
347
                                        PluginServices.getLogger().error(e.getMessage(),e);
348
//                                        NotificationManager.addError(e.getMessage(),e);
349
                                        return isStop;
350
                                } catch (CancelEditingLayerException e) {
351
                                        PluginServices.getLogger().error(e.getMessage(),e);
352
//                                        NotificationManager.addError(e.getMessage(),e);
353
                                        return isStop;
354
                                }
355
                                isStop=true;
356
                        }
357

    
358
                }
359
//                boolean isStop=stopEditing((FLyrVect)layer, null);
360
                if (isStop){
361
                        layer.removeLayerListener(edMan);
362
//                        if (layer instanceof FLyrAnnotation){
363
//                                FLyrAnnotation lva=(FLyrAnnotation)layer;
364
//                    lva.setMapping(lva.getMapping());
365
//                        }
366
                        org.gvsig.andami.ui.mdiManager.IWindow f = PluginServices.getMDIManager()
367
                                .getActiveWindow();
368
                        if (f instanceof View) {
369
                                vista = (View) f;
370
                                FLayer auxLayer=vista.getMapControl().getMapContext().getLayers().getLayer(layer.getName());
371
                                if (auxLayer!=null && auxLayer.equals(layer)) {
372
                                        vista.getMapControl().setTool("zoomIn");
373
                                        vista.hideConsole();
374
                                        vista.repaintMap();
375
                                        CADExtension.clearView();
376
                                }
377
                        }
378
                }
379
                } catch (ReadException e1) {
380
//                        PluginServices.getLogger().error(e1.getMessage(),e1);
381
                        NotificationManager.showMessageError(e1.getMessage(),e1);
382
                } catch (StartEditionLayerException e) {
383
//                        PluginServices.getLogger().error(e.getMessage(),e);
384
                        NotificationManager.showMessageError(e.getMessage(),e);
385
                } catch (DataException e) {
386
                        NotificationManager.showMessageError(e.getMessage(),e);
387
                }
388
                return isStop;
389
        }
390

    
391
        private class UnsavedLayer extends UnsavedData{
392

    
393
                private FLayer layer;
394

    
395
                public UnsavedLayer(IExtension extension) {
396
                        super(extension);
397
                }
398

    
399
                public String getDescription() {
400
                        return PluginServices.getText(this,"editing_layer_unsaved");
401
                }
402

    
403
                public String getResourceName() {
404
                        return layer.getName();
405
                }
406

    
407

    
408

    
409
                public boolean saveData() {
410
                        return executeSaveLayer((FLyrVect)layer);
411
                }
412

    
413
                public void setLayer(FLayer layer) {
414
                        this.layer=layer;
415

    
416
                }
417

    
418
                public String getIcon() {
419
                        return layer.getTocImageIcon();
420
                }
421

    
422
        }
423

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