Statistics
| Revision:

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

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

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

    
66
        private EditionManager editionManager = new EditionManager();
67

    
68
        public static final int ABSOLUTE = 0;
69

    
70
        public static final int RELATIVE_SCP = 1;
71

    
72
        public static final int RELATIVE_SCU = 2;
73

    
74
        public static final int POLAR_SCP = 3;
75

    
76
        public static final int POLAR_SCU = 4;
77

    
78
        private double[] previousPoint = null;
79

    
80
        private Stack cadToolStack = new Stack();
81

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

    
85
        private int lastY;
86

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

    
89
        private Point2D mapAdjustedPoint;
90

    
91
        private ISnapper usedSnap = null;
92

    
93
        private boolean questionAsked = false;
94

    
95
        private Point2D adjustedPoint;
96

    
97
        private boolean bRefent = true;
98

    
99
        private boolean bForceCoord = false;
100

    
101
        private CADGrid cadgrid = new CADGrid();
102

    
103
        private boolean bOrtoMode;
104

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

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

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

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

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

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

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

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

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

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

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

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

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

    
201

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

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

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

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

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

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

    
262

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

    
279
        }
280

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

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

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

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

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

    
306
                calculateSnapPoint(e.getPoint());
307

    
308
                showCoords(e.getPoint());
309

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

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

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

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

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

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

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

    
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
                                View vista = (View) PluginServices.getMDIManager()
689
                                                .getActiveWindow();
690
                                vista.getConsolePanel().addText(
691
                                                "\n" + PluginServices.getText(this, "incorrect_option")
692
                                                                + " : " + option, JConsole.ERROR);
693
                        }
694
                        askQuestion();
695
                }
696
                configureMenu();
697
                PluginServices.getMainFrame().enableControls();
698
        }
699

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

    
712
        public void setRefentEnabled(boolean activated) {
713
                bRefent = activated;
714
        }
715

    
716
        public boolean isRefentEnabled()
717
        {
718
                return bRefent;
719
        }
720

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

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

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

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

    
780
        /**
781
         * DOCUMENT ME!
782
         */
783
        public void popCadTool() {
784
                cadToolStack.pop();
785
        }
786

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

    
807
        }
808

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

    
821

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

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

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

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

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

    
910
                                pushCadTool(selCad);
911
                                // getVectorialAdapter().getSelection().clear();
912

    
913
                                refreshEditedLayer();
914

    
915

    
916
                                PluginServices.getMainFrame().setSelectedTool("_selection");
917
                                // askQuestion();
918
                        } else {
919
                                getMapControl().setPrevTool();
920
                        }
921
                }
922

    
923
                PluginServices.getMainFrame().enableControls();
924

    
925
        }
926

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

    
942
        }
943

    
944
        public CADGrid getGrid() {
945
                return cadgrid;
946
        }
947

    
948
        public boolean isOrtoMode() {
949
                return bOrtoMode;
950
        }
951

    
952
        public void setOrtoMode(boolean b) {
953
                bOrtoMode = b;
954
        }
955

    
956
        public static void addCADTool(String name, CADTool c) {
957
                namesCadTools.put(name, c);
958

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

    
968
        public EditionManager getEditionManager() {
969
                return editionManager;
970
        }
971

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

    
984
                double dx = prefs.getDouble("grid.distancex",getGrid().getGridSizeX());
985
                double dy = prefs.getDouble("grid.distancey",getGrid().getGridSizeY());
986

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

    
1005
}