Statistics
| Revision:

svn-gvsig-desktop / branches / v10 / extensions / extCAD / src / com / iver / cit / gvsig / StopEditing.java @ 19154

History | View | Annotate | Download (15.8 KB)

1
package com.iver.cit.gvsig;
2

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

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

    
10
import com.hardcode.gdbms.engine.instruction.FieldNotFoundException;
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.fmap.DriverException;
19
import com.iver.cit.gvsig.fmap.MapContext;
20
import com.iver.cit.gvsig.fmap.MapControl;
21
import com.iver.cit.gvsig.fmap.drivers.DriverIOException;
22
import com.iver.cit.gvsig.fmap.drivers.FieldDescription;
23
import com.iver.cit.gvsig.fmap.drivers.ILayerDefinition;
24
import com.iver.cit.gvsig.fmap.drivers.shp.IndexedShpDriver;
25
import com.iver.cit.gvsig.fmap.edition.EditionEvent;
26
import com.iver.cit.gvsig.fmap.edition.EditionException;
27
import com.iver.cit.gvsig.fmap.edition.ISpatialWriter;
28
import com.iver.cit.gvsig.fmap.edition.VectorialEditableAdapter;
29
import com.iver.cit.gvsig.fmap.layers.FLayer;
30
import com.iver.cit.gvsig.fmap.layers.FLayers;
31
import com.iver.cit.gvsig.fmap.layers.FLyrAnnotation;
32
import com.iver.cit.gvsig.fmap.layers.FLyrVect;
33
import com.iver.cit.gvsig.fmap.layers.LayersIterator;
34
import com.iver.cit.gvsig.fmap.rendering.VectorialLegend;
35
import com.iver.cit.gvsig.layers.VectorialLayerEdited;
36
import com.iver.cit.gvsig.project.documents.table.gui.Table;
37
import com.iver.cit.gvsig.project.documents.view.IProjectView;
38
import com.iver.cit.gvsig.project.documents.view.ProjectView;
39
import com.iver.cit.gvsig.project.documents.view.ProjectViewFactory;
40
import com.iver.cit.gvsig.project.documents.view.gui.View;
41
import com.iver.cit.gvsig.project.documents.view.legend.CreateSpatialIndexMonitorableTask;
42
import com.iver.utiles.swing.threads.IMonitorableTask;
43

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

    
55
        /**
56
         * @see com.iver.andami.plugins.IExtension#initialize()
57
         */
58
        public void initialize() {
59
        }
60

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

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

    
101
                        }
102
                }
103
                PluginServices.getMainFrame().enableControls();
104
        }
105

    
106
        /**
107
         * @see com.iver.andami.plugins.IExtension#isEnabled()
108
         */
109
        public boolean isEnabled() {
110
                FLayer[] lyrs = EditionUtilities.getActiveAndEditedLayers();
111
                if (lyrs == null)
112
                        return false;
113
                FLyrVect lyrVect = (FLyrVect) lyrs[0];
114
                if (lyrVect.getSource() instanceof VectorialEditableAdapter) {
115
                        return true;
116
                }
117
                return false;
118
        }
119
        /**
120
         * DOCUMENT ME!
121
         */
122
        public boolean stopEditing(FLyrVect layer, MapControl mapControl) {
123

    
124
                VectorialEditableAdapter vea = (VectorialEditableAdapter) layer
125
                                .getSource();
126
                int resp = JOptionPane.NO_OPTION;
127

    
128
                try {
129
                        if (layer.isWritable()) {
130
                                resp = JOptionPane.showConfirmDialog((Component) PluginServices
131
                                                .getMainFrame(), PluginServices.getText(this,
132
                                                "realmente_desea_guardar_la_capa")
133
                                                + " : " + layer.getName()+"?", PluginServices.getText(this,
134
                                                "guardar"), JOptionPane.YES_NO_OPTION);
135
                                if (resp != JOptionPane.YES_OPTION) { // CANCEL EDITING
136
                                        cancelEdition(layer);
137
                                } else { // GUARDAMOS EL TEMA
138
                                        saveLayer(layer);
139
                                }
140
                                vea.getCommandRecord().removeCommandListener(mapControl);
141
                                layer.setEditing(false);
142
                                if (layer.isSpatiallyIndexed())
143
                            {
144
                                    if(layer.getISpatialIndex() != null)
145
                                {
146
                                        try {
147
                                                                PluginServices.
148
                                                                        cancelableBackgroundExecution(new CreateSpatialIndexMonitorableTask((FLyrVect)layer));
149
                                                        } catch (DriverIOException e) {
150
                                                                NotificationManager.addError(e);
151
                                                        } catch (DriverException e) {
152
                                                                NotificationManager.addError(e);
153
                                                        }
154
                                }
155
                            }
156
                                return true;
157
                        }
158
                        // Si no existe writer para la capa que tenemos en edici?n
159
                                resp = JOptionPane
160
                                                .showConfirmDialog(
161
                                                                (Component) PluginServices.getMainFrame(),
162
                                                                PluginServices
163
                                                                                .getText(
164
                                                                                                this,
165
                                                                                                "no_existe_writer_para_este_formato_de_capa_o_no_tiene_permisos_de_escritura_los_datos_no_se_guardaran_desea_continuar")
166
                                                                                + " : " + layer.getName(),
167
                                                                PluginServices.getText(this, "cancelar_edicion"),
168
                                                                JOptionPane.YES_NO_OPTION);
169
                                if (resp == JOptionPane.YES_OPTION) { // CANCEL EDITING
170
                                        cancelEdition(layer);
171
                                        vea.getCommandRecord().removeCommandListener(mapControl);
172
                                        if (!(layer.getSource().getDriver() instanceof IndexedShpDriver)){
173
                                                VectorialLayerEdited vle=(VectorialLayerEdited)CADExtension.getEditionManager().getLayerEdited(layer);
174
                                                layer.setLegend((VectorialLegend)vle.getLegend());
175
                                        }
176
                                        layer.setEditing(false);
177
                                        return true;
178
                                }
179

    
180
                } catch (EditionException e) {
181
                        NotificationManager.addError(e);
182
                } catch (IOException e) {
183
                        NotificationManager.addError(e);
184
                } catch (DriverException e) {
185
                        NotificationManager.addError(e);
186
                } catch (FieldNotFoundException e) {
187
                        NotificationManager.addError(e);
188
                }
189
                return false;
190

    
191
        }
192

    
193

    
194
        private void saveLayer(FLyrVect layer) throws DriverException,
195
                        EditionException {
196
                layer.setProperty("stoppingEditing",new Boolean(true));
197
                VectorialEditableAdapter vea = (VectorialEditableAdapter) layer
198
                                .getSource();
199

    
200
                ISpatialWriter writer = (ISpatialWriter) vea.getWriter();
201
                com.iver.andami.ui.mdiManager.IWindow[] views = PluginServices
202
                                .getMDIManager().getAllWindows();
203
                for (int j = 0; j < views.length; j++) {
204
                        if (views[j] instanceof Table) {
205
                                Table table = (Table) views[j];
206
                                if (table.getModel().getAssociatedTable() != null
207
                                                && table.getModel().getAssociatedTable().equals(layer)) {
208
                                        table.stopEditingCell();
209
                                }
210
                        }
211
                }
212
                vea.cleanSelectableDatasource();
213
                layer.setRecordset(vea.getRecordset()); // Queremos que el recordset del layer
214
                // refleje los cambios en los campos.
215
                ILayerDefinition lyrDef = EditionUtilities.createLayerDefinition(layer);
216
                String aux="FIELDS:";
217
                FieldDescription[] flds = lyrDef.getFieldsDesc();
218
                for (int i=0; i < flds.length; i++)
219
                {
220
                        aux = aux + ", " + flds[i].getFieldAlias();
221
                }
222
                System.err.println("Escribiendo la capa " + lyrDef.getName() +
223
                                " con los campos " + aux);
224
                lyrDef.setShapeType(layer.getShapeType());
225
                writer.initialize(lyrDef);
226
                vea.stopEdition(writer, EditionEvent.GRAPHIC);
227
                layer.setProperty("stoppingEditing",new Boolean(false));
228
        }
229

    
230
        private void cancelEdition(FLyrVect layer) throws IOException {
231
                layer.setProperty("stoppingEditing",new Boolean(true));
232
                com.iver.andami.ui.mdiManager.IWindow[] views = PluginServices
233
                                .getMDIManager().getAllWindows();
234
                VectorialEditableAdapter vea = (VectorialEditableAdapter) layer
235
                                .getSource();
236
                vea.cancelEdition(EditionEvent.GRAPHIC);
237
                for (int j = 0; j < views.length; j++) {
238
                        if (views[j] instanceof Table) {
239
                                Table table = (Table) views[j];
240
                                if (table.getModel().getAssociatedTable() != null
241
                                                && table.getModel().getAssociatedTable().equals(layer)) {
242
                                        table.cancelEditing();
243
                                }
244
                        }
245
                }
246
                layer.setProperty("stoppingEditing",new Boolean(false));
247
        }
248
        /**
249
         * @see com.iver.andami.plugins.IExtension#isVisible()
250
         */
251
        public boolean isVisible() {
252
                if (EditionUtilities.getEditionStatus() == EditionUtilities.EDITION_STATUS_ONE_VECTORIAL_LAYER_ACTIVE_AND_EDITABLE)
253
                        return true;
254
                return false;
255

    
256
        }
257

    
258
        public IExtensionStatus getStatus() {
259
                return new StopEditingStatus();
260
        }
261
/**
262
 * Show the dialogs to save the layer without ask if don't like to save.
263
 * @param layer Layer to save.
264
 */
265
        public boolean executeSaveLayer(FLyrVect layer ) {
266
                EditionManager edMan = CADExtension.getEditionManager();
267
                VectorialLayerEdited lyrEd = (VectorialLayerEdited)        edMan.getLayerEdited(layer);
268
                lyrEd.clearSelection();
269
                boolean isStop=false;
270
                if (layer.isWritable()) {
271
                        try {
272
                                saveLayer((FLyrVect)layer);
273
                                layer.setEditing(false);
274
                                if (layer.isSpatiallyIndexed())
275
                            {
276
                                    if(layer.getISpatialIndex() != null)
277
                                {
278
                                        try {
279
                                                                PluginServices.
280
                                                                        cancelableBackgroundExecution(new CreateSpatialIndexMonitorableTask((FLyrVect)layer));
281
                                                        } catch (DriverIOException e) {
282
                                                                PluginServices.getLogger().error(e.getMessage(),e);
283
//                                                                NotificationManager.addError(e.getMessage(),e);
284
                                                        } catch (DriverException e) {
285
                                                                PluginServices.getLogger().error(e.getMessage(),e);
286
//                                                                NotificationManager.addError(e.getMessage(),e);
287
                                                        }
288
                                }
289
                            }
290

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

    
341
                }
342
//                boolean isStop=stopEditing((FLyrVect)layer, null);
343
                if (isStop){
344
                        layer.removeLayerListener(edMan);
345
                        if (layer instanceof FLyrAnnotation){
346
                                FLyrAnnotation lva=(FLyrAnnotation)layer;
347
                    lva.setMapping(lva.getMapping());
348
                        }
349
                        com.iver.andami.ui.mdiManager.IWindow f = PluginServices.getMDIManager()
350
                        .getActiveWindow();
351
                        if (f instanceof View) {
352
                                vista = (View) f;
353
                                if (vista.getMapControl().getMapContext().getLayers().getLayer(layer.getName()).equals(layer)) {
354
                                        vista.getMapControl().setTool("zoomIn");
355
                                        vista.hideConsole();
356
                                        vista.repaintMap();
357
                                        CADExtension.clearView();
358
                                }
359
                        }
360
                }
361
                return isStop;
362
        }
363

    
364
        private class UnsavedLayer extends UnsavedData{
365

    
366
                private FLayer layer;
367

    
368
                public UnsavedLayer(IExtension extension) {
369
                        super(extension);
370
                }
371

    
372
                public String getDescription() {
373
                        return PluginServices.getText(this,"editing_layer_unsaved");
374
                }
375

    
376
                public String getResourceName() {
377
                        return layer.getName();
378
                }
379

    
380

    
381

    
382
                public boolean saveData() {
383
                        return executeSaveLayer((FLyrVect)layer);
384
                }
385

    
386
                public void setLayer(FLayer layer) {
387
                        this.layer=layer;
388

    
389
                }
390

    
391
                public ImageIcon getIcon() {
392
                        return layer.getTocImageIcon();
393
                }
394

    
395
        }
396

    
397
        /**
398
         * <p>This class provides the status of extensions.
399
         * If this extension has some unsaved editing layer (and save them), and methods
400
         * to check if the extension has some associated background tasks.
401
         *
402
         * @author Vicente Caballero Navarro
403
         *
404
         */
405
        private class StopEditingStatus implements IExtensionStatus {
406
                /**
407
             * This method is used to check if this extension has some unsaved editing layer.
408
             *
409
             * @return true if the extension has some unsaved editing layer, false otherwise.
410
             */
411
                public boolean hasUnsavedData() {
412
                        ProjectExtension pe=(ProjectExtension)PluginServices.getExtension(ProjectExtension.class);
413
                        ProjectView[] views=(ProjectView[])pe.getProject().getDocumentsByType(ProjectViewFactory.registerName).toArray(new ProjectView[0]);
414

    
415
                        for (int i=0;i<views.length;i++) {
416
                                FLayers layers=views[i].getMapContext().getLayers();
417
                                LayersIterator iter = getEditingLayer(layers);
418
                                if (iter.hasNext()) {
419
                                        return true;
420
                                }
421
                        }
422
                        return false;
423
                }
424
                /**
425
             * This method is used to check if the extension has some associated
426
             * background process which is currently running.
427
             *
428
             * @return true if the extension has some associated background process,
429
             * false otherwise.
430
             */
431
                public boolean hasRunningProcesses() {
432
                        return false;
433
                }
434
                 /**
435
             * <p>Gets an array of the traceable background tasks associated with this
436
             * extension. These tasks may be tracked, canceled, etc.</p>
437
             *
438
             * @return An array of the associated background tasks, or null in case there is
439
             * no associated background tasks.
440
             */
441
                public IMonitorableTask[] getRunningProcesses() {
442
                        return null;
443
                }
444
                /**
445
             * <p>Gets an array of the UnsavedData objects, which contain information about
446
             * the unsaved editing layers and allows to save it.</p>
447
             *
448
             * @return An array of the associated unsaved editing layers, or null in case the extension
449
             * has not unsaved editing layers.
450
             */
451
                public IUnsavedData[] getUnsavedData() {
452
                        ProjectExtension pe=(ProjectExtension)PluginServices.getExtension(ProjectExtension.class);
453
                        ProjectView[] views=(ProjectView[])pe.getProject().getDocumentsByType(ProjectViewFactory.registerName).toArray(new ProjectView[0]);
454
                        ArrayList unsavedLayers=new ArrayList();
455
                        for (int i=0;i<views.length;i++) {
456
                                FLayers layers = views[i].getMapContext().getLayers();
457
                                LayersIterator iter = getEditingLayer(layers);
458
                                while (iter.hasNext()){
459
                                        UnsavedLayer ul=new UnsavedLayer(StopEditing.this);
460
                                        ul.setLayer(iter.nextLayer());
461
                                        unsavedLayers.add(ul);
462
                                }
463
                        }
464
                        return (IUnsavedData[])unsavedLayers.toArray(new IUnsavedData[0]);
465
                }
466

    
467
                private LayersIterator getEditingLayer(FLayers layers){
468
                        return new LayersIterator(layers){
469
                                public boolean evaluate(FLayer layer) {
470
                                        return layer.isEditing();
471
                                }
472
                        };
473
                }
474
        }
475
}