Statistics
| Revision:

svn-gvsig-desktop / trunk / extensions / extCAD / src / com / iver / cit / gvsig / gui / cad / CADToolAdapter.java @ 12296

History | View | Annotate | Download (28.4 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.util.ArrayList;
18
import java.util.HashMap;
19
import java.util.Stack;
20
import java.util.prefs.Preferences;
21

    
22
import org.cresques.cts.IProjection;
23

    
24
import com.hardcode.gdbms.driver.exceptions.ReadDriverException;
25
import com.iver.andami.PluginServices;
26
import com.iver.andami.messages.NotificationManager;
27
import com.iver.andami.ui.mdiFrame.MainFrame;
28
import com.iver.cit.gvsig.CADExtension;
29
import com.iver.cit.gvsig.EditionManager;
30
import com.iver.cit.gvsig.exceptions.expansionfile.ExpansionFileReadException;
31
import com.iver.cit.gvsig.fmap.MapControl;
32
import com.iver.cit.gvsig.fmap.ViewPort;
33
import com.iver.cit.gvsig.fmap.core.FShape;
34
import com.iver.cit.gvsig.fmap.core.SymbologyFactory;
35
import com.iver.cit.gvsig.fmap.core.symbols.ISymbol;
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.edition.EditionEvent;
40
import com.iver.cit.gvsig.fmap.edition.UtilFunctions;
41
import com.iver.cit.gvsig.fmap.edition.VectorialEditableAdapter;
42
import com.iver.cit.gvsig.fmap.layers.FBitSet;
43
import com.iver.cit.gvsig.fmap.layers.FLyrVect;
44
import com.iver.cit.gvsig.fmap.layers.SpatialCache;
45
import com.iver.cit.gvsig.fmap.tools.BehaviorException;
46
import com.iver.cit.gvsig.fmap.tools.Behavior.Behavior;
47
import com.iver.cit.gvsig.fmap.tools.Listeners.ToolListener;
48
import com.iver.cit.gvsig.gui.cad.tools.SelectionCADTool;
49
import com.iver.cit.gvsig.gui.preferences.SnapConfigPage;
50
import com.iver.cit.gvsig.layers.ILayerEdited;
51
import com.iver.cit.gvsig.layers.VectorialLayerEdited;
52
import com.iver.cit.gvsig.project.documents.view.gui.View;
53
import com.iver.cit.gvsig.project.documents.view.snapping.GeometriesSnappingVisitor;
54
import com.iver.cit.gvsig.project.documents.view.snapping.ISnapper;
55
import com.iver.cit.gvsig.project.documents.view.snapping.ISnapperGeometriesVectorial;
56
import com.iver.cit.gvsig.project.documents.view.snapping.ISnapperRaster;
57
import com.iver.cit.gvsig.project.documents.view.snapping.ISnapperVectorial;
58
import com.iver.cit.gvsig.project.documents.view.snapping.SnappingVisitor;
59
import com.iver.cit.gvsig.project.documents.view.toolListeners.StatusBarListener;
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 ISymbol symbol = SymbologyFactory.createDefaultSymbolByShapeType(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 Object lastQuestion;
108

    
109
        private static boolean flatnessInitialized=false;
110
        private static Preferences prefs = Preferences.userRoot().node( "cadtooladapter" );
111
        private StatusBarListener sbl=null;
112
        /* (non-Javadoc)
113
         * @see com.iver.cit.gvsig.fmap.tools.Behavior.IBehavior#setMapControl(com.iver.cit.gvsig.fmap.MapControl)
114
         */
115
        public void setMapControl(MapControl mc) {
116
                super.setMapControl(mc);
117
                sbl=new StatusBarListener(getMapControl());
118
        }
119
        /**
120
         * Pinta de alguna manera especial las geometrias seleccionadas para la
121
         * edici?n. En caso de que el snapping est? activado, pintar? el efecto del
122
         * mismo.
123
         *
124
         * @see com.iver.cit.gvsig.fmap.tools.Behavior.Behavior#paintComponent(java.awt.Graphics)
125
         */
126
        public void paintComponent(Graphics g) {
127
                super.paintComponent(g);
128
                if (CADExtension.getCADToolAdapter()!=this)
129
                        return;
130
                drawCursor(g);
131
                getGrid().drawGrid(g);
132
                if (adjustedPoint != null) {
133
                        Point2D p = null;
134
                        if (mapAdjustedPoint != null) {
135
                                p = mapAdjustedPoint;
136
                        } else {
137
                                p = getMapControl().getViewPort().toMapPoint(adjustedPoint);
138
                        }
139

    
140
                        ((CADTool) cadToolStack.peek())
141
                                        .drawOperation(g, p.getX(), p.getY());
142
                }
143
        }
144

    
145
        /**
146
         * @see java.awt.event.MouseListener#mouseClicked(java.awt.event.MouseEvent)
147
         */
148
        public void mouseClicked(MouseEvent e) throws BehaviorException {
149
                if (e.getButton() == MouseEvent.BUTTON3) {
150
                        CADExtension.showPopup(e);
151
                }
152
        }
153

    
154
        /**
155
         * @see java.awt.event.MouseListener#mouseEntered(java.awt.event.MouseEvent)
156
         */
157
        public void mouseEntered(MouseEvent e) throws BehaviorException {
158
                clearMouseImage();
159
        }
160

    
161
        /**
162
         * @see java.awt.event.MouseListener#mouseExited(java.awt.event.MouseEvent)
163
         */
164
        public void mouseExited(MouseEvent e) throws BehaviorException {
165
        }
166

    
167
        /**
168
         * @see java.awt.event.MouseListener#mousePressed(java.awt.event.MouseEvent)
169
         */
170
        public void mousePressed(MouseEvent e) throws BehaviorException {
171
                if (e.getButton() == MouseEvent.BUTTON1) {
172
                        ViewPort vp = getMapControl().getMapContext().getViewPort();
173
                        Point2D p;
174

    
175
                        if (mapAdjustedPoint != null) {
176
                                p = mapAdjustedPoint;
177
                        } else {
178
                                p = vp.toMapPoint(adjustedPoint);
179
                        }
180
                        transition(new double[] { p.getX(), p.getY() }, e, ABSOLUTE);
181
                }
182
        }
183

    
184
        /**
185
         * Ajusta un punto de la imagen que se pasa como par?metro al grid si ?ste
186
         * est? activo y devuelve la distancia de un punto al punto ajustado
187
         *
188
         * @param point
189
         * @param mapHandlerAdjustedPoint
190
         *            DOCUMENT ME!
191
         *
192
         * @return Distancia del punto que se pasa como
193
         *  par?metro al punto ajustado. Si no hay ajuste,
194
         *  devuelve Double.MAX_VALUE
195
         */
196
        private double adjustToHandler(Point2D point,
197
                        Point2D mapHandlerAdjustedPoint) {
198

    
199
                if (!isRefentEnabled())
200
                        return Double.MAX_VALUE;
201

    
202
                ILayerEdited aux = CADExtension.getEditionManager().getActiveLayerEdited();
203
                if (!(aux instanceof VectorialLayerEdited))
204
                        return Double.MAX_VALUE;
205
                VectorialLayerEdited vle = (VectorialLayerEdited) aux;
206

    
207
                ArrayList snappers = vle.getSnappers();
208
                ArrayList layersToSnap = vle.getLayersToSnap();
209

    
210

    
211
                ViewPort vp = getMapControl().getViewPort();
212

    
213
                snappers=SnapConfigPage.getActivesSnappers();
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

    
251
                                        if (theSnapper instanceof ISnapperVectorial)
252
                                        {
253
                                                if (theSnapper instanceof ISnapperGeometriesVectorial) {
254
                                                        snapVisitor=new GeometriesSnappingVisitor((ISnapperGeometriesVectorial) theSnapper,point,mapTolerance,lastPoint);
255
                                                }else {
256
                                                        snapVisitor = new SnappingVisitor((ISnapperVectorial) theSnapper, point, mapTolerance, lastPoint);
257
                                                }
258
                                                // System.out.println("Cache size = " + cache.size());
259
                                                cache.query(e, snapVisitor);
260
                                                theSnappedPoint = snapVisitor.getSnapPoint();
261

    
262
                                        }
263
                                        if (theSnapper instanceof ISnapperRaster)
264
                                        {
265
                                                ISnapperRaster snapRaster = (ISnapperRaster) theSnapper;
266
                                                theSnappedPoint = snapRaster.getSnapPoint(getMapControl(), point, mapTolerance, lastPoint);
267
                                        }
268

    
269

    
270
                                        if (theSnappedPoint != null) {
271
                                                double distAux = theSnappedPoint.distance(point);
272
                                                if (minDist > distAux)
273
                                                {
274
                                                        minDist = distAux;
275
                                                        usedSnap = theSnapper;
276
                                                        mapHandlerAdjustedPoint.setLocation(theSnappedPoint);
277
                                                }
278
                                        }
279
                                }
280
                        } // visible
281
                }
282
                if (usedSnap != null)
283
                        return minDist;
284
                return Double.MAX_VALUE;
285

    
286
        }
287

    
288
        /**
289
         * @see java.awt.event.MouseListener#mouseReleased(java.awt.event.MouseEvent)
290
         */
291
        public void mouseReleased(MouseEvent e) throws BehaviorException {
292
                getMapControl().repaint();
293
        }
294

    
295
        /**
296
         * @see java.awt.event.MouseMotionListener#mouseDragged(java.awt.event.MouseEvent)
297
         */
298
        public void mouseDragged(MouseEvent e) throws BehaviorException {
299
                lastX = e.getX();
300
                lastY = e.getY();
301

    
302
                calculateSnapPoint(e.getPoint());
303
        }
304

    
305
        /**
306
         * @see java.awt.event.MouseMotionListener#mouseMoved(java.awt.event.MouseEvent)
307
         */
308
        public void mouseMoved(MouseEvent e) throws BehaviorException {
309

    
310
                lastX = e.getX();
311
                lastY = e.getY();
312

    
313
                calculateSnapPoint(e.getPoint());
314

    
315
                showCoords(e.getPoint());
316

    
317
                getMapControl().repaint();
318
        }
319

    
320
        private void showCoords(Point2D pPix)
321
        {
322
                String[] axisText = new String[2];
323
                axisText[0] = "X = ";
324
                axisText[1] = "Y = ";
325
//                NumberFormat nf = NumberFormat.getInstance();
326
                MapControl mapControl = getMapControl();
327
                ViewPort vp = mapControl.getMapContext().getViewPort();
328
                IProjection iProj = vp.getProjection();
329

    
330
//                if (iProj.getAbrev().equals("EPSG:4326") || iProj.getAbrev().equals("EPSG:4230")) {
331
//                        axisText[0] = "Lon = ";
332
//                        axisText[1] = "Lat = ";
333
//                        nf.setMaximumFractionDigits(8);
334
//                } else {
335
//                        axisText[0] = "X = ";
336
//                        axisText[1] = "Y = ";
337
//                        nf.setMaximumFractionDigits(2);
338
//                }
339
                Point2D p;
340
                if (mapAdjustedPoint == null)
341
                {
342
                        p = vp.toMapPoint(pPix);
343
                }
344
                else
345
                {
346
                        p = mapAdjustedPoint;
347
                }
348
                sbl.setFractionDigits(p);
349
                axisText = sbl.setCoorDisplayText(axisText);
350
                MainFrame mF = PluginServices.getMainFrame();
351

    
352
                if (mF != null)
353
                {
354
            mF.getStatusBar().setMessage("units",
355
                            PluginServices.getText(this, FConstant.NAMES[vp.getDistanceUnits()]));
356
            mF.getStatusBar().setControlValue("scale",String.valueOf(mapControl.getMapContext().getScaleView()));
357
                        mF.getStatusBar().setMessage("projection", iProj.getAbrev());
358

    
359
                        String[] coords=sbl.getCoords(p);
360
                        mF.getStatusBar().setMessage("x",
361
                                        axisText[0] + coords[0]);
362
                        mF.getStatusBar().setMessage("y",
363
                                        axisText[1] + coords[1]);
364
                }
365
        }
366

    
367
        private void clearMouseImage() {
368
                int[] pixels = new int[16 * 16];
369
                Image image = Toolkit.getDefaultToolkit().createImage(
370
                                new MemoryImageSource(16, 16, pixels, 0, 16));
371
                Cursor transparentCursor = Toolkit.getDefaultToolkit()
372
                                .createCustomCursor(image, new Point(0, 0), "invisiblecursor");
373

    
374
                getMapControl().setCursor(transparentCursor);
375
        }
376

    
377
        /**
378
         * DOCUMENT ME!
379
         *
380
         * @param g
381
         *            DOCUMENT ME!
382
         */
383
        private void drawCursor(Graphics g) {
384

    
385
                Point2D p = adjustedPoint;
386

    
387
                if (p == null) {
388
                        getGrid().setViewPort(getMapControl().getViewPort());
389

    
390
                        return;
391
                }
392

    
393
                int size1 = 15;
394
                int size2 = 3;
395
                g.drawLine((int) (p.getX() - size1), (int) (p.getY()),
396
                                (int) (p.getX() + size1), (int) (p.getY()));
397
                g.drawLine((int) (p.getX()), (int) (p.getY() - size1),
398
                                (int) (p.getX()), (int) (p.getY() + size1));
399

    
400
                // getMapControl().setToolTipText(null);
401
                if (adjustedPoint != null) {
402
                        if (bForceCoord) {
403
                                /* g.setColor(Color.ORANGE);
404
                                g.drawRect((int) (adjustedPoint.getX() - 6),
405
                                                (int) (adjustedPoint.getY() - 6), 12, 12);
406
                                g.drawRect((int) (adjustedPoint.getX() - 3),
407
                                                (int) (adjustedPoint.getY() - 3), 6, 6);
408
                                g.setColor(Color.MAGENTA);
409
                                g.drawRect((int) (adjustedPoint.getX() - 4),
410
                                                (int) (adjustedPoint.getY() - 4), 8, 8); */
411
                                if (usedSnap != null)
412
                                {
413
                                        usedSnap.draw(g, adjustedPoint);
414

    
415
                                        Graphics2D g2 = (Graphics2D) g;
416
                                FontMetrics metrics = g2.getFontMetrics();
417
                                int w = metrics.stringWidth(usedSnap.getToolTipText()) + 5;
418
                                int h = metrics.getMaxAscent() + 5;
419
                                int x = (int)p.getX()+9;
420
                                int y = (int)p.getY()- 7;
421

    
422
                                g2.setColor(theTipColor );
423
                                g2.fillRect(x, y-h, w, h);
424
                                g2.setColor(Color.BLACK);
425
                                g2.drawRect(x, y-h, w, h);
426
                                        g2.drawString(usedSnap.getToolTipText(), x+3, y-3);
427

    
428

    
429
                                        // getMapControl().setToolTipText(usedSnap.getToolTipText());
430
                                }
431

    
432
                                bForceCoord = false;
433
                        } else {
434
                                g.drawRect((int) (p.getX() - size2), (int) (p.getY() - size2),
435
                                                (int) (size2 * 2), (int) (size2 * 2));
436
                        }
437
                }
438
        }
439

    
440
        /**
441
         * DOCUMENT ME!
442
         *
443
         * @param point
444
         */
445
        private void calculateSnapPoint(Point point) {
446
                // Se comprueba el ajuste a rejilla
447

    
448
                Point2D gridAdjustedPoint = getMapControl().getViewPort().toMapPoint(
449
                                point);
450
                double minDistance = Double.MAX_VALUE;
451
                CADTool ct = (CADTool) cadToolStack.peek();
452
                if (ct instanceof SelectionCADTool
453
                                && ((SelectionCADTool) ct).getStatus().equals(
454
                                                "Selection.FirstPoint")) {
455
                        mapAdjustedPoint = gridAdjustedPoint;
456
                        adjustedPoint = (Point2D) point.clone();
457
                } else {
458

    
459
                        minDistance = getGrid().adjustToGrid(gridAdjustedPoint);
460
                        if (minDistance < Double.MAX_VALUE) {
461
                                adjustedPoint = getMapControl().getViewPort().fromMapPoint(
462
                                                gridAdjustedPoint);
463
                                mapAdjustedPoint = gridAdjustedPoint;
464
                        } else {
465
                                mapAdjustedPoint = null;
466
                        }
467
                }
468
                Point2D handlerAdjustedPoint = null;
469

    
470
                // Se comprueba el ajuste a los handlers
471
                if (mapAdjustedPoint != null) {
472
                        handlerAdjustedPoint = (Point2D) mapAdjustedPoint.clone(); // getMapControl().getViewPort().toMapPoint(point);
473
                } else {
474
                        handlerAdjustedPoint = getMapControl().getViewPort().toMapPoint(
475
                                        point);
476
                }
477

    
478
                Point2D mapPoint = new Point2D.Double();
479
                double distance = adjustToHandler(handlerAdjustedPoint, mapPoint);
480

    
481
                if (distance < minDistance) {
482
                        bForceCoord = true;
483
                        adjustedPoint = getMapControl().getViewPort().fromMapPoint(mapPoint);
484
                        mapAdjustedPoint = mapPoint;
485
                        minDistance = distance;
486
                }
487

    
488
                // Si no hay ajuste
489
                if (minDistance == Double.MAX_VALUE) {
490
                        adjustedPoint = point;
491
                        mapAdjustedPoint = null;
492
                }
493

    
494
        }
495

    
496
        /**
497
         * @see java.awt.event.MouseWheelListener#mouseWheelMoved(java.awt.event.MouseWheelEvent)
498
         */
499
        public void mouseWheelMoved(MouseWheelEvent e) throws BehaviorException {
500
        }
501

    
502
        /**
503
         * M?todo que realiza las transiciones en las herramientas en funci?n de un
504
         * texto introducido en la consola
505
         *
506
         * @param text
507
         *            DOCUMENT ME!
508
         */
509
        public void textEntered(String text) {
510
                if (text == null) {
511
                        transition(PluginServices.getText(this,"cancel"));
512
                } else {
513
                        /*
514
                         * if ("".equals(text)) { transition("aceptar"); } else {
515
                         */
516
                        text = text.trim();
517
                        int type = ABSOLUTE;
518
                        String[] numbers = new String[1];
519
                        numbers[0] = text;
520
                        if (text.indexOf(",") != -1) {
521

    
522
                                numbers = text.split(",");
523
                                if (numbers[0].substring(0, 1).equals("@")) {
524
                                        numbers[0] = numbers[0].substring(1, numbers[0].length());
525
                                        type = RELATIVE_SCU;
526
                                        if (numbers[0].substring(0, 1).equals("*")) {
527
                                                type = RELATIVE_SCP;
528
                                                numbers[0] = numbers[0].substring(1, numbers[0]
529
                                                                .length());
530
                                        }
531
                                }
532
                        } else if (text.indexOf("<") != -1) {
533
                                type = POLAR_SCP;
534
                                numbers = text.split("<");
535
                                if (numbers[0].substring(0, 1).equals("@")) {
536
                                        numbers[0] = numbers[0].substring(1, numbers[0].length());
537
                                        type = POLAR_SCU;
538
                                        if (numbers[0].substring(0, 1).equals("*")) {
539
                                                type = POLAR_SCP;
540
                                                numbers[0] = numbers[0].substring(1, numbers[0]
541
                                                                .length());
542
                                        }
543
                                }
544
                        }
545

    
546
                        double[] values = null;
547

    
548
                        try {
549
                                if (numbers.length == 2) {
550
                                        // punto
551
                                        values = new double[] { Double.parseDouble(numbers[0]),
552
                                                        Double.parseDouble(numbers[1]) };
553
                                        transition(values, null, type);
554
                                } else if (numbers.length == 1) {
555
                                        // valor
556
                                        values = new double[] { Double.parseDouble(numbers[0]) };
557
                                        transition(values[0]);
558
                                }
559
                        } catch (NumberFormatException e) {
560
                                transition(text);
561
                        } catch (NullPointerException e) {
562
                                transition(text);
563
                        }
564
                        // }
565
                }
566
                getMapControl().repaint();
567
        }
568

    
569
        /**
570
         * DOCUMENT ME!
571
         */
572
        public void configureMenu() {
573
                String[] desc = ((CADTool) cadToolStack.peek()).getDescriptions();
574
                // String[] labels = ((CADTool)
575
                // cadToolStack.peek()).getCurrentTransitions();
576
                CADExtension.clearMenu();
577

    
578
                for (int i = 0; i < desc.length; i++) {
579
                        if (desc[i] != null) {
580
                                CADExtension
581
                                                .addMenuEntry(PluginServices.getText(this, desc[i]));// ,
582
                                // labels[i]);
583
                        }
584
                }
585

    
586
        }
587

    
588
        /**
589
         * Recibe los valores de la transici?n (normalmente un punto) y el evento
590
         * con el que se gener? (si fue de rat?n ser? MouseEvent, el que viene en el
591
         * pressed) y si es de teclado, ser? un KeyEvent. Del evento se puede sacar
592
         * informaci?n acerca de si estaba pulsada la tecla CTRL, o Alt, etc.
593
         *
594
         * @param values
595
         * @param event
596
         */
597
        private void transition(double[] values, InputEvent event, int type) {
598
                questionAsked = true;
599
                if (!cadToolStack.isEmpty()) {
600
                        CADTool ct = (CADTool) cadToolStack.peek();
601

    
602
                        switch (type) {
603
                        case ABSOLUTE:
604
                                ct.transition(values[0], values[1], event);
605
                                previousPoint = values;
606
                                break;
607
                        case RELATIVE_SCU:
608
                                // Comprobar que tenemos almacenado el punto anterior
609
                                // y crear nuevo con coordenadas relativas a ?l.
610
                                double[] auxSCU = values;
611
                                if (previousPoint != null) {
612
                                        auxSCU[0] = previousPoint[0] + values[0];
613
                                        auxSCU[1] = previousPoint[1] + values[1];
614
                                }
615
                                ct.transition(auxSCU[0], auxSCU[1], event);
616

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

    
671
        /**
672
         * DOCUMENT ME!
673
         *
674
         * @param text
675
         *            DOCUMENT ME!
676
         * @param source
677
         *            DOCUMENT ME!
678
         * @param sel
679
         *            DOCUMENT ME!
680
         * @param values
681
         *            DOCUMENT ME!
682
         */
683
        private void transition(double value) {
684
                questionAsked = true;
685
                if (!cadToolStack.isEmpty()) {
686
                        CADTool ct = (CADTool) cadToolStack.peek();
687
                        ct.transition(value);
688
                        askQuestion();
689
                }
690
                configureMenu();
691
                PluginServices.getMainFrame().enableControls();
692
        }
693

    
694
        public void transition(String option) {
695
                questionAsked = true;
696
                if (!cadToolStack.isEmpty()) {
697
                        CADTool ct = (CADTool) cadToolStack.peek();
698
                        try {
699
                                ct.transition(option);
700
                        } catch (Exception e) {
701
                                View vista = (View) PluginServices.getMDIManager()
702
                                                .getActiveWindow();
703
                                vista.getConsolePanel().addText(
704
                                                "\n" + PluginServices.getText(this, "incorrect_option")
705
                                                                + " : " + option, JConsole.ERROR);
706
                        }
707
                        askQuestion();
708
                }
709
                configureMenu();
710
                PluginServices.getMainFrame().enableControls();
711
        }
712

    
713
        /**
714
         * DOCUMENT ME!
715
         *
716
         * @param value
717
         *            DOCUMENT ME!
718
         */
719
        public void setGridVisibility(boolean value) {
720
                getGrid().setShowGrid(value);
721
                getGrid().setViewPort(getMapControl().getViewPort());
722
                getMapControl().repaint();
723
        }
724

    
725
        public void setRefentEnabled(boolean activated) {
726
                bRefent = activated;
727
        }
728

    
729
        public boolean isRefentEnabled()
730
        {
731
                return bRefent;
732
        }
733

    
734
        /**
735
         * @see com.iver.cit.gvsig.fmap.tools.Behavior.Behavior#getListener()
736
         */
737
        public ToolListener getListener() {
738
                return new ToolListener() {
739
                        /**
740
                         * @see com.iver.cit.gvsig.fmap.tools.Listeners.ToolListener#getCursor()
741
                         */
742
                        public Cursor getCursor() {
743
                                return null;
744
                        }
745

    
746
                        /**
747
                         * @see com.iver.cit.gvsig.fmap.tools.Listeners.ToolListener#cancelDrawing()
748
                         */
749
                        public boolean cancelDrawing() {
750
                                return false;
751
                        }
752
                };
753
        }
754

    
755
        /**
756
         * DOCUMENT ME!
757
         *
758
         * @return DOCUMENT ME!
759
         */
760
        public CADTool getCadTool() {
761
                return (CADTool) cadToolStack.peek();
762
        }
763

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

    
793
        /**
794
         * DOCUMENT ME!
795
         */
796
        public void popCadTool() {
797
                cadToolStack.pop();
798
        }
799

    
800
        /**
801
         * DOCUMENT ME!
802
         */
803
        public void askQuestion() {
804
                CADTool cadtool = (CADTool) cadToolStack.peek();
805
                /*
806
                 * if (cadtool..getStatus()==0){
807
                 * PluginServices.getMainFrame().addTextToConsole("\n"
808
                 * +cadtool.getName()); }
809
                 */
810
                if (PluginServices.getMDIManager().getActiveWindow() instanceof View)
811
                {
812
                        View vista = (View) PluginServices.getMDIManager().getActiveWindow();
813
                        String question=cadtool.getQuestion();
814
                        if (lastQuestion==null || !(lastQuestion.equals(question)) || questionAsked) {
815
                        vista.getConsolePanel().addText(
816
                                        "\n" + "#" + question + " > ", JConsole.MESSAGE);
817
                        // ***PluginServices.getMainFrame().addTextToConsole("\n" +
818
                        // cadtool.getQuestion());
819
                        questionAsked = false;
820
                        }
821
                        lastQuestion=question;
822
                }
823

    
824
        }
825

    
826
        /**
827
         * DOCUMENT ME!
828
         *
829
         * @param cadTool
830
         *            DOCUMENT ME!
831
         */
832
        public void setCadTool(CADTool cadTool) {
833
                cadToolStack.clear();
834
                pushCadTool(cadTool);
835
                // askQuestion();
836
        }
837

    
838

    
839
        /**
840
         * Elimina las geometr?as seleccionadas actualmente
841
         */
842
        private void delete() {
843
                ILayerEdited aux = CADExtension.getEditionManager().getActiveLayerEdited();
844
                if (!(aux instanceof VectorialLayerEdited))
845
                        return;
846
                VectorialLayerEdited vle = (VectorialLayerEdited) aux;
847
                VectorialEditableAdapter vea = vle.getVEA();
848

    
849
                vea.startComplexRow();
850
                try {
851
                        FBitSet selection = vea.getSelection();
852
                        int[] indexesToDel = new int[selection.cardinality()];
853
                        int j = 0;
854
                        for (int i = selection.nextSetBit(0); i >= 0; i = selection
855
                                        .nextSetBit(i + 1)) {
856
                                indexesToDel[j++] = i;
857
                                // /vea.removeRow(i);
858
                        }
859

    
860
//                          ArrayList selectedRow = vle.getSelectedRow();
861
//
862
//                          int[] indexesToDel = new int[selectedRow.size()];
863
//                          for (int i = 0;i < selectedRow.size(); i++) {
864
//                                  IRowEdited edRow = (IRowEdited) selectedRow.get(i);
865
//                                  indexesToDel[i] = vea.getInversedIndex(edRow.getIndex());
866
//                                  }
867
//
868
                        for (int i = indexesToDel.length - 1; i >= 0; i--) {
869
                                vea.removeRow(indexesToDel[i], PluginServices.getText(this,
870
                                                "deleted_feature"),EditionEvent.GRAPHIC);
871
                        }
872
                        System.out.println("clear Selection");
873
                        selection.clear();
874
                        vle.clearSelection(VectorialLayerEdited.NOTSAVEPREVIOUS);
875
                } catch (ReadDriverException e) {
876
                        // TODO Auto-generated catch block
877
                        e.printStackTrace();
878
                } catch (ExpansionFileReadException e) {
879
                        // TODO Auto-generated catch block
880
                        e.printStackTrace();
881
                } finally {
882
                        String description=PluginServices.getText(this,"remove_geometry");
883
                        vea.endComplexRow(description);
884
                }
885

    
886

    
887
                /*
888
                 * if (getCadTool() instanceof SelectionCADTool) { SelectionCADTool
889
                 * selTool = (SelectionCADTool) getCadTool(); selTool.clearSelection(); }
890
                 */
891
                refreshEditedLayer();
892
        }
893

    
894
        /**
895
         * DOCUMENT ME!
896
         *
897
         * @param b
898
         */
899
        public void setAdjustGrid(boolean b) {
900
                getGrid().setAdjustGrid(b);
901
        }
902

    
903
        /**
904
         * DOCUMENT ME!
905
         *
906
         * @param actionCommand
907
         */
908
        public void keyPressed(String actionCommand) {
909
                if (CADExtension.getEditionManager().getActiveLayerEdited()== null) {
910
                        return;
911
                }
912
                if (actionCommand.equals("eliminar")) {
913
                        delete();
914
                } else if (actionCommand.equals("escape")) {
915
                        if (getMapControl().getCurrentTool().equals("cadtooladapter")) {
916
                                CADTool ct = (CADTool) cadToolStack.peek();
917
                                ct.end();
918
                                cadToolStack.clear();
919
                                SelectionCADTool selCad = new SelectionCADTool();
920
                                selCad.init();
921
                                VectorialLayerEdited vle = (VectorialLayerEdited) CADExtension
922
                                                .getEditionManager().getActiveLayerEdited();
923
                                try {
924
                                        vle.clearSelection(VectorialLayerEdited.NOTSAVEPREVIOUS);
925
                                } catch (ReadDriverException e) {
926
                                        // TODO Auto-generated catch block
927
                                        e.printStackTrace();
928
                                }
929

    
930
                                pushCadTool(selCad);
931
                                // getVectorialAdapter().getSelection().clear();
932

    
933
                                refreshEditedLayer();
934

    
935

    
936
                                PluginServices.getMainFrame().setSelectedTool("_selection");
937
                                // askQuestion();
938
                        } else {
939
                                getMapControl().setPrevTool();
940
                        }
941
                }
942

    
943
                PluginServices.getMainFrame().enableControls();
944

    
945
        }
946

    
947
        /**
948
         * Provoca un repintado "soft" de la capa activa en edici?n.
949
         * Las capas por debajo de ella no se dibujan de verdad, solo
950
         * se dibuja la que est? en edici?n y las que est?n por encima
951
         * de ella en el TOC.
952
         */
953
        public void refreshEditedLayer()
954
        {
955
                ILayerEdited edLayer = CADExtension.getEditionManager().getActiveLayerEdited();
956
                if (edLayer != null)
957
                {
958
                        edLayer.getLayer().setDirty(true);
959
                        getMapControl().rePaintDirtyLayers();
960
                }
961

    
962
        }
963

    
964
        public CADGrid getGrid() {
965
                return cadgrid;
966
        }
967

    
968
        public boolean isOrtoMode() {
969
                return bOrtoMode;
970
        }
971

    
972
        public void setOrtoMode(boolean b) {
973
                bOrtoMode = b;
974
        }
975

    
976
        public static void addCADTool(String name, CADTool c) {
977
                namesCadTools.put(name, c);
978

    
979
        }
980
        public static CADTool[] getCADTools() {
981
                return (CADTool[]) CADToolAdapter.namesCadTools.values().toArray(new CADTool[0]);
982
        }
983
        public CADTool getCADTool(String text) {
984
                CADTool ct = (CADTool) namesCadTools.get(text);
985
                return ct;
986
        }
987

    
988
        public EditionManager getEditionManager() {
989
                return editionManager;
990
        }
991

    
992
        public void initializeFlatness() {
993
                if (!flatnessInitialized){
994
                        flatnessInitialized=true;
995
                        Preferences prefs = Preferences.userRoot().node( "cadtooladapter" );
996
                        double flatness = prefs.getDouble("flatness",FConverter.FLATNESS);
997
                        FConverter.FLATNESS=flatness;
998
                }
999
        }
1000
        public void initializeGrid(){
1001
                boolean showGrid = prefs.getBoolean("grid.showgrid",getGrid().isShowGrid());
1002
                boolean adjustGrid = prefs.getBoolean("grid.adjustgrid",getGrid().isAdjustGrid());
1003

    
1004
                double dx = prefs.getDouble("grid.distancex",getGrid().getGridSizeX());
1005
                double dy = prefs.getDouble("grid.distancey",getGrid().getGridSizeY());
1006

    
1007
                setGridVisibility(showGrid);
1008
                setAdjustGrid(adjustGrid);
1009
                getGrid().setGridSizeX(dx);
1010
                getGrid().setGridSizeY(dy);
1011
        }
1012
        /**
1013
        * Returns the type of active layer.
1014
        **/
1015
        public int getActiveLayerType() {
1016
                int type=FShape.MULTI;
1017
                try {
1018
                        type=((FLyrVect)CADExtension.getEditionManager().getActiveLayerEdited().getLayer()).getShapeType();
1019
                } catch (ReadDriverException e) {
1020
                        NotificationManager.addError(e);
1021
                }
1022
                return type;
1023
        }
1024
}