Statistics
| Revision:

svn-gvsig-desktop / branches / v2_0_0_prep / extensions / extEditing / src / org / gvsig / editing / StopEditing.java @ 38872

History | View | Annotate | Download (16.2 KB)

1
package org.gvsig.editing;
2

    
3
import java.awt.BorderLayout;
4
import java.awt.Component;
5
import java.awt.Font;
6
import java.awt.GridBagConstraints;
7
import java.awt.GridBagLayout;
8
import java.awt.Insets;
9
import java.util.ArrayList;
10

    
11
import javax.swing.JLabel;
12
import javax.swing.JOptionPane;
13
import javax.swing.JPanel;
14

    
15
import org.cresques.cts.IProjection;
16
import org.gvsig.andami.PluginServices;
17
import org.gvsig.andami.PluginsLocator;
18
import org.gvsig.andami.messages.NotificationManager;
19
import org.gvsig.andami.plugins.Extension;
20
import org.gvsig.andami.plugins.IExtension;
21
import org.gvsig.andami.plugins.status.IExtensionStatus;
22
import org.gvsig.andami.plugins.status.IUnsavedData;
23
import org.gvsig.andami.plugins.status.UnsavedData;
24
import org.gvsig.app.project.Project;
25
import org.gvsig.app.project.ProjectManager;
26
import org.gvsig.app.project.documents.view.DefaultViewDocument;
27
import org.gvsig.app.project.documents.view.ViewDocument;
28
import org.gvsig.app.project.documents.view.ViewManager;
29
import org.gvsig.app.project.documents.view.gui.DefaultViewPanel;
30
import org.gvsig.editing.gui.cad.CADToolAdapter;
31
import org.gvsig.editing.layers.VectorialLayerEdited;
32
import org.gvsig.exportto.app.extension.ExporttoLayerExtension;
33
import org.gvsig.fmap.dal.exception.DataException;
34
import org.gvsig.fmap.dal.exception.ReadException;
35
import org.gvsig.fmap.dal.exception.WriteException;
36
import org.gvsig.fmap.dal.feature.FeatureStore;
37
import org.gvsig.fmap.mapcontext.MapContext;
38
import org.gvsig.fmap.mapcontext.exceptions.CancelEditingLayerException;
39
import org.gvsig.fmap.mapcontext.exceptions.StartEditionLayerException;
40
import org.gvsig.fmap.mapcontext.layers.FLayer;
41
import org.gvsig.fmap.mapcontext.layers.FLayers;
42
import org.gvsig.fmap.mapcontext.layers.LayersIterator;
43
import org.gvsig.fmap.mapcontext.layers.vectorial.FLyrVect;
44
import org.gvsig.fmap.mapcontrol.MapControl;
45
import org.gvsig.i18n.Messages;
46
import org.gvsig.utils.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
53
 *         no lo implementa, esta opci?n estar? deshabilitada y la ?nica
54
 *         posibilidad de guardar este tema ser? "Guardando como..."
55
 *         
56
 */
57
public class StopEditing extends Extension {
58
        private DefaultViewPanel vista;
59

    
60
        /**
61
         * @see org.gvsig.andami.plugins.IExtension#initialize()
62
         */
63
        public void initialize() {
64
        }
65

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

    
73
                vista = (DefaultViewPanel) f;
74
                boolean isStop = false;
75
                ViewDocument model = vista.getModel();
76
                MapContext mapa = model.getMapContext();
77
                FLayers layers = mapa.getLayers();
78
                EditionManager edMan = CADExtension.getEditionManager();
79

    
80
                if (s.equals("layer-stop-editing")) {
81
                        vista.getMapControl().getCanceldraw().setCanceled(true);
82
                        FLayer[] actives = layers.getActives();
83
                        // TODO: Comprobar que solo hay una activa, o al menos
84
                        // que solo hay una en edici?n que est? activa, etc, etc
85
                        for (int i = 0; i < actives.length; i++) {
86
                                if (actives[i] instanceof FLyrVect && actives[i].isEditing()) {
87
                                        FLyrVect lv = (FLyrVect) actives[i];
88
                                        MapControl mapControl = vista.getMapControl();
89
                                        VectorialLayerEdited lyrEd = (VectorialLayerEdited) edMan
90
                                                        .getActiveLayerEdited();
91
                                        lv.getFeatureStore().deleteObserver(lyrEd);
92
                                        isStop = stopEditing(lv, mapControl);
93
                                        if (isStop) {
94
                                                lv.removeLayerListener(edMan);
95
                                                mapControl.getMapContext().removeLayerDrawListener(
96
                                                                lyrEd);
97
                                                // if (lv instanceof FLyrAnnotation){
98
                                                // FLyrAnnotation lva=(FLyrAnnotation)lv;
99
                                                // lva.setMapping(lva.getMapping());
100
                                                // }
101
                                        } else {
102
                                                lv.getFeatureStore().addObserver(lyrEd);
103

    
104
                                        }
105
                                }
106
                        }
107
                        if (isStop) {
108
                                vista.getMapControl().setTool("zoomIn");
109
                                vista.hideConsole();
110
                                vista.repaintMap();
111
                                CADExtension.clearView();
112

    
113
                        }
114
                }
115
                PluginServices.getMainFrame().enableControls();
116
        }
117

    
118
        /**
119
         * @see org.gvsig.andami.plugins.IExtension#isEnabled()
120
         */
121
        public boolean isEnabled() {
122
                FLayer[] lyrs = EditionUtilities.getActiveAndEditedLayers();
123
                if (lyrs == null) {
124
                        return false;
125
                }
126
                FLyrVect lyrVect = (FLyrVect) lyrs[0];
127
                if (lyrVect.isEditing()) {
128
                        return true;
129
                }
130
                return false;
131
        }
132

    
133
        /**
134
         * DOCUMENT ME!
135
         */
136
        public boolean stopEditing(FLyrVect layer, MapControl mapControl) {
137
                int resp = JOptionPane.CANCEL_OPTION;
138

    
139
                try {
140
                        if (layer.isWritable()) {
141
                                Object[] options = {
142
                                                PluginServices.getText(this, "_Guardar"),
143
                                                "       " + PluginServices.getText(this, "_Descartar") + "       ",
144
                                                PluginServices.getText(this, "_Continuar") };
145
                                
146
                                JPanel explanation_panel = getExplanationPanel(layer.getName());
147

    
148
                                resp = JOptionPane
149
                                                .showOptionDialog(
150
                                                                (Component) PluginServices.getMainFrame(),
151
                                                                explanation_panel,
152
                                                                PluginServices.getText(this, "stop_edition"),
153
                                                                JOptionPane.YES_NO_CANCEL_OPTION,
154
                                                                JOptionPane.QUESTION_MESSAGE, null, options,
155
                                                                options[2]);
156
                                
157
                                if (resp == JOptionPane.YES_OPTION) {
158
                                    // SAVE
159
                                        saveLayer(layer);
160
                                        layer.setEditing(false);
161
                    return true;
162
                                } else if (resp == JOptionPane.NO_OPTION) {
163
                                    // CANCEL EDITING
164
                                        cancelEdition(layer);
165
                                        layer.setEditing(false);
166
                                        return true;
167
                                } else if (resp == JOptionPane.CANCEL_OPTION) {
168
                                    // CONTINUE EDITING
169
                                    return false;
170
                                } else {
171
                                    // This happens when user clicks on [x]
172
                                    // to abruptly close previous JOptionPane dialog
173
                                    // We make it equivalent to CONTINUE EDITING
174
                    return false;
175
                                }
176
                                
177
                        }
178
                        // ========================================
179
                        // Layer cannot save changes:
180
                        
181
                        Object[] options = {
182
                                        PluginServices.getText(this, "export"),
183
                                        PluginServices.getText(this,
184
                                                        "finish_editing_without_saving_changes"),
185
                                        PluginServices.getText(this, "continue_editing") };
186

    
187
                        resp = JOptionPane
188
                                        .showOptionDialog(
189
                                                        (Component) PluginServices.getMainFrame(),
190
                                                        PluginServices
191
                                                                        .getText(
192
                                                                                        this,
193
                                                                                        "no_existe_writer_para_este_formato_de_capa_o_no_tiene_permisos_de_escritura_los_datos_que_desea_hacer")
194
                                                                        + " : " + layer.getName(), PluginServices
195
                                                                        .getText(this, "stop_edition"),
196
                                                        JOptionPane.YES_NO_CANCEL_OPTION,
197
                                                        JOptionPane.QUESTION_MESSAGE, null, options,
198
                                                        options[2]);
199
                        if (resp == JOptionPane.NO_OPTION) { // CANCEL EDITING
200
                                cancelEdition(layer);
201
                                layer.setEditing(false);
202
                                return true;
203
                        } else if (resp == JOptionPane.YES_OPTION) {
204
                                int status = exportLayer(layer);
205
                                if (status == JOptionPane.OK_OPTION) {
206
                                        cancelEdition(layer);
207
                                        layer.setEditing(false);
208
                                }
209
                        }
210

    
211
                } catch (StartEditionLayerException e) {
212
                        NotificationManager.addError(e);
213
                } catch (ReadException e) {
214
                        NotificationManager.addError(e);
215
                } catch (CancelEditingLayerException e) {
216
                        NotificationManager.addError(e);
217
                }
218
                return false;
219

    
220
        }
221

    
222

    
223
    private JPanel getExplanationPanel(
224
        String layer_name) {
225
        
226
        JPanel resp = new JPanel(new BorderLayout(10, 10));
227
        
228
        String msg = Messages.getText("realmente_desea_guardar_la_capa");
229
        msg = msg + " '" + layer_name + "'?";
230
        JLabel topLabel = new JLabel(msg);
231
        
232
        JPanel mainPanel = new JPanel(new GridBagLayout());
233
        GridBagConstraints cc = new GridBagConstraints();
234
        
235
        cc.gridx = 0;
236
        cc.gridy = 0;
237
        cc.anchor = GridBagConstraints.WEST;
238
        
239
        cc.insets = new Insets(3, 6, 3, 6);
240
        
241
        Font boldf = mainPanel.getFont().deriveFont(Font.BOLD);
242
        
243
        JLabel lbl = new JLabel(Messages.getText("_Guardar"));
244
        lbl.setFont(boldf);
245
        mainPanel.add(lbl, cc);
246
        cc.gridx = 1;
247
        mainPanel.add(new JLabel(Messages.getText("_Save_changes_performed")), cc);
248
        
249
        cc.gridx = 0;
250
        cc.gridy = 1;
251
        lbl = new JLabel(Messages.getText("_Descartar"));
252
        lbl.setFont(boldf);
253
        mainPanel.add(lbl, cc);
254
        cc.gridx = 1;
255
        mainPanel.add(new JLabel(Messages.getText("_Discard_and_lose_changes")), cc);
256

    
257
        cc.gridx = 0;
258
        cc.gridy = 2;
259
        lbl = new JLabel(Messages.getText("_Continuar"));
260
        lbl.setFont(boldf);
261
        mainPanel.add(lbl, cc);
262
        cc.gridx = 1;
263
        mainPanel.add(new JLabel(Messages.getText("_Do_not_save_yet_Stay_in_editing_mode")), cc);
264

    
265
        resp.add(mainPanel, BorderLayout.CENTER);
266
        resp.add(topLabel, BorderLayout.NORTH);
267
        return resp;
268
    }
269
    
270

    
271
    private void saveLayer(FLyrVect layer) throws ReadException {
272
                FeatureStore featureStore = layer.getFeatureStore();
273
                try {
274
                        featureStore.finishEditing();
275
                } catch (WriteException e) {
276
                        throw new ReadException(featureStore.getName(), e);
277
                } catch (DataException e) {
278
                        throw new ReadException(featureStore.getName(), e);
279
                }
280
        }
281

    
282
        private void cancelEdition(FLyrVect layer)
283
                        throws CancelEditingLayerException {
284
                FeatureStore featureStore = null;
285
                try {
286
                        featureStore = layer.getFeatureStore();
287

    
288
                        featureStore.cancelEditing();
289
                } catch (ReadException e) {
290
                        throw new CancelEditingLayerException(layer.getName(), e);
291
                } catch (DataException e) {
292
                        throw new CancelEditingLayerException(layer.getName(), e);
293
                }
294
        }
295

    
296
        private int exportLayer(FLyrVect layer) throws ReadException {
297
                ViewDocument model = vista.getModel();
298
                MapContext mapContext = model.getMapContext();
299
                IProjection projection = mapContext.getProjection();
300

    
301
                ExporttoLayerExtension extension = (ExporttoLayerExtension) PluginsLocator
302
                                .getManager().getExtension(ExporttoLayerExtension.class);
303
                return extension.showExportto(layer, projection, mapContext);
304
        }
305

    
306
        /**
307
         * @see org.gvsig.andami.plugins.IExtension#isVisible()
308
         */
309
        public boolean isVisible() {
310
                if (EditionUtilities.getEditionStatus() == EditionUtilities.EDITION_STATUS_ONE_VECTORIAL_LAYER_ACTIVE_AND_EDITABLE) {
311
                        return true;
312
                }
313
                return false;
314

    
315
        }
316

    
317
        public IExtensionStatus getStatus() {
318
                return new StopEditingStatus();
319
        }
320

    
321
        /**
322
         * Show the dialogs to save the layer without ask if don't like to save.
323
         * 
324
         * @param layer
325
         *            Layer to save.
326
         */
327
        public boolean executeSaveLayer(FLyrVect layer) {
328
                CADToolAdapter cadtoolAdapter = CADExtension.getCADToolAdapter(layer);
329
                EditionManager edMan = cadtoolAdapter.getEditionManager();
330
                VectorialLayerEdited lyrEd = (VectorialLayerEdited) edMan
331
                                .getLayerEdited(layer);
332
                boolean isStop = false;
333
                try {
334
                        lyrEd.clearSelection();
335

    
336
                        if (layer.isWritable()) {
337
                                saveLayer(layer);
338
                                layer.setEditing(false);
339
                                // if (layer.isSpatiallyIndexed())
340
                                // {
341
                                // if(layer.getISpatialIndex() != null)
342
                                // {
343
                                // PluginServices.
344
                                // cancelableBackgroundExecution(new
345
                                // CreateSpatialIndexMonitorableTask((FLyrVect)layer));
346
                                // }
347
                                // }
348

    
349
                                isStop = true;
350
                        } else {
351
                                // Si no existe writer para la capa que tenemos en edici?n
352
                                int resp = JOptionPane
353
                                                .showConfirmDialog(
354
                                                                (Component) PluginServices.getMainFrame(),
355
                                                                PluginServices
356
                                                                                .getText(
357
                                                                                                this,
358
                                                                                                "no_existe_writer_para_este_formato_de_capa_o_no_tiene_permisos_de_escritura_los_datos_no_se_guardaran_desea_continuar")
359
                                                                                + " : " + layer.getName(),
360
                                                                PluginServices
361
                                                                                .getText(this, "cancelar_edicion"),
362
                                                                JOptionPane.YES_NO_OPTION);
363
                                if (resp == JOptionPane.YES_OPTION) { // CANCEL EDITING
364
                                        try {
365
                                                cancelEdition(layer);
366
                                                layer.setEditing(false);
367
                                                // if (!(layer.getSource().getDriver() instanceof
368
                                                // IndexedShpDriver)){
369
                                                // VectorialLayerEdited
370
                                                // vle=(VectorialLayerEdited)CADExtension.getEditionManager().getLayerEdited(layer);
371
                                                // layer.setLegend((IVectorLegend)vle.getLegend());
372
                                                // }
373
                                        } catch (CancelEditingLayerException e) {
374
                                                PluginServices.getLogger().error(e.getMessage(), e);
375
                                                return isStop;
376
                                        }
377
                                        isStop = true;
378
                                }
379

    
380
                        }
381
                        if (isStop) {
382
                                layer.removeLayerListener(edMan);
383
                                // if (layer instanceof FLyrAnnotation){
384
                                // FLyrAnnotation lva=(FLyrAnnotation)layer;
385
                                // lva.setMapping(lva.getMapping());
386
                                // }
387
                                org.gvsig.andami.ui.mdiManager.IWindow f = PluginServices
388
                                                .getMDIManager().getActiveWindow();
389
                                if (f instanceof DefaultViewPanel) {
390
                                        vista = (DefaultViewPanel) f;
391
                                        FLayer auxLayer = vista.getMapControl().getMapContext()
392
                                                        .getLayers().getLayer(layer.getName());
393
                                        if (auxLayer != null && auxLayer.equals(layer)) {
394
                                                vista.getMapControl().setTool("zoomIn");
395
                                                vista.hideConsole();
396
                                                vista.repaintMap();
397
                                                CADExtension.clearView();
398
                                        }
399
                                }
400
                        }
401
                } catch (ReadException e1) {
402
                        NotificationManager.showMessageError(e1.getMessage(), e1);
403
                } catch (StartEditionLayerException e) {
404
                        NotificationManager.showMessageError(e.getMessage(), e);
405
                } catch (DataException e) {
406
                        NotificationManager.showMessageError(e.getMessage(), e);
407
                }
408
                return isStop;
409
        }
410

    
411
        private class UnsavedLayer extends UnsavedData {
412

    
413
                private FLayer layer;
414

    
415
                public UnsavedLayer(IExtension extension) {
416
                        super(extension);
417
                }
418

    
419
                public String getDescription() {
420
                        return PluginServices.getText(this, "editing_layer_unsaved");
421
                }
422

    
423
                public String getResourceName() {
424
                        return layer.getName();
425
                }
426

    
427
                public boolean saveData() {
428
                        return executeSaveLayer((FLyrVect) layer);
429
                }
430

    
431
                public void setLayer(FLayer layer) {
432
                        this.layer = layer;
433

    
434
                }
435

    
436
                public String getIcon() {
437
                        return layer.getTocImageIcon();
438
                }
439

    
440
        }
441

    
442
        /**
443
         * <p>
444
         * This class provides the status of extensions. If this extension has some
445
         * unsaved editing layer (and save them), and methods to check if the
446
         * extension has some associated background tasks.
447
         * 
448
         * @author Vicente Caballero Navarro
449
         * 
450
         */
451
        private class StopEditingStatus implements IExtensionStatus {
452
                /**
453
                 * This method is used to check if this extension has some unsaved
454
                 * editing layer.
455
                 * 
456
                 * @return true if the extension has some unsaved editing layer, false
457
                 *         otherwise.
458
                 */
459
                public boolean hasUnsavedData() {
460
                        Project project = ProjectManager.getInstance().getCurrentProject();
461
                        DefaultViewDocument[] views = project.getDocuments(
462
                                        ViewManager.TYPENAME).toArray(new DefaultViewDocument[0]);
463
                        for (int i = 0; i < views.length; i++) {
464
                                FLayers layers = views[i].getMapContext().getLayers();
465
                                LayersIterator iter = getEditingLayer(layers);
466
                                if (iter.hasNext()) {
467
                                        return true;
468
                                }
469
                        }
470
                        return false;
471
                }
472

    
473
                /**
474
                 * This method is used to check if the extension has some associated
475
                 * background process which is currently running.
476
                 * 
477
                 * @return true if the extension has some associated background process,
478
                 *         false otherwise.
479
                 */
480
                public boolean hasRunningProcesses() {
481
                        return false;
482
                }
483

    
484
                /**
485
                 * <p>
486
                 * Gets an array of the traceable background tasks associated with this
487
                 * extension. These tasks may be tracked, canceled, etc.
488
                 * </p>
489
                 * 
490
                 * @return An array of the associated background tasks, or null in case
491
                 *         there is no associated background tasks.
492
                 */
493
                public IMonitorableTask[] getRunningProcesses() {
494
                        return null;
495
                }
496

    
497
                /**
498
                 * <p>
499
                 * Gets an array of the UnsavedData objects, which contain information
500
                 * about the unsaved editing layers and allows to save it.
501
                 * </p>
502
                 * 
503
                 * @return An array of the associated unsaved editing layers, or null in
504
                 *         case the extension has not unsaved editing layers.
505
                 */
506
                public IUnsavedData[] getUnsavedData() {
507
                        Project project = ProjectManager.getInstance().getCurrentProject();
508
                        DefaultViewDocument[] views = project.getDocuments(
509
                                        ViewManager.TYPENAME).toArray(new DefaultViewDocument[0]);
510
                        ArrayList unsavedLayers = new ArrayList();
511
                        for (int i = 0; i < views.length; i++) {
512
                                FLayers layers = views[i].getMapContext().getLayers();
513
                                LayersIterator iter = getEditingLayer(layers);
514
                                while (iter.hasNext()) {
515
                                        UnsavedLayer ul = new UnsavedLayer(StopEditing.this);
516
                                        ul.setLayer(iter.nextLayer());
517
                                        unsavedLayers.add(ul);
518
                                }
519
                        }
520
                        return (IUnsavedData[]) unsavedLayers.toArray(new IUnsavedData[0]);
521
                }
522
        }
523

    
524
        private LayersIterator getEditingLayer(FLayers layers) {
525
                return new LayersIterator(layers) {
526
                        public boolean evaluate(FLayer layer) {
527
                                return layer.isEditing();
528
                        }
529
                };
530
        }
531
}