Statistics
| Revision:

svn-gvsig-desktop / branches / gvSIG_CAD_Layout_version / applications / appgvSIG / src / com / iver / cit / gvsig / gui / cad / CADToolAdapter.java @ 1729

History | View | Annotate | Download (16.2 KB)

1
package com.iver.cit.gvsig.gui.cad;
2

    
3
import java.awt.Color;
4
import java.awt.Cursor;
5
import java.awt.Graphics;
6
import java.awt.Point;
7
import java.awt.event.MouseEvent;
8
import java.awt.event.MouseWheelEvent;
9
import java.awt.geom.AffineTransform;
10
import java.awt.geom.Point2D;
11
import java.awt.geom.Rectangle2D;
12
import java.io.IOException;
13
import java.util.Stack;
14

    
15
import org.apache.log4j.Logger;
16

    
17
import com.iver.andami.PluginServices;
18
import com.iver.cit.gvsig.fmap.core.FGeometry;
19
import com.iver.cit.gvsig.fmap.core.Handler;
20
import com.iver.cit.gvsig.fmap.core.IGeometry;
21
import com.iver.cit.gvsig.fmap.drivers.DriverIOException;
22
import com.iver.cit.gvsig.fmap.edition.EditableFeatureSource;
23
import com.iver.cit.gvsig.fmap.layers.FBitSet;
24
import com.iver.cit.gvsig.fmap.tools.BehaviorException;
25
import com.iver.cit.gvsig.fmap.tools.Behavior.Behavior;
26
import com.iver.cit.gvsig.fmap.tools.Listeners.ToolListener;
27
import com.iver.cit.gvsig.gui.cad.tools.SelectionCadTool;
28
import com.iver.fsac.Automaton;
29
import com.iver.utiles.console.InvalidResponseException;
30
import com.iver.utiles.console.JConsole;
31
import com.iver.utiles.console.ResponseListener;
32

    
33

    
34
/**
35
 * DOCUMENT ME!
36
 *
37
 * @author Fernando Gonz?lez Cort?s
38
 */
39
public class CADToolAdapter extends Behavior {
40
        private static Logger logger = Logger.getLogger(CADToolAdapter.class.getName());
41
        private Stack cadToolStack = new Stack();
42
        private FBitSet selection;
43
        private EditableFeatureSource editableFeatureSource;
44

    
45
        //Para pasarle las coordenadas cuando se produce un evento textEntered
46
        private int lastX;
47
        private int lastY;
48
        //private FSymbol symbol = new FSymbol(FConstant.SYMBOL_TYPE_POINT, Color.RED);
49
        private JConsole console;
50
        private Point2D mapAdjustedPoint;
51
        private CadMapControl cadMapControl;
52
        private boolean questionAsked = false;
53
        protected CadGrid grid;// = new CadGrid();
54
        protected Point adjustedPoint;
55
        private boolean snapping=true;
56
        private boolean adjustSnapping=false;
57
        
58
        public CADToolAdapter(){
59
                 grid= new CadGrid(this);
60
        }
61
        /**
62
         * Pinta de alguna manera especial las geometrias seleccionadas para la
63
         * edici?n. En caso de que el snapping est? activado, pintar? el efecto
64
         * del mismo.
65
         *
66
         * @see com.iver.cit.gvsig.fmap.tools.Behavior.Behavior#paintComponent(java.awt.Graphics)
67
         */
68
        public void paintComponent(Graphics g) {
69
                super.paintComponent(g);
70

    
71
                /*
72
                   for (int i = selection.nextSetBit(0); i >= 0;
73
                                   i = selection.nextSetBit(i + 1)) {
74
                           try {
75
                                   IGeometry geom = editableFeatureSource.getGeometry(i);
76
                                   Handler[] handlers=geom.getHandlers();
77
                                   geom.draw((Graphics2D) g, getMapControl().getViewPort(), symbol);
78
                                   FGraphicUtilities.DrawHandlers((Graphics2D)g,getMapControl().getViewPort().getAffineTransform(),handlers);
79
                           } catch (IOException e) {
80
                                   e.printStackTrace();
81
                           } catch (DriverIOException e) {
82
                                   e.printStackTrace();
83
                           }
84
                   }
85
                 */
86
                grid.drawGrid(g);
87
                drawCursor(g);
88
                
89
                if (adjustedPoint!=null){
90
                Point2D p = getMapControl().getViewPort().toMapPoint((int) adjustedPoint.getX(),
91
                                (int) adjustedPoint.getY());
92
                CadTool cadtool=(CadTool) cadToolStack.peek();
93
                cadtool.setAT(getMapControl().getViewPort().getAffineTransform());
94
                cadtool.drawOperation(g, editableFeatureSource,
95
                        selection, p.getX(), p.getY());
96
                }
97
        }
98

    
99
        /**
100
         * @see java.awt.event.MouseListener#mouseClicked(java.awt.event.MouseEvent)
101
         */
102
        public void mouseClicked(MouseEvent e) throws BehaviorException {
103
        }
104

    
105
        /**
106
         * @see java.awt.event.MouseListener#mouseEntered(java.awt.event.MouseEvent)
107
         */
108
        public void mouseEntered(MouseEvent e) throws BehaviorException {
109
        }
110

    
111
        /**
112
         * @see java.awt.event.MouseListener#mouseExited(java.awt.event.MouseEvent)
113
         */
114
        public void mouseExited(MouseEvent e) throws BehaviorException {
115
        }
116

    
117
        /**
118
         * @see java.awt.event.MouseListener#mousePressed(java.awt.event.MouseEvent)
119
         */
120
        public void mousePressed(MouseEvent e) throws BehaviorException {
121
                if (e.getButton() == MouseEvent.BUTTON1) {
122
                        //ViewPort vp = getMapControl().getMapContext().getViewPort();
123
                Point2D p;
124

    
125
                        if (mapAdjustedPoint != null) {
126
                                p = mapAdjustedPoint;
127
                        } else {
128
                                p = toPoint(adjustedPoint);
129
                        }
130

    
131
                        transition("punto", editableFeatureSource, selection,
132
                                new double[] { p.getX(), p.getY() });
133
                }
134
        }
135

    
136
        
137
        /**
138
         * Ajusta un punto de la imagen que se pasa como  par?metro al grid si ?ste
139
         * est? activo y devuelve la distancia de un punto al punto ajustado
140
         *
141
         * @param point
142
         *
143
         * @return Distancia del punto que se pasa como par?metro al punto ajustado
144
         */
145
        private double adjustToHandler(Point point, Point2D mapHandlerAdjustedPoint) {
146
                //if (selection.cardinality() > 0) {
147
                        try {
148
                                Point2D mapPoint = toPoint(point);
149

    
150
                                Rectangle2D r = new Rectangle2D.Double(mapPoint.getX() - 1,
151
                                                mapPoint.getY() - 1, 2, 2);
152

    
153
                                int[] indexes = editableFeatureSource.getGeometriesIndexes(r);
154
                                
155
                                double min = Double.MAX_VALUE;
156
                                Point2D argmin = null;
157
                                Point2D mapArgmin = null;
158

    
159
                                for (int i = 0; i < indexes.length; i++) {
160
                                        //if (!selection.get(indexes[i])) continue;
161
                                        IGeometry geom;
162
                                        geom = editableFeatureSource.getGeometry(indexes[i]);
163

    
164
                                        Handler[] handlers = geom.getHandlers(FGeometry.STRETCHINGHANDLER);
165

    
166
                                        for (int j = 0; j < handlers.length; j++) {
167
                                                Point2D handlerPoint = handlers[j].getPoint();
168
                                                Point2D handlerImagePoint = fromPoint(handlerPoint);
169
                                                double dist = handlerImagePoint.distance(point);
170

    
171
                                                if ((dist < SelectionCadTool.tolerance) &&
172
                                                                (dist < min)) {
173
                                                        min = dist;
174
                                                        argmin = handlerImagePoint;
175
                                                        mapArgmin = handlerPoint;
176
                                                }
177
                                        }
178
                                }
179

    
180
                                if (argmin != null) {
181
                                        point.setLocation(argmin);
182

    
183
                                        //Se hace el casting porque no se quiere redondeo
184
                                        point.setLocation((int)argmin.getX(),
185
                                                        (int) argmin.getY());
186
                                        
187
                                        mapHandlerAdjustedPoint.setLocation(mapArgmin);
188
                                        return min;
189
                                }
190
                        } catch (IOException e) {
191
                                e.printStackTrace();
192
                        } catch (DriverIOException e) {
193
                                e.printStackTrace();
194
                        }
195
                //}
196

    
197
                return Double.MAX_VALUE;
198
        }
199

    
200
        /**
201
         * @see java.awt.event.MouseListener#mouseReleased(java.awt.event.MouseEvent)
202
         */
203
        public void mouseReleased(MouseEvent e) throws BehaviorException {
204
        }
205

    
206
        /**
207
         * @see java.awt.event.MouseMotionListener#mouseDragged(java.awt.event.MouseEvent)
208
         */
209
        public void mouseDragged(MouseEvent e) throws BehaviorException {
210
                lastX = e.getX();
211
                lastY = e.getY();
212

    
213
                calculateSnapPoint(e.getPoint());
214
        }
215

    
216
        /**
217
         * @see java.awt.event.MouseMotionListener#mouseMoved(java.awt.event.MouseEvent)
218
         */
219
        public void mouseMoved(MouseEvent e) throws BehaviorException {
220
                lastX = e.getX();
221
                lastY = e.getY();
222

    
223
                calculateSnapPoint(e.getPoint());
224

    
225
                getMapControl().repaint();
226
        }
227

    
228
        /**
229
         * DOCUMENT ME!
230
         *
231
         * @param g DOCUMENT ME!
232
         */
233
        public void drawCursor(Graphics g) {
234
                Point p = adjustedPoint;
235
                if (p==null) grid.setAT(getAT());
236
                //else{
237
                int size1 = 15;
238
                int size2 = 3;
239
                g.drawLine((int) (p.getX() - size1), (int) (p.getY()),
240
                        (int) (p.getX() + size1), (int) (p.getY()));
241
                g.drawLine((int) (p.getX()), (int) (p.getY() - size1),
242
                        (int) (p.getX()), (int) (p.getY() + size1));
243
                if (adjustedPoint!=null){
244
                        if (adjustSnapping){
245
                                g.setColor(Color.ORANGE);
246
                                g.drawRect((int)(adjustedPoint.getX()-5),(int)(adjustedPoint.getY()-5),10,10);
247
                                g.drawRect((int)(adjustedPoint.getX()-3),(int)(adjustedPoint.getY()-3),6,6);
248
                                g.setColor(Color.MAGENTA);
249
                                g.drawRect((int)(adjustedPoint.getX()-4),(int)(adjustedPoint.getY()-4),8,8);
250
                                
251
                                adjustSnapping=false;
252
                        }else{
253
                                g.drawRect((int) (p.getX() - size2), (int) (p.getY() - size2),
254
                                                (int) (size2 * 2), (int) (size2 * 2));
255
                        }
256
                }
257
                //}
258
        }
259
        /**
260
         * DOCUMENT ME!
261
         *
262
         * @param point
263
         */
264
        protected void calculateSnapPoint(Point point) {
265
                //Se comprueba el ajuste a rejilla
266
                Point gridAdjustedPoint = (Point) point.clone();
267
                double minDistance = grid.adjustToGrid(gridAdjustedPoint);
268
                if (minDistance < Double.MAX_VALUE) {
269
                        adjustedPoint = gridAdjustedPoint;
270
                        mapAdjustedPoint = toPoint(adjustedPoint);
271
                }
272
                
273
                //Se comprueba el ajuste a los handlers
274
                Point handlerAdjustedPoint = gridAdjustedPoint;
275
                Point2D mapPoint = new Point2D.Double();
276
                double distance = adjustToHandler(handlerAdjustedPoint, mapPoint);
277
                if (distance < minDistance) {
278
                        adjustSnapping=true;
279
                        adjustedPoint = handlerAdjustedPoint;
280
                        mapAdjustedPoint = mapPoint;
281
                        minDistance = distance;
282
                }
283

    
284
                //Si no hay ajuste
285
                if (minDistance == Double.MAX_VALUE) {
286
                        adjustedPoint = point;
287
                        mapAdjustedPoint = null;
288
                }
289
        }
290

    
291

    
292
        /**
293
         * @see java.awt.event.MouseWheelListener#mouseWheelMoved(java.awt.event.MouseWheelEvent)
294
         */
295
        public void mouseWheelMoved(MouseWheelEvent e) throws BehaviorException {
296
        }
297

    
298
        /**
299
         * DOCUMENT ME!
300
         *
301
         * @param text DOCUMENT ME!
302
         */
303
        public void textEntered(String text) {
304
                text = text.trim();
305

    
306
                String[] numbers = text.split(",");
307
                double[] values = null;
308

    
309
                try {
310
                        if (numbers.length == 2) {
311
                                //punto
312
                                values = new double[] {
313
                                                Double.parseDouble(numbers[0]),
314
                                                Double.parseDouble(numbers[1])
315
                                        };
316
                                transition("punto", editableFeatureSource, selection, values);
317
                        } else if (numbers.length == 1) {
318
                                //valor
319
                                values = new double[] { Double.parseDouble(numbers[0]) };
320
                                transition("numero", editableFeatureSource, selection, values);
321
                        }
322
                } catch (NumberFormatException e) {
323
                        transition(text, editableFeatureSource, selection, new double[0]);
324
                }
325
        }
326

    
327
        /**
328
         * DOCUMENT ME!
329
         *
330
         * @param text DOCUMENT ME!
331
         */
332
        public void transition(String text) {
333
                transition(text, editableFeatureSource, selection, new double[0]);
334
                configureMenu();
335
        }
336

    
337
        /**
338
         * DOCUMENT ME!
339
         */
340
        private void configureMenu() {
341
                String[] desc = ((CadTool) cadToolStack.peek()).getAutomaton()
342
                                                 .getCurrentTransitionDescriptions();
343
                String[] labels = ((CadTool) cadToolStack.peek()).getAutomaton()
344
                                                   .getCurrentTransitions();
345
                if (getCadMapControl()!=null){
346
                getCadMapControl().clearMenu();
347

    
348
                for (int i = 0; i < desc.length; i++) {
349
                        if (desc[i] != null) {
350
                                getCadMapControl().addMenuEntry(desc[i], labels[i]);
351
                        }
352
                }
353
                }
354
        }
355

    
356
        /**
357
         * DOCUMENT ME!
358
         *
359
         * @param text DOCUMENT ME!
360
         * @param source DOCUMENT ME!
361
         * @param sel DOCUMENT ME!
362
         * @param values DOCUMENT ME!
363
         */
364
        protected void transition(String text, EditableFeatureSource source,
365
                FBitSet sel, double[] values) {
366
                questionAsked = false;
367
                logger.debug(text);
368

    
369
                int ret = ((CadTool) cadToolStack.peek()).transition(text, source, sel,
370
                                values);
371

    
372
                if ((ret & Automaton.AUTOMATON_FINISHED) == Automaton.AUTOMATON_FINISHED) {
373
                        popCadTool();
374

    
375
                        if (cadToolStack.isEmpty()) {
376
                                pushCadTool(new SelectionCadTool());
377
                                PluginServices.getMainFrame().selectTool("selection");
378
                        }
379

    
380
                        askQuestion();
381
                        if (getMapControl()!=null)
382
                        getMapControl().drawMap(false);
383
                } else {
384
                        if (((CadTool) cadToolStack.peek()).getAutomaton().checkState('c')) {
385
                                refresh();
386
                        }
387

    
388
                        if (!questionAsked) {
389
                                askQuestion();
390
                        }
391
                }
392
                if (console!=null){
393
                        configureMenu();
394
                }
395
                PluginServices.getMainFrame().enableControls();
396
        }
397

    
398
        /**
399
         * DOCUMENT ME!
400
         *
401
         * @param value DOCUMENT ME!
402
         */
403
        public void setGrid(boolean value) {
404
                grid.setUseGrid(value);
405
                grid.setAT(getAT());
406
                setGridSizeX(toDistance(20));
407
                setGridSizeY(toDistance(20));
408
        }
409

    
410
        /**
411
         * DOCUMENT ME!
412
         *
413
         * @param activated DOCUMENT ME!
414
         */
415
        public void setSnapping(boolean activated) {
416
                snapping=activated;
417
        }
418

    
419
        /**
420
         * DOCUMENT ME!
421
         *
422
         * @param x DOCUMENT ME!
423
         * @param y DOCUMENT ME!
424
         */
425
        public void getSnapPoint(double x, double y,double dist) {
426
        }
427

    
428
        /**
429
         * @see com.iver.cit.gvsig.fmap.tools.Behavior.Behavior#getListener()
430
         */
431
        public ToolListener getListener() {
432
                return new ToolListener() {
433
                                /**
434
                                 * @see com.iver.cit.gvsig.fmap.tools.Listeners.ToolListener#getCursor()
435
                                 */
436
                                public Cursor getCursor() {
437
                                        return null;
438
                                }
439

    
440
                                /**
441
                                 * @see com.iver.cit.gvsig.fmap.tools.Listeners.ToolListener#cancelDrawing()
442
                                 */
443
                                public boolean cancelDrawing() {
444
                                        return false;
445
                                }
446
                        };
447
        }
448

    
449
        /**
450
         * DOCUMENT ME!
451
         *
452
         * @return DOCUMENT ME!
453
         */
454
        public CadTool getCadTool() {
455
                return (CadTool) cadToolStack.peek();
456
        }
457

    
458
        /**
459
         * DOCUMENT ME!
460
         *
461
         * @param cadTool DOCUMENT ME!
462
         */
463
        public void pushCadTool(CadTool cadTool) {
464
                cadToolStack.push(cadTool);
465
                cadTool.setCadToolAdapter(this);
466
                cadTool.initializeStatus();
467
                int ret = cadTool.transition(null, editableFeatureSource, selection, new double[0]);
468
                if ((ret & Automaton.AUTOMATON_FINISHED) == Automaton.AUTOMATON_FINISHED) {
469
                        popCadTool();
470

    
471
                        if (cadToolStack.isEmpty()) {
472
                                pushCadTool(new SelectionCadTool());
473
                                PluginServices.getMainFrame().selectTool("selection");
474
                        }
475

    
476
                        askQuestion();
477

    
478
                        getMapControl().drawMap(false);
479
                }
480
        }
481

    
482
        /**
483
         * DOCUMENT ME!
484
         */
485
        public void popCadTool() {
486
                if (console!=null)
487
                console.cancelQuestion();
488
                cadToolStack.pop();
489
        }
490

    
491
        /**
492
         * DOCUMENT ME!
493
         */
494
        private void askQuestion() {
495
                if (console!=null){
496
                console.askQuestion(((CadTool) cadToolStack.peek()).getQuestion(),
497
                        new ResponseListener() {
498
                                public void acceptResponse(String response,
499
                                        boolean userCancelled) throws InvalidResponseException {
500
                                        if (response != null) {
501
                                                if ("".equals(response)) {
502
                                                        transition("aceptar");
503
                                                }
504

    
505
                                                textEntered(response);
506
                                        } else if (userCancelled) {
507
                                                transition("cancel");
508
                                        }
509
                                }
510
                        });
511
                }
512
                questionAsked = true;
513
                
514
        }
515

    
516
        /**
517
         * DOCUMENT ME!
518
         *
519
         * @param cadTool DOCUMENT ME!
520
         */
521
        public void setCadTool(CadTool cadTool) {
522
                cadToolStack.clear();
523
                pushCadTool(cadTool);
524
                if (console!=null)
525
                askQuestion();
526
        }
527

    
528
        /**
529
         * DOCUMENT ME!
530
         *
531
         * @return DOCUMENT ME!
532
         */
533
        public EditableFeatureSource getEditableFeatureSource() {
534
                return editableFeatureSource;
535
        }
536

    
537
        /**
538
         * DOCUMENT ME!
539
         *
540
         * @param editableFeatureSource DOCUMENT ME!
541
         * @param selection DOCUMENT ME!
542
         */
543
        public void setEditableFeatureSource(
544
                EditableFeatureSource editableFeatureSource, FBitSet selection) {
545
                this.editableFeatureSource = editableFeatureSource;
546
                this.selection = selection;
547
        }
548

    
549
        /**
550
         * DOCUMENT ME!
551
         *
552
         * @param console
553
         */
554
        public void setConsole(JConsole console) {
555
                this.console = console;
556
        }
557

    
558
        /**
559
         * DOCUMENT ME!
560
         *
561
         * @return DOCUMENT ME!
562
         */
563
        public CadMapControl getCadMapControl() {
564
                return cadMapControl;
565
        }
566

    
567
        /**
568
         * DOCUMENT ME!
569
         *
570
         * @param cadMapControl DOCUMENT ME!
571
         */
572
        public void setCadMapControl(CadMapControl cadMapControl) {
573
                this.cadMapControl = cadMapControl;
574
        }
575

    
576
        /**
577
         * Elimina las geometr?as seleccionadas actualmente
578
         */
579
        private void delete() {
580
                editableFeatureSource.startComplexGeometry();
581
                try {
582
                for (int i = selection.nextSetBit(0); i >= 0;
583
                                i = selection.nextSetBit(i + 1)) {
584
                                editableFeatureSource.removeGeometry(i);
585
                }
586
                } catch (DriverIOException e) {
587
                        e.printStackTrace();
588
                } catch (IOException e) {
589
                        e.printStackTrace();
590
                } finally {
591
                try {
592
                        editableFeatureSource.endComplexGeometry();
593
                } catch (IOException e1) {
594
                        e1.printStackTrace();
595
                } catch (DriverIOException e1) {
596
                        e1.printStackTrace();
597
                }
598
                }
599
                selection.clear();
600
                getCadMapControl().getMapControl().drawMap(false);
601
        }
602

    
603
        /**
604
         * @param b
605
         */
606
        public void setAdjustGrid(boolean b) {
607
                grid.setAdjustGrid(b);
608
        }
609

    
610
        /**
611
         * @param actionCommand
612
         */
613
        public void keyPressed(String actionCommand) {
614
                if (actionCommand.equals("eliminar")){
615
                        delete();
616
                }else if (actionCommand.equals("escape")){
617
                        transition("cancel");
618
                }
619
                PluginServices.getMainFrame().enableControls();
620
        }
621
        public AffineTransform getAT(){
622
                return getMapControl().getViewPort().getAffineTransform();
623
        }
624
        public double toDistance(int i){
625
                return getMapControl().getViewPort().toMapDistance(i);
626
        }
627
        public FBitSet getSelection(){
628
                return selection;
629
        }
630
        public void refresh(){
631
                getMapControl().drawMap(false);
632
        }
633
        public Point2D toPoint(Point2D p){
634
                return getMapControl().getViewPort().toMapPoint(p);
635
        }
636
        public Rectangle2D getExtent(){
637
                return getMapControl().getViewPort().getAdjustedExtent();
638
        }
639
        public double fromDistance(double d){
640
                return getMapControl().getViewPort().fromMapDistance(d);
641
        }
642
        public Point2D fromPoint(Point2D p){
643
                return getMapControl().getViewPort().fromMapPoint(p);
644
        }
645
        public void setGridSizeX(double i1){
646
                grid.setGridSizeX(i1);
647
        }
648
        public void setGridSizeY(double i1){
649
                grid.setGridSizeY(i1);
650
        }
651
        public double getGridSizeX(){
652
                return grid.getGridSizeX();
653
        }
654
        public double getGridSizeY(){
655
                return grid.getGridSizeY();
656
        }
657
        public Point2D getAdjustedPoint(){
658
                return adjustedPoint;
659
        }
660
}