Statistics
| Revision:

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

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
                if (adjustedPoint != null) {
123
                        Point2D p = null;
124
                        if (mapAdjustedPoint != null) {
125
                                p = mapAdjustedPoint;
126
                        } else {
127
                                p = getMapControl().getViewPort().toMapPoint(adjustedPoint);
128
                        }
129

    
130
                        ((CADTool) cadToolStack.peek())
131
                                        .drawOperation(g, p.getX(), p.getY());
132
                }
133
                drawCursor(g);
134
                getGrid().drawGrid(g);
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
                Point2D p = adjustedPoint;
373

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

    
377
                        return;
378
                }
379

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

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

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

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

    
415

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

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

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

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

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

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

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

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

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

    
481
        }
482

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

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

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

    
533
                        double[] values = null;
534

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

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

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

    
573
        }
574

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
810
        }
811

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

    
824

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

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

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

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

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

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

    
916
                                refreshEditedLayer();
917

    
918

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

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

    
928
        }
929

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

    
945
        }
946

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

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

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

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

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

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

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

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

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

    
1008
}