Statistics
| Revision:

svn-gvsig-desktop / branches / v2_0_0_prep / extensions / extEditing / src / org / gvsig / editing / gui / cad / tools / SelectionCADTool.java @ 36005

History | View | Annotate | Download (17.5 KB)

1
/* gvSIG. Sistema de Informaci?n Geogr?fica de la Generalitat Valenciana
2
 *
3
 * Copyright (C) 2004 IVER T.I. and Generalitat Valenciana.
4
 *
5
 * This program is free software; you can redistribute it and/or
6
 * modify it under the terms of the GNU General Public License
7
 * as published by the Free Software Foundation; either version 2
8
 * of the License, or (at your option) any later version.
9
 *
10
 * This program is distributed in the hope that it will be useful,
11
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13
 * GNU General Public License for more details.
14
 *
15
 * You should have received a copy of the GNU General Public License
16
 * along with this program; if not, write to the Free Software
17
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307,USA.
18
 *
19
 * For more information, contact:
20
 *
21
 *  Generalitat Valenciana
22
 *   Conselleria d'Infraestructures i Transport
23
 *   Av. Blasco Ib??ez, 50
24
 *   46010 VALENCIA
25
 *   SPAIN
26
 *
27
 *      +34 963862235
28
 *   gvsig@gva.es
29
 *      www.gvsig.gva.es
30
 *
31
 *    or
32
 *
33
 *   IVER T.I. S.A
34
 *   Salamanca 50
35
 *   46005 Valencia
36
 *   Spain
37
 *
38
 *   +34 963163400
39
 *   dac@iver.es
40
 */
41
package org.gvsig.editing.gui.cad.tools;
42

    
43
import java.awt.Color;
44
import java.awt.event.InputEvent;
45
import java.awt.geom.Point2D;
46
import java.util.ArrayList;
47

    
48
import org.gvsig.andami.PluginServices;
49
import org.gvsig.andami.messages.NotificationManager;
50
import org.gvsig.app.project.documents.table.gui.FeatureTableDocumentPanel;
51
import org.gvsig.editing.CADExtension;
52
import org.gvsig.editing.gui.cad.DefaultCADTool;
53
import org.gvsig.editing.gui.cad.exception.CommandException;
54
import org.gvsig.editing.gui.cad.tools.smc.SelectionCADToolContext;
55
import org.gvsig.editing.gui.cad.tools.smc.SelectionCADToolContext.SelectionCADToolState;
56
import org.gvsig.editing.layers.VectorialLayerEdited;
57
import org.gvsig.fmap.dal.exception.DataException;
58
import org.gvsig.fmap.dal.exception.ReadException;
59
import org.gvsig.fmap.dal.feature.EditableFeature;
60
import org.gvsig.fmap.dal.feature.Feature;
61
import org.gvsig.fmap.dal.feature.FeatureSelection;
62
import org.gvsig.fmap.dal.feature.FeatureSet;
63
import org.gvsig.fmap.dal.feature.FeatureStore;
64
import org.gvsig.fmap.dal.feature.exception.NeedEditingModeException;
65
import org.gvsig.fmap.geom.Geometry;
66
import org.gvsig.fmap.geom.handler.Handler;
67
import org.gvsig.fmap.geom.primitive.Curve;
68
import org.gvsig.fmap.mapcontext.MapContext;
69
import org.gvsig.fmap.mapcontext.ViewPort;
70
import org.gvsig.fmap.mapcontext.layers.FLayer;
71
import org.gvsig.fmap.mapcontext.layers.vectorial.FLyrVect;
72
import org.gvsig.fmap.mapcontrol.MapControlDrawer;
73
import org.gvsig.tools.dispose.DisposableIterator;
74

    
75

    
76
/**
77
 * DOCUMENT ME!
78
 *
79
 * @author Vicente Caballero Navarro
80
 */
81
public class SelectionCADTool extends DefaultCADTool {
82
    //        public static int tolerance = 4;
83

    
84
    protected SelectionCADToolContext _fsm;
85

    
86
    protected Point2D firstPoint;
87

    
88
    protected String nextState;
89
    // Registros de los que se ha seleccionado alg?n handler.
90
    protected ArrayList rowselectedHandlers = new ArrayList();
91
    protected String type = PluginServices.getText(this,"simple");
92

    
93
    protected boolean multipleSelection=false;
94

    
95
    /**
96
     * Crea un nuevo SelectionCADTool.
97
     */
98
    public SelectionCADTool() {
99

    
100
    }
101

    
102
    /**
103
     * M?todo de incio, para poner el c?digo de todo lo que se requiera de una
104
     * carga previa a la utilizaci?n de la herramienta.
105
     */
106
    public void init() {
107
        _fsm = new SelectionCADToolContext(this);
108
        setNextTool("selection");
109
        setType(PluginServices.getText(this,"simple"));
110
    }
111

    
112
    public void transition(double x, double y, InputEvent event) {
113
        System.out.println("TRANSICION DESDE ESTADO " + _fsm.getState()
114
            + " x= " + x + " y=" + y);
115
        try{
116
            _fsm.addPoint(x, y, event);
117
        }catch (Exception e) {
118
            init();
119
            PluginServices.getMDIManager().restoreCursor();
120
        }
121
        System.out.println("ESTADO ACTUAL: " + getStatus());
122

    
123
        // ESTO LO QUITO POR AHORA, PERO PUEDE QUE LO NECESITEMOS VOLVER A PONER.
124
        // Lo he quitado porque cuando seleccionas algo con CAD, molesta que
125
        // te hagan un redibujado.
126
        FLyrVect lv = (FLyrVect)((VectorialLayerEdited)CADExtension.getEditionManager().getActiveLayerEdited()).getLayer();
127
        org.gvsig.andami.ui.mdiManager.IWindow[] views = PluginServices.getMDIManager().getAllWindows();
128

    
129
        for (int i=0 ; i<views.length ; i++){
130
            if (views[i] instanceof FeatureTableDocumentPanel){
131
                FeatureTableDocumentPanel table=(FeatureTableDocumentPanel)views[i];
132
                if (table.getModel().getAssociatedLayer()!=null && table.getModel().getAssociatedLayer().equals(lv)) {
133
                    table.updateSelection();
134
                }
135
            }
136
        }
137
    }
138

    
139
    public void transition(double d) {
140
        _fsm.addValue(d);
141
    }
142

    
143
    public void transition(String s) throws CommandException {
144
        if (!super.changeCommand(s)){
145
            _fsm.addOption(s);
146
        }
147
    }
148

    
149
    public String getNextState() {
150
        return nextState;
151
    }
152

    
153
    protected void pointDoubleClick(MapContext map) throws ReadException {
154
        FLayer[] actives = map.getLayers().getActives();
155
    }
156

    
157
    /**
158
     * Equivale al transition del prototipo pero sin pasarle como par? metro el
159
     * editableFeatureSource que ya estar? creado.
160
     *
161
     * @param selection
162
     *            Bitset con las geometr?as que est?n seleccionadas.
163
     * @param x
164
     *            par?metro x del punto que se pase en esta transici?n.
165
     * @param y
166
     *            par?metro y del punto que se pase en esta transici?n.
167
     */
168
    public void addPoint(double x, double y, InputEvent event) {
169
        SelectionCADToolState actualState = (SelectionCADToolState) _fsm.getPreviousState();
170
        String status = actualState.getName();
171
        System.out.println("PREVIOUSSTATE =" + status);         
172
        VectorialLayerEdited vle = getVLE();      
173
        try {            
174
            System.out.println("STATUS ACTUAL = " + _fsm.getTransition());
175
            if (status.equals("Selection.FirstPoint")) {
176
                firstPoint = new Point2D.Double(x, y);                                
177
            } else if (status.equals("Selection.SecondPoint")) {
178
            } else if (status.equals("Selection.WithFeatures")) {
179
            } else if (status.equals("Selection.WithHandlers")) {             
180
                addPointWithHandlers(x, y, vle.getFeatureStore(), vle.getSelectedHandler());        
181
            }
182
        } catch (DataException e) {
183
            LOG.error("Error reding the store", e);
184
        }
185
    }
186

    
187
    /**
188
     * AddPoint method for the WithHandlers option
189
     * @param x
190
     *          selected x coordinate.
191
     * @param y
192
     *          selected y coordinate.
193
     * @param featureStore
194
     *          the selected feature store.
195
     * @param selectedHandlers
196
     *          the selected handlers
197
     */
198
    protected void addPointWithHandlers(double x, double y, FeatureStore featureStore, ArrayList selectedHandlers){
199
        String description = PluginServices.getText(this, "move_handlers");
200
        DisposableIterator iterator = null;
201
        try {
202
            featureStore.beginEditingGroup(description); 
203

    
204
            iterator = ((FeatureSelection) featureStore.getSelection()).fastIterator();
205

    
206
            while (iterator.hasNext()) {
207
                Feature feature = (Feature) iterator.next();
208

    
209
                Geometry geometry = (feature.getDefaultGeometry()).cloneGeometry();
210

    
211
                // Movemos los handlers que hemos seleccionado
212
                // previamente dentro del m?todo select()
213
                Handler[] handlers = geometry.getHandlers(Geometry.SELECTHANDLER);
214
                for (int k = 0; k < selectedHandlers.size(); k++) {
215
                    Handler h = (Handler) selectedHandlers.get(k);
216
                    for (int j = 0; j < handlers.length; j++) {
217
                        if (h.getPoint().equals(handlers[j].getPoint())) {
218
                            handlers[j].set(x, y);
219
                        }
220
                    }
221
                }
222
                EditableFeature eFeature = feature.getEditable();
223
                eFeature.setDefaultGeometry(geometry);
224
                featureStore.update(eFeature);
225

    
226
            }
227

    
228
            firstPoint = new Point2D.Double(x, y);
229

    
230
            featureStore.endEditingGroup();
231
        } catch (DataException e1) {           
232
            LOG.error("Error reading the store", e1);
233
        } finally {
234
            if (iterator != null) {
235
                iterator.dispose();
236
            }
237
        }
238
    }
239

    
240
    /**
241
     * Receives second point
242
     * @param x
243
     * @param y
244
     * @return numFeatures selected
245
     */
246
    public long selectWithSecondPoint(double x, double y, InputEvent event) {
247
        VectorialLayerEdited vle = getVLE();
248
        PluginServices.getMDIManager().setWaitCursor();
249
        vle.selectWithSecondPoint(x,y);
250
        FeatureSet selection=null;
251
        try {
252
            selection = (FeatureSet)vle.getFeatureStore().getSelection();
253
            PluginServices.getMDIManager().restoreCursor();
254
            long countSel=selection.getSize();
255
            if (countSel > 0) {
256
                nextState = "Selection.WithSelectedFeatures";
257
            } else {
258
                nextState = "Selection.FirstPoint";
259
            }
260
            return countSel;
261
        } catch (ReadException e) {
262
            e.printStackTrace();
263
            return 0;
264
        } catch (DataException e) {
265
            e.printStackTrace();
266
            return 0;
267
        }
268
    }
269

    
270
    /**
271
     * M?todo para dibujar la lo necesario para el estado en el que nos
272
     * encontremos.
273
     *
274
     * @param g
275
     *            Graphics sobre el que dibujar.
276
     * @param selectedGeometries
277
     *            BitSet con las geometr?as seleccionadas.
278
     * @param x
279
     *            par?metro x del punto que se pase para dibujar.
280
     * @param y
281
     *            par?metro x del punto que se pase para dibujar.
282
     */
283
    public void drawOperation(MapControlDrawer renderer, double x, double y) {
284
        SelectionCADToolState actualState = _fsm.getState();
285
        String status = actualState.getName();
286
        VectorialLayerEdited vle = getVLE();
287
        if (vle == null) {
288
            return;
289
        }
290
        ArrayList selectedHandler = vle.getSelectedHandler();
291
        ViewPort vp=vle.getLayer().getMapContext().getViewPort();
292
        if (status.equals("Selection.SecondPoint")) {
293
            // Dibuja el rect?ngulo de selecci?n
294
            Curve curve = createCurve();
295
            curve.addMoveToVertex(createPoint(firstPoint.getX(), firstPoint.getY()));
296
            curve.addVertex(createPoint(x, firstPoint.getY()));
297
            curve.addVertex(createPoint(x, y));
298
            curve.addVertex(createPoint(firstPoint.getX(), y));
299
            curve.addVertex(createPoint(firstPoint.getX(), firstPoint.getY()));
300

    
301
            renderer.draw(curve, mapControlManager.getGeometrySelectionSymbol());
302

    
303
            return;
304
        }else if (status.equals("Selection.WithHandlers")) {
305
            // Movemos los handlers que hemos seleccionado
306
            // previamente dentro del m?todo select()
307
            double xPrev=0;
308
            double yPrev=0;
309
            for (int k = 0; k < selectedHandler.size(); k++) {
310
                Handler h = (Handler)selectedHandler.get(k);
311
                xPrev=h.getPoint().getX();
312
                yPrev=h.getPoint().getY();
313
                h.set(x, y);
314
            }
315
            // Y una vez movidos los v?rtices (handles)
316
            // redibujamos la nueva geometr?a.
317
            for (int i = 0; i < rowselectedHandlers.size(); i++) {
318
                Feature feature=(Feature)rowselectedHandlers.get(i);
319

    
320
                Geometry geom=(feature.getDefaultGeometry()).cloneGeometry();
321
                renderer.setColor(Color.gray);
322
                renderer.draw(geom, mapControlManager.getAxisReferenceSymbol());
323
            }
324
            for (int k = 0; k < selectedHandler.size(); k++) {
325
                Handler h = (Handler)selectedHandler.get(k);
326
                h.set(xPrev, yPrev);
327
            }
328
            return;
329
        }
330
    }
331

    
332
    /**
333
     * Add a diferent option.
334
     *
335
     * @param sel
336
     *            DOCUMENT ME!
337
     * @param s
338
     *            Diferent option.
339
     */
340
    public void addOption(String s) {
341
        SelectionCADToolState actualState = (SelectionCADToolState) _fsm
342
        .getPreviousState();
343
        String status = actualState.getName();
344
        System.out.println("PREVIOUSSTATE =" + status);
345
        System.out.println("STATUS ACTUAL = " + _fsm.getTransition());
346
        if (s.equals(PluginServices.getText(this,"cancel"))){
347
            init();
348
            return;
349
        }
350
        if (status.equals("Selection.FirstPoint")) {
351
            setType(s);
352
            return;
353
        }
354
        init();
355
    }
356

    
357
    /*
358
     * (non-Javadoc)
359
     *
360
     * @see com.iver.cit.gvsig.gui.cad.CADTool#addvalue(double)
361
     */
362
    public void addValue(double d) {
363
    }
364

    
365
    public String getStatus() {
366
        try {
367
            SelectionCADToolState actualState = (SelectionCADToolState) _fsm
368
            .getPreviousState();
369
            String status = actualState.getName();
370

    
371
            return status;
372
        } catch (NullPointerException e) {
373
            return "Selection.FirstPoint";
374
        }
375
    }
376

    
377
    public void end() {
378
        if (!getNextTool().equals("selection")) {
379
            CADExtension.setCADTool(getNextTool(),false);
380
        }
381
    }
382

    
383
    public String getName() {
384
        return PluginServices.getText(this,"selection_");
385
    }
386

    
387
    public boolean selectFeatures(double x, double y, InputEvent event) {
388
        SelectionCADToolState actualState = _fsm.getState();
389

    
390
        String status = actualState.getName();
391
        VectorialLayerEdited vle = getVLE();
392
        multipleSelection = event.isControlDown();
393

    
394
        if ((status.equals("Selection.FirstPoint"))
395
            || (status.equals("Selection.WithSelectedFeatures"))) {
396
            PluginServices.getMDIManager().setWaitCursor();
397
            firstPoint = new Point2D.Double(x, y);
398
            try {
399
                vle.getFeatureStore().beginEditingGroup(getName());
400
                vle.selectWithPoint(x, y, multipleSelection);
401
                vle.getFeatureStore().endEditingGroup();
402
            } catch (NeedEditingModeException e) {
403
                NotificationManager.showMessageError(getName(), e);
404
            } catch (ReadException e) {
405
                NotificationManager.showMessageError(getName(), e);
406
            }
407
            PluginServices.getMDIManager().restoreCursor();
408
        }
409
        FeatureSet selection = null;
410
        try {
411
            selection = (FeatureSet)vle.getFeatureStore().getSelection();
412
            long countSel=selection.getSize();
413
            if (countSel > 0) {
414
                nextState = "Selection.WithSelectedFeatures";
415
                return true;
416
            } else {
417
                {
418
                    nextState = "Selection.SecondPoint";
419
                    return true;
420
                }
421
            }
422
        } catch (ReadException e) {
423
            LOG.error("Error selecting the features", e);
424
            return false;
425
        } catch (DataException e) {
426
            LOG.error("Error selecting the features", e);
427
            return false;
428
        }
429
    }
430

    
431
    public int selectHandlers(double x, double y, InputEvent event) {
432
        Point2D auxPoint = new Point2D.Double(x, y);
433

    
434
        VectorialLayerEdited vle = getVLE();
435
        ArrayList selectedHandler = vle.getSelectedHandler();
436
        FeatureSet selection=null;
437
        DisposableIterator iterator = null;
438
        try {
439
            selection = (FeatureSet)vle.getFeatureStore().getSelection();
440

    
441
            long countSel = selection.getSize();
442
            System.out.println("DENTRO DE selectHandlers. selectedRow.size= " + countSel);
443
            selectedHandler.clear();
444

    
445
            // Se comprueba si se pincha en una gemometr?a
446
            PluginServices.getMDIManager().setWaitCursor();
447

    
448
            double tam = getCadToolAdapter().getMapControl().getViewPort()
449
            .toMapDistance(mapControlManager.getTolerance());
450

    
451
            Handler[] handlers = null;
452
            rowselectedHandlers.clear();
453
            iterator = selection.fastIterator();
454
            while (iterator.hasNext()) {
455
                Feature feature = (Feature) iterator.next();
456
                handlers = (feature.getDefaultGeometry()).getHandlers(Geometry.SELECTHANDLER);
457

    
458
                // y miramos los handlers de cada entidad seleccionada
459
                double min = tam;
460

    
461
                for (int j = 0; j < handlers.length; j++) {
462
                    Point2D handlerPoint = handlers[j].getPoint();
463
                    double distance = auxPoint.distance(handlerPoint);
464
                    if (distance <= min) {
465
                        min = distance;                                                
466
                        selectedHandler.add(handlers[j]);
467
                        rowselectedHandlers.add(feature);
468
                    }
469
                }
470
            }
471
            PluginServices.getMDIManager().restoreCursor();
472
        } catch (DataException e) {
473
            LOG.error("Error reading the store", e);
474
        } finally {
475
            if (iterator != null) {
476
                iterator.dispose();
477
            }
478
        }
479

    
480
        return selectedHandler.size();
481
    }
482

    
483
    public String getType() {
484
        return type;
485
    }
486

    
487
    public void setType(String type) {
488
        if (type.equals("S") || type.equals("s")){
489
            this.type=PluginServices.getText(this,"simple");
490
        }else{
491
            this.type = type;
492
        }
493
    }
494

    
495
    public String toString() {
496
        return "_selection";
497
    }
498

    
499
    public void multipleSelection(boolean b) {
500
        multipleSelection=b;
501

    
502
    }
503
}