Statistics
| Revision:

svn-gvsig-desktop / tags / v1_1_Build_1010 / extensions / extCAD / src / com / iver / cit / gvsig / gui / cad / CADToolAdapter.java @ 12804

History | View | Annotate | Download (27.8 KB)

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

    
3
import java.awt.Color;
4
import java.awt.Cursor;
5
import java.awt.FontMetrics;
6
import java.awt.Graphics;
7
import java.awt.Graphics2D;
8
import java.awt.Image;
9
import java.awt.Point;
10
import java.awt.Toolkit;
11
import java.awt.event.InputEvent;
12
import java.awt.event.MouseEvent;
13
import java.awt.event.MouseWheelEvent;
14
import java.awt.geom.Point2D;
15
import java.awt.geom.Rectangle2D;
16
import java.awt.image.MemoryImageSource;
17
import java.io.IOException;
18
import java.text.NumberFormat;
19
import java.util.ArrayList;
20
import java.util.HashMap;
21
import java.util.Stack;
22
import java.util.prefs.Preferences;
23

    
24
import org.cresques.cts.IProjection;
25

    
26
import com.iver.andami.PluginServices;
27
import com.iver.andami.messages.NotificationManager;
28
import com.iver.andami.ui.mdiFrame.MainFrame;
29
import com.iver.andami.ui.mdiManager.IWindow;
30
import com.iver.cit.gvsig.CADExtension;
31
import com.iver.cit.gvsig.EditionManager;
32
import com.iver.cit.gvsig.fmap.DriverException;
33
import com.iver.cit.gvsig.fmap.MapContext;
34
import com.iver.cit.gvsig.fmap.MapControl;
35
import com.iver.cit.gvsig.fmap.ViewPort;
36
import com.iver.cit.gvsig.fmap.core.FShape;
37
import com.iver.cit.gvsig.fmap.core.v02.FConstant;
38
import com.iver.cit.gvsig.fmap.core.v02.FConverter;
39
import com.iver.cit.gvsig.fmap.core.v02.FSymbol;
40
import com.iver.cit.gvsig.fmap.drivers.DriverIOException;
41
import com.iver.cit.gvsig.fmap.edition.EditionEvent;
42
import com.iver.cit.gvsig.fmap.edition.UtilFunctions;
43
import com.iver.cit.gvsig.fmap.edition.VectorialEditableAdapter;
44
import com.iver.cit.gvsig.fmap.layers.FBitSet;
45
import com.iver.cit.gvsig.fmap.layers.FLyrVect;
46
import com.iver.cit.gvsig.fmap.layers.SpatialCache;
47
import com.iver.cit.gvsig.fmap.tools.BehaviorException;
48
import com.iver.cit.gvsig.fmap.tools.Behavior.Behavior;
49
import com.iver.cit.gvsig.fmap.tools.Listeners.ToolListener;
50
import com.iver.cit.gvsig.gui.cad.snapping.FinalPointSnapper;
51
import com.iver.cit.gvsig.gui.cad.snapping.ISnapper;
52
import com.iver.cit.gvsig.gui.cad.snapping.ISnapperRaster;
53
import com.iver.cit.gvsig.gui.cad.snapping.ISnapperVectorial;
54
import com.iver.cit.gvsig.gui.cad.snapping.NearestPointSnapper;
55
import com.iver.cit.gvsig.gui.cad.snapping.PixelSnapper;
56
import com.iver.cit.gvsig.gui.cad.snapping.SnappingVisitor;
57
import com.iver.cit.gvsig.gui.cad.tools.SelectionCADTool;
58
import com.iver.cit.gvsig.layers.ILayerEdited;
59
import com.iver.cit.gvsig.layers.VectorialLayerEdited;
60
import com.iver.cit.gvsig.project.documents.view.gui.View;
61
import com.iver.utiles.console.JConsole;
62
import com.vividsolutions.jts.geom.Envelope;
63

    
64
public class CADToolAdapter extends Behavior {
65
        private static HashMap namesCadTools = new HashMap();
66

    
67
        private EditionManager editionManager = new EditionManager();
68

    
69
        public static final int ABSOLUTE = 0;
70

    
71
        public static final int RELATIVE_SCP = 1;
72

    
73
        public static final int RELATIVE_SCU = 2;
74

    
75
        public static final int POLAR_SCP = 3;
76

    
77
        public static final int POLAR_SCU = 4;
78

    
79
        private double[] previousPoint = null;
80

    
81
        private Stack cadToolStack = new Stack();
82

    
83
        // Para pasarle las coordenadas cuando se produce un evento textEntered
84
        private int lastX;
85

    
86
        private int lastY;
87

    
88
        private FSymbol symbol = new FSymbol(FConstant.SYMBOL_TYPE_POINT, Color.RED);
89

    
90
        private Point2D mapAdjustedPoint;
91

    
92
        private ISnapper usedSnap = null;
93

    
94
        private boolean questionAsked = false;
95

    
96
        private Point2D adjustedPoint;
97

    
98
        private boolean bRefent = true;
99

    
100
        private boolean bForceCoord = false;
101

    
102
        private CADGrid cadgrid = new CADGrid();
103

    
104
        private boolean bOrtoMode;
105

    
106
        private Color theTipColor = new Color(255, 255, 155);
107

    
108
        private static boolean flatnessInitialized=false;
109
        private static Preferences prefs = Preferences.userRoot().node( "cadtooladapter" );
110

    
111
        /**
112
         * Pinta de alguna manera especial las geometrias seleccionadas para la
113
         * edici?n. En caso de que el snapping est? activado, pintar? el efecto del
114
         * mismo.
115
         *
116
         * @see com.iver.cit.gvsig.fmap.tools.Behavior.Behavior#paintComponent(java.awt.Graphics)
117
         */
118
        public void paintComponent(Graphics g) {
119
                super.paintComponent(g);
120
                if (CADExtension.getCADToolAdapter()!=this)
121
                        return;
122
                drawCursor(g);
123
                getGrid().drawGrid(g);
124
                if (adjustedPoint != null) {
125
                        Point2D p = null;
126
                        if (mapAdjustedPoint != null) {
127
                                p = mapAdjustedPoint;
128
                        } else {
129
                                p = getMapControl().getViewPort().toMapPoint(adjustedPoint);
130
                        }
131

    
132
                        ((CADTool) cadToolStack.peek())
133
                                        .drawOperation(g, p.getX(), p.getY());
134
                }
135
        }
136

    
137
        /**
138
         * @see java.awt.event.MouseListener#mouseClicked(java.awt.event.MouseEvent)
139
         */
140
        public void mouseClicked(MouseEvent e) throws BehaviorException {
141
                if (e.getButton() == MouseEvent.BUTTON3) {
142
                        CADExtension.showPopup(e);
143
                }
144
        }
145

    
146
        /**
147
         * @see java.awt.event.MouseListener#mouseEntered(java.awt.event.MouseEvent)
148
         */
149
        public void mouseEntered(MouseEvent e) throws BehaviorException {
150
                clearMouseImage();
151
        }
152

    
153
        /**
154
         * @see java.awt.event.MouseListener#mouseExited(java.awt.event.MouseEvent)
155
         */
156
        public void mouseExited(MouseEvent e) throws BehaviorException {
157
        }
158

    
159
        /**
160
         * @see java.awt.event.MouseListener#mousePressed(java.awt.event.MouseEvent)
161
         */
162
        public void mousePressed(MouseEvent e) throws BehaviorException {
163
                if (e.getButton() == MouseEvent.BUTTON1) {
164
                        ViewPort vp = getMapControl().getMapContext().getViewPort();
165
                        Point2D p;
166

    
167
                        if (mapAdjustedPoint != null) {
168
                                p = mapAdjustedPoint;
169
                        } else {
170
                                p = vp.toMapPoint(adjustedPoint);
171
                        }
172
                        transition(new double[] { p.getX(), p.getY() }, e, ABSOLUTE);
173
                }
174
        }
175

    
176
        /**
177
         * Ajusta un punto de la imagen que se pasa como par?metro al grid si ?ste
178
         * est? activo y devuelve la distancia de un punto al punto ajustado
179
         *
180
         * @param point
181
         * @param mapHandlerAdjustedPoint
182
         *            DOCUMENT ME!
183
         *
184
         * @return Distancia del punto que se pasa como
185
         *  par?metro al punto ajustado. Si no hay ajuste,
186
         *  devuelve Double.MAX_VALUE
187
         */
188
        private double adjustToHandler(Point2D point,
189
                        Point2D mapHandlerAdjustedPoint) {
190

    
191
                if (!isRefentEnabled())
192
                        return Double.MAX_VALUE;
193

    
194
                ILayerEdited aux = CADExtension.getEditionManager().getActiveLayerEdited();
195
                if (!(aux instanceof VectorialLayerEdited))
196
                        return Double.MAX_VALUE;
197
                VectorialLayerEdited vle = (VectorialLayerEdited) aux;
198

    
199
                ArrayList snappers = vle.getSnappers();
200
                ArrayList layersToSnap = vle.getLayersToSnap();
201

    
202

    
203
                ViewPort vp = getMapControl().getViewPort();
204

    
205
                // TODO: PROVISIONAL. PONER ALGO COMO ESTO EN UN CUADRO DE DIALOGO
206
                // DE CONFIGURACI?N DEL SNAPPING
207
                FinalPointSnapper defaultSnap = new FinalPointSnapper();
208
                NearestPointSnapper nearestSnap = new NearestPointSnapper();
209
                // PixelSnapper pixSnap = new PixelSnapper();
210
                snappers.clear();
211
                snappers.add(defaultSnap);
212
                snappers.add(nearestSnap);
213
                // snappers.add(pixSnap);
214

    
215
                double mapTolerance = vp.toMapDistance(SelectionCADTool.tolerance);
216
                double minDist = mapTolerance;
217
//                double rw = getMapControl().getViewPort().toMapDistance(5);
218
                Point2D mapPoint = point;
219
                Rectangle2D r = new Rectangle2D.Double(mapPoint.getX() - mapTolerance / 2,
220
                                mapPoint.getY() - mapTolerance / 2, mapTolerance, mapTolerance);
221

    
222
                Envelope e = FConverter.convertRectangle2DtoEnvelope(r);
223

    
224
                usedSnap = null;
225
                Point2D lastPoint = null;
226
                if (previousPoint != null)
227
                {
228
                        lastPoint = new Point2D.Double(previousPoint[0], previousPoint[1]);
229
                }
230
                for (int j = 0; j < layersToSnap.size(); j++)
231
                {
232
                        FLyrVect lyrVect = (FLyrVect) layersToSnap.get(j);
233
                        SpatialCache cache = lyrVect.getSpatialCache();
234
                        if (lyrVect.isVisible())
235
                        {
236
                                // La lista de snappers est? siempre ordenada por prioridad. Los de mayor
237
                                // prioridad est?n primero.
238
                                for (int i = 0; i < snappers.size(); i++)
239
                                {
240
                                        ISnapper theSnapper = (ISnapper) snappers.get(i);
241

    
242
                                        if (usedSnap != null)
243
                                        {
244
                                                // Si ya tenemos un snap y es de alta prioridad, cogemos ese. (A no ser que en otra capa encontremos un snapper mejor)
245
                                                if (theSnapper.getPriority() < usedSnap.getPriority())
246
                                                        break;
247
                                        }
248
                                        SnappingVisitor snapVisitor = null;
249
                                        Point2D theSnappedPoint = null;
250
                                        if (theSnapper instanceof ISnapperVectorial)
251
                                        {
252
                                                snapVisitor = new SnappingVisitor((ISnapperVectorial) theSnapper, point, mapTolerance, lastPoint);
253
                                                // System.out.println("Cache size = " + cache.size());
254
                                                cache.query(e, snapVisitor);
255
                                                theSnappedPoint = snapVisitor.getSnapPoint();
256
                                        }
257
                                        if (theSnapper instanceof ISnapperRaster)
258
                                        {
259
                                                ISnapperRaster snapRaster = (ISnapperRaster) theSnapper;
260
                                                theSnappedPoint = snapRaster.getSnapPoint(getMapControl(), point, mapTolerance, lastPoint);
261
                                        }
262

    
263

    
264
                                        if (theSnappedPoint != null) {
265
                                                double distAux = theSnappedPoint.distance(point);
266
                                                if (minDist > distAux)
267
                                                {
268
                                                        minDist = distAux;
269
                                                        usedSnap = theSnapper;
270
                                                        mapHandlerAdjustedPoint.setLocation(theSnappedPoint);
271
                                                }
272
                                        }
273
                                }
274
                        } // visible
275
                }
276
                if (usedSnap != null)
277
                        return minDist;
278
                return Double.MAX_VALUE;
279

    
280
        }
281

    
282
        /**
283
         * @see java.awt.event.MouseListener#mouseReleased(java.awt.event.MouseEvent)
284
         */
285
        public void mouseReleased(MouseEvent e) throws BehaviorException {
286
                getMapControl().repaint();
287
        }
288

    
289
        /**
290
         * @see java.awt.event.MouseMotionListener#mouseDragged(java.awt.event.MouseEvent)
291
         */
292
        public void mouseDragged(MouseEvent e) throws BehaviorException {
293
                lastX = e.getX();
294
                lastY = e.getY();
295

    
296
                calculateSnapPoint(e.getPoint());
297
        }
298

    
299
        /**
300
         * @see java.awt.event.MouseMotionListener#mouseMoved(java.awt.event.MouseEvent)
301
         */
302
        public void mouseMoved(MouseEvent e) throws BehaviorException {
303

    
304
                lastX = e.getX();
305
                lastY = e.getY();
306

    
307
                calculateSnapPoint(e.getPoint());
308

    
309
                showCoords(e.getPoint());
310

    
311
                getMapControl().repaint();
312
        }
313

    
314
        private void showCoords(Point2D pPix)
315
        {
316
                String[] axisText = new String[2];
317
                NumberFormat nf = NumberFormat.getInstance();
318
                MapControl mapControl = getMapControl();
319
                ViewPort vp = mapControl.getMapContext().getViewPort();
320
                IProjection iProj = vp.getProjection();
321
                if (iProj.getAbrev().equals("EPSG:4326") || iProj.getAbrev().equals("EPSG:4230")) {
322
                        axisText[0] = "Lon = ";
323
                        axisText[1] = "Lat = ";
324
                        nf.setMaximumFractionDigits(8);
325
                } else {
326
                        axisText[0] = "X = ";
327
                        axisText[1] = "Y = ";
328
                        nf.setMaximumFractionDigits(2);
329
                }
330
                Point2D p;
331
                if (mapAdjustedPoint == null)
332
                {
333
                        p = vp.toMapPoint(pPix);
334
                }
335
                else
336
                {
337
                        p = mapAdjustedPoint;
338
                }
339
                MainFrame mF = PluginServices.getMainFrame();
340

    
341
                if (mF != null)
342
                {
343
            mF.getStatusBar().setMessage("units",
344
                            PluginServices.getText(this, FConstant.NAMES[vp.getDistanceUnits()]));
345
            mF.getStatusBar().setControlValue("scale",String.valueOf(mapControl.getMapContext().getScaleView()));
346
                        mF.getStatusBar().setMessage("projection", iProj.getAbrev());
347

    
348
                        mF.getStatusBar().setMessage("x",
349
                                        axisText[0] + String.valueOf(nf.format(p.getX()/MapContext.CHANGEM[vp.getDistanceUnits()])));
350
                        mF.getStatusBar().setMessage("y",
351
                                        axisText[1] + String.valueOf(nf.format(p.getY()/MapContext.CHANGEM[vp.getDistanceUnits()])));
352
                }
353
        }
354

    
355
        private void clearMouseImage() {
356
                int[] pixels = new int[16 * 16];
357
                Image image = Toolkit.getDefaultToolkit().createImage(
358
                                new MemoryImageSource(16, 16, pixels, 0, 16));
359
                Cursor transparentCursor = Toolkit.getDefaultToolkit()
360
                                .createCustomCursor(image, new Point(0, 0), "invisiblecursor");
361

    
362
                getMapControl().setCursor(transparentCursor);
363
        }
364

    
365
        /**
366
         * DOCUMENT ME!
367
         *
368
         * @param g
369
         *            DOCUMENT ME!
370
         */
371
        private void drawCursor(Graphics g) {
372

    
373
                Point2D p = adjustedPoint;
374

    
375
                if (p == null) {
376
                        getGrid().setViewPort(getMapControl().getViewPort());
377

    
378
                        return;
379
                }
380

    
381
                int size1 = 15;
382
                int size2 = 3;
383
                g.drawLine((int) (p.getX() - size1), (int) (p.getY()),
384
                                (int) (p.getX() + size1), (int) (p.getY()));
385
                g.drawLine((int) (p.getX()), (int) (p.getY() - size1),
386
                                (int) (p.getX()), (int) (p.getY() + size1));
387

    
388
                // getMapControl().setToolTipText(null);
389
                if (adjustedPoint != null) {
390
                        if (bForceCoord) {
391
                                /* g.setColor(Color.ORANGE);
392
                                g.drawRect((int) (adjustedPoint.getX() - 6),
393
                                                (int) (adjustedPoint.getY() - 6), 12, 12);
394
                                g.drawRect((int) (adjustedPoint.getX() - 3),
395
                                                (int) (adjustedPoint.getY() - 3), 6, 6);
396
                                g.setColor(Color.MAGENTA);
397
                                g.drawRect((int) (adjustedPoint.getX() - 4),
398
                                                (int) (adjustedPoint.getY() - 4), 8, 8); */
399
                                if (usedSnap != null)
400
                                {
401
                                        usedSnap.draw(g, adjustedPoint);
402

    
403
                                        Graphics2D g2 = (Graphics2D) g;
404
                                FontMetrics metrics = g2.getFontMetrics();
405
                                int w = metrics.stringWidth(usedSnap.getToolTipText()) + 5;
406
                                int h = metrics.getMaxAscent() + 5;
407
                                int x = (int)p.getX()+9;
408
                                int y = (int)p.getY()- 7;
409

    
410
                                g2.setColor(theTipColor );
411
                                g2.fillRect(x, y-h, w, h);
412
                                g2.setColor(Color.BLACK);
413
                                g2.drawRect(x, y-h, w, h);
414
                                        g2.drawString(usedSnap.getToolTipText(), x+3, y-3);
415

    
416

    
417
                                        // getMapControl().setToolTipText(usedSnap.getToolTipText());
418
                                }
419

    
420
                                bForceCoord = false;
421
                        } else {
422
                                g.drawRect((int) (p.getX() - size2), (int) (p.getY() - size2),
423
                                                (int) (size2 * 2), (int) (size2 * 2));
424
                        }
425
                }
426
        }
427

    
428
        /**
429
         * DOCUMENT ME!
430
         *
431
         * @param point
432
         */
433
        private void calculateSnapPoint(Point point) {
434
                // Se comprueba el ajuste a rejilla
435

    
436
                Point2D gridAdjustedPoint = getMapControl().getViewPort().toMapPoint(
437
                                point);
438
                double minDistance = Double.MAX_VALUE;
439
                CADTool ct = (CADTool) cadToolStack.peek();
440
                if (ct instanceof SelectionCADTool
441
                                && ((SelectionCADTool) ct).getStatus().equals(
442
                                                "Selection.FirstPoint")) {
443
                        mapAdjustedPoint = gridAdjustedPoint;
444
                        adjustedPoint = (Point2D) point.clone();
445
                } else {
446

    
447
                        minDistance = getGrid().adjustToGrid(gridAdjustedPoint);
448
                        if (minDistance < Double.MAX_VALUE) {
449
                                adjustedPoint = getMapControl().getViewPort().fromMapPoint(
450
                                                gridAdjustedPoint);
451
                                mapAdjustedPoint = gridAdjustedPoint;
452
                        } else {
453
                                mapAdjustedPoint = null;
454
                        }
455
                }
456
                Point2D handlerAdjustedPoint = null;
457

    
458
                // Se comprueba el ajuste a los handlers
459
                if (mapAdjustedPoint != null) {
460
                        handlerAdjustedPoint = (Point2D) mapAdjustedPoint.clone(); // getMapControl().getViewPort().toMapPoint(point);
461
                } else {
462
                        handlerAdjustedPoint = getMapControl().getViewPort().toMapPoint(
463
                                        point);
464
                }
465

    
466
                Point2D mapPoint = new Point2D.Double();
467
                double distance = adjustToHandler(handlerAdjustedPoint, mapPoint);
468

    
469
                if (distance < minDistance) {
470
                        bForceCoord = true;
471
                        adjustedPoint = getMapControl().getViewPort().fromMapPoint(mapPoint);
472
                        mapAdjustedPoint = mapPoint;
473
                        minDistance = distance;
474
                }
475

    
476
                // Si no hay ajuste
477
                if (minDistance == Double.MAX_VALUE) {
478
                        adjustedPoint = point;
479
                        mapAdjustedPoint = null;
480
                }
481

    
482
        }
483

    
484
        /**
485
         * @see java.awt.event.MouseWheelListener#mouseWheelMoved(java.awt.event.MouseWheelEvent)
486
         */
487
        public void mouseWheelMoved(MouseWheelEvent e) throws BehaviorException {
488
        }
489

    
490
        /**
491
         * M?todo que realiza las transiciones en las herramientas en funci?n de un
492
         * texto introducido en la consola
493
         *
494
         * @param text
495
         *            DOCUMENT ME!
496
         */
497
        public void textEntered(String text) {
498
                if (text == null) {
499
                        transition(PluginServices.getText(this,"cancel"));
500
                } else {
501
                        /*
502
                         * if ("".equals(text)) { transition("aceptar"); } else {
503
                         */
504
                        text = text.trim();
505
                        int type = ABSOLUTE;
506
                        String[] numbers = new String[1];
507
                        numbers[0] = text;
508
                        if (text.indexOf(",") != -1) {
509

    
510
                                numbers = text.split(",");
511
                                if (numbers[0].substring(0, 1).equals("@")) {
512
                                        numbers[0] = numbers[0].substring(1, numbers[0].length());
513
                                        type = RELATIVE_SCU;
514
                                        if (numbers[0].substring(0, 1).equals("*")) {
515
                                                type = RELATIVE_SCP;
516
                                                numbers[0] = numbers[0].substring(1, numbers[0]
517
                                                                .length());
518
                                        }
519
                                }
520
                        } else if (text.indexOf("<") != -1) {
521
                                type = POLAR_SCP;
522
                                numbers = text.split("<");
523
                                if (numbers[0].substring(0, 1).equals("@")) {
524
                                        numbers[0] = numbers[0].substring(1, numbers[0].length());
525
                                        type = POLAR_SCU;
526
                                        if (numbers[0].substring(0, 1).equals("*")) {
527
                                                type = POLAR_SCP;
528
                                                numbers[0] = numbers[0].substring(1, numbers[0]
529
                                                                .length());
530
                                        }
531
                                }
532
                        }
533

    
534
                        double[] values = null;
535

    
536
                        try {
537
                                if (numbers.length == 2) {
538
                                        // punto
539
                                        values = new double[] { Double.parseDouble(numbers[0]),
540
                                                        Double.parseDouble(numbers[1]) };
541
                                        transition(values, null, type);
542
                                } else if (numbers.length == 1) {
543
                                        // valor
544
                                        values = new double[] { Double.parseDouble(numbers[0]) };
545
                                        transition(values[0]);
546
                                }
547
                        } catch (NumberFormatException e) {
548
                                transition(text);
549
                        } catch (NullPointerException e) {
550
                                transition(text);
551
                        }
552
                        // }
553
                }
554
                getMapControl().repaint();
555
        }
556

    
557
        /**
558
         * DOCUMENT ME!
559
         */
560
        public void configureMenu() {
561
                String[] desc = ((CADTool) cadToolStack.peek()).getDescriptions();
562
                // String[] labels = ((CADTool)
563
                // cadToolStack.peek()).getCurrentTransitions();
564
                CADExtension.clearMenu();
565

    
566
                for (int i = 0; i < desc.length; i++) {
567
                        if (desc[i] != null) {
568
                                CADExtension
569
                                                .addMenuEntry(PluginServices.getText(this, desc[i]));// ,
570
                                // labels[i]);
571
                        }
572
                }
573

    
574
        }
575

    
576
        /**
577
         * Recibe los valores de la transici?n (normalmente un punto) y el evento
578
         * con el que se gener? (si fue de rat?n ser? MouseEvent, el que viene en el
579
         * pressed) y si es de teclado, ser? un KeyEvent. Del evento se puede sacar
580
         * informaci?n acerca de si estaba pulsada la tecla CTRL, o Alt, etc.
581
         *
582
         * @param values
583
         * @param event
584
         */
585
        private void transition(double[] values, InputEvent event, int type) {
586
                questionAsked = true;
587
                if (!cadToolStack.isEmpty()) {
588
                        CADTool ct = (CADTool) cadToolStack.peek();
589

    
590
                        switch (type) {
591
                        case ABSOLUTE:
592
                                ct.transition(values[0], values[1], event);
593
                                previousPoint = values;
594
                                break;
595
                        case RELATIVE_SCU:
596
                                // Comprobar que tenemos almacenado el punto anterior
597
                                // y crear nuevo con coordenadas relativas a ?l.
598
                                double[] auxSCU = values;
599
                                if (previousPoint != null) {
600
                                        auxSCU[0] = previousPoint[0] + values[0];
601
                                        auxSCU[1] = previousPoint[1] + values[1];
602
                                }
603
                                ct.transition(auxSCU[0], auxSCU[1], event);
604

    
605
                                previousPoint = auxSCU;
606
                                break;
607
                        case RELATIVE_SCP:
608
                                // TODO de momento no implementado.
609
                                ct.transition(values[0], values[1], event);
610
                                previousPoint = values;
611
                                break;
612
                        case POLAR_SCU:
613
                                // Comprobar que tenemos almacenado el punto anterior
614
                                // y crear nuevo con coordenadas relativas a ?l.
615
                                double[] auxPolarSCU = values;
616
                                if (previousPoint != null) {
617
                                        Point2D point = UtilFunctions.getPoint(new Point2D.Double(
618
                                                        previousPoint[0], previousPoint[1]), Math
619
                                                        .toRadians(values[1]), values[0]);
620
                                        auxPolarSCU[0] = point.getX();
621
                                        auxPolarSCU[1] = point.getY();
622
                                        ct.transition(auxPolarSCU[0], auxPolarSCU[1], event);
623
                                } else {
624
                                        Point2D point = UtilFunctions.getPoint(new Point2D.Double(
625
                                                        0, 0), Math.toRadians(values[1]), values[0]);
626
                                        auxPolarSCU[0] = point.getX();
627
                                        auxPolarSCU[1] = point.getY();
628
                                        ct.transition(auxPolarSCU[0], auxPolarSCU[1], event);
629
                                }
630
                                previousPoint = auxPolarSCU;
631
                                break;
632
                        case POLAR_SCP:
633
                                double[] auxPolarSCP = values;
634
                                if (previousPoint != null) {
635
                                        Point2D point = UtilFunctions.getPoint(new Point2D.Double(
636
                                                        previousPoint[0], previousPoint[1]), values[1],
637
                                                        values[0]);
638
                                        auxPolarSCP[0] = point.getX();
639
                                        auxPolarSCP[1] = point.getY();
640
                                        ct.transition(auxPolarSCP[0], auxPolarSCP[1], event);
641
                                } else {
642
                                        Point2D point = UtilFunctions.getPoint(new Point2D.Double(
643
                                                        0, 0), values[1], values[0]);
644
                                        auxPolarSCP[0] = point.getX();
645
                                        auxPolarSCP[1] = point.getY();
646
                                        ct.transition(auxPolarSCP[0], auxPolarSCP[1], event);
647
                                }
648
                                previousPoint = auxPolarSCP;
649
                                break;
650
                        default:
651
                                break;
652
                        }
653
                        askQuestion();
654
                }
655
                configureMenu();
656
                PluginServices.getMainFrame().enableControls();
657
        }
658

    
659
        /**
660
         * DOCUMENT ME!
661
         *
662
         * @param text
663
         *            DOCUMENT ME!
664
         * @param source
665
         *            DOCUMENT ME!
666
         * @param sel
667
         *            DOCUMENT ME!
668
         * @param values
669
         *            DOCUMENT ME!
670
         */
671
        private void transition(double value) {
672
                questionAsked = true;
673
                if (!cadToolStack.isEmpty()) {
674
                        CADTool ct = (CADTool) cadToolStack.peek();
675
                        ct.transition(value);
676
                        askQuestion();
677
                }
678
                configureMenu();
679
                PluginServices.getMainFrame().enableControls();
680
        }
681

    
682
        public void transition(String option) {
683
                questionAsked = true;
684
                if (!cadToolStack.isEmpty()) {
685
                        CADTool ct = (CADTool) cadToolStack.peek();
686
                        try {
687
                                ct.transition(option);
688
                        } catch (Exception e) {
689
                                IWindow window = (IWindow) PluginServices.getMDIManager()
690
                                                .getActiveWindow();
691

    
692
                                if (window instanceof View) {
693
                                        ((View)window).getConsolePanel().addText(
694
                                                "\n" + PluginServices.getText(this, "incorrect_option")
695
                                                                + " : " + option, JConsole.ERROR);
696
                                }
697
                        }
698
                        askQuestion();
699
                }
700
                configureMenu();
701
                PluginServices.getMainFrame().enableControls();
702
        }
703

    
704
        /**
705
         * DOCUMENT ME!
706
         *
707
         * @param value
708
         *            DOCUMENT ME!
709
         */
710
        public void setGridVisibility(boolean value) {
711
                getGrid().setShowGrid(value);
712
                getGrid().setViewPort(getMapControl().getViewPort());
713
                getMapControl().repaint();
714
        }
715

    
716
        public void setRefentEnabled(boolean activated) {
717
                bRefent = activated;
718
        }
719

    
720
        public boolean isRefentEnabled()
721
        {
722
                return bRefent;
723
        }
724

    
725
        /**
726
         * @see com.iver.cit.gvsig.fmap.tools.Behavior.Behavior#getListener()
727
         */
728
        public ToolListener getListener() {
729
                return new ToolListener() {
730
                        /**
731
                         * @see com.iver.cit.gvsig.fmap.tools.Listeners.ToolListener#getCursor()
732
                         */
733
                        public Cursor getCursor() {
734
                                return null;
735
                        }
736

    
737
                        /**
738
                         * @see com.iver.cit.gvsig.fmap.tools.Listeners.ToolListener#cancelDrawing()
739
                         */
740
                        public boolean cancelDrawing() {
741
                                return false;
742
                        }
743
                };
744
        }
745

    
746
        /**
747
         * DOCUMENT ME!
748
         *
749
         * @return DOCUMENT ME!
750
         */
751
        public CADTool getCadTool() {
752
                return (CADTool) cadToolStack.peek();
753
        }
754

    
755
        /**
756
         * DOCUMENT ME!
757
         *
758
         * @param cadTool
759
         *            DOCUMENT ME!
760
         */
761
        public void pushCadTool(CADTool cadTool) {
762
                cadToolStack.push(cadTool);
763
                cadTool.setCadToolAdapter(this);
764
                // cadTool.initializeStatus();
765
                // cadTool.setVectorialAdapter(vea);
766
                /*
767
                 * int ret = cadTool.transition(null, editableFeatureSource, selection,
768
                 * new double[0]);
769
                 *
770
                 * if ((ret & Automaton.AUTOMATON_FINISHED) ==
771
                 * Automaton.AUTOMATON_FINISHED) { popCadTool();
772
                 *
773
                 * if (cadToolStack.isEmpty()) { pushCadTool(new
774
                 * com.iver.cit.gvsig.gui.cad.smc.gen.CADTool());//new
775
                 * SelectionCadTool());
776
                 * PluginServices.getMainFrame().setSelectedTool("selection"); }
777
                 *
778
                 * askQuestion();
779
                 *
780
                 * getMapControl().drawMap(false); }
781
                 */
782
        }
783

    
784
        /**
785
         * DOCUMENT ME!
786
         */
787
        public void popCadTool() {
788
                cadToolStack.pop();
789
        }
790

    
791
        /**
792
         * DOCUMENT ME!
793
         */
794
        public void askQuestion() {
795
                CADTool cadtool = (CADTool) cadToolStack.peek();
796
                /*
797
                 * if (cadtool..getStatus()==0){
798
                 * PluginServices.getMainFrame().addTextToConsole("\n"
799
                 * +cadtool.getName()); }
800
                 */
801
                if (PluginServices.getMDIManager().getActiveWindow() instanceof View)
802
                {
803
                        View vista = (View) PluginServices.getMDIManager().getActiveWindow();
804
                        vista.getConsolePanel().addText(
805
                                        "\n" + "#" + cadtool.getQuestion() + " > ", JConsole.MESSAGE);
806
                        // ***PluginServices.getMainFrame().addTextToConsole("\n" +
807
                        // cadtool.getQuestion());
808
                        questionAsked = true;
809
                }
810

    
811
        }
812

    
813
        /**
814
         * DOCUMENT ME!
815
         *
816
         * @param cadTool
817
         *            DOCUMENT ME!
818
         */
819
        public void setCadTool(CADTool cadTool) {
820
                cadToolStack.clear();
821
                pushCadTool(cadTool);
822
                // askQuestion();
823
        }
824

    
825

    
826
        /**
827
         * Elimina las geometr?as seleccionadas actualmente
828
         */
829
        private void delete() {
830
                ILayerEdited aux = CADExtension.getEditionManager().getActiveLayerEdited();
831
                if (!(aux instanceof VectorialLayerEdited))
832
                        return;
833
                VectorialLayerEdited vle = (VectorialLayerEdited) aux;
834
                VectorialEditableAdapter vea = vle.getVEA();
835

    
836
                vea.startComplexRow();
837
                FBitSet selection = vea.getSelection();
838
                try {
839
                        int[] indexesToDel = new int[selection.cardinality()];
840
                        int j = 0;
841
                        for (int i = selection.nextSetBit(0); i >= 0; i = selection
842
                                        .nextSetBit(i + 1)) {
843
                                indexesToDel[j++] = i;
844
                                // /vea.removeRow(i);
845
                        }
846

    
847
//                          ArrayList selectedRow = vle.getSelectedRow();
848
//
849
//                          int[] indexesToDel = new int[selectedRow.size()];
850
//                          for (int i = 0;i < selectedRow.size(); i++) {
851
//                                  IRowEdited edRow = (IRowEdited) selectedRow.get(i);
852
//                                  indexesToDel[i] = vea.getInversedIndex(edRow.getIndex());
853
//                                  }
854
//
855
                        for (int i = indexesToDel.length - 1; i >= 0; i--) {
856
                                vea.removeRow(indexesToDel[i], PluginServices.getText(this,
857
                                                "deleted_feature"),EditionEvent.GRAPHIC);
858
                        }
859
                } catch (DriverIOException e) {
860
                        NotificationManager.addError(e.getMessage(), e);
861
                } catch (IOException e) {
862
                        NotificationManager.addError(e.getMessage(), e);
863
                } finally {
864
                        try {
865
                                String description=PluginServices.getText(this,"remove_geometry");
866
                                vea.endComplexRow(description);
867
                        } catch (IOException e1) {
868
                                NotificationManager.addError(e1.getMessage(), e1);
869
                        } catch (DriverIOException e1) {
870
                                NotificationManager.addError(e1.getMessage(), e1);
871
                        }
872
                }
873
                System.out.println("clear Selection");
874
                selection.clear();
875
                vle.clearSelection();
876
                /*
877
                 * if (getCadTool() instanceof SelectionCADTool) { SelectionCADTool
878
                 * selTool = (SelectionCADTool) getCadTool(); selTool.clearSelection(); }
879
                 */
880
                refreshEditedLayer();
881
        }
882

    
883
        /**
884
         * DOCUMENT ME!
885
         *
886
         * @param b
887
         */
888
        public void setAdjustGrid(boolean b) {
889
                getGrid().setAdjustGrid(b);
890
        }
891

    
892
        /**
893
         * DOCUMENT ME!
894
         *
895
         * @param actionCommand
896
         */
897
        public void keyPressed(String actionCommand) {
898
                if (CADExtension.getEditionManager().getActiveLayerEdited()== null) {
899
                        return;
900
                }
901
                if (actionCommand.equals("eliminar")) {
902
                        delete();
903
                } else if (actionCommand.equals("escape")) {
904
                        if (getMapControl().getCurrentTool().equals("cadtooladapter")) {
905
                                CADTool ct = (CADTool) cadToolStack.peek();
906
                                ct.end();
907
                                cadToolStack.clear();
908
                                SelectionCADTool selCad = new SelectionCADTool();
909
                                selCad.init();
910
                                VectorialLayerEdited vle = (VectorialLayerEdited) CADExtension
911
                                                .getEditionManager().getActiveLayerEdited();
912
                                vle.clearSelection();
913

    
914
                                pushCadTool(selCad);
915
                                // getVectorialAdapter().getSelection().clear();
916

    
917
                                refreshEditedLayer();
918

    
919

    
920
                                PluginServices.getMainFrame().setSelectedTool("_selection");
921
                                // askQuestion();
922
                        } else {
923
                                getMapControl().setPrevTool();
924
                        }
925
                }
926

    
927
                PluginServices.getMainFrame().enableControls();
928

    
929
        }
930

    
931
        /**
932
         * Provoca un repintado "soft" de la capa activa en edici?n.
933
         * Las capas por debajo de ella no se dibujan de verdad, solo
934
         * se dibuja la que est? en edici?n y las que est?n por encima
935
         * de ella en el TOC.
936
         */
937
        public void refreshEditedLayer()
938
        {
939
                ILayerEdited edLayer = CADExtension.getEditionManager().getActiveLayerEdited();
940
                if (edLayer != null)
941
                {
942
                        edLayer.getLayer().setDirty(true);
943
                        getMapControl().rePaintDirtyLayers();
944
                }
945

    
946
        }
947

    
948
        public CADGrid getGrid() {
949
                return cadgrid;
950
        }
951

    
952
        public boolean isOrtoMode() {
953
                return bOrtoMode;
954
        }
955

    
956
        public void setOrtoMode(boolean b) {
957
                bOrtoMode = b;
958
        }
959

    
960
        public static void addCADTool(String name, CADTool c) {
961
                namesCadTools.put(name, c);
962

    
963
        }
964
        public static CADTool[] getCADTools() {
965
                return (CADTool[]) CADToolAdapter.namesCadTools.values().toArray(new CADTool[0]);
966
        }
967
        public CADTool getCADTool(String text) {
968
                CADTool ct = (CADTool) namesCadTools.get(text);
969
                return ct;
970
        }
971

    
972
        public EditionManager getEditionManager() {
973
                return editionManager;
974
        }
975

    
976
        public void initializeFlatness() {
977
                if (!flatnessInitialized){
978
                        flatnessInitialized=true;
979
                        Preferences prefs = Preferences.userRoot().node( "cadtooladapter" );
980
                        double flatness = prefs.getDouble("flatness",FConverter.FLATNESS);
981
                        FConverter.FLATNESS=flatness;
982
                }
983
        }
984
        public void initializeGrid(){
985
                boolean showGrid = prefs.getBoolean("grid.showgrid",getGrid().isShowGrid());
986
                boolean adjustGrid = prefs.getBoolean("grid.adjustgrid",getGrid().isAdjustGrid());
987

    
988
                double dx = prefs.getDouble("grid.distancex",getGrid().getGridSizeX());
989
                double dy = prefs.getDouble("grid.distancey",getGrid().getGridSizeY());
990

    
991
                setGridVisibility(showGrid);
992
                setAdjustGrid(adjustGrid);
993
                getGrid().setGridSizeX(dx);
994
                getGrid().setGridSizeY(dy);
995
        }
996
        /**
997
        * Returns the type of active layer.
998
        **/
999
        public int getActiveLayerType() {
1000
                int type=FShape.MULTI;
1001
                try {
1002
                        type=((FLyrVect)CADExtension.getEditionManager().getActiveLayerEdited().getLayer()).getShapeType();
1003
                } catch (DriverException e) {
1004
                        NotificationManager.addError(e);
1005
                }
1006
                return type;
1007
        }
1008

    
1009
}