Statistics
| Revision:

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

History | View | Annotate | Download (46.5 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.andami.ui.mdiManager.IWindow;
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.FShape;
35
import com.iver.cit.gvsig.fmap.core.SymbologyFactory;
36
import com.iver.cit.gvsig.fmap.core.symbols.ISymbol;
37
import com.iver.cit.gvsig.fmap.core.v02.FConstant;
38
import com.iver.cit.gvsig.fmap.core.v02.FConverter;
39
import com.iver.cit.gvsig.fmap.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
/**
64
 * <p>Allows user interact with different CAD tools, on a layer being edited.</p>
65
 *
66
 * <p>There are two ways of interacting:
67
 *  <ul>
68
 *   <li><b>With the mouse</b> : user selects any {@link CADTool CADTool} that produces mouse events as consequence
69
 *    of the actions working with the layer being edited.
70
 *   </li>
71
 *   <li><b>Writing commands in the edition console</b> : most of the {@link CADTool CADTool} mouse actions can also
72
 *    be called writing a command or a command's parameter in the associated edition console, and pressing the key <code>Enter</code>.
73
 *    If the command isn't valid, will notify it.
74
 *   </li>
75
 *  </ul>
76
 * </p>
77
 *
78
 * <p>The edition has been implemented as a <i>finite machine</i>, with three kind of transitions between states according
79
 *  the parameters introduced:
80
 *  <ul>
81
 *   <li><i>First transition type: <b>Point</i></b>: if <code>text</code> matches with any pattern of
82
 *    parameters needed for any kind of point coordinates.<br>
83
 *    There are eight ways of introducing point 2D coordinates:
84
 *    <ul>
85
 *    <li><i>X,Y</i> : absolute cardinal 2D coordinate from the center <i>(0,0)</i> of the CCS <i>Current Coordinate System</i>.</li>
86
 *    <li><i>@X,Y</i> : relative cardinal 2D distances from the last point added of the CCS. If it's the first point of the geometry,
87
 *     works like <i>X,Y</i>.</li>
88
 *    <li><i>length< angle</i> : absolute polar 2D coordinate from the center <i>(0,0)</i> of the CCS <i>Current Coordinate System</i>, using
89
 *     <i>angle</i> from the <i>X</i> axis of CCS, and <i>length</i> far away.</li>
90
 *    <li><i>@length< angle</i> : relative polar 2D coordinate from the last point added of the CCS <i>Current Coordinate System</i>, using
91
 *     <i>angle</i> from the <i>X</i> axis of CCS, and <i>length</i> far away. If it's the first point of the geometry,
92
 *     works like <i>length< angle</i>.</li>
93
 *    <li><i>*X,Y</i> : like <i>X,Y</i> but using UCS <i>Universal Coordinate System</i> as reference.</li>
94
 *    <li><i>@*X,Y</i> : like <i>@X,Y</i> but using UCS <i>Universal Coordinate System</i> as reference.
95
 *      If it's the first point of the geometry, works like <i>*X,Y</i>.</li>
96
 *    <li><i>*length< angle</i> : like <i>length< angle</i> but using UCS <i>Universal Coordinate System</i> as reference.</li>
97
 *    <li><i>@*length< angle</i> : like <i>@length< angle</i> but using UCS <i>Universal Coordinate System</i> as reference.
98
 *      If it's the first point of the geometry, works like <i>*length< angle</i>.</li>
99
 *    </ul>
100
 *   </li>
101
 *   <li><i>Second transition type: <b>Value</i></b>: if recognizes it as a single number.</li>
102
 *   <li><i>Third transition type: <b>Option</i></b>: by default, if can't classify the information as a single number
103
 *    neither as a point. This information will be an <code>String</code> and dealt as an option of the current
104
 *    tool state. Ultimately, if isn't valid, <code>text</code> will be rewritten in the console notifying the user
105
 *    that isn't correct.</li>
106
 *  </ul>
107
 * </p>
108
 *
109
 * @see Behavior
110
 * @see MapControl
111
 */
112
public class CADToolAdapter extends Behavior {
113
        /**
114
         * Stores the CAD tools to edit the layers of the associated <code>MapControl</code>.
115
         *
116
         * @see #addCADTool(String, CADTool)
117
         * @see #getCadTool()
118
         * @see #getCADTool(String)
119
         */
120
        private static HashMap namesCadTools = new HashMap();
121

    
122
        /**
123
         * Reference to the object used to manage the edition of the layers of the associated <code>MapControl</code>.
124
         *
125
         * @see EditionManager
126
         * @see #getEditionManager()
127
         */
128
        private EditionManager editionManager = new EditionManager();
129

    
130
        /**
131
         * Identifies that the data are absolute coordinates of the new point from the (0, 0) position.
132
         */
133
        public static final int ABSOLUTE = 0;
134

    
135
        /**
136
         * Equivalent to {@link CADToolAdapter#ABSOLUTE CADToolAdapter#ABSOLUTE}.
137
         */
138
        public static final int RELATIVE_SCP = 1;
139

    
140
        /**
141
         * Identifies that the data are relative distances of the new point from the previous introduced.
142
         */
143
        public static final int RELATIVE_SCU = 2;
144

    
145
        /**
146
         * Identifies that the data are relative polar distances (longitude of the line and angle given in degrees)
147
         *  of the new point from the previous introduced.
148
         */
149
        public static final int POLAR_SCP = 3;
150

    
151
        /**
152
         * Identifies that the data are relative polar distances (longitude of the line and angle given in radians)
153
         *  of the new point from the previous introduced.
154
         */
155
        public static final int POLAR_SCU = 4;
156

    
157
        /**
158
         * Stores the 2D map coordinates of the last point added.
159
         */
160
        private double[] previousPoint = null;
161

    
162
        /**
163
         * <i>Stack with CAD tools.</i>
164
         *
165
         * <i>For each CAD tool we use, the last item added in this stack will
166
         *  display a different icon according to the current operation and its status.</i>
167
         */
168
        private Stack cadToolStack = new Stack();
169

    
170
        /**
171
         * X coordinate of the last dragging or moving mouse event.
172
         */
173
        private int lastX;
174

    
175
        /**
176
         * Y coordinate of the last dragging or moving mouse event.
177
         */
178
        private int lastY;
179

    
180
        /**
181
         * Unused attribute.
182
         */
183
        private ISymbol symbol = SymbologyFactory.createDefaultSymbolByShapeType(FConstant.SYMBOL_TYPE_POINT, Color.RED);
184

    
185
        /**
186
         * Represents the cursor's point selected in <i>map coordinates</i>.
187
         *
188
         * @see MapControl#toMapPoint
189
         */
190
        private Point2D mapAdjustedPoint;
191

    
192
        /**
193
         * Kind of geometry drawn to identify the kind of control point selected by the cursor's mouse.
194
         */
195
        private ISnapper usedSnap = null;
196

    
197
        /**
198
         * Determines if has displayed at the edition console, the question for the operations that can do
199
         *  the user with the current CAD tool, in its current state.
200
         */
201
        private boolean questionAsked = false;
202

    
203
        /**
204
         * Represents the cursor's point selected in <i>screen coordinates</i>.
205
         *
206
         * @see ViewPort#fromMapPoint(Point2D)
207
         */
208
        private Point2D adjustedPoint;
209

    
210
        /**
211
         * Determines if the snap tools are enabled or disabled.
212
         *
213
         * @see #isRefentEnabled()
214
         * @see #setRefentEnabled(boolean)
215
         */
216
        private boolean bRefent = true;
217

    
218
        /**
219
         * <p>Determines if the position of the snap of the mouse's cursor on the <code>MapControl</code>
220
         * is within the area around a control point of a geometry.</p>
221
         *
222
         * <p>The area is calculated as a circle centered at the control point and with radius the pixels tolerance
223
         *  defined in the preferences.</p>
224
         */
225
        private boolean bForceCoord = false;
226

    
227
        /**
228
         * Optional grid that could be applied on the <code>MapControl</code>'s view port.
229
         *
230
         * @see #getGrid()
231
         * @see #setAdjustGrid(boolean)
232
         */
233
        private CADGrid cadgrid = new CADGrid();
234

    
235
        /**
236
         * Determines is is enabled or not the <i>Orto</i> mode.
237
         */
238
        private boolean bOrtoMode;
239

    
240
        /**
241
         * A light yellow color for the tool tip text box associated to the point indicated by the mouse's cursor.
242
         */
243
        private Color theTipColor = new Color(255, 255, 155);
244

    
245
        /**
246
         * Last question asked to the user in the CAD console.
247
         */
248
        private Object lastQuestion;
249

    
250
        /**
251
         * Maximum tolerance in the approximation of a curved line by a polyline.
252
         *
253
         * @see #initializeFlatness()
254
         */
255
        private static boolean flatnessInitialized=false;
256

    
257
        /**
258
         * Edition preferences.
259
         */
260
        private static Preferences prefs = Preferences.userRoot().node( "cadtooladapter" );
261

    
262
        /**
263
         * Listener to display the coordinates in the current application's status bar.
264
         */
265
        private StatusBarListener sbl=null;
266

    
267
        /*
268
         * (non-Javadoc)
269
         * @see com.iver.cit.gvsig.fmap.tools.Behavior.Behavior#setMapControl(com.iver.cit.gvsig.fmap.MapControl)
270
         */
271
        public void setMapControl(MapControl mc) {
272
                super.setMapControl(mc);
273
                sbl=new StatusBarListener(getMapControl());
274
        }
275

    
276
        /**
277
         * <p>Draws the selected geometries to edit. And, if the <i>snapping</i> is enabled,
278
         *  draws also its effect over them.</p>
279
         *
280
         * @see com.iver.cit.gvsig.fmap.tools.Behavior.Behavior#paintComponent(java.awt.Graphics)
281
         */
282
        public void paintComponent(Graphics g) {
283
                super.paintComponent(g);
284
                if (CADExtension.getCADToolAdapter()!=this)
285
                        return;
286

    
287
                if (adjustedPoint != null) {
288
                        Point2D p = null;
289
                        if (mapAdjustedPoint != null) {
290
                                p = mapAdjustedPoint;
291
                        } else {
292
                                p = getMapControl().getViewPort().toMapPoint(adjustedPoint);
293
                        }
294

    
295
                        ((CADTool) cadToolStack.peek())
296
                                        .drawOperation(g, p.getX(), p.getY());
297
                }
298
                drawCursor(g);
299
                getGrid().drawGrid(g);
300
        }
301

    
302
        /**
303
         * <p>Responds two kind of mouse click events:
304
         *  <ul>
305
         *   <li><b><i>One click of the third mouse's button</i></b>: displays a popup with edition options.</li>
306
         *   <li><b><i>Two clicks of the first mouse's button</i></b>: ends the last cad tool setting as end transition
307
         *    point the event's one.</li>
308
         *  </ul>
309
         * </p>
310
         *
311
         *
312
         * @see com.iver.cit.gvsig.fmap.tools.Behavior.Behavior#mouseClicked(java.awt.event.MouseEvent)
313
         * @see CADExtension#showPopup(MouseEvent)
314
         */
315
        public void mouseClicked(MouseEvent e) throws BehaviorException {
316
                if (e.getButton() == MouseEvent.BUTTON3) {
317
                        CADExtension.showPopup(e);
318
                }else if (e.getButton() == MouseEvent.BUTTON1 && e.getClickCount()==2){
319
                        questionAsked = true;
320
                        if (!cadToolStack.isEmpty()) {
321
                                CADTool ct = (CADTool) cadToolStack.peek();
322
                                ViewPort vp = getMapControl().getMapContext().getViewPort();
323
                                Point2D p;
324

    
325
                                if (mapAdjustedPoint != null) {
326
                                        p = mapAdjustedPoint;
327
                                } else {
328
                                        p = vp.toMapPoint(adjustedPoint);
329
                                }
330
                                ct.endTransition(p.getX(), p.getY(), e);
331
                                previousPoint = new double[]{p.getX(),p.getY()};
332
                        }
333
                }
334
        }
335

    
336
        /*
337
         * (non-Javadoc)
338
         * @see com.iver.cit.gvsig.fmap.tools.Behavior.Behavior#mouseEntered(java.awt.event.MouseEvent)
339
         */
340
        public void mouseEntered(MouseEvent e) throws BehaviorException {
341
                clearMouseImage();
342
        }
343

    
344
        /*
345
         * (non-Javadoc)
346
         * @see com.iver.cit.gvsig.fmap.tools.Behavior.Behavior#mouseExited(java.awt.event.MouseEvent)
347
         */
348
        public void mouseExited(MouseEvent e) throws BehaviorException {
349
        }
350

    
351
        /**
352
         * Selects the vertex of a geometry at the point selected on the <code>MapControl</code>
353
         * by pressing the first mouse's button.
354
         *
355
         * @see com.iver.cit.gvsig.fmap.tools.Behavior.Behavior#mousePressed(java.awt.event.MouseEvent)
356
         */
357
        public void mousePressed(MouseEvent e) throws BehaviorException {
358
                if (e.getButton() == MouseEvent.BUTTON1) {
359
                        ViewPort vp = getMapControl().getMapContext().getViewPort();
360
                        Point2D p;
361

    
362
                        if (mapAdjustedPoint != null) {
363
                                p = mapAdjustedPoint;
364
                        } else {
365
                                p = vp.toMapPoint(adjustedPoint);
366
                        }
367
                        transition(new double[] { p.getX(), p.getY() }, e, ABSOLUTE);
368
                }
369
        }
370

    
371
        /**
372
         * <p>Adjusts the <code>point</code> to the grid if its enabled, and
373
         *  sets <code>mapHandlerAdjustedPoint</code> with that new value.</p>
374
         *
375
         * <p>The value returned is the distance between those points: the original and
376
         *  the adjusted one.</p>
377
         *
378
         * @param point point to adjust
379
         * @param mapHandlerAdjustedPoint <code>point</code> adjusted
380
         *
381
         * @return distance from <code>point</code> to the adjusted one. If there is no
382
         *  adjustment, returns <code>Double.MAX_VALUE</code>.
383
         */
384
        private double adjustToHandler(Point2D point,
385
                        Point2D mapHandlerAdjustedPoint) {
386

    
387
                if (!isRefentEnabled())
388
                        return Double.MAX_VALUE;
389

    
390
                ILayerEdited aux = CADExtension.getEditionManager().getActiveLayerEdited();
391
                if (!(aux instanceof VectorialLayerEdited))
392
                        return Double.MAX_VALUE;
393
                VectorialLayerEdited vle = (VectorialLayerEdited) aux;
394

    
395
                ArrayList snappers = vle.getSnappers();
396
                ArrayList layersToSnap = vle.getLayersToSnap();
397

    
398

    
399
                ViewPort vp = getMapControl().getViewPort();
400

    
401
                snappers=SnapConfigPage.getActivesSnappers();
402

    
403
                double mapTolerance = vp.toMapDistance(SelectionCADTool.tolerance);
404
                double minDist = mapTolerance;
405
//                double rw = getMapControl().getViewPort().toMapDistance(5);
406
                Point2D mapPoint = point;
407
                Rectangle2D r = new Rectangle2D.Double(mapPoint.getX() - mapTolerance / 2,
408
                                mapPoint.getY() - mapTolerance / 2, mapTolerance, mapTolerance);
409

    
410
                Envelope e = FConverter.convertRectangle2DtoEnvelope(r);
411

    
412
                usedSnap = null;
413
                Point2D lastPoint = null;
414
                if (previousPoint != null)
415
                {
416
                        lastPoint = new Point2D.Double(previousPoint[0], previousPoint[1]);
417
                }
418
                for (int j = 0; j < layersToSnap.size(); j++)
419
                {
420
                        FLyrVect lyrVect = (FLyrVect) layersToSnap.get(j);
421
                        SpatialCache cache = lyrVect.getSpatialCache();
422
                        if (lyrVect.isVisible())
423
                        {
424
                                // La lista de snappers est? siempre ordenada por prioridad. Los de mayor
425
                                // prioridad est?n primero.
426
                                for (int i = 0; i < snappers.size(); i++)
427
                                {
428
                                        ISnapper theSnapper = (ISnapper) snappers.get(i);
429

    
430
                                        if (usedSnap != null)
431
                                        {
432
                                                // Si ya tenemos un snap y es de alta prioridad, cogemos ese. (A no ser que en otra capa encontremos un snapper mejor)
433
                                                if (theSnapper.getPriority() < usedSnap.getPriority())
434
                                                        break;
435
                                        }
436
                                        SnappingVisitor snapVisitor = null;
437
                                        Point2D theSnappedPoint = null;
438

    
439
                                        if (theSnapper instanceof ISnapperVectorial)
440
                                        {
441
                                                if (theSnapper instanceof ISnapperGeometriesVectorial) {
442
                                                        snapVisitor=new GeometriesSnappingVisitor((ISnapperGeometriesVectorial) theSnapper,point,mapTolerance,lastPoint);
443
                                                }else {
444
                                                        snapVisitor = new SnappingVisitor((ISnapperVectorial) theSnapper, point, mapTolerance, lastPoint);
445
                                                }
446
                                                // System.out.println("Cache size = " + cache.size());
447
                                                cache.query(e, snapVisitor);
448
                                                theSnappedPoint = snapVisitor.getSnapPoint();
449

    
450
                                        }
451
                                        if (theSnapper instanceof ISnapperRaster)
452
                                        {
453
                                                ISnapperRaster snapRaster = (ISnapperRaster) theSnapper;
454
                                                theSnappedPoint = snapRaster.getSnapPoint(getMapControl(), point, mapTolerance, lastPoint);
455
                                        }
456

    
457

    
458
                                        if (theSnappedPoint != null) {
459
                                                double distAux = theSnappedPoint.distance(point);
460
                                                if (minDist > distAux)
461
                                                {
462
                                                        minDist = distAux;
463
                                                        usedSnap = theSnapper;
464
                                                        mapHandlerAdjustedPoint.setLocation(theSnappedPoint);
465
                                                }
466
                                        }
467
                                }
468
                        } // visible
469
                }
470
                if (usedSnap != null)
471
                        return minDist;
472
                return Double.MAX_VALUE;
473

    
474
        }
475

    
476
        /*
477
         * (non-Javadoc)
478
         * @see com.iver.cit.gvsig.fmap.tools.Behavior.Behavior#mouseReleased(java.awt.event.MouseEvent)
479
         */
480
        public void mouseReleased(MouseEvent e) throws BehaviorException {
481
                getMapControl().repaint();
482
        }
483

    
484
        /*
485
         * (non-Javadoc)
486
         * @see com.iver.cit.gvsig.fmap.tools.Behavior.Behavior#mouseDragged(java.awt.event.MouseEvent)
487
         */
488
        public void mouseDragged(MouseEvent e) throws BehaviorException {
489
                lastX = e.getX();
490
                lastY = e.getY();
491

    
492
                calculateSnapPoint(e.getPoint());
493
        }
494

    
495
        /*
496
         * (non-Javadoc)
497
         * @see com.iver.cit.gvsig.fmap.tools.Behavior.Behavior#mouseMoved(java.awt.event.MouseEvent)
498
         */
499
        public void mouseMoved(MouseEvent e) throws BehaviorException {
500

    
501
                lastX = e.getX();
502
                lastY = e.getY();
503

    
504
                calculateSnapPoint(e.getPoint());
505

    
506
                showCoords(e.getPoint());
507

    
508
                getMapControl().repaint();
509
        }
510

    
511
        /**
512
         * Displays the current coordinates of the mouse's cursor on the associated <code>MapControl</code>
513
         *  object, at the status bar of the application's main frame.
514
         *
515
         * @param pPix current 2D mouse's cursor coordinates on the <code>MapControl</code>
516
         */
517
        private void showCoords(Point2D pPix)
518
        {
519
                String[] axisText = new String[2];
520
                axisText[0] = "X = ";
521
                axisText[1] = "Y = ";
522
//                NumberFormat nf = NumberFormat.getInstance();
523
                MapControl mapControl = getMapControl();
524
                ViewPort vp = mapControl.getMapContext().getViewPort();
525
                IProjection iProj = vp.getProjection();
526

    
527
//                if (iProj.getAbrev().equals("EPSG:4326") || iProj.getAbrev().equals("EPSG:4230")) {
528
//                        axisText[0] = "Lon = ";
529
//                        axisText[1] = "Lat = ";
530
//                        nf.setMaximumFractionDigits(8);
531
//                } else {
532
//                        axisText[0] = "X = ";
533
//                        axisText[1] = "Y = ";
534
//                        nf.setMaximumFractionDigits(2);
535
//                }
536
                Point2D p;
537
                if (mapAdjustedPoint == null)
538
                {
539
                        p = vp.toMapPoint(pPix);
540
                }
541
                else
542
                {
543
                        p = mapAdjustedPoint;
544
                }
545
                sbl.setFractionDigits(p);
546
                axisText = sbl.setCoorDisplayText(axisText);
547
                MainFrame mF = PluginServices.getMainFrame();
548

    
549
                if (mF != null)
550
                {
551
            mF.getStatusBar().setMessage("units",
552
                            PluginServices.getText(this, MapContext.getDistanceNames()[vp.getDistanceUnits()]));
553
            mF.getStatusBar().setControlValue("scale",String.valueOf(mapControl.getMapContext().getScaleView()));
554
                        mF.getStatusBar().setMessage("projection", iProj.getAbrev());
555

    
556
                        String[] coords=sbl.getCoords(p);
557
                        mF.getStatusBar().setMessage("x",
558
                                        axisText[0] + coords[0]);
559
                        mF.getStatusBar().setMessage("y",
560
                                        axisText[1] + coords[1]);
561
                }
562
        }
563

    
564
        /**
565
         * Hides the mouse's cursor.
566
         */
567
        private void clearMouseImage() {
568
                int[] pixels = new int[16 * 16];
569
                Image image = Toolkit.getDefaultToolkit().createImage(
570
                                new MemoryImageSource(16, 16, pixels, 0, 16));
571
                Cursor transparentCursor = Toolkit.getDefaultToolkit()
572
                                .createCustomCursor(image, new Point(0, 0), "invisiblecursor");
573

    
574
                getMapControl().setCursor(transparentCursor);
575
        }
576

    
577
        /**
578
         * <p>Draws a 31x31 pixels cross round the mouse's cursor with an small geometry centered:
579
         *  <ul>
580
         *   <li><i>an square centered</i>: if isn't over a <i>control point</i>.
581
         *   <li><i>an small geometry centered according to the kind of control point</i>: if it's over a control
582
         *    point. In this case, the small geometry is drawn by a {@link ISnapper ISnapper} type object.<br>
583
         *    On the other hand, a light-yellowed background tool tip text with the type of <i>control point</i> will
584
         *     be displayed.</li>
585
         * </p>
586
         *
587
         * @param g <code>MapControl</code>'s graphics where the data will be drawn
588
         */
589
        private void drawCursor(Graphics g) {
590
                g.setColor(Color.black);
591
                Point2D p = adjustedPoint;
592

    
593
                if (p == null) {
594
                        getGrid().setViewPort(getMapControl().getViewPort());
595

    
596
                        return;
597
                }
598

    
599
                int size1 = 15;
600
                int size2 = 3;
601
                g.drawLine((int) (p.getX() - size1), (int) (p.getY()),
602
                                (int) (p.getX() + size1), (int) (p.getY()));
603
                g.drawLine((int) (p.getX()), (int) (p.getY() - size1),
604
                                (int) (p.getX()), (int) (p.getY() + size1));
605

    
606
                // getMapControl().setToolTipText(null);
607
                if (adjustedPoint != null) {
608
                        if (bForceCoord) {
609
                                /* g.setColor(Color.ORANGE);
610
                                g.drawRect((int) (adjustedPoint.getX() - 6),
611
                                                (int) (adjustedPoint.getY() - 6), 12, 12);
612
                                g.drawRect((int) (adjustedPoint.getX() - 3),
613
                                                (int) (adjustedPoint.getY() - 3), 6, 6);
614
                                g.setColor(Color.MAGENTA);
615
                                g.drawRect((int) (adjustedPoint.getX() - 4),
616
                                                (int) (adjustedPoint.getY() - 4), 8, 8); */
617
                                if (usedSnap != null)
618
                                {
619
                                        usedSnap.draw(g, adjustedPoint);
620

    
621
                                        Graphics2D g2 = (Graphics2D) g;
622
                                FontMetrics metrics = g2.getFontMetrics();
623
                                int w = metrics.stringWidth(usedSnap.getToolTipText()) + 5;
624
                                int h = metrics.getMaxAscent() + 5;
625
                                int x = (int)p.getX()+9;
626
                                int y = (int)p.getY()- 7;
627

    
628
                                g2.setColor(theTipColor );
629
                                g2.fillRect(x, y-h, w, h);
630
                                g2.setColor(Color.BLACK);
631
                                g2.drawRect(x, y-h, w, h);
632
                                        g2.drawString(usedSnap.getToolTipText(), x+3, y-3);
633

    
634

    
635
                                        // getMapControl().setToolTipText(usedSnap.getToolTipText());
636
                                }
637

    
638
                                bForceCoord = false;
639
                        } else {
640
                                g.drawRect((int) (p.getX() - size2), (int) (p.getY() - size2),
641
                                                (int) (size2 * 2), (int) (size2 * 2));
642
                        }
643
                }
644
        }
645

    
646
        /**
647
         * <p>Tries to find the nearest geometry or grid control point by the position of the current snap tool.</p>
648
         *
649
         * <p>Prioritizes the grid control points than the geometries ones.</p>
650
         *
651
         * <p>If finds any near, stores the <i>map</i> and <i>pixel</i> coordinates for the snap, and enables
652
         *  the <code>bForceCoord</code> attribute for the next draw of the mouse's cursor.</p>
653
         *
654
         * @param point current mouse 2D position
655
         */
656
        private void calculateSnapPoint(Point point) {
657
                // Se comprueba el ajuste a rejilla
658

    
659
                Point2D gridAdjustedPoint = getMapControl().getViewPort().toMapPoint(
660
                                point);
661
                double minDistance = Double.MAX_VALUE;
662
                CADTool ct = (CADTool) cadToolStack.peek();
663
                if (ct instanceof SelectionCADTool
664
                                && ((SelectionCADTool) ct).getStatus().equals(
665
                                                "Selection.FirstPoint")) {
666
                        mapAdjustedPoint = gridAdjustedPoint;
667
                        adjustedPoint = (Point2D) point.clone();
668
                } else {
669

    
670
                        minDistance = getGrid().adjustToGrid(gridAdjustedPoint);
671
                        if (minDistance < Double.MAX_VALUE) {
672
                                adjustedPoint = getMapControl().getViewPort().fromMapPoint(
673
                                                gridAdjustedPoint);
674
                                mapAdjustedPoint = gridAdjustedPoint;
675
                        } else {
676
                                mapAdjustedPoint = null;
677
                        }
678
                }
679
                Point2D handlerAdjustedPoint = null;
680

    
681
                // Se comprueba el ajuste a los handlers
682
                if (mapAdjustedPoint != null) {
683
                        handlerAdjustedPoint = (Point2D) mapAdjustedPoint.clone(); // getMapControl().getViewPort().toMapPoint(point);
684
                } else {
685
                        handlerAdjustedPoint = getMapControl().getViewPort().toMapPoint(
686
                                        point);
687
                }
688

    
689
                Point2D mapPoint = new Point2D.Double();
690
                double distance = adjustToHandler(handlerAdjustedPoint, mapPoint);
691

    
692
                if (distance < minDistance) {
693
                        bForceCoord = true;
694
                        adjustedPoint = getMapControl().getViewPort().fromMapPoint(mapPoint);
695
                        mapAdjustedPoint = mapPoint;
696
                        minDistance = distance;
697
                }
698

    
699
                // Si no hay ajuste
700
                if (minDistance == Double.MAX_VALUE) {
701
                        adjustedPoint = point;
702
                        mapAdjustedPoint = null;
703
                }
704

    
705
        }
706

    
707
        /*
708
         * (non-Javadoc)
709
         * @see com.iver.cit.gvsig.fmap.tools.Behavior.Behavior#mouseWheelMoved(java.awt.event.MouseWheelEvent)
710
         */
711
        public void mouseWheelMoved(MouseWheelEvent e) throws BehaviorException {
712
        }
713

    
714
        /**
715
         * <p>Process the information written by the user about the next point coordinate, determining
716
         *  the kind of <i>transition</i> according the parameters written.</p>
717
         *
718
         * <p>After, invokes one of the three possible <i>transition</i> methods of the <i>finite machine</i> of
719
         *  edition:
720
         *  <ul>
721
         *   <li><i>First transition type: <b>Point</i></b>: if <code>text</code> matches with any pattern of
722
         *    parameters needed for any kind of point coordinates.<br>
723
         *    There are eight ways of introducing point 2D coordinates:
724
         *    <ul>
725
         *    <li><i>X,Y</i> : absolute cardinal 2D coordinate from the center <i>(0,0)</i> of the CCS <i>Current Coordinate System</i>.</li>
726
         *    <li><i>@X,Y</i> : relative cardinal 2D distances from the last point added of the CCS. If it's the first point of the geometry,
727
         *     works like <i>X,Y</i>.</li>
728
         *    <li><i>length< angle</i> : absolute polar 2D coordinate from the center <i>(0,0)</i> of the CCS <i>Current Coordinate System</i>, using
729
         *     <i>angle</i> from the <i>X</i> axis of CCS, and <i>length</i> far away.</li>
730
         *    <li><i>@length< angle</i> : relative polar 2D coordinate from the last point added of the CCS <i>Current Coordinate System</i>, using
731
         *     <i>angle</i> from the <i>X</i> axis of CCS, and <i>length</i> far away. If it's the first point of the geometry,
732
         *     works like <i>length< angle</i>.</li>
733
         *    <li><i>*X,Y</i> : like <i>X,Y</i> but using UCS <i>Universal Coordinate System</i> as reference.</li>
734
         *    <li><i>@*X,Y</i> : like <i>@X,Y</i> but using UCS <i>Universal Coordinate System</i> as reference.
735
         *      If it's the first point of the geometry, works like <i>*X,Y</i>.</li>
736
         *    <li><i>*length< angle</i> : like <i>length< angle</i> but using UCS <i>Universal Coordinate System</i> as reference.</li>
737
         *    <li><i>@*length< angle</i> : like <i>@length< angle</i> but using UCS <i>Universal Coordinate System</i> as reference.
738
         *      If it's the first point of the geometry, works like <i>*length< angle</i>.</li>
739
         *    </ul>
740
         *   </li>
741
         *   <li><i>Second transition type: <b>Value</i></b>: if recognizes it as a single number.</li>
742
         *   <li><i>Third transition type: <b>Option</i></b>: by default, if can't classify the information as a single number
743
         *    neither as a point. This information will be an <code>String</code> and dealt as an option of the current
744
         *    tool state. Ultimately, if isn't valid, <code>text</code> will be rewritten in the console notifying the user
745
         *    that isn't correct.</li>
746
         *  </ul>
747
         * </p>
748
         *
749
         * @param text command written by user in the edition's console
750
         */
751
        public void textEntered(String text) {
752
                if (text == null) {
753
                        transition(PluginServices.getText(this,"cancel"));
754
                } else {
755
                        /*
756
                         * if ("".equals(text)) { transition("aceptar"); } else {
757
                         */
758
                        text = text.trim();
759
                        int type = ABSOLUTE;
760
                        String[] numbers = new String[1];
761
                        numbers[0] = text;
762
                        if (text.indexOf(",") != -1) {
763

    
764
                                numbers = text.split(",");
765
                                if (numbers[0].substring(0, 1).equals("@")) {
766
                                        numbers[0] = numbers[0].substring(1, numbers[0].length());
767
                                        type = RELATIVE_SCU;
768
                                        if (numbers[0].substring(0, 1).equals("*")) {
769
                                                type = RELATIVE_SCP;
770
                                                numbers[0] = numbers[0].substring(1, numbers[0]
771
                                                                .length());
772
                                        }
773
                                }
774
                        } else if (text.indexOf("<") != -1) {
775
                                type = POLAR_SCP;
776
                                numbers = text.split("<");
777
                                if (numbers[0].substring(0, 1).equals("@")) {
778
                                        numbers[0] = numbers[0].substring(1, numbers[0].length());
779
                                        type = POLAR_SCU;
780
                                        if (numbers[0].substring(0, 1).equals("*")) {
781
                                                type = POLAR_SCP;
782
                                                numbers[0] = numbers[0].substring(1, numbers[0]
783
                                                                .length());
784
                                        }
785
                                }
786
                        }
787

    
788
                        double[] values = null;
789

    
790
                        try {
791
                                if (numbers.length == 2) {
792
                                        // punto
793
                                        values = new double[] { Double.parseDouble(numbers[0]),
794
                                                        Double.parseDouble(numbers[1]) };
795
                                        transition(values, null, type);
796
                                } else if (numbers.length == 1) {
797
                                        // valor
798
                                        values = new double[] { Double.parseDouble(numbers[0]) };
799
                                        transition(values[0]);
800
                                }
801
                        } catch (NumberFormatException e) {
802
                                transition(text);
803
                        } catch (NullPointerException e) {
804
                                transition(text);
805
                        }
806
                        // }
807
                }
808
                getMapControl().repaint();
809
        }
810

    
811
        /**
812
         * If there are options related with the <code>CADTool</code> at the peek of the CAD tool stack,
813
         *  displays them as a popup.
814
         */
815
        public void configureMenu() {
816
                String[] desc = ((CADTool) cadToolStack.peek()).getDescriptions();
817
                // String[] labels = ((CADTool)
818
                // cadToolStack.peek()).getCurrentTransitions();
819
                CADExtension.clearMenu();
820

    
821
                for (int i = 0; i < desc.length; i++) {
822
                        if (desc[i] != null) {
823
                                CADExtension
824
                                                .addMenuEntry(PluginServices.getText(this, desc[i]));// ,
825
                                // labels[i]);
826
                        }
827
                }
828

    
829
        }
830

    
831
        /**
832
         * <p>One of the three kind of transaction methods of the <i>finite machine</i> of
833
         *  edition.</p>
834
         *
835
         * <p>This one deals <code>values</code> as two numbers that, according <code>type</code>
836
         *  calculate a new point 2D in the current layer edited in the associated <code>MapControl</code>.</p>
837
         *
838
         * <p>There are different ways of calculating the new point 2D coordinates, according the value of <code>type</code>, see
839
         *  {@link #textEntered(String) #textEntered(String)}.</p>
840
         *
841
         * <p>After applying the changes, updates the controls available for managing the current data.</p>
842
         *
843
         * @param values numbers needed to calculate the new point coordinates according <code>type</code>
844
         * @param event event which generated this invocation (a <code>MouseEvent</code> or a <code>KeyEvent</code>)
845
         * @param type kind of information that is <code>values</code>. According this parameter, will calculate the
846
         *  new point in a different way
847
         *
848
         * @see CADTool#transition(double, double, InputEvent)
849
         * @see #transition(double)
850
         * @see #transition(String)
851
         */
852
        private void transition(double[] values, InputEvent event, int type) {
853
                questionAsked = true;
854
                if (!cadToolStack.isEmpty()) {
855
                        CADTool ct = (CADTool) cadToolStack.peek();
856

    
857
                        switch (type) {
858
                        case ABSOLUTE:
859
                                ct.transition(values[0], values[1], event);
860
                                previousPoint = values;
861
                                break;
862
                        case RELATIVE_SCU:
863
                                // Comprobar que tenemos almacenado el punto anterior
864
                                // y crear nuevo con coordenadas relativas a ?l.
865
                                double[] auxSCU = values;
866
                                if (previousPoint != null) {
867
                                        auxSCU[0] = previousPoint[0] + values[0];
868
                                        auxSCU[1] = previousPoint[1] + values[1];
869
                                }
870
                                ct.transition(auxSCU[0], auxSCU[1], event);
871

    
872
                                previousPoint = auxSCU;
873
                                break;
874
                        case RELATIVE_SCP:
875
                                // TODO de momento no implementado.
876
                                ct.transition(values[0], values[1], event);
877
                                previousPoint = values;
878
                                break;
879
                        case POLAR_SCU://Relativo
880
                                // Comprobar que tenemos almacenado el punto anterior
881
                                // y crear nuevo con coordenadas relativas a ?l.
882
                                double[] auxPolarSCU = values;
883
                                if (previousPoint != null) {
884
                                        Point2D point = UtilFunctions.getPoint(new Point2D.Double(
885
                                                        previousPoint[0], previousPoint[1]), Math
886
                                                        .toRadians(values[1]), values[0]);
887
                                        auxPolarSCU[0] = point.getX();
888
                                        auxPolarSCU[1] = point.getY();
889
                                        ct.transition(auxPolarSCU[0], auxPolarSCU[1], event);
890
                                } else {
891
                                        Point2D point = UtilFunctions.getPoint(new Point2D.Double(
892
                                                        0, 0), Math.toRadians(values[1]), values[0]);
893
                                        auxPolarSCU[0] = point.getX();
894
                                        auxPolarSCU[1] = point.getY();
895
                                        ct.transition(auxPolarSCU[0], auxPolarSCU[1], event);
896
                                }
897
                                previousPoint = auxPolarSCU;
898
                                break;
899
                        case POLAR_SCP://Absoluto
900
                                double[] auxPolarSCP = values;
901
                                if (previousPoint != null) {
902
                                        Point2D point = UtilFunctions.getPoint(new Point2D.Double(
903
                                                        0, 0),  Math
904
                                                        .toRadians(values[1]), values[0]);
905
                                        auxPolarSCP[0] = point.getX();
906
                                        auxPolarSCP[1] = point.getY();
907
                                        ct.transition(auxPolarSCP[0], auxPolarSCP[1], event);
908
                                } else {
909
                                        Point2D point = UtilFunctions.getPoint(new Point2D.Double(
910
                                                        0, 0), values[1], values[0]);
911
                                        auxPolarSCP[0] = point.getX();
912
                                        auxPolarSCP[1] = point.getY();
913
                                        ct.transition(auxPolarSCP[0], auxPolarSCP[1], event);
914
                                }
915
                                previousPoint = auxPolarSCP;
916
                                break;
917
                        default:
918
                                break;
919
                        }
920
                        askQuestion();
921
                }
922
                configureMenu();
923
                PluginServices.getMainFrame().enableControls();
924
        }
925

    
926
        /**
927
         * <p>One of the three kind of transaction methods of the <i>finite machine</i> of
928
         *  edition.</p>
929
         *
930
         * <p>This one deals <code>value</code> as a single number used as a parameter for the current
931
         *    tool state. Ultimately, if isn't valid, <code>number</code> will be rewritten in the
932
         *    console notifying the user that isn't correct.</p>
933
         *
934
         * <p>After applying the changes, updates the controls available for managing the current data.</p>
935
         *
936
         * @param value value for the current tool state
937
         *
938
         * @see CADTool#transition(double)
939
         * @see #transition(double[], InputEvent, int)
940
         * @see #transition(String)
941
         */
942
        private void transition(double value) {
943
                questionAsked = true;
944
                if (!cadToolStack.isEmpty()) {
945
                        CADTool ct = (CADTool) cadToolStack.peek();
946
                        ct.transition(value);
947
                        askQuestion();
948
                }
949
                configureMenu();
950
                PluginServices.getMainFrame().enableControls();
951
        }
952

    
953
        /**
954
         * <p>One of the three kind of transaction methods of the <i>finite machine</i> of
955
         *  edition.</p>
956
         *
957
         * <p>This one deals <code>option</code> as an option of the current
958
         *    tool state. Ultimately, if isn't valid, <code>option</code> will be rewritten in the
959
         *    console notifying the user that isn't correct.</p>
960
         *
961
         * @param option option for the current tool state
962
         *
963
         * @see CADTool#transition(String)
964
         * @see #transition(double[], InputEvent, int)
965
         * @see #transition(double)
966
         */
967
        public void transition(String option) {
968
                questionAsked = true;
969
                if (!cadToolStack.isEmpty()) {
970
                        CADTool ct = (CADTool) cadToolStack.peek();
971
                        try {
972
                                ct.transition(option);
973
                        } catch (Exception e) {
974
                                IWindow window = PluginServices.getMDIManager().getActiveWindow();
975

    
976
                                if (window instanceof View) {
977
                                        ((View)window).getConsolePanel().addText(
978
                                                        "\n" + PluginServices.getText(this, "incorrect_option")
979
                                                        + " : " + option, JConsole.ERROR);
980
                                }
981
                        }
982
                        askQuestion();
983
                }
984
                configureMenu();
985
                PluginServices.getMainFrame().enableControls();
986
        }
987

    
988
        /**
989
         * Shows or hides a grid on the <code>ViewPort</code> of the associated <code>MapControl</code>.
990
         *
991
         * @param value <code>true</code> to make the grid visible; <code>false</code> to make it invisible
992
         */
993
        public void setGridVisibility(boolean value) {
994
                getGrid().setShowGrid(value);
995
                if (getMapControl()!=null){
996
                        getGrid().setViewPort(getMapControl().getViewPort());
997
                        getMapControl().repaint();
998
                }
999
        }
1000

    
1001
        /**
1002
         * Sets the snap tools enabled or disabled.
1003
         *
1004
         * @param activated <code>true</code> to enable the snap tools; <code>false</code> to disable them
1005
         *
1006
         * @see #isRefentEnabled()
1007
         */
1008
        public void setRefentEnabled(boolean activated) {
1009
                bRefent = activated;
1010
        }
1011

    
1012
        /**
1013
         * Determines if snap tools are enabled or disabled.
1014
         *
1015
         * @return <code>true</code> to enable the snap tools; <code>false</code> to disable them
1016
         *
1017
         * @see #setRefentEnabled(boolean)
1018
         */
1019
        public boolean isRefentEnabled()
1020
        {
1021
                return bRefent;
1022
        }
1023

    
1024
        /*
1025
         * (non-Javadoc)
1026
         * @see com.iver.cit.gvsig.fmap.tools.Behavior.Behavior#getListener()
1027
         */
1028
        public ToolListener getListener() {
1029
                return new ToolListener() {
1030
                        /**
1031
                         * @see com.iver.cit.gvsig.fmap.tools.Listeners.ToolListener#getCursor()
1032
                         */
1033
                        public Cursor getCursor() {
1034
                                return null;
1035
                        }
1036

    
1037
                        /**
1038
                         * @see com.iver.cit.gvsig.fmap.tools.Listeners.ToolListener#cancelDrawing()
1039
                         */
1040
                        public boolean cancelDrawing() {
1041
                                return false;
1042
                        }
1043
                };
1044
        }
1045

    
1046
        /**
1047
         * Returns the {@link CADTool CADTool} at the top of the stack without removing it from the CAD tool stack.
1048
         *
1049
         * @return the {@link CADTool CADTool} at the top of the stack
1050
         *
1051
         * @see #pushCadTool(CADTool)
1052
         * @see #popCadTool()
1053
         * @see #setCadTool(CADTool)
1054
         */
1055
        public CADTool getCadTool() {
1056
                return (CADTool) cadToolStack.peek();
1057
        }
1058

    
1059
        /**
1060
         * <p>Pushes a {@link CADTool CADTool} onto the top of the CAD tool stack, and sets it as current.</p>
1061
         *
1062
         * @param cadTool CAD tool to enable as current
1063
         *
1064
         * @see #getCadTool()
1065
         * @see #popCadTool()
1066
         * @see #setCadTool(CADTool)
1067
         */
1068
        public void pushCadTool(CADTool cadTool) {
1069
                cadToolStack.push(cadTool);
1070
                cadTool.setCadToolAdapter(this);
1071
                // cadTool.initializeStatus();
1072
                // cadTool.setVectorialAdapter(vea);
1073
                /*
1074
                 * int ret = cadTool.transition(null, editableFeatureSource, selection,
1075
                 * new double[0]);
1076
                 *
1077
                 * if ((ret & Automaton.AUTOMATON_FINISHED) ==
1078
                 * Automaton.AUTOMATON_FINISHED) { popCadTool();
1079
                 *
1080
                 * if (cadToolStack.isEmpty()) { pushCadTool(new
1081
                 * com.iver.cit.gvsig.gui.cad.smc.gen.CADTool());//new
1082
                 * SelectionCadTool());
1083
                 * PluginServices.getMainFrame().setSelectedTool("selection"); }
1084
                 *
1085
                 * askQuestion();
1086
                 *
1087
                 * getMapControl().drawMap(false); }
1088
                 */
1089
        }
1090

    
1091
        /**
1092
         * Removes the peek of the CAD tool stack.
1093
         *
1094
         * @see #pushCadTool(CADTool)
1095
         * @see #getCadTool()
1096
         * @see #setCadTool(CADTool)
1097
         */
1098
        public void popCadTool() {
1099
                cadToolStack.pop();
1100
        }
1101

    
1102
        /**
1103
         * <p>Displays at the console associated to the current active view that's being edited, the question of the following
1104
         *  operation that user can do with the current <code>CADTool</code>, only if it hasn't just answered.</p>
1105
         *
1106
         * <p>The format of the question will be according the following pattern:<br>
1107
         *   "\n#"<i>{cadtool at CAD tool stack peek}</i>.getQuestion()">"
1108
         * </p>
1109
         */
1110
        public void askQuestion() {
1111
                CADTool cadtool = (CADTool) cadToolStack.peek();
1112
                /*
1113
                 * if (cadtool..getStatus()==0){
1114
                 * PluginServices.getMainFrame().addTextToConsole("\n"
1115
                 * +cadtool.getName()); }
1116
                 */
1117
                if (PluginServices.getMDIManager().getActiveWindow() instanceof View)
1118
                {
1119
                        View vista = (View) PluginServices.getMDIManager().getActiveWindow();
1120
                        String question=cadtool.getQuestion();
1121
                        if (lastQuestion==null || !(lastQuestion.equals(question)) || questionAsked) {
1122
                        vista.getConsolePanel().addText(
1123
                                        "\n" + "#" + question + " > ", JConsole.MESSAGE);
1124
                        // ***PluginServices.getMainFrame().addTextToConsole("\n" +
1125
                        // cadtool.getQuestion());
1126
                        questionAsked = false;
1127
                        }
1128
                        lastQuestion=question;
1129
                }
1130

    
1131
        }
1132

    
1133
        /**
1134
         * Empties the CAD tools stack and pushes <code>cadTool</code> in it.
1135
         *
1136
         * @param cadTool CAD tool to set at the peek of the stack
1137
         *
1138
         * @see #pushCadTool(CADTool)
1139
         * @see #popCadTool()
1140
         * @see #getCadTool()
1141
         */
1142
        public void setCadTool(CADTool cadTool) {
1143
                cadToolStack.clear();
1144
                pushCadTool(cadTool);
1145
                // askQuestion();
1146
        }
1147

    
1148
        /**
1149
         * <p>Removes all geometries selected in the associated <code>MapControl</code>.
1150
         */
1151
        public void delete() {
1152
                ILayerEdited aux = CADExtension.getEditionManager().getActiveLayerEdited();
1153
                if (!(aux instanceof VectorialLayerEdited))
1154
                        return;
1155
                VectorialLayerEdited vle = (VectorialLayerEdited) aux;
1156
                VectorialEditableAdapter vea = vle.getVEA();
1157

    
1158
                vea.startComplexRow();
1159
                try {
1160
                        FBitSet selection = vea.getSelection();
1161
                        int[] indexesToDel = new int[selection.cardinality()];
1162
                        int j = 0;
1163
                        for (int i = selection.nextSetBit(0); i >= 0; i = selection
1164
                                        .nextSetBit(i + 1)) {
1165
                                indexesToDel[j++] = i;
1166
                                // /vea.removeRow(i);
1167
                        }
1168

    
1169
//                          ArrayList selectedRow = vle.getSelectedRow();
1170
//
1171
//                          int[] indexesToDel = new int[selectedRow.size()];
1172
//                          for (int i = 0;i < selectedRow.size(); i++) {
1173
//                                  IRowEdited edRow = (IRowEdited) selectedRow.get(i);
1174
//                                  indexesToDel[i] = vea.getInversedIndex(edRow.getIndex());
1175
//                                  }
1176
//
1177
                        for (int i = indexesToDel.length - 1; i >= 0; i--) {
1178
                                vea.removeRow(indexesToDel[i], PluginServices.getText(this,
1179
                                                "deleted_feature"),EditionEvent.GRAPHIC);
1180
                        }
1181
                        System.out.println("clear Selection");
1182
                        selection.clear();
1183
                        vle.clearSelection(VectorialLayerEdited.NOTSAVEPREVIOUS);
1184
                } catch (ReadDriverException e) {
1185
                        NotificationManager.addError(e.getMessage(),e);
1186
                } finally {
1187
                        String description=PluginServices.getText(this,"remove_geometry");
1188
                        vea.endComplexRow(description);
1189
                }
1190

    
1191

    
1192
                /*
1193
                 * if (getCadTool() instanceof SelectionCADTool) { SelectionCADTool
1194
                 * selTool = (SelectionCADTool) getCadTool(); selTool.clearSelection(); }
1195
                 */
1196
                refreshEditedLayer();
1197
        }
1198

    
1199
        /**
1200
         * @see CADGrid#setAdjustGrid(boolean)
1201
         */
1202
        public void setAdjustGrid(boolean b) {
1203
                getGrid().setAdjustGrid(b);
1204
        }
1205

    
1206
        /**
1207
         * <p>Responds to actions of writing common key commands for all kind of CAD operations, enabling/disabling after
1208
         *  the controls to manage the available information according the tool selected:
1209
         *  <ul>
1210
         *   <li><i>eliminar</i>: removes the geometries that are now selected.</li>
1211
         *   <li><i>escape</i>: executes different actions according to the current CAD tool of the associated <code>MapControl</code>:
1212
         *    <ul>
1213
         *     <li>If the tool enabled is identified by <i>cadtooladapter</i>: empties the CAD tools stack, changing the current tool by
1214
         *      a {@link SelectionCADTool SelectionCADTool}, which is identified by <i>_selection</i> and allows select features of the
1215
         *      active vector layer of the associated <code>MapControl</code> instance. </li>
1216
         *     <li>Otherwise, that means current associated <code>MapControl</code> instance isn't identified by "<i>cadtooladapter</i>",
1217
         *      changes the enabled tool by the previous.</li>
1218
         *    </ul>
1219
         *   </li>
1220
         *  </ul>
1221
         * </p>
1222
         *
1223
         * @param actionCommand identifier of the key action command executed by the user
1224
         *
1225
         * @see SelectionCADTool
1226
         * @see MapControl#setPrevTool()
1227
         */
1228
        public void keyPressed(String actionCommand) {
1229
                if (CADExtension.getEditionManager().getActiveLayerEdited()== null) {
1230
                        return;
1231
                }
1232
                if (actionCommand.equals("eliminar")) {
1233
                        delete();
1234
                } else if (actionCommand.equals("escape")) {
1235
                        if (getMapControl().getCurrentTool().equals("cadtooladapter")) {
1236
                                CADTool ct = (CADTool) cadToolStack.peek();
1237
                                ct.end();
1238
                                cadToolStack.clear();
1239
                                SelectionCADTool selCad = new SelectionCADTool();
1240
                                selCad.init();
1241
                                VectorialLayerEdited vle = (VectorialLayerEdited) CADExtension
1242
                                                .getEditionManager().getActiveLayerEdited();
1243
                                try {
1244
                                        vle.clearSelection(VectorialLayerEdited.NOTSAVEPREVIOUS);
1245
                                } catch (ReadDriverException e) {
1246
                                        NotificationManager.addError(e.getMessage(),e);
1247
                                }
1248

    
1249
                                pushCadTool(selCad);
1250
                                // getVectorialAdapter().getSelection().clear();
1251

    
1252
                                refreshEditedLayer();
1253

    
1254

    
1255
                                PluginServices.getMainFrame().setSelectedTool("_selection");
1256
                                // askQuestion();
1257
                        } else {
1258
                                getMapControl().setPrevTool();
1259
                        }
1260
                }
1261

    
1262
                PluginServices.getMainFrame().enableControls();
1263

    
1264
        }
1265

    
1266
        /**
1267
         * <p>Applies a lightweight repaint of the active layer being edited.</p>
1268
         *
1269
         * <p>All layers under it won't be drawn, only the upper one and whose are over that layer in the TOC.</p>
1270
         *
1271
         * @see MapControl#rePaintDirtyLayers()
1272
         */
1273
        public void refreshEditedLayer()
1274
        {
1275
                ILayerEdited edLayer = CADExtension.getEditionManager().getActiveLayerEdited();
1276
                if (edLayer != null)
1277
                {
1278
//                        edLayer.getLayer().setDirty(true);
1279
                        getMapControl().rePaintDirtyLayers();
1280
                }
1281

    
1282
        }
1283

    
1284
        /**
1285
         * Gets the {@link CADGrid CADGrid} that can be drawn on the <code>ViewPort</code> of the associated <code>MapControl</code>.
1286
         *
1287
         * @return reference to the <i>grid</i> that can be applied on the <code>ViewPort</code>
1288
         *
1289
         * @see #setGridVisibility(boolean)
1290
         */
1291
        public CADGrid getGrid() {
1292
                return cadgrid;
1293
        }
1294

    
1295
        /**
1296
         * Determines if is enabled or not the <i>orto</i> mode.
1297
         *
1298
         * @return <code>true</code> if is enabled the <i>orto</i> mode; otherwise <code>false</code>
1299
         *
1300
         * @see #setOrtoMode(boolean)
1301
         */
1302
        public boolean isOrtoMode() {
1303
                return bOrtoMode;
1304
        }
1305

    
1306
        /**
1307
         * Enables / disables the <i>orto</i> mode.
1308
         *
1309
         * @param b the desired value
1310
         *
1311
         * @see #isOrtoMode()
1312
         */
1313
        public void setOrtoMode(boolean b) {
1314
                bOrtoMode = b;
1315
        }
1316

    
1317
        /**
1318
         * Associates and stores the specified name with the specified {@link CADTool CADTool}.
1319
         *
1320
         * @param name name of the tool
1321
         * @param c CAD tool to interactuate editing the layers
1322
         *
1323
         * @see #getCADTools()
1324
         * @see #getCADTool(String)
1325
         */
1326
        public static void addCADTool(String name, CADTool c) {
1327
                namesCadTools.put(name, c);
1328

    
1329
        }
1330

    
1331
        /**
1332
         * Gets all CAD tools available to edit layers with this tool listener.
1333
         *
1334
         * @return CAD tools available to edit layers with this tool listener
1335
         *
1336
         * @see #addCADTool(String, CADTool)
1337
         * @see #getCADTool(String)
1338
         */
1339
        public static CADTool[] getCADTools() {
1340
                return (CADTool[]) CADToolAdapter.namesCadTools.values().toArray(new CADTool[0]);
1341
        }
1342

    
1343
        /**
1344
         * Returns the {@link CADTool CADTool} to which the specified name is mapped.
1345
         *
1346
         * @param text name of the tool
1347
         * @return the CAD tool whose associated name is to be returned
1348
         *
1349
         * @see #addCADTool(String, CADTool)
1350
         * @see #getCADTools()
1351
         */
1352
        public CADTool getCADTool(String text) {
1353
                CADTool ct = (CADTool) namesCadTools.get(text);
1354
                return ct;
1355
        }
1356

    
1357
        /**
1358
         * Gets the object used to manage the edition of the layers of the associated <code>MapControl</code>.
1359
         *
1360
         * @see EditionManager
1361
         *
1362
         * @return object used to manage the edition of the layers
1363
         */
1364
        public EditionManager getEditionManager() {
1365
                return editionManager;
1366
        }
1367

    
1368
        /**
1369
         * <p>Initializes the <i>flatness</i> with the defined in preferences.</p>
1370
         *
1371
         * <p>The <i>flatness</i> is the maximum tolerance used to approximate curved lines in a <i>shape</i> by polylines.</p>
1372
         * <p>The shapes doesn't support primitive like arcs neither other curved lines to draw their geometries, then for drawing any
1373
         *  kind of this geometries the curved lines are drawn approximately by a polyline. And for doing more realistic that curves,
1374
         *  is used the <i>flatness</i> parameter, that indicates that the difference between each arc and the straight segment that
1375
         *  approximates it must be in the worse case, like the <i>flatness</i>.</p>
1376
         *
1377
         * @see FConverter#FLATNESS
1378
         */
1379
        public void initializeFlatness() {
1380
                if (!flatnessInitialized){
1381
                        flatnessInitialized=true;
1382
                        Preferences prefs = Preferences.userRoot().node( "cadtooladapter" );
1383
                        double flatness = prefs.getDouble("flatness",FConverter.FLATNESS);
1384
                        FConverter.FLATNESS=flatness;
1385
                }
1386
        }
1387

    
1388
        /**
1389
         * <p>Updates the grid on the <code>ViewPort</code> of the associated <code>MapControl</code>
1390
         *  object according the values in the {@link com.iver.cit.gvsig.gui.cad.CADToolAdapter.prefs.Preferences com.iver.cit.gvsig.gui.cad.CADToolAdapter.prefs.Preferences}.</p>
1391
         *
1392
         * <p>The preferences are:
1393
         *  <ul>
1394
         *   <li>Show/hide the grid.</li>
1395
         *   <li>Adjust or not the grid.</li>
1396
         *   <li>Horizontal ( X ) line separation.</li>
1397
         *   <li>Vertical ( Y ) line separation.</li>
1398
         *  </ul>
1399
         * </p>
1400
         */
1401
        public void initializeGrid(){
1402
                boolean showGrid = prefs.getBoolean("grid.showgrid",getGrid().isShowGrid());
1403
                boolean adjustGrid = prefs.getBoolean("grid.adjustgrid",getGrid().isAdjustGrid());
1404

    
1405
                double dx = prefs.getDouble("grid.distancex",getGrid().getGridSizeX());
1406
                double dy = prefs.getDouble("grid.distancey",getGrid().getGridSizeY());
1407

    
1408
                setGridVisibility(showGrid);
1409
                setAdjustGrid(adjustGrid);
1410
                getGrid().setGridSizeX(dx);
1411
                getGrid().setGridSizeY(dy);
1412
        }
1413

    
1414
        /**
1415
         * <p>Returns the type of the shape that's the current active and vector layer being edited.</p>
1416
         *
1417
         * @see FLyrVect#getShapeType()
1418
         *
1419
         * @return type of the shape that's the current active and vector layer being edited
1420
         */
1421
        public int getActiveLayerType() {
1422
                int type=FShape.MULTI;
1423
                try {
1424
                        type=((FLyrVect)CADExtension.getEditionManager().getActiveLayerEdited().getLayer()).getShapeType();
1425
                } catch (ReadDriverException e) {
1426
                        NotificationManager.addError(e);
1427
                }
1428
                return type;
1429
        }
1430
}