Statistics
| Revision:

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

History | View | Annotate | Download (17.4 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
        public void saveLayer(FLyrVect layer) throws ReadDriverException, InitializeWriterException, StopWriterVisitorException{
217
                
218
                layer.setWaitTodraw(true);
219
                
220
                try {
221
                        vista.getMapControl().cancelDrawing();
222
                        layer.setProperty("stoppingEditing",new Boolean(true));
223
                        VectorialEditableAdapter vea = (VectorialEditableAdapter) layer
224
                                        .getSource();
225

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

    
273
        public void cancelEdition(FLyrVect layer) throws CancelEditingTableException, CancelEditingLayerException {
274
                layer.setProperty("stoppingEditing",new Boolean(true));
275
                com.iver.andami.ui.mdiManager.IWindow[] views = PluginServices
276
                                .getMDIManager().getAllWindows();
277
                VectorialEditableAdapter vea = (VectorialEditableAdapter) layer
278
                                .getSource();
279
                vea.cancelEdition(EditionEvent.GRAPHIC);
280
                for (int j = 0; j < views.length; j++) {
281
                        if (views[j] instanceof Table) {
282
                                Table table = (Table) views[j];
283
                                if (table.getModel().getAssociatedTable() != null
284
                                                && table.getModel().getAssociatedTable().equals(layer)) {
285
                                        table.cancelEditing();
286
                                }
287
                        }
288
                }
289
                layer.setProperty("stoppingEditing",new Boolean(false));
290
        }
291
        /**
292
         * @see com.iver.andami.plugins.IExtension#isVisible()
293
         */
294
        public boolean isVisible() {
295
                if (EditionUtilities.getEditionStatus() == EditionUtilities.EDITION_STATUS_ONE_VECTORIAL_LAYER_ACTIVE_AND_EDITABLE)
296
                        return true;
297
                return false;
298

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

    
316

    
317
                if (layer.isWritable()) {
318
                                saveLayer(layer);
319
                                layer.setEditing(false);
320
                                if (layer.isSpatiallyIndexed())
321
                            {
322
                                    if(layer.getISpatialIndex() != null)
323
                                {
324
                                        PluginServices.
325
                                                                        cancelableBackgroundExecution(new CreateSpatialIndexMonitorableTask((FLyrVect)layer));
326
                                                }
327
                            }
328

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

    
366
                }
367
//                boolean isStop=stopEditing((FLyrVect)layer, null);
368
                if (isStop){
369
                        layer.removeLayerListener(edMan);
370
                        if (layer instanceof FLyrAnnotation){
371
                                FLyrAnnotation lva=(FLyrAnnotation)layer;
372
                    lva.setMapping(lva.getMapping());
373
                        }
374
                        com.iver.andami.ui.mdiManager.IWindow f = PluginServices.getMDIManager()
375
                        .getActiveWindow();
376
                        if (f instanceof View) {
377
                                vista = (View) f;
378
                                FLayer auxLayer=vista.getMapControl().getMapContext().getLayers().getLayer(layer.getName());
379
                                if (auxLayer!=null && auxLayer.equals(layer)) {
380
                                        vista.getMapControl().setTool("zoomIn");
381
                                        vista.hideConsole();
382
                                        vista.repaintMap();
383
                                        CADExtension.clearView();
384
                                }
385
                        }
386
                }
387
                } catch (ReadDriverException e1) {
388
                        PluginServices.getLogger().error(e1.getMessage(),e1);
389
//                        NotificationManager.addError(e.getMessage(),e);
390
                } catch (StartEditionLayerException e) {
391
                        PluginServices.getLogger().error(e.getMessage(),e);
392
//                        NotificationManager.addError(e.getMessage(),e);
393
                } catch (StopWriterVisitorException e) {
394
                        PluginServices.getLogger().error(e.getMessage(),e);
395
//                        NotificationManager.addError(e.getMessage(),e);
396
                } catch (InitializeWriterException e) {
397
                        PluginServices.getLogger().error(e.getMessage(),e);
398
//                        NotificationManager.addError(e.getMessage(),e);
399
                }
400
                return isStop;
401
        }
402

    
403
        private class UnsavedLayer extends UnsavedData{
404

    
405
                private FLayer layer;
406

    
407
                public UnsavedLayer(IExtension extension) {
408
                        super(extension);
409
                }
410

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

    
415
                public String getResourceName() {
416
                        return layer.getName();
417
                }
418

    
419

    
420

    
421
                public boolean saveData() {
422
                        return executeSaveLayer((FLyrVect)layer);
423
                }
424

    
425
                public void setLayer(FLayer layer) {
426
                        this.layer=layer;
427

    
428
                }
429

    
430
                public ImageIcon getIcon() {
431
                        return layer.getTocImageIcon();
432
                }
433

    
434
        }
435

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

    
514
// [eiel-error-postgis]