Statistics
| Revision:

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

History | View | Annotate | Download (27.1 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.ui.mdiFrame.MainFrame;
28
import com.iver.cit.gvsig.CADExtension;
29
import com.iver.cit.gvsig.EditionManager;
30
import com.iver.cit.gvsig.fmap.MapContext;
31
import com.iver.cit.gvsig.fmap.MapControl;
32
import com.iver.cit.gvsig.fmap.ViewPort;
33
import com.iver.cit.gvsig.fmap.core.v02.FConstant;
34
import com.iver.cit.gvsig.fmap.core.v02.FConverter;
35
import com.iver.cit.gvsig.fmap.core.v02.FSymbol;
36
import com.iver.cit.gvsig.fmap.drivers.DriverIOException;
37
import com.iver.cit.gvsig.fmap.edition.EditionEvent;
38
import com.iver.cit.gvsig.fmap.edition.UtilFunctions;
39
import com.iver.cit.gvsig.fmap.edition.VectorialEditableAdapter;
40
import com.iver.cit.gvsig.fmap.layers.FBitSet;
41
import com.iver.cit.gvsig.fmap.layers.FLyrVect;
42
import com.iver.cit.gvsig.fmap.layers.SpatialCache;
43
import com.iver.cit.gvsig.fmap.tools.BehaviorException;
44
import com.iver.cit.gvsig.fmap.tools.Behavior.Behavior;
45
import com.iver.cit.gvsig.fmap.tools.Listeners.ToolListener;
46
import com.iver.cit.gvsig.gui.cad.snapping.FinalPointSnapper;
47
import com.iver.cit.gvsig.gui.cad.snapping.ISnapper;
48
import com.iver.cit.gvsig.gui.cad.snapping.ISnapperRaster;
49
import com.iver.cit.gvsig.gui.cad.snapping.ISnapperVectorial;
50
import com.iver.cit.gvsig.gui.cad.snapping.NearestPointSnapper;
51
import com.iver.cit.gvsig.gui.cad.snapping.PixelSnapper;
52
import com.iver.cit.gvsig.gui.cad.snapping.SnappingVisitor;
53
import com.iver.cit.gvsig.gui.cad.tools.SelectionCADTool;
54
import com.iver.cit.gvsig.layers.ILayerEdited;
55
import com.iver.cit.gvsig.layers.VectorialLayerEdited;
56
import com.iver.cit.gvsig.project.documents.view.gui.View;
57
import com.iver.utiles.console.JConsole;
58
import com.vividsolutions.jts.geom.Envelope;
59

    
60
public class CADToolAdapter extends Behavior {
61
        private static HashMap namesCadTools = new HashMap();
62

    
63
        private EditionManager editionManager = new EditionManager();
64

    
65
        public static final int ABSOLUTE = 0;
66

    
67
        public static final int RELATIVE_SCP = 1;
68

    
69
        public static final int RELATIVE_SCU = 2;
70

    
71
        public static final int POLAR_SCP = 3;
72

    
73
        public static final int POLAR_SCU = 4;
74

    
75
        private double[] previousPoint = null;
76

    
77
        private Stack cadToolStack = new Stack();
78

    
79
        // Para pasarle las coordenadas cuando se produce un evento textEntered
80
        private int lastX;
81

    
82
        private int lastY;
83

    
84
        private FSymbol symbol = new FSymbol(FConstant.SYMBOL_TYPE_POINT, Color.RED);
85

    
86
        private Point2D mapAdjustedPoint;
87

    
88
        private ISnapper usedSnap = null;
89

    
90
        private boolean questionAsked = false;
91

    
92
        private Point2D adjustedPoint;
93

    
94
        private boolean bRefent = true;
95

    
96
        private boolean bForceCoord = false;
97

    
98
        private CADGrid cadgrid = new CADGrid();
99

    
100
        private boolean bOrtoMode;
101

    
102
        private Color theTipColor = new Color(255, 255, 155);
103

    
104
        private static boolean flatnessInitialized=false;
105
        private static Preferences prefs = Preferences.userRoot().node( "cadtooladapter" );
106

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

    
128
                        ((CADTool) cadToolStack.peek())
129
                                        .drawOperation(g, p.getX(), p.getY());
130
                }
131
        }
132

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

    
142
        /**
143
         * @see java.awt.event.MouseListener#mouseEntered(java.awt.event.MouseEvent)
144
         */
145
        public void mouseEntered(MouseEvent e) throws BehaviorException {
146
                clearMouseImage();
147
        }
148

    
149
        /**
150
         * @see java.awt.event.MouseListener#mouseExited(java.awt.event.MouseEvent)
151
         */
152
        public void mouseExited(MouseEvent e) throws BehaviorException {
153
        }
154

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

    
163
                        if (mapAdjustedPoint != null) {
164
                                p = mapAdjustedPoint;
165
                        } else {
166
                                p = vp.toMapPoint(adjustedPoint);
167
                        }
168
                        transition(new double[] { p.getX(), p.getY() }, e, ABSOLUTE);
169
                }
170
        }
171

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

    
187
                if (!isRefentEnabled())
188
                        return Double.MAX_VALUE;
189

    
190
                ILayerEdited aux = CADExtension.getEditionManager().getActiveLayerEdited();
191
                if (!(aux instanceof VectorialLayerEdited))
192
                        return Double.MAX_VALUE;
193
                VectorialLayerEdited vle = (VectorialLayerEdited) aux;
194

    
195
                ArrayList snappers = vle.getSnappers();
196
                ArrayList layersToSnap = vle.getLayersToSnap();
197

    
198

    
199
                ViewPort vp = getMapControl().getViewPort();
200

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

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

    
218
                Envelope e = FConverter.convertRectangle2DtoEnvelope(r);
219

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

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

    
259

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

    
276
        }
277

    
278
        /**
279
         * @see java.awt.event.MouseListener#mouseReleased(java.awt.event.MouseEvent)
280
         */
281
        public void mouseReleased(MouseEvent e) throws BehaviorException {
282
                getMapControl().repaint();
283
        }
284

    
285
        /**
286
         * @see java.awt.event.MouseMotionListener#mouseDragged(java.awt.event.MouseEvent)
287
         */
288
        public void mouseDragged(MouseEvent e) throws BehaviorException {
289
                lastX = e.getX();
290
                lastY = e.getY();
291

    
292
                calculateSnapPoint(e.getPoint());
293
        }
294

    
295
        /**
296
         * @see java.awt.event.MouseMotionListener#mouseMoved(java.awt.event.MouseEvent)
297
         */
298
        public void mouseMoved(MouseEvent e) throws BehaviorException {
299

    
300
                lastX = e.getX();
301
                lastY = e.getY();
302

    
303
                calculateSnapPoint(e.getPoint());
304

    
305
                showCoords(e.getPoint());
306

    
307
                getMapControl().repaint();
308
        }
309

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

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

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

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

    
358
                getMapControl().setCursor(transparentCursor);
359
        }
360

    
361
        /**
362
         * DOCUMENT ME!
363
         *
364
         * @param g
365
         *            DOCUMENT ME!
366
         */
367
        private void drawCursor(Graphics g) {
368

    
369
                Point2D p = adjustedPoint;
370

    
371
                if (p == null) {
372
                        getGrid().setViewPort(getMapControl().getViewPort());
373

    
374
                        return;
375
                }
376

    
377
                int size1 = 15;
378
                int size2 = 3;
379
                g.drawLine((int) (p.getX() - size1), (int) (p.getY()),
380
                                (int) (p.getX() + size1), (int) (p.getY()));
381
                g.drawLine((int) (p.getX()), (int) (p.getY() - size1),
382
                                (int) (p.getX()), (int) (p.getY() + size1));
383

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

    
399
                                        Graphics2D g2 = (Graphics2D) g;
400
                                FontMetrics metrics = g2.getFontMetrics();
401
                                int w = metrics.stringWidth(usedSnap.getToolTipText()) + 5;
402
                                int h = metrics.getMaxAscent() + 5;
403
                                int x = (int)p.getX()+9;
404
                                int y = (int)p.getY()- 7;
405

    
406
                                g2.setColor(theTipColor );
407
                                g2.fillRect(x, y-h, w, h);
408
                                g2.setColor(Color.BLACK);
409
                                g2.drawRect(x, y-h, w, h);
410
                                        g2.drawString(usedSnap.getToolTipText(), x+3, y-3);
411

    
412

    
413
                                        // getMapControl().setToolTipText(usedSnap.getToolTipText());
414
                                }
415

    
416
                                bForceCoord = false;
417
                        } else {
418
                                g.drawRect((int) (p.getX() - size2), (int) (p.getY() - size2),
419
                                                (int) (size2 * 2), (int) (size2 * 2));
420
                        }
421
                }
422
        }
423

    
424
        /**
425
         * DOCUMENT ME!
426
         *
427
         * @param point
428
         */
429
        private void calculateSnapPoint(Point point) {
430
                // Se comprueba el ajuste a rejilla
431

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

    
443
                        minDistance = getGrid().adjustToGrid(gridAdjustedPoint);
444
                        if (minDistance < Double.MAX_VALUE) {
445
                                adjustedPoint = getMapControl().getViewPort().fromMapPoint(
446
                                                gridAdjustedPoint);
447
                                mapAdjustedPoint = gridAdjustedPoint;
448
                        } else {
449
                                mapAdjustedPoint = null;
450
                        }
451
                }
452
                Point2D handlerAdjustedPoint = null;
453

    
454
                // Se comprueba el ajuste a los handlers
455
                if (mapAdjustedPoint != null) {
456
                        handlerAdjustedPoint = (Point2D) mapAdjustedPoint.clone(); // getMapControl().getViewPort().toMapPoint(point);
457
                } else {
458
                        handlerAdjustedPoint = getMapControl().getViewPort().toMapPoint(
459
                                        point);
460
                }
461

    
462
                Point2D mapPoint = new Point2D.Double();
463
                double distance = adjustToHandler(handlerAdjustedPoint, mapPoint);
464

    
465
                if (distance < minDistance) {
466
                        bForceCoord = true;
467
                        adjustedPoint = getMapControl().getViewPort().fromMapPoint(mapPoint);
468
                        mapAdjustedPoint = mapPoint;
469
                        minDistance = distance;
470
                }
471

    
472
                // Si no hay ajuste
473
                if (minDistance == Double.MAX_VALUE) {
474
                        adjustedPoint = point;
475
                        mapAdjustedPoint = null;
476
                }
477

    
478
        }
479

    
480
        /**
481
         * @see java.awt.event.MouseWheelListener#mouseWheelMoved(java.awt.event.MouseWheelEvent)
482
         */
483
        public void mouseWheelMoved(MouseWheelEvent e) throws BehaviorException {
484
        }
485

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

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

    
530
                        double[] values = null;
531

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

    
553
        /**
554
         * DOCUMENT ME!
555
         */
556
        public void configureMenu() {
557
                String[] desc = ((CADTool) cadToolStack.peek()).getDescriptions();
558
                // String[] labels = ((CADTool)
559
                // cadToolStack.peek()).getCurrentTransitions();
560
                CADExtension.clearMenu();
561

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

    
570
        }
571

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

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

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

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

    
678
        public void transition(String option) {
679
                questionAsked = true;
680
                if (!cadToolStack.isEmpty()) {
681
                        CADTool ct = (CADTool) cadToolStack.peek();
682
                        try {
683
                                ct.transition(option);
684
                        } catch (Exception e) {
685
                                View vista = (View) PluginServices.getMDIManager()
686
                                                .getActiveWindow();
687
                                vista.getConsolePanel().addText(
688
                                                "\n" + PluginServices.getText(this, "incorrect_option")
689
                                                                + " : " + option, JConsole.ERROR);
690
                        }
691
                        askQuestion();
692
                }
693
                configureMenu();
694
                PluginServices.getMainFrame().enableControls();
695
        }
696

    
697
        /**
698
         * DOCUMENT ME!
699
         *
700
         * @param value
701
         *            DOCUMENT ME!
702
         */
703
        public void setGridVisibility(boolean value) {
704
                getGrid().setShowGrid(value);
705
                getGrid().setViewPort(getMapControl().getViewPort());
706
                getMapControl().repaint();
707
        }
708

    
709
        public void setRefentEnabled(boolean activated) {
710
                bRefent = activated;
711
        }
712

    
713
        public boolean isRefentEnabled()
714
        {
715
                return bRefent;
716
        }
717

    
718
        /**
719
         * @see com.iver.cit.gvsig.fmap.tools.Behavior.Behavior#getListener()
720
         */
721
        public ToolListener getListener() {
722
                return new ToolListener() {
723
                        /**
724
                         * @see com.iver.cit.gvsig.fmap.tools.Listeners.ToolListener#getCursor()
725
                         */
726
                        public Cursor getCursor() {
727
                                return null;
728
                        }
729

    
730
                        /**
731
                         * @see com.iver.cit.gvsig.fmap.tools.Listeners.ToolListener#cancelDrawing()
732
                         */
733
                        public boolean cancelDrawing() {
734
                                return false;
735
                        }
736
                };
737
        }
738

    
739
        /**
740
         * DOCUMENT ME!
741
         *
742
         * @return DOCUMENT ME!
743
         */
744
        public CADTool getCadTool() {
745
                return (CADTool) cadToolStack.peek();
746
        }
747

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

    
777
        /**
778
         * DOCUMENT ME!
779
         */
780
        public void popCadTool() {
781
                cadToolStack.pop();
782
        }
783

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

    
804
        }
805

    
806
        /**
807
         * DOCUMENT ME!
808
         *
809
         * @param cadTool
810
         *            DOCUMENT ME!
811
         */
812
        public void setCadTool(CADTool cadTool) {
813
                cadToolStack.clear();
814
                pushCadTool(cadTool);
815
                // askQuestion();
816
        }
817

    
818

    
819
        /**
820
         * Elimina las geometr?as seleccionadas actualmente
821
         */
822
        private void delete() {
823
                ILayerEdited aux = CADExtension.getEditionManager().getActiveLayerEdited();
824
                if (!(aux instanceof VectorialLayerEdited))
825
                        return;
826
                VectorialLayerEdited vle = (VectorialLayerEdited) aux;
827
                VectorialEditableAdapter vea = vle.getVEA();
828

    
829
                vea.startComplexRow();
830
                FBitSet selection = vea.getSelection();
831
                try {
832
                        int[] indexesToDel = new int[selection.cardinality()];
833
                        int j = 0;
834
                        for (int i = selection.nextSetBit(0); i >= 0; i = selection
835
                                        .nextSetBit(i + 1)) {
836
                                indexesToDel[j++] = i;
837
                                // /vea.removeRow(i);
838
                        }
839

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

    
876
        /**
877
         * DOCUMENT ME!
878
         *
879
         * @param b
880
         */
881
        public void setAdjustGrid(boolean b) {
882
                getGrid().setAdjustGrid(b);
883
        }
884

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

    
907
                                pushCadTool(selCad);
908
                                // getVectorialAdapter().getSelection().clear();
909

    
910
                                refreshEditedLayer();
911

    
912

    
913
                                PluginServices.getMainFrame().setSelectedTool("_selection");
914
                                // askQuestion();
915
                        } else {
916
                                getMapControl().setPrevTool();
917
                        }
918
                }
919

    
920
                PluginServices.getMainFrame().enableControls();
921

    
922
        }
923

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

    
939
        }
940

    
941
        public CADGrid getGrid() {
942
                return cadgrid;
943
        }
944

    
945
        public boolean isOrtoMode() {
946
                return bOrtoMode;
947
        }
948

    
949
        public void setOrtoMode(boolean b) {
950
                bOrtoMode = b;
951
        }
952

    
953
        public static void addCADTool(String name, CADTool c) {
954
                namesCadTools.put(name, c);
955

    
956
        }
957
        public static CADTool[] getCADTools() {
958
                return (CADTool[]) CADToolAdapter.namesCadTools.values().toArray(new CADTool[0]);
959
        }
960
        public CADTool getCADTool(String text) {
961
                CADTool ct = (CADTool) namesCadTools.get(text);
962
                return ct;
963
        }
964

    
965
        public EditionManager getEditionManager() {
966
                return editionManager;
967
        }
968

    
969
        public void initializeFlatness() {
970
                if (!flatnessInitialized){
971
                        flatnessInitialized=true;
972
                        Preferences prefs = Preferences.userRoot().node( "cadtooladapter" );
973
                        double flatness = prefs.getDouble("flatness",FConverter.FLATNESS);
974
                        FConverter.FLATNESS=flatness;
975
                }
976
        }
977
        public void initializeGrid(){
978
                boolean showGrid = prefs.getBoolean("grid.showgrid",getGrid().isShowGrid());
979
                boolean adjustGrid = prefs.getBoolean("grid.adjustgrid",getGrid().isAdjustGrid());
980

    
981
                double dx = prefs.getDouble("grid.distancex",getGrid().getGridSizeX());
982
                double dy = prefs.getDouble("grid.distancey",getGrid().getGridSizeY());
983

    
984
                setGridVisibility(showGrid);
985
                setAdjustGrid(adjustGrid);
986
                getGrid().setGridSizeX(dx);
987
                getGrid().setGridSizeY(dy);
988
        }
989

    
990
}