Statistics
| Revision:

root / branches / v2_0_0_prep / extensions / extCAD / src / com / iver / cit / gvsig / gui / cad / tools / SelectionCADTool.java @ 23657

History | View | Annotate | Download (18.1 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 com.iver.cit.gvsig.gui.cad.tools;
42

    
43
import java.awt.Color;
44
import java.awt.Graphics;
45
import java.awt.Graphics2D;
46
import java.awt.Image;
47
import java.awt.event.InputEvent;
48
import java.awt.geom.Point2D;
49
import java.util.ArrayList;
50
import java.util.Iterator;
51

    
52
import org.gvsig.fmap.data.ReadException;
53
import org.gvsig.fmap.data.feature.Feature;
54
import org.gvsig.fmap.data.feature.FeatureCollection;
55
import org.gvsig.fmap.data.feature.FeatureStore;
56
import org.gvsig.fmap.geom.Geometry;
57
import org.gvsig.fmap.geom.GeometryFactory;
58
import org.gvsig.fmap.geom.GeometryManager;
59
import org.gvsig.fmap.geom.handler.Handler;
60
import org.gvsig.fmap.geom.operation.Draw;
61
import org.gvsig.fmap.geom.operation.DrawOperationContext;
62
import org.gvsig.fmap.geom.operation.GeometryOperationException;
63
import org.gvsig.fmap.geom.operation.GeometryOperationNotSupportedException;
64
import org.gvsig.fmap.geom.primitive.GeneralPathX;
65
import org.gvsig.fmap.mapcontext.MapContext;
66
import org.gvsig.fmap.mapcontext.ViewPort;
67
import org.gvsig.fmap.mapcontext.layers.FLayer;
68
import org.gvsig.fmap.mapcontext.layers.vectorial.FLyrVect;
69
import org.gvsig.fmap.mapcontrol.MapControl;
70

    
71
import com.iver.andami.PluginServices;
72
import com.iver.cit.gvsig.CADExtension;
73
import com.iver.cit.gvsig.gui.cad.DefaultCADTool;
74
import com.iver.cit.gvsig.gui.cad.exception.CommandException;
75
import com.iver.cit.gvsig.gui.cad.tools.smc.SelectionCADToolContext;
76
import com.iver.cit.gvsig.gui.cad.tools.smc.SelectionCADToolContext.SelectionCADToolState;
77
import com.iver.cit.gvsig.layers.VectorialLayerEdited;
78
import com.iver.cit.gvsig.project.documents.table.gui.Table;
79

    
80
/**
81
 * DOCUMENT ME!
82
 *
83
 * @author Vicente Caballero Navarro
84
 */
85
public class SelectionCADTool extends DefaultCADTool {
86
//        public static int tolerance = 4;
87

    
88
        private SelectionCADToolContext _fsm;
89

    
90
        protected Point2D firstPoint;
91
        protected GeometryFactory geomFactory=GeometryManager.getInstance().getGeometryFactory();
92

    
93
        protected String nextState;
94
// Registros de los que se ha seleccionado alg?n handler.
95
        protected ArrayList rowselectedHandlers=new ArrayList();
96
        protected String type=PluginServices.getText(this,"simple");
97
//        protected ArrayList pointsPolygon=new ArrayList();
98

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

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

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

    
138
                for (int i=0 ; i<views.length ; i++){
139
                        if (views[i] instanceof Table){
140
                                Table table=(Table)views[i];
141
                                if (table.getModel().getAssociatedTable()!=null && table.getModel().getAssociatedTable().equals(lv))
142
                                        table.updateSelection();
143
                        }
144
                }
145
        }
146

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

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

    
169
        public String getNextState() {
170
                return nextState;
171
        }
172

    
173
        protected void pointDoubleClick(MapContext map) throws ReadException {
174
                FLayer[] actives = map
175
           .getLayers().getActives();
176
//        for (int i=0; i < actives.length; i++){
177
//            if (actives[i] instanceof FLyrAnnotation && actives[i].isEditing()) {
178
//                FLyrAnnotation lyrAnnotation = (FLyrAnnotation) actives[i];
179
//                       lyrAnnotation.setSelectedEditing();
180
//                       lyrAnnotation.setInEdition(lyrAnnotation.getRecordset().getSelection().nextSetBit(0));
181
//                       FLabel fl=lyrAnnotation.getLabel(lyrAnnotation.getInEdition());
182
//                       if (fl!=null){
183
//                               View vista=(View)PluginServices.getMDIManager().getActiveWindow();
184
//                                       TextFieldEdit tfe=new TextFieldEdit(lyrAnnotation);
185
//                                tfe.show(vista.getMapControl().getViewPort().fromMapPoint(fl.getOrig()),vista.getMapControl());
186
//                               }
187
//            }
188
//        }
189
}
190
        /**
191
         * Equivale al transition del prototipo pero sin pasarle como par? metro el
192
         * editableFeatureSource que ya estar? creado.
193
         *
194
         * @param selection
195
         *            Bitset con las geometr?as que est?n seleccionadas.
196
         * @param x
197
         *            par?metro x del punto que se pase en esta transici?n.
198
         * @param y
199
         *            par?metro y del punto que se pase en esta transici?n.
200
         */
201
        public void addPoint(double x, double y, InputEvent event) {
202
//                if (event!=null && ((MouseEvent)event).getClickCount()==2){
203
//                        try {
204
//                                pointDoubleClick((MapControl)event.getComponent());
205
//                        } catch (ReadException e) {
206
//                                NotificationManager.addError(e.getMessage(),e);
207
//                        }
208
//                        return;
209
//                }
210
                SelectionCADToolState actualState = (SelectionCADToolState) _fsm
211
                                .getPreviousState();
212
                String status = actualState.getName();
213
                System.out.println("PREVIOUSSTATE =" + status); // + "ESTADO ACTUAL: " +
214
                                                                                                                // _fsm.getState());
215
                VectorialLayerEdited vle = getVLE();
216
                FeatureStore featureStore=null;
217
                try {
218
                        featureStore = vle.getFeatureStore();
219
                } catch (ReadException e) {
220
                        // TODO Auto-generated catch block
221
                        e.printStackTrace();
222
                }
223
                ArrayList selectedHandler = vle.getSelectedHandler();
224
                FeatureCollection selection = (FeatureCollection)featureStore.getSelection();//vle.getSelectedRow();
225
                System.out.println("STATUS ACTUAL = " + _fsm.getTransition());
226
                if (status.equals("Selection.FirstPoint")) {
227
                        firstPoint=new Point2D.Double(x,y);
228
//                        pointsPolygon.add(firstPoint);
229
                } else if (status.equals("Selection.SecondPoint")) {
230
                } else if (status.equals("Selection.WithFeatures")) {
231
                } else if (status.equals("Selection.WithHandlers")) {
232
                        featureStore.getCommandsRecord().startComplex();
233
                        ArrayList selectedRowsAux=new ArrayList();
234
                        Iterator iterator=selection.iterator();
235
                        while (iterator.hasNext()) {
236
                                Feature feature = (Feature) iterator.next();
237
//                        }
238
//                        for (int i = 0; i < selectedRow.size(); i++) {
239
//                                IRowEdited row = (IRowEdited) selectedRow.get(i);
240
//                                IFeature feat = (IFeature) row.getLinkedRow().cloneRow();
241
                                Geometry ig = (Geometry)feature.getDefaultGeometry();
242
//                                if (vea instanceof AnnotationEditableAdapter) {
243
//                                        // Movemos la geometr?a
244
//                    UtilFunctions.moveGeom(ig, x -
245
//                            firstPoint.getX(), y - firstPoint.getY());
246
//                                }else {
247
                                        // Movemos los handlers que hemos seleccionado
248
                                        // previamente dentro del m?todo select()
249
                                        Handler[] handlers=ig.getHandlers(Geometry.SELECTHANDLER);
250
                                        for (int k = 0; k < selectedHandler.size(); k++) {
251
                                                Handler h = (Handler)selectedHandler.get(k);
252
                                                for (int j=0;j<handlers.length;j++) {
253
                                                        if (h.getPoint().equals(handlers[j].getPoint()))
254
                                                                handlers[j].set(x,y);
255
                                                }
256
                                        }
257
//                                }
258
                                modifyFeature(feature, feature);
259
//                                selectedRowsAux.add(new DefaultRowEdited(feat,IRowEdited.STATUS_MODIFIED,row.getIndex()));
260
                        }
261
                        firstPoint=new Point2D.Double(x,y);
262
//                        vle.setSelectionCache(VectorialLayerEdited.SAVEPREVIOUS, selectedRowsAux);
263
                        //clearSelection();
264
                        //selectedRow.addAll(selectedRowsAux);
265
                        String description=PluginServices.getText(this,"move_handlers");
266
                        featureStore.getCommandsRecord().endComplex(description);
267
                }
268
        }
269

    
270
        /**
271
         * Receives second point
272
         * @param x
273
         * @param y
274
         * @return numFeatures selected
275
         */
276
        public int selectWithSecondPoint(double x, double y, InputEvent event) {
277
                VectorialLayerEdited vle = getVLE();
278
                PluginServices.getMDIManager().setWaitCursor();
279
                vle.selectWithSecondPoint(x,y);
280
                FeatureCollection selection=null;
281
                try {
282
                        selection = (FeatureCollection)vle.getFeatureStore().getSelection();
283
                } catch (ReadException e) {
284
                        // TODO Auto-generated catch block
285
                        e.printStackTrace();
286
                }//getSelectedRow();
287
                PluginServices.getMDIManager().restoreCursor();
288
                int countSel=selection.size();
289
                if (countSel > 0) {
290
                        nextState = "Selection.WithSelectedFeatures";
291
                } else
292
                        nextState = "Selection.FirstPoint";
293
                return countSel;
294
        }
295

    
296
        /**
297
         * M?todo para dibujar la lo necesario para el estado en el que nos
298
         * encontremos.
299
         *
300
         * @param g
301
         *            Graphics sobre el que dibujar.
302
         * @param selectedGeometries
303
         *            BitSet con las geometr?as seleccionadas.
304
         * @param x
305
         *            par?metro x del punto que se pase para dibujar.
306
         * @param y
307
         *            par?metro x del punto que se pase para dibujar.
308
         */
309
        public void drawOperation(Graphics g, double x, double y) {
310
                SelectionCADToolState actualState = _fsm.getState();
311
                String status = actualState.getName();
312
                VectorialLayerEdited vle = getVLE();
313
                if (vle == null) return;
314
                ArrayList selectedHandler = vle.getSelectedHandler();
315
                ViewPort vp=vle.getLayer().getMapContext().getViewPort();
316
                if (status.equals("Selection.SecondPoint")) {
317
                        // Dibuja el rect?ngulo de selecci?n
318
                        GeneralPathX elShape = new GeneralPathX(GeneralPathX.WIND_EVEN_ODD,
319
                                        4);
320
                        elShape.moveTo(firstPoint.getX(), firstPoint.getY());
321
                        elShape.lineTo(x, firstPoint.getY());
322
                        elShape.lineTo(x, y);
323
                        elShape.lineTo(firstPoint.getX(), y);
324
                        elShape.lineTo(firstPoint.getX(), firstPoint.getY());
325
                        DrawOperationContext doc=new DrawOperationContext();
326
                        doc.setGraphics((Graphics2D)g);
327
                        doc.setViewPort(vp);
328
                        doc.setSymbol(DefaultCADTool.geometrySelectSymbol);
329
                try {
330
                        geomFactory.createPolyline2D(elShape).cloneGeometry().invokeOperation(Draw.CODE,doc);
331
                        } catch (GeometryOperationNotSupportedException e) {
332
                                e.printStackTrace();
333
                        } catch (GeometryOperationException e) {
334
                                e.printStackTrace();
335
                        }
336
//                        geomFactory.createPolyline2D(elShape).draw((Graphics2D) g,
337
//                                        vp,
338
//                                        DefaultCADTool.geometrySelectSymbol);
339
                        Image img = vle.getSelectionImage();
340
                g.drawImage(img, 0, 0, null);
341
                return;
342
                }else if (status.equals("Selection.WithHandlers")) {
343
                        // Movemos los handlers que hemos seleccionado
344
                        // previamente dentro del m?todo select()
345
                        double xPrev=0;
346
                        double yPrev=0;
347
                        for (int k = 0; k < selectedHandler.size(); k++) {
348
                                Handler h = (Handler)selectedHandler.get(k);
349
                                xPrev=h.getPoint().getX();
350
                                yPrev=h.getPoint().getY();
351
                                h.set(x, y);
352
                        }
353
                        // Y una vez movidos los v?rtices (handles)
354
                        // redibujamos la nueva geometr?a.
355
                        for (int i = 0; i < rowselectedHandlers.size(); i++) {
356
                                Feature feature=(Feature)rowselectedHandlers.get(i);
357
//                                IRowEdited rowEd = (IRowEdited) rowselectedHandlers.get(i);
358
//                                IGeometry geom = ((IFeature) rowEd.getLinkedRow())
359
//                                                .getGeometry().cloneGeometry();
360
                                Geometry geom=((Geometry)feature.getDefaultGeometry()).cloneGeometry();
361
                                g.setColor(Color.gray);
362
                                DrawOperationContext doc=new DrawOperationContext();
363
                            doc.setGraphics((Graphics2D)g);
364
                            doc.setViewPort(vp);
365
                            doc.setSymbol(DefaultCADTool.axisReferencesSymbol);
366
                    try {
367
                                        geom.invokeOperation(Draw.CODE,doc);
368
                                } catch (GeometryOperationNotSupportedException e) {
369
                                        e.printStackTrace();
370
                                } catch (GeometryOperationException e) {
371
                                        e.printStackTrace();
372
                                }
373
                        }
374
                        for (int k = 0; k < selectedHandler.size(); k++) {
375
                                Handler h = (Handler)selectedHandler.get(k);
376
                                h.set(xPrev, yPrev);
377
                        }
378
                        return;
379
                }else{
380
                        if (!vle.getLayer().isVisible())
381
                                return;
382
                        try{
383
                        Image imgSel = vle.getSelectionImage();
384
                if (imgSel!=null)
385
                        g.drawImage(imgSel, 0, 0, null);
386
                Image imgHand = vle.getHandlersImage();
387
                if (imgHand!=null)
388
                        g.drawImage(imgHand, 0, 0, null);
389
                        }catch (Exception e) {
390
                        }
391
                }
392
        }
393

    
394
        /**
395
         * Add a diferent option.
396
         *
397
         * @param sel
398
         *            DOCUMENT ME!
399
         * @param s
400
         *            Diferent option.
401
         */
402
        public void addOption(String s) {
403
                SelectionCADToolState actualState = (SelectionCADToolState) _fsm
404
                                .getPreviousState();
405
                String status = actualState.getName();
406
                System.out.println("PREVIOUSSTATE =" + status); // + "ESTADO ACTUAL: " +
407
                // _fsm.getState());
408
                System.out.println("STATUS ACTUAL = " + _fsm.getTransition());
409
                if (s.equals(PluginServices.getText(this,"cancel"))){
410
                        init();
411
                        return;
412
                }
413
                if (status.equals("Selection.FirstPoint")) {
414
                        setType(s);
415
                        return;
416
                }
417
                init();
418
        }
419

    
420

    
421

    
422

    
423
        /*
424
         * (non-Javadoc)
425
         *
426
         * @see com.iver.cit.gvsig.gui.cad.CADTool#addvalue(double)
427
         */
428
        public void addValue(double d) {
429
        }
430

    
431
        public String getStatus() {
432
                try {
433
                        SelectionCADToolState actualState = (SelectionCADToolState) _fsm
434
                                        .getPreviousState();
435
                        String status = actualState.getName();
436

    
437
                        return status;
438
                } catch (NullPointerException e) {
439
                        return "Selection.FirstPoint";
440
                }
441
        }
442

    
443

    
444

    
445
        public void end() {
446
                if (!getNextTool().equals("selection"))
447
                        CADExtension.setCADTool(getNextTool(),false);
448
        }
449

    
450
        public String getName() {
451
                return PluginServices.getText(this,"selection_");
452
        }
453

    
454
        public boolean selectFeatures(double x, double y, InputEvent event) {
455
                SelectionCADToolState actualState = (SelectionCADToolState) _fsm
456
                                .getState();
457

    
458
                String status = actualState.getName();
459
                VectorialLayerEdited vle = getVLE();
460

    
461

    
462
                if ((status.equals("Selection.FirstPoint"))
463
                                || (status.equals("Selection.WithSelectedFeatures"))) {
464
                        PluginServices.getMDIManager().setWaitCursor();
465
                        firstPoint = new Point2D.Double(x, y);
466
                        vle.selectWithPoint(x,y,multipleSelection);
467
                        PluginServices.getMDIManager().restoreCursor();
468
                }
469
                FeatureCollection selection=null;
470
                try {
471
                        selection = (FeatureCollection)vle.getFeatureStore().getSelection();
472
                } catch (ReadException e) {
473
                        // TODO Auto-generated catch block
474
                        e.printStackTrace();
475
                }
476
//                ArrayList selectedRow = vle.getSelectedRow();
477
                int countSel=selection.size();
478
                if (countSel > 0) {
479
                        nextState = "Selection.WithSelectedFeatures";
480
                        return true;
481
                } else {
482
                        {
483
                                nextState = "Selection.SecondPoint";
484
                                return true;
485
                        }
486
                }
487
        }
488

    
489
        public int selectHandlers(double x, double y, InputEvent event) {
490
                Point2D auxPoint = new Point2D.Double(x, y);
491

    
492
                VectorialLayerEdited vle = getVLE();
493
                ArrayList selectedHandler = vle.getSelectedHandler();
494
                FeatureCollection selection=null;
495
                try {
496
                        selection = (FeatureCollection)vle.getFeatureStore().getSelection();
497
                } catch (ReadException e) {
498
                        // TODO Auto-generated catch block
499
                        e.printStackTrace();
500
                }
501
//                ArrayList selectedRow = vle.getSelectedRow();
502
                int countSel=selection.size();
503
                System.out.println("DENTRO DE selectHandlers. selectedRow.size= "
504
                                + countSel);
505
                selectedHandler.clear();
506

    
507
                // Se comprueba si se pincha en una gemometr?a
508
                PluginServices.getMDIManager().setWaitCursor();
509

    
510
                double tam = getCadToolAdapter().getMapControl().getViewPort()
511
                                .toMapDistance(MapControl.tolerance);
512

    
513
                Handler[] handlers = null;
514
                rowselectedHandlers.clear();
515
                Iterator iterator=selection.iterator();
516
                while (iterator.hasNext()) {
517
                        Feature feature = (Feature) iterator.next();
518

    
519
//                }
520
//                for (int i = 0; i < selectedRow.size(); i++) {
521
//                        IRowEdited rowEd = (IRowEdited) selectedRow.get(i);
522
//
523
//                        IFeature fea = (IFeature) rowEd.getLinkedRow();
524
                        handlers = ((Geometry)feature.getDefaultGeometry()).getHandlers(Geometry.SELECTHANDLER);
525
                        // y miramos los handlers de cada entidad seleccionada
526
                        double min = tam;
527
                        // int hSel = -1;
528

    
529
                        for (int j = 0; j < handlers.length; j++) {
530
                                Point2D handlerPoint = handlers[j].getPoint();
531
                                double distance = auxPoint.distance(handlerPoint);
532
                                if (distance <= min) {
533
                                        min = distance;
534
                                        // hSel = j;
535
                                        selectedHandler.add(handlers[j]);
536
                                        rowselectedHandlers.add(feature);
537
                                }
538
                        }
539
                }
540
                PluginServices.getMDIManager().restoreCursor();
541

    
542
                int numHandlesSelected = selectedHandler.size();
543

    
544
                /*
545
                 * if (numHandlesSelected == 0) selectFeatures(x,y);
546
                 */
547

    
548
                return numHandlesSelected;
549
        }
550

    
551
        public String getType() {
552
                return type;
553
        }
554

    
555
        public void setType(String type) {
556
                if (type.equals("S") || type.equals("s")){
557
                        this.type=PluginServices.getText(this,"simple");
558
                }else{
559
                        this.type = type;
560
                }
561
//                pointsPolygon.clear();
562
        }
563

    
564
        public String toString() {
565
                return "_selection";
566
        }
567
        public void multipleSelection(boolean b) {
568
                multipleSelection=b;
569

    
570
        }
571

    
572
}