Statistics
| Revision:

root / branches / v2_0_0_prep / extensions / extEditing / src / org / gvsig / editing / gui / cad / tools / SelectionCADTool.java @ 35954

History | View | Annotate | Download (19.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
    //        protected ArrayList pointsPolygon=new ArrayList();
93

    
94
    protected boolean multipleSelection=false;
95
    /**
96
     * Crea un nuevo SelectionCADTool.
97
     */
98
    public SelectionCADTool() {
99
    }
100
    /**
101
     * M?todo de incio, para poner el c?digo de todo lo que se requiera de una
102
     * carga previa a la utilizaci?n de la herramienta.
103
     */
104
    public void init() {
105
        _fsm = new SelectionCADToolContext(this);
106
        setNextTool("selection");
107
        setType(PluginServices.getText(this,"simple"));
108
    }
109

    
110
    /*
111
     * (non-Javadoc)
112
     *
113
     * @see com.iver.cit.gvsig.gui.cad.CADTool#transition(com.iver.cit.gvsig.fmap.layers.FBitSet,
114
     *      double, double)
115
     */
116
    public void transition(double x, double y, InputEvent event) {
117
        System.out.println("TRANSICION DESDE ESTADO " + _fsm.getState()
118
            + " x= " + x + " y=" + y);
119
        try{
120
            _fsm.addPoint(x, y, event);
121
        }catch (Exception e) {
122
            init();
123
            PluginServices.getMDIManager().restoreCursor();
124
        }
125
        System.out.println("ESTADO ACTUAL: " + getStatus());
126

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

    
134
        for (int i=0 ; i<views.length ; i++){
135
            if (views[i] instanceof FeatureTableDocumentPanel){
136
                FeatureTableDocumentPanel table=(FeatureTableDocumentPanel)views[i];
137
                if (table.getModel().getAssociatedLayer()!=null && table.getModel().getAssociatedLayer().equals(lv)) {
138
                    table.updateSelection();
139
                }
140
            }
141
        }
142
    }
143

    
144
    /*
145
     * (non-Javadoc)
146
     *
147
     * @see com.iver.cit.gvsig.gui.cad.CADTool#transition(com.iver.cit.gvsig.fmap.layers.FBitSet,
148
     *      double)
149
     */
150
    public void transition(double d) {
151
        _fsm.addValue(d);
152
    }
153

    
154
    /*
155
     * (non-Javadoc)
156
     *
157
     * @see com.iver.cit.gvsig.gui.cad.CADTool#transition(com.iver.cit.gvsig.fmap.layers.FBitSet,
158
     *      java.lang.String)
159
     */
160
    public void transition(String s) throws CommandException {
161
        if (!super.changeCommand(s)){
162
            _fsm.addOption(s);
163
        }
164
    }
165

    
166
    public String getNextState() {
167
        return nextState;
168
    }
169

    
170
    protected void pointDoubleClick(MapContext map) throws ReadException {
171
        FLayer[] actives = map
172
        .getLayers().getActives();
173
        //        for (int i=0; i < actives.length; i++){
174
        //            if (actives[i] instanceof FLyrAnnotation && actives[i].isEditing()) {
175
        //                FLyrAnnotation lyrAnnotation = (FLyrAnnotation) actives[i];
176
        //                       lyrAnnotation.setSelectedEditing();
177
        //                       lyrAnnotation.setInEdition(lyrAnnotation.getRecordset().getSelection().nextSetBit(0));
178
        //                       FLabel fl=lyrAnnotation.getLabel(lyrAnnotation.getInEdition());
179
        //                       if (fl!=null){
180
        //                               View vista=(View)PluginServices.getMDIManager().getActiveWindow();
181
        //                                       TextFieldEdit tfe=new TextFieldEdit(lyrAnnotation);
182
        //                                tfe.show(vista.getMapControl().getViewPort().fromMapPoint(fl.getOrig()),vista.getMapControl());
183
        //                               }
184
        //            }
185
        //        }
186
    }
187
    /**
188
     * Equivale al transition del prototipo pero sin pasarle como par? metro el
189
     * editableFeatureSource que ya estar? creado.
190
     *
191
     * @param selection
192
     *            Bitset con las geometr?as que est?n seleccionadas.
193
     * @param x
194
     *            par?metro x del punto que se pase en esta transici?n.
195
     * @param y
196
     *            par?metro y del punto que se pase en esta transici?n.
197
     */
198
    public void addPoint(double x, double y, InputEvent event) {
199
        SelectionCADToolState actualState = (SelectionCADToolState) _fsm.getPreviousState();
200
        String status = actualState.getName();
201
        System.out.println("PREVIOUSSTATE =" + status);         
202
        VectorialLayerEdited vle = getVLE();
203
        FeatureStore featureStore = null;
204
        DisposableIterator iterator = null;
205
        try {
206
            featureStore = vle.getFeatureStore();
207

    
208
            ArrayList selectedHandler = vle.getSelectedHandler();
209
            FeatureSet selection = (FeatureSet) featureStore.getSelection();
210
            System.out.println("STATUS ACTUAL = " + _fsm.getTransition());
211
            if (status.equals("Selection.FirstPoint")) {
212
                firstPoint = new Point2D.Double(x, y);                                
213
            } else if (status.equals("Selection.SecondPoint")) {
214
            } else if (status.equals("Selection.WithFeatures")) {
215
            } else if (status.equals("Selection.WithHandlers")) {
216
                addPointWithHandlers(x, y, featureStore, vle.getSelectedHandler());        
217
            }
218
        } catch (DataException e) {
219
            LOG.error("Error reding the store", e);
220
        } finally {
221
            if (iterator != null) {
222
                iterator.dispose();
223
            }
224
        }
225
    }
226

    
227
    /**
228
     * AddPoint method for the WithHandlers option
229
     * @param x
230
     *          selected x coordinate.
231
     * @param y
232
     *          selected y coordinate.
233
     * @param featureStore
234
     *          the selected feature store.
235
     * @param selectedHandlers
236
     *          the selected handlers
237
     */
238
    protected void addPointWithHandlers(double x, double y, FeatureStore featureStore, ArrayList selectedHandlers){
239
        String description = PluginServices.getText(this, "move_handlers");
240
        DisposableIterator iterator = null;
241
        try {
242
            featureStore.beginEditingGroup(description); 
243

    
244
            iterator = ((FeatureSelection) featureStore.getSelection()).fastIterator();
245

    
246
            while (iterator.hasNext()) {
247
                Feature feature = (Feature) iterator.next();
248

    
249
                Geometry geometry = (feature.getDefaultGeometry()).cloneGeometry();
250

    
251
                // Movemos los handlers que hemos seleccionado
252
                // previamente dentro del m?todo select()
253
                Handler[] handlers = geometry.getHandlers(Geometry.SELECTHANDLER);
254
                for (int k = 0; k < selectedHandlers.size(); k++) {
255
                    Handler h = (Handler) selectedHandlers.get(k);
256
                    for (int j = 0; j < handlers.length; j++) {
257
                        if (h.getPoint().equals(handlers[j].getPoint())) {
258
                            handlers[j].set(x, y);
259
                        }
260
                    }
261
                }
262
                EditableFeature eFeature = feature.getEditable();
263
                eFeature.setDefaultGeometry(geometry);
264
                featureStore.update(eFeature);
265

    
266
            }
267

    
268
            firstPoint = new Point2D.Double(x, y);
269

    
270
            featureStore.endEditingGroup();
271
        } catch (DataException e1) {           
272
            LOG.error("Error reading the store", e1);
273
        } finally {
274
            if (iterator != null) {
275
                iterator.dispose();
276
            }
277
        }
278
    }
279

    
280
    /**
281
     * Receives second point
282
     * @param x
283
     * @param y
284
     * @return numFeatures selected
285
     */
286
    public long selectWithSecondPoint(double x, double y, InputEvent event) {
287
        VectorialLayerEdited vle = getVLE();
288
        PluginServices.getMDIManager().setWaitCursor();
289
        vle.selectWithSecondPoint(x,y);
290
        FeatureSet selection=null;
291
        try {
292
            selection = (FeatureSet)vle.getFeatureStore().getSelection();
293
            PluginServices.getMDIManager().restoreCursor();
294
            long countSel=selection.getSize();
295
            if (countSel > 0) {
296
                nextState = "Selection.WithSelectedFeatures";
297
            } else {
298
                nextState = "Selection.FirstPoint";
299
            }
300
            return countSel;
301
        } catch (ReadException e) {
302
            e.printStackTrace();
303
            return 0;
304
        } catch (DataException e) {
305
            e.printStackTrace();
306
            return 0;
307
        }
308
    }
309

    
310
    /**
311
     * M?todo para dibujar la lo necesario para el estado en el que nos
312
     * encontremos.
313
     *
314
     * @param g
315
     *            Graphics sobre el que dibujar.
316
     * @param selectedGeometries
317
     *            BitSet con las geometr?as seleccionadas.
318
     * @param x
319
     *            par?metro x del punto que se pase para dibujar.
320
     * @param y
321
     *            par?metro x del punto que se pase para dibujar.
322
     */
323
    public void drawOperation(MapControlDrawer renderer, double x, double y) {
324
        SelectionCADToolState actualState = _fsm.getState();
325
        String status = actualState.getName();
326
        VectorialLayerEdited vle = getVLE();
327
        if (vle == null) {
328
            return;
329
        }
330
        ArrayList selectedHandler = vle.getSelectedHandler();
331
        ViewPort vp=vle.getLayer().getMapContext().getViewPort();
332
        if (status.equals("Selection.SecondPoint")) {
333
            // Dibuja el rect?ngulo de selecci?n
334
            Curve curve = createCurve();
335
            curve.addMoveToVertex(createPoint(firstPoint.getX(), firstPoint.getY()));
336
            curve.addVertex(createPoint(x, firstPoint.getY()));
337
            curve.addVertex(createPoint(x, y));
338
            curve.addVertex(createPoint(firstPoint.getX(), y));
339
            curve.addVertex(createPoint(firstPoint.getX(), firstPoint.getY()));
340

    
341
            renderer.draw(curve, mapControlManager.getGeometrySelectionSymbol());
342

    
343
            return;
344
        }else if (status.equals("Selection.WithHandlers")) {
345
            // Movemos los handlers que hemos seleccionado
346
            // previamente dentro del m?todo select()
347
            double xPrev=0;
348
            double yPrev=0;
349
            for (int k = 0; k < selectedHandler.size(); k++) {
350
                Handler h = (Handler)selectedHandler.get(k);
351
                xPrev=h.getPoint().getX();
352
                yPrev=h.getPoint().getY();
353
                h.set(x, y);
354
            }
355
            // Y una vez movidos los v?rtices (handles)
356
            // redibujamos la nueva geometr?a.
357
            for (int i = 0; i < rowselectedHandlers.size(); i++) {
358
                Feature feature=(Feature)rowselectedHandlers.get(i);
359

    
360
                Geometry geom=(feature.getDefaultGeometry()).cloneGeometry();
361
                renderer.setColor(Color.gray);
362
                renderer.draw(geom, mapControlManager.getAxisReferenceSymbol());
363
            }
364
            for (int k = 0; k < selectedHandler.size(); k++) {
365
                Handler h = (Handler)selectedHandler.get(k);
366
                h.set(xPrev, yPrev);
367
            }
368
            return;
369
        }
370
    }
371

    
372
    /**
373
     * Add a diferent option.
374
     *
375
     * @param sel
376
     *            DOCUMENT ME!
377
     * @param s
378
     *            Diferent option.
379
     */
380
    public void addOption(String s) {
381
        SelectionCADToolState actualState = (SelectionCADToolState) _fsm
382
        .getPreviousState();
383
        String status = actualState.getName();
384
        System.out.println("PREVIOUSSTATE =" + status); // + "ESTADO ACTUAL: " +
385
        // _fsm.getState());
386
        System.out.println("STATUS ACTUAL = " + _fsm.getTransition());
387
        if (s.equals(PluginServices.getText(this,"cancel"))){
388
            init();
389
            return;
390
        }
391
        if (status.equals("Selection.FirstPoint")) {
392
            setType(s);
393
            return;
394
        }
395
        init();
396
    }
397

    
398

    
399

    
400

    
401
    /*
402
     * (non-Javadoc)
403
     *
404
     * @see com.iver.cit.gvsig.gui.cad.CADTool#addvalue(double)
405
     */
406
    public void addValue(double d) {
407
    }
408

    
409
    public String getStatus() {
410
        try {
411
            SelectionCADToolState actualState = (SelectionCADToolState) _fsm
412
            .getPreviousState();
413
            String status = actualState.getName();
414

    
415
            return status;
416
        } catch (NullPointerException e) {
417
            return "Selection.FirstPoint";
418
        }
419
    }
420

    
421

    
422

    
423
    public void end() {
424
        if (!getNextTool().equals("selection")) {
425
            CADExtension.setCADTool(getNextTool(),false);
426
        }
427
    }
428

    
429
    public String getName() {
430
        return PluginServices.getText(this,"selection_");
431
    }
432

    
433
    public boolean selectFeatures(double x, double y, InputEvent event) {
434
        SelectionCADToolState actualState = _fsm
435
        .getState();
436

    
437
        String status = actualState.getName();
438
        VectorialLayerEdited vle = getVLE();
439
        multipleSelection=event.isControlDown();
440

    
441
        if ((status.equals("Selection.FirstPoint"))
442
            || (status.equals("Selection.WithSelectedFeatures"))) {
443
            PluginServices.getMDIManager().setWaitCursor();
444
            firstPoint = new Point2D.Double(x, y);
445
            try {
446
                vle.getFeatureStore().beginEditingGroup(getName());
447
                vle.selectWithPoint(x,y,multipleSelection);
448
                vle.getFeatureStore().endEditingGroup();
449
            } catch (NeedEditingModeException e) {
450
                NotificationManager.showMessageError(getName(), e);
451
            } catch (ReadException e) {
452
                NotificationManager.showMessageError(getName(), e);
453
            }
454
            PluginServices.getMDIManager().restoreCursor();
455
        }
456
        FeatureSet selection=null;
457
        try {
458
            selection = (FeatureSet)vle.getFeatureStore().getSelection();
459

    
460
            //                ArrayList selectedRow = vle.getSelectedRow();
461
            long countSel=selection.getSize();
462
            if (countSel > 0) {
463
                nextState = "Selection.WithSelectedFeatures";
464
                return true;
465
            } else {
466
                {
467
                    nextState = "Selection.SecondPoint";
468
                    return true;
469
                }
470
            }
471
        } catch (ReadException e) {
472
            e.printStackTrace();
473
            return false;
474
        } catch (DataException e) {
475
            e.printStackTrace();
476
            return false;
477
        }
478
    }
479

    
480
    public int selectHandlers(double x, double y, InputEvent event) {
481
        Point2D auxPoint = new Point2D.Double(x, y);
482

    
483
        VectorialLayerEdited vle = getVLE();
484
        ArrayList selectedHandler = vle.getSelectedHandler();
485
        FeatureSet selection=null;
486
        DisposableIterator iterator = null;
487
        try {
488
            selection = (FeatureSet)vle.getFeatureStore().getSelection();
489

    
490
            long countSel = selection.getSize();
491
            System.out.println("DENTRO DE selectHandlers. selectedRow.size= " + countSel);
492
            selectedHandler.clear();
493

    
494
            // Se comprueba si se pincha en una gemometr?a
495
            PluginServices.getMDIManager().setWaitCursor();
496

    
497
            double tam = getCadToolAdapter().getMapControl().getViewPort()
498
            .toMapDistance(mapControlManager.getTolerance());
499

    
500
            Handler[] handlers = null;
501
            rowselectedHandlers.clear();
502
            iterator = selection.fastIterator();
503
            while (iterator.hasNext()) {
504
                Feature feature = (Feature) iterator.next();
505
                handlers = (feature.getDefaultGeometry()).getHandlers(Geometry.SELECTHANDLER);
506

    
507
                // y miramos los handlers de cada entidad seleccionada
508
                double min = tam;
509

    
510
                for (int j = 0; j < handlers.length; j++) {
511
                    Point2D handlerPoint = handlers[j].getPoint();
512
                    double distance = auxPoint.distance(handlerPoint);
513
                    if (distance <= min) {
514
                        min = distance;                                                
515
                        selectedHandler.add(handlers[j]);
516
                        rowselectedHandlers.add(feature);
517
                    }
518
                }
519
            }
520
            PluginServices.getMDIManager().restoreCursor();
521
        } catch (DataException e) {
522
            LOG.error("Error reading the store", e);
523
        } finally {
524
            if (iterator != null) {
525
                iterator.dispose();
526
            }
527
        }
528

    
529
        return selectedHandler.size();
530
    }
531

    
532
    public String getType() {
533
        return type;
534
    }
535

    
536
    public void setType(String type) {
537
        if (type.equals("S") || type.equals("s")){
538
            this.type=PluginServices.getText(this,"simple");
539
        }else{
540
            this.type = type;
541
        }
542
        //                pointsPolygon.clear();
543
    }
544

    
545
    public String toString() {
546
        return "_selection";
547
    }
548
    public void multipleSelection(boolean b) {
549
        multipleSelection=b;
550

    
551
    }
552

    
553
}