Statistics
| Revision:

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

History | View | Annotate | Download (19.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.slf4j.Logger;
17
import org.slf4j.LoggerFactory;
18

    
19
import org.gvsig.andami.PluginServices;
20
import org.gvsig.andami.PluginsLocator;
21
import org.gvsig.andami.messages.NotificationManager;
22
import org.gvsig.andami.plugins.Extension;
23
import org.gvsig.andami.plugins.IExtension;
24
import org.gvsig.andami.plugins.status.IExtensionStatus;
25
import org.gvsig.andami.plugins.status.IUnsavedData;
26
import org.gvsig.andami.plugins.status.UnsavedData;
27
import org.gvsig.app.project.Project;
28
import org.gvsig.app.project.ProjectManager;
29
import org.gvsig.app.project.documents.view.DefaultViewDocument;
30
import org.gvsig.app.project.documents.view.ViewDocument;
31
import org.gvsig.app.project.documents.view.ViewManager;
32
import org.gvsig.app.project.documents.view.gui.DefaultViewPanel;
33
import org.gvsig.editing.layers.VectorialLayerEdited;
34
import org.gvsig.exportto.app.extension.ExporttoLayerExtension;
35
import org.gvsig.fmap.dal.exception.DataException;
36
import org.gvsig.fmap.dal.exception.ReadException;
37
import org.gvsig.fmap.mapcontext.MapContext;
38
import org.gvsig.fmap.mapcontext.layers.FLayer;
39
import org.gvsig.fmap.mapcontext.layers.FLayers;
40
import org.gvsig.fmap.mapcontext.layers.LayersIterator;
41
import org.gvsig.fmap.mapcontext.layers.vectorial.FLyrVect;
42
import org.gvsig.fmap.mapcontrol.MapControl;
43
import org.gvsig.i18n.Messages;
44
import org.gvsig.utils.swing.threads.IMonitorableTask;
45

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

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

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

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

    
81
                if (s.equals("layer-stop-editing")) {
82
                        vista.getMapControl().getCanceldraw().setCanceled(true);
83
                        FLayer[] actives = layers.getActives();
84
                        // TODO: Comprobar que solo hay una activa, o al menos
85
                        // que solo hay una en edici?n que est? activa, etc, etc
86
                        for (int i = 0; i < actives.length; i++) {
87
                                if (actives[i] instanceof FLyrVect && actives[i].isEditing()) {
88
                                        FLyrVect lv = (FLyrVect) actives[i];
89
                                        MapControl mapControl = vista.getMapControl();
90

    
91
                                        int user_opt = confirmStop(lv, mapControl);
92
                                        if (user_opt != IEditionManager.CONTINUE_EDITING) {
93
                                            isStop = true;
94
                                        }
95
                                        
96
                                        try {
97
                            edMan.stopEditLayer(vista, lv, user_opt);
98
                                        } catch (Exception ex) {
99
                                            logger.error("While stopping layer editing.", ex);
100
                                        }
101
                                }
102
                        }
103
                        
104
                        if (isStop) {
105
                                CADExtension.clearView();
106
                        }
107
                }
108
                PluginServices.getMainFrame().enableControls();
109
        }
110

    
111

    
112
        /**
113
         * @see org.gvsig.andami.plugins.IExtension#isEnabled()
114
         */
115
        public boolean isEnabled() {
116
                FLayer[] lyrs = EditionUtilities.getActiveAndEditedLayers();
117
                if (lyrs == null) {
118
                        return false;
119
                }
120
                FLyrVect lyrVect = (FLyrVect) lyrs[0];
121
                if (lyrVect.isEditing()) {
122
                        return true;
123
                }
124
                return false;
125
        }
126

    
127
        /**
128
         * DOCUMENT ME!
129
         */
130
        
131
        /*
132
        public boolean stopEditing(FLyrVect layer, MapControl mapControl) {
133
                int resp = JOptionPane.CANCEL_OPTION;
134

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

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

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

207
                } catch (ReadException e) {
208
                        NotificationManager.addError(e);
209
                } catch (CancelEditingLayerException e) {
210
                        NotificationManager.addError(e);
211
                }
212
                return false;
213

214
        }
215
        */
216

    
217
        
218
           public int confirmStop(FLyrVect layer, MapControl mapControl) {
219
                int resp = JOptionPane.CANCEL_OPTION;
220

    
221
                try {
222
                    if (layer.isWritable()) {
223
                        Object[] options = {
224
                                PluginServices.getText(this, "_Guardar"),
225
                                "       " + PluginServices.getText(this, "_Descartar") + "       ",
226
                                PluginServices.getText(this, "_Continuar") };
227
                        
228
                        JPanel explanation_panel = getExplanationPanel(layer.getName());
229

    
230
                        resp = JOptionPane
231
                                .showOptionDialog(
232
                                        (Component) PluginServices.getMainFrame(),
233
                                        explanation_panel,
234
                                        PluginServices.getText(this, "stop_edition"),
235
                                        JOptionPane.YES_NO_CANCEL_OPTION,
236
                                        JOptionPane.QUESTION_MESSAGE, null, options,
237
                                        options[2]);
238
                        
239
                        if (resp == JOptionPane.YES_OPTION) {
240
                            return IEditionManager.ACCEPT_EDITING;
241
                        } else if (resp == JOptionPane.NO_OPTION) {
242
                        return IEditionManager.CANCEL_EDITING;
243
                        } else if (resp == JOptionPane.CANCEL_OPTION) {
244
                        return IEditionManager.CONTINUE_EDITING;
245
                        } else {
246
                            // This happens when user clicks on [x]
247
                            // to abruptly close previous JOptionPane dialog
248
                            // We make it equivalent to CONTINUE EDITING
249
                        return IEditionManager.CONTINUE_EDITING;
250
                        }
251
                        
252
                    }
253
                    // ========================================
254
                    // Layer cannot save changes:
255
                    
256
                    Object[] options = {
257
                            PluginServices.getText(this, "export"),
258
                            PluginServices.getText(this,
259
                                    "finish_editing_without_saving_changes"),
260
                            PluginServices.getText(this, "continue_editing") };
261

    
262
                    resp = JOptionPane
263
                            .showOptionDialog(
264
                                    (Component) PluginServices.getMainFrame(),
265
                                    PluginServices
266
                                            .getText(
267
                                                    this,
268
                                                    "no_existe_writer_para_este_formato_de_capa_o_no_tiene_permisos_de_escritura_los_datos_que_desea_hacer")
269
                                            + " : " + layer.getName(), PluginServices
270
                                            .getText(this, "stop_edition"),
271
                                    JOptionPane.YES_NO_CANCEL_OPTION,
272
                                    JOptionPane.QUESTION_MESSAGE, null, options,
273
                                    options[2]);
274
                    if (resp == JOptionPane.NO_OPTION) { // CANCEL EDITING
275
                    return IEditionManager.CANCEL_EDITING;
276
                    } else if (resp == JOptionPane.YES_OPTION) {
277
                        int status = exportLayer(layer);
278
                        if (status == JOptionPane.OK_OPTION) {
279
                            return IEditionManager.CANCEL_EDITING;
280
                        }
281
                    }
282

    
283
                } catch (ReadException e) {
284
                    NotificationManager.addError(e);
285
                }
286
            return IEditionManager.CONTINUE_EDITING;
287

    
288

    
289
            }
290

    
291

    
292
    private JPanel getExplanationPanel(
293
        String layer_name) {
294
        
295
        JPanel resp = new JPanel(new BorderLayout(10, 10));
296
        
297
        String msg = Messages.getText("realmente_desea_guardar_la_capa");
298
        msg = msg + " '" + layer_name + "'?";
299
        JLabel topLabel = new JLabel(msg);
300
        
301
        JPanel mainPanel = new JPanel(new GridBagLayout());
302
        GridBagConstraints cc = new GridBagConstraints();
303
        
304
        cc.gridx = 0;
305
        cc.gridy = 0;
306
        cc.anchor = GridBagConstraints.WEST;
307
        
308
        cc.insets = new Insets(3, 6, 3, 6);
309
        
310
        Font boldf = mainPanel.getFont().deriveFont(Font.BOLD);
311
        
312
        JLabel lbl = new JLabel(Messages.getText("_Guardar"));
313
        lbl.setFont(boldf);
314
        mainPanel.add(lbl, cc);
315
        cc.gridx = 1;
316
        mainPanel.add(new JLabel(Messages.getText("_Save_changes_performed")), cc);
317
        
318
        cc.gridx = 0;
319
        cc.gridy = 1;
320
        lbl = new JLabel(Messages.getText("_Descartar"));
321
        lbl.setFont(boldf);
322
        mainPanel.add(lbl, cc);
323
        cc.gridx = 1;
324
        mainPanel.add(new JLabel(Messages.getText("_Discard_and_lose_changes")), cc);
325

    
326
        cc.gridx = 0;
327
        cc.gridy = 2;
328
        lbl = new JLabel(Messages.getText("_Continuar"));
329
        lbl.setFont(boldf);
330
        mainPanel.add(lbl, cc);
331
        cc.gridx = 1;
332
        mainPanel.add(new JLabel(Messages.getText("_Do_not_save_yet_Stay_in_editing_mode")), cc);
333

    
334
        resp.add(mainPanel, BorderLayout.CENTER);
335
        resp.add(topLabel, BorderLayout.NORTH);
336
        return resp;
337
    }
338
    
339

    
340
    /*
341
    private void saveLayer(FLyrVect layer) throws ReadException {
342
                FeatureStore featureStore = layer.getFeatureStore();
343
                try {
344
                        featureStore.finishEditing();
345
                } catch (WriteException e) {
346
                        throw new ReadException(featureStore.getName(), e);
347
                } catch (DataException e) {
348
                        throw new ReadException(featureStore.getName(), e);
349
                }
350
        }
351

352
        private void cancelEdition(FLyrVect layer)
353
                        throws CancelEditingLayerException {
354
                FeatureStore featureStore = null;
355
                try {
356
                        featureStore = layer.getFeatureStore();
357

358
                        featureStore.cancelEditing();
359
                } catch (ReadException e) {
360
                        throw new CancelEditingLayerException(layer.getName(), e);
361
                } catch (DataException e) {
362
                        throw new CancelEditingLayerException(layer.getName(), e);
363
                }
364
        }
365
        */
366

    
367
        private int exportLayer(FLyrVect layer) throws ReadException {
368
                ViewDocument model = vista.getModel();
369
                MapContext mapContext = model.getMapContext();
370
                IProjection projection = mapContext.getProjection();
371

    
372
                ExporttoLayerExtension extension = (ExporttoLayerExtension) PluginsLocator
373
                                .getManager().getExtension(ExporttoLayerExtension.class);
374
                return extension.showExportto(layer, projection, mapContext);
375
        }
376

    
377
        /**
378
         * @see org.gvsig.andami.plugins.IExtension#isVisible()
379
         */
380
        public boolean isVisible() {
381
                if (EditionUtilities.getEditionStatus() == EditionUtilities.EDITION_STATUS_ONE_VECTORIAL_LAYER_ACTIVE_AND_EDITABLE) {
382
                        return true;
383
                }
384
                return false;
385

    
386
        }
387

    
388
        public IExtensionStatus getStatus() {
389
                return new StopEditingStatus();
390
        }
391

    
392
        /**
393
         * Show the dialogs to save the layer without ask if don't like to save.
394
         * 
395
         * @param layer
396
         *            Layer to save.
397
         */
398
        public boolean executeSaveLayer(FLyrVect layer) {
399
            
400
            IEditionManager edMan = EditionLocator.getEditionManager(layer);
401

    
402
                VectorialLayerEdited lyrEd = (VectorialLayerEdited) edMan
403
                                .getLayerEdited(layer);
404
                boolean isStop = false;
405
                try {
406
                        lyrEd.clearSelection();
407

    
408
                        if (layer.isWritable()) {
409

    
410
                            try {
411
                                edMan.stopEditLayer(null, layer, IEditionManager.ACCEPT_EDITING);
412
                            } catch (Exception ex) {
413
                                logger.error("While stopping layer editing.", ex);
414
                            }
415

    
416
                                // saveLayer(layer);
417
                                // layer.setEditing(false);
418
                                // if (layer.isSpatiallyIndexed())
419
                                // {
420
                                // if(layer.getISpatialIndex() != null)
421
                                // {
422
                                // PluginServices.
423
                                // cancelableBackgroundExecution(new
424
                                // CreateSpatialIndexMonitorableTask((FLyrVect)layer));
425
                                // }
426
                                // }
427

    
428
                                isStop = true;
429
                        } else {
430
                                // Si no existe writer para la capa que tenemos en edici?n
431
                                int resp = JOptionPane
432
                                                .showConfirmDialog(
433
                                                                (Component) PluginServices.getMainFrame(),
434
                                                                PluginServices
435
                                                                                .getText(
436
                                                                                                this,
437
                                                                                                "no_existe_writer_para_este_formato_de_capa_o_no_tiene_permisos_de_escritura_los_datos_no_se_guardaran_desea_continuar")
438
                                                                                + " : " + layer.getName(),
439
                                                                PluginServices
440
                                                                                .getText(this, "cancelar_edicion"),
441
                                                                JOptionPane.YES_NO_OPTION);
442
                                if (resp == JOptionPane.YES_OPTION) { // CANCEL EDITING
443

    
444
                                    try {
445
                                        edMan.stopEditLayer(null, layer, IEditionManager.CANCEL_EDITING);
446
                                    } catch (Exception ex) {
447
                                        logger.error("While stopping layer editing.", ex);
448
                                    }
449

    
450
                                                // cancelEdition(layer);
451
                                                // layer.setEditing(false);
452
                                                // if (!(layer.getSource().getDriver() instanceof
453
                                                // IndexedShpDriver)){
454
                                                // VectorialLayerEdited
455
                                                // vle=(VectorialLayerEdited)CADExtension.getEditionManager().getLayerEdited(layer);
456
                                                // layer.setLegend((IVectorLegend)vle.getLegend());
457
                                                // }
458
                                        isStop = true;
459
                                }
460

    
461
                        }
462
                        /*
463
                        if (isStop) {
464
                                layer.removeLayerListener(edMan);
465
                                // if (layer instanceof FLyrAnnotation){
466
                                // FLyrAnnotation lva=(FLyrAnnotation)layer;
467
                                // lva.setMapping(lva.getMapping());
468
                                // }
469
                                org.gvsig.andami.ui.mdiManager.IWindow f = PluginServices
470
                                                .getMDIManager().getActiveWindow();
471
                                if (f instanceof DefaultViewPanel) {
472
                                        vista = (DefaultViewPanel) f;
473
                                        FLayer auxLayer = vista.getMapControl().getMapContext()
474
                                                        .getLayers().getLayer(layer.getName());
475
                                        if (auxLayer != null && auxLayer.equals(layer)) {
476
                                                vista.getMapControl().setTool("zoomIn");
477
                                                vista.hideConsole();
478
                                                vista.repaintMap();
479
                                                CADExtension.clearView();
480
                                        }
481
                                }
482
                        }
483
                        */
484
                } catch (ReadException e1) {
485
                        NotificationManager.showMessageError(e1.getMessage(), e1);
486
                } catch (DataException e) {
487
                        NotificationManager.showMessageError(e.getMessage(), e);
488
                }
489
                return isStop;
490
        }
491

    
492
        private class UnsavedLayer extends UnsavedData {
493

    
494
                private FLayer layer;
495

    
496
                public UnsavedLayer(IExtension extension) {
497
                        super(extension);
498
                }
499

    
500
                public String getDescription() {
501
                        return PluginServices.getText(this, "editing_layer_unsaved");
502
                }
503

    
504
                public String getResourceName() {
505
                        return layer.getName();
506
                }
507

    
508
                public boolean saveData() {
509
                        return executeSaveLayer((FLyrVect) layer);
510
                }
511

    
512
                public void setLayer(FLayer layer) {
513
                        this.layer = layer;
514

    
515
                }
516

    
517
                public String getIcon() {
518
                        return layer.getTocImageIcon();
519
                }
520

    
521
        }
522

    
523
        /**
524
         * <p>
525
         * This class provides the status of extensions. If this extension has some
526
         * unsaved editing layer (and save them), and methods to check if the
527
         * extension has some associated background tasks.
528
         * 
529
         * @author Vicente Caballero Navarro
530
         * 
531
         */
532
        private class StopEditingStatus implements IExtensionStatus {
533
                /**
534
                 * This method is used to check if this extension has some unsaved
535
                 * editing layer.
536
                 * 
537
                 * @return true if the extension has some unsaved editing layer, false
538
                 *         otherwise.
539
                 */
540
                public boolean hasUnsavedData() {
541
                        Project project = ProjectManager.getInstance().getCurrentProject();
542
                        DefaultViewDocument[] views = project.getDocuments(
543
                                        ViewManager.TYPENAME).toArray(new DefaultViewDocument[0]);
544
                        for (int i = 0; i < views.length; i++) {
545
                                FLayers layers = views[i].getMapContext().getLayers();
546
                                LayersIterator iter = getEditingLayer(layers);
547
                                if (iter.hasNext()) {
548
                                        return true;
549
                                }
550
                        }
551
                        return false;
552
                }
553

    
554
                /**
555
                 * This method is used to check if the extension has some associated
556
                 * background process which is currently running.
557
                 * 
558
                 * @return true if the extension has some associated background process,
559
                 *         false otherwise.
560
                 */
561
                public boolean hasRunningProcesses() {
562
                        return false;
563
                }
564

    
565
                /**
566
                 * <p>
567
                 * Gets an array of the traceable background tasks associated with this
568
                 * extension. These tasks may be tracked, canceled, etc.
569
                 * </p>
570
                 * 
571
                 * @return An array of the associated background tasks, or null in case
572
                 *         there is no associated background tasks.
573
                 */
574
                public IMonitorableTask[] getRunningProcesses() {
575
                        return null;
576
                }
577

    
578
                /**
579
                 * <p>
580
                 * Gets an array of the UnsavedData objects, which contain information
581
                 * about the unsaved editing layers and allows to save it.
582
                 * </p>
583
                 * 
584
                 * @return An array of the associated unsaved editing layers, or null in
585
                 *         case the extension has not unsaved editing layers.
586
                 */
587
                public IUnsavedData[] getUnsavedData() {
588
                        Project project = ProjectManager.getInstance().getCurrentProject();
589
                        DefaultViewDocument[] views = project.getDocuments(
590
                                        ViewManager.TYPENAME).toArray(new DefaultViewDocument[0]);
591
                        ArrayList unsavedLayers = new ArrayList();
592
                        for (int i = 0; i < views.length; i++) {
593
                                FLayers layers = views[i].getMapContext().getLayers();
594
                                LayersIterator iter = getEditingLayer(layers);
595
                                while (iter.hasNext()) {
596
                                        UnsavedLayer ul = new UnsavedLayer(StopEditing.this);
597
                                        ul.setLayer(iter.nextLayer());
598
                                        unsavedLayers.add(ul);
599
                                }
600
                        }
601
                        return (IUnsavedData[]) unsavedLayers.toArray(new IUnsavedData[0]);
602
                }
603
        }
604

    
605
        private LayersIterator getEditingLayer(FLayers layers) {
606
                return new LayersIterator(layers) {
607
                        public boolean evaluate(FLayer layer) {
608
                                return layer.isEditing();
609
                        }
610
                };
611
        }
612
}