Statistics
| Revision:

root / trunk / extensions / extCAD / src / com / iver / cit / gvsig / gui / cad / CADToolAdapter.java @ 9956

History | View | Annotate | Download (28.2 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
import org.gvsig.gui.beans.controls.combolabel.ComboCoords;
26

    
27
import com.iver.andami.PluginServices;
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.MapContext;
32
import com.iver.cit.gvsig.fmap.MapControl;
33
import com.iver.cit.gvsig.fmap.ViewPort;
34
import com.iver.cit.gvsig.fmap.core.v02.FConstant;
35
import com.iver.cit.gvsig.fmap.core.v02.FConverter;
36
import com.iver.cit.gvsig.fmap.core.v02.FSymbol;
37
import com.iver.cit.gvsig.fmap.drivers.DriverIOException;
38
import com.iver.cit.gvsig.fmap.edition.EditionEvent;
39
import com.iver.cit.gvsig.fmap.edition.UtilFunctions;
40
import com.iver.cit.gvsig.fmap.edition.VectorialEditableAdapter;
41
import com.iver.cit.gvsig.fmap.layers.FBitSet;
42
import com.iver.cit.gvsig.fmap.layers.FLyrVect;
43
import com.iver.cit.gvsig.fmap.layers.SpatialCache;
44
import com.iver.cit.gvsig.fmap.tools.BehaviorException;
45
import com.iver.cit.gvsig.fmap.tools.Behavior.Behavior;
46
import com.iver.cit.gvsig.fmap.tools.Listeners.ToolListener;
47
import com.iver.cit.gvsig.gui.cad.tools.SelectionCADTool;
48
import com.iver.cit.gvsig.gui.preferences.SnapConfigPage;
49
import com.iver.cit.gvsig.layers.ILayerEdited;
50
import com.iver.cit.gvsig.layers.VectorialLayerEdited;
51
import com.iver.cit.gvsig.project.documents.view.gui.View;
52
import com.iver.cit.gvsig.project.documents.view.snapping.GeometriesSnappingVisitor;
53
import com.iver.cit.gvsig.project.documents.view.snapping.ISnapper;
54
import com.iver.cit.gvsig.project.documents.view.snapping.ISnapperGeometriesVectorial;
55
import com.iver.cit.gvsig.project.documents.view.snapping.ISnapperRaster;
56
import com.iver.cit.gvsig.project.documents.view.snapping.ISnapperVectorial;
57
import com.iver.cit.gvsig.project.documents.view.snapping.SnappingVisitor;
58
import com.iver.cit.gvsig.project.documents.view.toolListeners.StatusBarListener;
59
import com.iver.utiles.console.JConsole;
60
import com.vividsolutions.jts.geom.Envelope;
61

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

    
65
        private EditionManager editionManager = new EditionManager();
66

    
67
        public static final int ABSOLUTE = 0;
68

    
69
        public static final int RELATIVE_SCP = 1;
70

    
71
        public static final int RELATIVE_SCU = 2;
72

    
73
        public static final int POLAR_SCP = 3;
74

    
75
        public static final int POLAR_SCU = 4;
76

    
77
        private double[] previousPoint = null;
78

    
79
        private Stack cadToolStack = new Stack();
80

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

    
84
        private int lastY;
85

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

    
88
        private Point2D mapAdjustedPoint;
89

    
90
        private ISnapper usedSnap = null;
91

    
92
        private boolean questionAsked = false;
93

    
94
        private Point2D adjustedPoint;
95

    
96
        private boolean bRefent = true;
97

    
98
        private boolean bForceCoord = false;
99

    
100
        private CADGrid cadgrid = new CADGrid();
101

    
102
        private boolean bOrtoMode;
103

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

    
106
        private Object lastQuestion;
107

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

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

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

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

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

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

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

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

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

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

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

    
209

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

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

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

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

    
268

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

    
285
        }
286

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

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

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

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

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

    
312
                calculateSnapPoint(e.getPoint());
313

    
314
                showCoords(e.getPoint());
315

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

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

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

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

    
358
//                        mF.getStatusBar().setMessage("x",
359
//                                        axisText[0] + String.valueOf(nf.format(p.getX()/MapContext.CHANGEM[vp.getDistanceUnits()])));
360
//                        mF.getStatusBar().setMessage("y",
361
//                                        axisText[1] + String.valueOf(nf.format(p.getY()/MapContext.CHANGEM[vp.getDistanceUnits()])));
362
                        String[] coords=sbl.getCoords(p);
363
                        ComboCoords combocoords=(ComboCoords)PluginServices.getMainFrame().getComponentByName("coords");
364
                        combocoords.setLabelX(axisText[0]);
365
                        combocoords.setLabelY(axisText[1]);
366
                        combocoords.setValueX(coords[0]);
367
                        combocoords.setValueY(coords[1]);
368
                }
369
        }
370

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

    
378
                getMapControl().setCursor(transparentCursor);
379
        }
380

    
381
        /**
382
         * DOCUMENT ME!
383
         *
384
         * @param g
385
         *            DOCUMENT ME!
386
         */
387
        private void drawCursor(Graphics g) {
388

    
389
                Point2D p = adjustedPoint;
390

    
391
                if (p == null) {
392
                        getGrid().setViewPort(getMapControl().getViewPort());
393

    
394
                        return;
395
                }
396

    
397
                int size1 = 15;
398
                int size2 = 3;
399
                g.drawLine((int) (p.getX() - size1), (int) (p.getY()),
400
                                (int) (p.getX() + size1), (int) (p.getY()));
401
                g.drawLine((int) (p.getX()), (int) (p.getY() - size1),
402
                                (int) (p.getX()), (int) (p.getY() + size1));
403

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

    
419
                                        Graphics2D g2 = (Graphics2D) g;
420
                                FontMetrics metrics = g2.getFontMetrics();
421
                                int w = metrics.stringWidth(usedSnap.getToolTipText()) + 5;
422
                                int h = metrics.getMaxAscent() + 5;
423
                                int x = (int)p.getX()+9;
424
                                int y = (int)p.getY()- 7;
425

    
426
                                g2.setColor(theTipColor );
427
                                g2.fillRect(x, y-h, w, h);
428
                                g2.setColor(Color.BLACK);
429
                                g2.drawRect(x, y-h, w, h);
430
                                        g2.drawString(usedSnap.getToolTipText(), x+3, y-3);
431

    
432

    
433
                                        // getMapControl().setToolTipText(usedSnap.getToolTipText());
434
                                }
435

    
436
                                bForceCoord = false;
437
                        } else {
438
                                g.drawRect((int) (p.getX() - size2), (int) (p.getY() - size2),
439
                                                (int) (size2 * 2), (int) (size2 * 2));
440
                        }
441
                }
442
        }
443

    
444
        /**
445
         * DOCUMENT ME!
446
         *
447
         * @param point
448
         */
449
        private void calculateSnapPoint(Point point) {
450
                // Se comprueba el ajuste a rejilla
451

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

    
463
                        minDistance = getGrid().adjustToGrid(gridAdjustedPoint);
464
                        if (minDistance < Double.MAX_VALUE) {
465
                                adjustedPoint = getMapControl().getViewPort().fromMapPoint(
466
                                                gridAdjustedPoint);
467
                                mapAdjustedPoint = gridAdjustedPoint;
468
                        } else {
469
                                mapAdjustedPoint = null;
470
                        }
471
                }
472
                Point2D handlerAdjustedPoint = null;
473

    
474
                // Se comprueba el ajuste a los handlers
475
                if (mapAdjustedPoint != null) {
476
                        handlerAdjustedPoint = (Point2D) mapAdjustedPoint.clone(); // getMapControl().getViewPort().toMapPoint(point);
477
                } else {
478
                        handlerAdjustedPoint = getMapControl().getViewPort().toMapPoint(
479
                                        point);
480
                }
481

    
482
                Point2D mapPoint = new Point2D.Double();
483
                double distance = adjustToHandler(handlerAdjustedPoint, mapPoint);
484

    
485
                if (distance < minDistance) {
486
                        bForceCoord = true;
487
                        adjustedPoint = getMapControl().getViewPort().fromMapPoint(mapPoint);
488
                        mapAdjustedPoint = mapPoint;
489
                        minDistance = distance;
490
                }
491

    
492
                // Si no hay ajuste
493
                if (minDistance == Double.MAX_VALUE) {
494
                        adjustedPoint = point;
495
                        mapAdjustedPoint = null;
496
                }
497

    
498
        }
499

    
500
        /**
501
         * @see java.awt.event.MouseWheelListener#mouseWheelMoved(java.awt.event.MouseWheelEvent)
502
         */
503
        public void mouseWheelMoved(MouseWheelEvent e) throws BehaviorException {
504
        }
505

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

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

    
550
                        double[] values = null;
551

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

    
573
        /**
574
         * DOCUMENT ME!
575
         */
576
        public void configureMenu() {
577
                String[] desc = ((CADTool) cadToolStack.peek()).getDescriptions();
578
                // String[] labels = ((CADTool)
579
                // cadToolStack.peek()).getCurrentTransitions();
580
                CADExtension.clearMenu();
581

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

    
590
        }
591

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

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

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

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

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

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

    
729
        public void setRefentEnabled(boolean activated) {
730
                bRefent = activated;
731
        }
732

    
733
        public boolean isRefentEnabled()
734
        {
735
                return bRefent;
736
        }
737

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

    
750
                        /**
751
                         * @see com.iver.cit.gvsig.fmap.tools.Listeners.ToolListener#cancelDrawing()
752
                         */
753
                        public boolean cancelDrawing() {
754
                                return false;
755
                        }
756
                };
757
        }
758

    
759
        /**
760
         * DOCUMENT ME!
761
         *
762
         * @return DOCUMENT ME!
763
         */
764
        public CADTool getCadTool() {
765
                return (CADTool) cadToolStack.peek();
766
        }
767

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

    
797
        /**
798
         * DOCUMENT ME!
799
         */
800
        public void popCadTool() {
801
                cadToolStack.pop();
802
        }
803

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

    
828
        }
829

    
830
        /**
831
         * DOCUMENT ME!
832
         *
833
         * @param cadTool
834
         *            DOCUMENT ME!
835
         */
836
        public void setCadTool(CADTool cadTool) {
837
                cadToolStack.clear();
838
                pushCadTool(cadTool);
839
                // askQuestion();
840
        }
841

    
842

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

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

    
864
//                          ArrayList selectedRow = vle.getSelectedRow();
865
//
866
//                          int[] indexesToDel = new int[selectedRow.size()];
867
//                          for (int i = 0;i < selectedRow.size(); i++) {
868
//                                  IRowEdited edRow = (IRowEdited) selectedRow.get(i);
869
//                                  indexesToDel[i] = vea.getInversedIndex(edRow.getIndex());
870
//                                  }
871
//
872
                        for (int i = indexesToDel.length - 1; i >= 0; i--) {
873
                                vea.removeRow(indexesToDel[i], PluginServices.getText(this,
874
                                                "deleted_feature"),EditionEvent.GRAPHIC);
875
                        }
876
                } catch (DriverIOException e) {
877
                        e.printStackTrace();
878
                } catch (IOException e) {
879
                        e.printStackTrace();
880
                } finally {
881
                        try {
882
                                String description=PluginServices.getText(this,"remove_geometry");
883
                                vea.endComplexRow(description);
884
                        } catch (IOException e1) {
885
                                e1.printStackTrace();
886
                        } catch (DriverIOException e1) {
887
                                e1.printStackTrace();
888
                        }
889
                }
890
                System.out.println("clear Selection");
891
                selection.clear();
892
                vle.clearSelection(VectorialLayerEdited.NOTSAVEPREVIOUS);
893
                /*
894
                 * if (getCadTool() instanceof SelectionCADTool) { SelectionCADTool
895
                 * selTool = (SelectionCADTool) getCadTool(); selTool.clearSelection(); }
896
                 */
897
                refreshEditedLayer();
898
        }
899

    
900
        /**
901
         * DOCUMENT ME!
902
         *
903
         * @param b
904
         */
905
        public void setAdjustGrid(boolean b) {
906
                getGrid().setAdjustGrid(b);
907
        }
908

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

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

    
934
                                refreshEditedLayer();
935

    
936

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

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

    
946
        }
947

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

    
963
        }
964

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

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

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

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

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

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

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

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

    
1008
                setGridVisibility(showGrid);
1009
                setAdjustGrid(adjustGrid);
1010
                getGrid().setGridSizeX(dx);
1011
                getGrid().setGridSizeY(dy);
1012
        }
1013

    
1014
}