Statistics
| Revision:

svn-gvsig-desktop / trunk / libraries / libFMap / src / com / iver / cit / gvsig / fmap / MapControl.java @ 6261

History | View | Annotate | Download (25.3 KB)

1
/* gvSIG. Sistema de Informaci?n Geogr?fica de la Generalitat Valenciana
2
 *
3
 * Copyright (C) 2004 IVER T.I. and Generalitat Valenciana.
4
 *
5
 * This program is free software; you can redistribute it and/or
6
 * modify it under the terms of the GNU General Public License
7
 * as published by the Free Software Foundation; either version 2
8
 * of the License, or (at your option) any later version.
9
 *
10
 * This program is distributed in the hope that it will be useful,
11
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13
 * GNU General Public License for more details.
14
 *
15
 * You should have received a copy of the GNU General Public License
16
 * along with this program; if not, write to the Free Software
17
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307,USA.
18
 *
19
 * For more information, contact:
20
 *
21
 *  Generalitat Valenciana
22
 *   Conselleria d'Infraestructures i Transport
23
 *   Av. Blasco Ib??ez, 50
24
 *   46010 VALENCIA
25
 *   SPAIN
26
 *
27
 *      +34 963862235
28
 *   gvsig@gva.es
29
 *      www.gvsig.gva.es
30
 *
31
 *    or
32
 *
33
 *   IVER T.I. S.A
34
 *   Salamanca 50
35
 *   46005 Valencia
36
 *   Spain
37
 *
38
 *   +34 963163400
39
 *   dac@iver.es
40
 */
41
package com.iver.cit.gvsig.fmap;
42

    
43
import java.awt.Color;
44
import java.awt.Dimension;
45
import java.awt.Graphics;
46
import java.awt.Graphics2D;
47
import java.awt.GraphicsEnvironment;
48
import java.awt.event.ActionEvent;
49
import java.awt.event.ActionListener;
50
import java.awt.event.ComponentEvent;
51
import java.awt.event.ComponentListener;
52
import java.awt.event.MouseEvent;
53
import java.awt.event.MouseListener;
54
import java.awt.event.MouseMotionListener;
55
import java.awt.event.MouseWheelEvent;
56
import java.awt.event.MouseWheelListener;
57
import java.awt.geom.Point2D;
58
import java.awt.geom.Rectangle2D;
59
import java.awt.image.BufferedImage;
60
import java.util.HashMap;
61

    
62
import javax.swing.JComponent;
63
import javax.swing.Timer;
64

    
65
import org.cresques.cts.IProjection;
66

    
67
import com.iver.cit.gvsig.fmap.crs.CRSFactory;
68
import com.iver.cit.gvsig.fmap.edition.commands.CommandListener;
69
import com.iver.cit.gvsig.fmap.layers.LayerEvent;
70
import com.iver.cit.gvsig.fmap.tools.BehaviorException;
71
import com.iver.cit.gvsig.fmap.tools.CompoundBehavior;
72
import com.iver.cit.gvsig.fmap.tools.Behavior.Behavior;
73
import com.iver.utiles.exceptionHandling.ExceptionHandlingSupport;
74
import com.iver.utiles.exceptionHandling.ExceptionListener;
75
import com.iver.utiles.swing.threads.Cancellable;
76

    
77

    
78
/**
79
 * MapControl.
80
 *
81
 * @author Fernando Gonz?lez Cort?s
82
 */
83
public class MapControl extends JComponent implements ComponentListener,
84
                        CommandListener {
85
        /** Cuando la vista est? actualizada. */
86
        public static final int ACTUALIZADO = 0;
87

    
88
        /** Cuando la vista est? desactualizada. */
89
        public static final int DESACTUALIZADO = 1;
90
    public static final int ONLY_GRAPHICS = 2;
91
    // public static final int FAST_PAINT = 3;
92
        //private static Logger logger = Logger.getLogger(MapControl.class.getName());
93
        private FMap mapContext = null;
94
    //private boolean drawerAlive = false;
95
        private HashMap namesMapTools = new HashMap();
96
        private Behavior currentMapTool = null;
97
        private int status = DESACTUALIZADO;
98
        private BufferedImage image = null;
99
        private String currentTool;
100
        private CancelDraw canceldraw;
101
        //private boolean isCancelled = true;
102
        private Timer timer;
103
        protected ViewPort vp;
104
        //private Drawer drawer;
105
    private Drawer2 drawer2;
106
    // private boolean firstDraw = true;
107
        private MapToolListener mapToolListener = new MapToolListener();
108
        private MapContextListener mapContextListener = new MapContextListener();
109
        private ExceptionHandlingSupport exceptionHandlingSupport = new ExceptionHandlingSupport();
110

    
111
        private String prevTool;
112

    
113
        /**
114
     * We need this to avoid not wanted refresh. REMEMBER TO SET TO TRUE!!
115
     */
116
    // private boolean paintEnabled = false;
117

    
118
        /**
119
         * Crea un nuevo NewMapControl.
120
         */
121
        public MapControl() {
122
                this.setName("MapControl");
123
                setDoubleBuffered(false);
124
                setOpaque(true);
125
                status = DESACTUALIZADO;
126

    
127
                //Clase usada para cancelar el dibujado
128
                canceldraw = new CancelDraw();
129

    
130
                //Modelo de datos y ventana del mismo
131
                // TODO: Cuando creamos un mapControl, deber?amos asignar
132
                // la projecci?n por defecto con la que vayamos a trabajar.
133
                // 23030 es el c?digo EPSG del UTM30 elipsoide ED50
134
                vp = new ViewPort(CRSFactory.getCRS("EPSG:23030"));
135
                setMapContext(new FMap(vp));
136

    
137
                //eventos
138
                this.addComponentListener(this);
139
                this.addMouseListener(mapToolListener);
140
                this.addMouseMotionListener(mapToolListener);
141
                this.addMouseWheelListener(mapToolListener);
142

    
143
        this.drawer2 = new Drawer2();
144
                //Timer para mostrar el redibujado mientras se dibuja
145
                timer = new Timer(300,
146
                                new ActionListener() {
147
                                        public void actionPerformed(ActionEvent e) {
148
                                                MapControl.this.repaint();
149
                                        }
150
                                });
151
        }
152

    
153
        /**
154
         * Inserta el modelo.
155
         *
156
         * @param model FMap.
157
         */
158
        public void setMapContext(FMap model) {
159
                if (mapContext != null) {
160
                        mapContext.removeAtomicEventListener(mapContextListener);
161
                }
162

    
163
                mapContext = model;
164

    
165
                if (mapContext.getViewPort() == null) {
166
                        mapContext.setViewPort(vp);
167
                } else {
168
                        vp = mapContext.getViewPort();
169

    
170
                        // vp.setImageSize(new Dimension(getWidth(), getHeight()));
171
                        //System.err.println("Viewport en setMapContext:" + vp);
172
                }
173

    
174
                mapContext.addAtomicEventListener(mapContextListener);
175

    
176
                status = DESACTUALIZADO;
177
        }
178

    
179
        /**
180
         * Devuelve la proyecci?n.
181
         *
182
         * @return Proyecci?n.
183
         */
184
        public IProjection getProjection() {
185
                return getMapContext().getProjection();
186
        }
187

    
188
        /**
189
         * Inserta una proyecci?n.
190
         *
191
         * @param proj Proyecci?n.
192
         */
193
        public void setProjection(IProjection proj) {
194
                getMapContext().setProjection(proj);
195
        }
196

    
197
        /**
198
         * Devuelve el modelo.
199
         *
200
         * @return FMap.
201
         */
202
        public FMap getMapContext() {
203
                return mapContext;
204
        }
205

    
206
        /**
207
         * Registra una herramienta (tool).
208
         *
209
         * @param name Nombre de la herramienta.
210
         * @param tool Herramienta.
211
         */
212
        public void addMapTool(String name, Behavior tool) {
213
                namesMapTools.put(name, tool);
214
                tool.setMapControl(this);
215
        }
216

    
217
        public void addMapTool(String name, Behavior[] tools){
218
                CompoundBehavior tool = new CompoundBehavior(tools);
219
                addMapTool(name, tool);
220
        }
221

    
222
        /**
223
         * DOCUMENT ME!
224
         *
225
         * @param toolName DOCUMENT ME!
226
         */
227
        public void setTool(String toolName) {
228
                prevTool=getTool();
229
                Behavior mapTool = (Behavior) namesMapTools.get(toolName);
230
                currentMapTool = mapTool;
231
                currentTool = toolName;
232
                this.setCursor(mapTool.getCursor());
233
        }
234
        public Behavior getCurrentMapTool(){
235
                return currentMapTool;
236
        }
237
        /**
238
         * Devuelve el nombre de la herramienta seleccionada.
239
         *
240
         * @return nombre.
241
         */
242
        public String getTool() {
243
                return currentTool;
244
        }
245

    
246
        /**
247
         * Cancela el dibujado. Se espera a que la cancelaci?n surta efecto
248
         */
249
        public void cancelDrawing() {
250
                /* if (drawer != null) {
251
                        if (!drawer.isAlive()) {
252
                                return;
253
                        }
254
                }
255
                */
256
                canceldraw.setCanceled(true);
257

    
258
                /* while (!isCancelled) {
259
                        if (!drawer.isAlive()) {
260
                            // Si hemos llegado aqu? con un thread vivo, seguramente
261
                            // no estamos actualizados.
262

263
                                break;
264
                        }
265

266
                }
267
                canceldraw.setCancel(false);
268
                isCancelled = false;
269
        drawerAlive = false; */
270
        }
271

    
272
    private boolean adaptToImageSize()
273
    {
274
        if ((image == null) || (vp.getImageWidth() != this.getWidth()) || (vp.getImageHeight() != this.getHeight()))
275
        {
276
            image = new BufferedImage(this.getWidth(), this.getHeight(),
277
                    BufferedImage.TYPE_INT_ARGB);
278
            // ESTILO MAC
279
//                image = GraphicsEnvironment.getLocalGraphicsEnvironment()
280
//                                .getDefaultScreenDevice().getDefaultConfiguration()
281
//                                .createCompatibleImage(this.getWidth(), this.getHeight());
282
            vp.setImageSize(new Dimension(getWidth(), getHeight()));
283
            getMapContext().getViewPort().setScale();
284

    
285

    
286
            Graphics gTemp = image.createGraphics();
287
            Color theBackColor = vp.getBackColor();
288
            if (theBackColor == null)
289
                gTemp.setColor(Color.WHITE);
290
            else
291
                gTemp.setColor(theBackColor);
292

    
293
            gTemp.fillRect(0,0,getWidth(), getHeight());
294
            gTemp.dispose();
295
            status = DESACTUALIZADO;
296
            // g.drawImage(image,0,0,null);
297
            return true;
298
        }
299
        return false;
300
    }
301

    
302
        /**
303
         * @see javax.swing.JComponent#paintComponent(java.awt.Graphics)
304
         */
305
        protected void paintComponent(Graphics g) {
306
        adaptToImageSize();
307
        /* if (status == FAST_PAINT) {
308
            System.out.println("FAST_PAINT");
309
            g.drawImage(image,0,0,null);
310
            status = ACTUALIZADO;
311
            return;
312
        } */
313
        // System.out.println("PINTANDO MAPCONTROL" + this);
314
                if (status == ACTUALIZADO) {
315
                        // LWS logger.debug("Dibujando la imagen obtenida");
316

    
317
                        /*
318
                         * Si hay un behaviour y la imagen es distinta de null se delega el dibujado
319
                         * en dicho behaviour
320
                         */
321
            if (image != null)
322
            {
323
                if (currentMapTool != null)
324
                    currentMapTool.paintComponent(g);
325
                else
326
                    g.drawImage(image,0,0,null);
327

    
328
                                // System.out.println("Pinto ACTUALIZADO");
329
                        }
330
                } else if ((status == DESACTUALIZADO)
331
                || (status == ONLY_GRAPHICS)) {
332
                        // LWS System.out.println("DESACTUALIZADO: Obteniendo la imagen de la cartograf?a");
333
                        /* if (isOpaque())
334
                        {
335
                            if (image==null)
336
                            {
337
                                g.setColor(vp.getBackColor());
338
                                g.fillRect(0,0,getWidth(), getHeight());
339
                            }
340
                            // else g.drawImage(image,0,0,null);
341
                        } */
342
            // cancelDrawing();
343
                        //Se crea la imagen con el color de fonde deseado
344
                        /* if (image == null)
345
                        {
346
                                image = new BufferedImage(this.getWidth(), this.getHeight(),
347
                                                BufferedImage.TYPE_INT_ARGB);
348
                                vp.setImageSize(new Dimension(getWidth(), getHeight()));
349
                                Graphics gTemp = image.createGraphics();
350
                            Color theBackColor = vp.getBackColor();
351
                            if (theBackColor == null)
352
                                gTemp.setColor(Color.WHITE);
353
                            else
354
                                gTemp.setColor(theBackColor);
355

356
                                gTemp.fillRect(0,0,getWidth(), getHeight());
357
                                gTemp.dispose();
358
                                // g.drawImage(image,0,0,null);
359
                                System.out.println("Imagen con null en DESACTUALIZADO. Width = " + this.getWidth());
360
                        } */
361
            // else
362
            // {
363

    
364

    
365
            // if (image != null)
366
            //  {
367
                g.drawImage(image,0,0,null);
368

    
369
                drawer2.put(new PaintingRequest());
370
                timer.start();
371
            /* }
372
            else
373
                return; */
374
            // }
375

    
376
            /* if (drawerAlive == false)
377
            {
378
                drawer = new Drawer(image, canceldraw);
379
                drawer.start();
380
                        //Se lanza el tread de dibujado
381
            } */
382

    
383
                        // status = ACTUALIZADO;
384
                }
385
        }
386

    
387
        /**
388
         * Devuelve la imagen de la vista.
389
         *
390
         * @return imagen.
391
         */
392
        public BufferedImage getImage() {
393
                return image;
394
        }
395

    
396
        /**
397
         * Marca el mapa para que en el pr?ximo redibujado se acceda a la
398
         * cartograf?a para reobtener la imagen
399
         * @param doClear Solo deber?a ser true cuando se llama desde pan
400
         */
401
        public void drawMap(boolean doClear) {
402
                cancelDrawing();
403
                System.out.println("drawMap con doClear=" + doClear);
404
        status = DESACTUALIZADO;
405
        getMapContext().getLayers().setDirty(true);
406
                if (doClear)
407
        {
408
            // image = null; // Se usa para el PAN
409
            if (image != null)
410
            {
411
                Graphics2D g = image.createGraphics();
412
                Color theBackColor = vp.getBackColor();
413
                if (theBackColor == null)
414
                    g.setColor(Color.WHITE);
415
                else
416
                    g.setColor(theBackColor);
417
                g.fillRect(0, 0, vp.getImageWidth(), vp.getImageHeight());
418
                g.dispose();
419
            }
420
        }
421
                repaint();
422
        }
423
        
424
        public void rePaintDirtyLayers()
425
        {
426
                cancelDrawing();
427
        status = DESACTUALIZADO;
428
        repaint();
429
        }
430
        
431
    public void drawGraphics() {
432
        status = ONLY_GRAPHICS;
433
        repaint();
434
    }
435

    
436
        /**
437
         * @see java.awt.event.ComponentListener#componentHidden(java.awt.event.ComponentEvent)
438
         */
439
        public void componentHidden(ComponentEvent e) {
440
        }
441

    
442
        /**
443
         * @see java.awt.event.ComponentListener#componentMoved(java.awt.event.ComponentEvent)
444
         */
445
        public void componentMoved(ComponentEvent e) {
446
        }
447

    
448
        /**
449
         * @see java.awt.event.ComponentListener#componentResized(java.awt.event.ComponentEvent)
450
         */
451
        public void componentResized(ComponentEvent e) {
452
                /* image = new BufferedImage(this.getWidth(), this.getHeight(),
453
                                BufferedImage.TYPE_INT_ARGB);
454
                Graphics gTemp = image.createGraphics();
455
                gTemp.setColor(vp.getBackColor());
456
                gTemp.fillRect(0,0,getWidth(), getHeight());
457
        System.out.println("MapControl resized");
458
            // image = null;
459
            vp.setImageSize(new Dimension(getWidth(), getHeight()));
460
                getMapContext().getViewPort().setScale(); */
461
                // drawMap(true);
462
        }
463

    
464
        /**
465
         * @see java.awt.event.ComponentListener#componentShown(java.awt.event.ComponentEvent)
466
         */
467
        public void componentShown(ComponentEvent e) {
468
        }
469

    
470
        /**
471
         * A?ade un listener de tipo ExceptionListener.
472
         *
473
         * @param o ExceptionListener.
474
         */
475
        public void addExceptionListener(ExceptionListener o) {
476
                exceptionHandlingSupport.addExceptionListener(o);
477
        }
478

    
479
        /**
480
         * Borra la ExceptioListener que se pasa como par?metro.
481
         *
482
         * @param o ExceptionListener.
483
         *
484
         * @return True si se borra correctamente.
485
         */
486
        public boolean removeExceptionListener(ExceptionListener o) {
487
                return exceptionHandlingSupport.removeExceptionListener(o);
488
        }
489

    
490
        /**
491
         * Lanza una Excepci?n.
492
         *
493
         * @param t Excepci?n.
494
         */
495
        private void throwException(Throwable t) {
496
                exceptionHandlingSupport.throwException(t);
497
        }
498

    
499

    
500
    private class PaintingRequest
501
    {
502

    
503
        public PaintingRequest()
504
        {
505
        }
506

    
507
        public void paint()
508
        {
509
            try
510
            {
511
                    canceldraw.setCanceled(false);
512
                /* if (image == null)
513
                {
514
                    image = new BufferedImage(vp.getImageWidth(), vp.getImageHeight(),
515
                            BufferedImage.TYPE_INT_ARGB);
516
                    Graphics gTemp = image.createGraphics();
517
                    Color theBackColor = vp.getBackColor();
518
                    if (theBackColor == null)
519
                        gTemp.setColor(Color.WHITE);
520
                    else
521
                        gTemp.setColor(theBackColor);
522

523
                    gTemp.fillRect(0,0,getWidth(), getHeight());
524
                    gTemp.dispose();
525
                    // g.drawImage(image,0,0,null);
526
                    System.out.println("Imagen con null en DESACTUALIZADO. Width = " + this.getWidth());
527
                } */
528
                Graphics2D g = image.createGraphics();
529

    
530
                ViewPort viewPort = mapContext.getViewPort();
531

    
532
                if (status == DESACTUALIZADO)
533
                {
534
                        Graphics2D gTemp = image.createGraphics();
535
                    Color theBackColor = viewPort.getBackColor();
536
                    if (theBackColor == null)
537
                        gTemp.setColor(Color.WHITE);
538
                    else
539
                        gTemp.setColor(theBackColor);
540
                    gTemp.fillRect(0, 0, viewPort.getImageWidth(), viewPort.getImageHeight());
541
                    status = ACTUALIZADO;
542
                    // ESTILO MAC
543
//                    BufferedImage imgMac = new BufferedImage(vp.getImageWidth(), vp.getImageHeight(),
544
//                            BufferedImage.TYPE_INT_ARGB);
545
// 
546
//                    mapContext.draw(imgMac, g, canceldraw, mapContext.getScaleView());
547
//                    g.drawImage(imgMac, 0, 0, null);
548
                    // FIN ESTILO MAC
549
                    // SIN MAC:
550
                    mapContext.draw(image, g, canceldraw, mapContext.getScaleView());
551

    
552
                }
553
                else if (status == ONLY_GRAPHICS)
554
                {
555
                    status = ACTUALIZADO;
556
                    mapContext.drawGraphics(image, g, canceldraw,mapContext.getScaleView());
557

    
558
                }
559

    
560

    
561
                // status = FAST_PAINT;
562
              //  drawerAlive = false;
563
                timer.stop();
564
                repaint();
565

    
566

    
567
            } catch (Throwable e) {
568
                timer.stop();
569
              //  isCancelled = true;
570
                e.printStackTrace();
571
                throwException(e);
572
            } finally {
573
            }
574

    
575
        }
576

    
577
    }
578

    
579
    /**
580
     * @author fjp
581
     *
582
     * Basasdo en el patr?n WorkerThread
583
     *
584
     */
585
    public class Drawer2
586
    {
587
        // Una mini cola de 2. No acumulamos peticiones de dibujado
588
        // dibujamos solo lo ?ltimo que nos han pedido.
589
        private PaintingRequest paintingRequest;
590
        private PaintingRequest waitingRequest;
591

    
592
        private boolean waiting;
593
        private boolean shutdown;
594

    
595
        public void setShutdown(boolean isShutdown)
596
        {
597
            shutdown = isShutdown;
598
        }
599

    
600
        public Drawer2()
601
        {
602
            paintingRequest = null;
603
            waitingRequest = null;
604
            waiting = false;
605
            shutdown = false;
606
            new Thread(new Worker()).start();
607
        }
608

    
609
        public void put(PaintingRequest newPaintRequest)
610
        {
611
            waitingRequest = newPaintRequest;
612
            if (waiting)
613
            {
614
                synchronized (this) {
615
                    notifyAll();
616
                }
617
            }
618
        }
619

    
620
        public PaintingRequest take()
621
        {
622
            if (waitingRequest == null)
623
            {
624
                synchronized (this) {
625
                    waiting = true;
626
                    try {
627
                        wait();
628
                    }
629
                    catch (InterruptedException ie)
630
                    {
631
                        waiting = false;
632
                    }
633
                }
634
            }
635
            paintingRequest = waitingRequest;
636
            waitingRequest = null;
637
            return paintingRequest;
638
        }
639

    
640

    
641
        private class Worker implements Runnable
642
        {
643
            public void run()
644
            {
645
                while (!shutdown)
646
                {
647
                    PaintingRequest p = take();
648
                    System.out.println("Pintando");
649
                    if (image != null){
650
                            cancelDrawing();
651
                        p.paint();
652
                    } else
653
                        status = DESACTUALIZADO;
654
                }
655
            }
656
        }
657
    }
658

    
659
        /**
660
         * Clase utilizada para dibujar las capas.
661
         *
662
         * @author Vicente Caballero Navarro
663
         */
664
        public class Drawer extends Thread {
665
                //private Graphics g;
666
                private BufferedImage image = null;
667
                private CancelDraw cancel;
668
                //private boolean threadCancel = false;
669

    
670
                /**
671
                 * Crea un nuevo Drawer.
672
                 *
673
                 */
674
                public Drawer(BufferedImage image, CancelDraw cancel)
675
        {
676
                        this.image = image;
677
                        this.cancel = cancel;
678
         //   drawerAlive = true;
679
                }
680

    
681
                /**
682
                 * @see java.lang.Runnable#run()
683
                 */
684
                public void run() {
685
                        try {
686
                                // synchronized (Drawer.class) {
687
                                    Graphics2D g = image.createGraphics();
688

    
689
                                    ViewPort viewPort = mapContext.getViewPort();
690
                    if (status == DESACTUALIZADO)
691
                    {
692
                                        Color theBackColor = viewPort.getBackColor();
693
                                        if (theBackColor == null)
694
                                            g.setColor(Color.WHITE);
695
                                        else
696
                                            g.setColor(theBackColor);
697
                                            g.fillRect(0, 0, viewPort.getImageWidth(), viewPort.getImageHeight());
698
                        status = ACTUALIZADO;
699
                        mapContext.draw(image, g, cancel,mapContext.getScaleView());
700
                    }
701
                    else if (status == ONLY_GRAPHICS)
702
                    {
703
                        status = ACTUALIZADO;
704
                        mapContext.drawGraphics(image, g, cancel,mapContext.getScaleView());
705
                    }
706

    
707
                                        timer.stop();
708
                    // status = FAST_PAINT;
709
                  //  drawerAlive = false;
710
                                        repaint();
711

    
712

    
713

    
714
                                // }
715
                        } catch (Throwable e) {
716
                            timer.stop();
717
                                //isCancelled = true;
718
                e.printStackTrace();
719
                                throwException(e);
720
                        } finally {
721
                        }
722
                }
723
        }
724

    
725
        /**
726
         * Clase para cancelar el dibujado.
727
         *
728
         * @author Fernando Gonz?lez Cort?s
729
         */
730
        public class CancelDraw implements Cancellable {
731
                private boolean cancel = false;
732

    
733
                /**
734
                 * Crea un nuevo CancelDraw.
735
                 */
736
                public CancelDraw() {
737
                }
738

    
739
                /**
740
                 * Insertar si se debe cancelar el dibujado.
741
                 *
742
                 * @param b true si se debe cancelar el dibujado.
743
                 */
744
                public void setCanceled(boolean b) {
745
                        cancel = b;
746
                }
747

    
748
                /**
749
                 * @see com.iver.utiles.swing.threads.Cancellable#isCanceled()
750
                 */
751
                public boolean isCanceled() {
752
                        return cancel;
753
                }
754
        }
755
        
756

    
757
        /**
758
         * Listener del MapTool.
759
         *
760
         * @author Fernando Gonz?lez Cort?s
761
         */
762
        public class MapToolListener implements MouseListener, MouseWheelListener,
763
                MouseMotionListener {
764

    
765
                long t1;
766
                Point2D pReal;
767
                /**
768
                 * @see java.awt.event.MouseListener#mouseClicked(java.awt.event.MouseEvent)
769
                 */
770
                public void mouseClicked(MouseEvent e) {
771
                        try {
772
                                currentMapTool.mouseClicked(e);
773
                        } catch (BehaviorException t) {
774
                                throwException(t);
775
                        }
776
                }
777

    
778
                /**
779
                 * @see java.awt.event.MouseListener#mouseEntered(java.awt.event.MouseEvent)
780
                 */
781
                public void mouseEntered(MouseEvent e) {
782
                        try {
783
                                currentMapTool.mouseEntered(e);
784
                        } catch (BehaviorException t) {
785
                                throwException(t);
786
                        }
787
                }
788

    
789
                /**
790
                 * @see java.awt.event.MouseListener#mouseExited(java.awt.event.MouseEvent)
791
                 */
792
                public void mouseExited(MouseEvent e) {
793
                        try {
794
                                currentMapTool.mouseExited(e);
795
                        } catch (BehaviorException t) {
796
                                throwException(t);
797
                        }
798
                }
799

    
800
                /**
801
                 * @see java.awt.event.MouseListener#mousePressed(java.awt.event.MouseEvent)
802
                 */
803
                public void mousePressed(MouseEvent e) {
804
                        try {
805
                                currentMapTool.mousePressed(e);
806
                        } catch (BehaviorException t) {
807
                                throwException(t);
808
                        }
809
                }
810

    
811
                /**
812
                 * @see java.awt.event.MouseListener#mouseReleased(java.awt.event.MouseEvent)
813
                 */
814
                public void mouseReleased(MouseEvent e) {
815
                        try {
816
                                currentMapTool.mouseReleased(e);
817
                        } catch (BehaviorException t) {
818
                                throwException(t);
819
                        }
820
                }
821

    
822
                /**
823
                 * @see java.awt.event.MouseWheelListener#mouseWheelMoved(java.awt.event.MouseWheelEvent)
824
                 */
825
                public void mouseWheelMoved(MouseWheelEvent e) {
826
                        try {
827
                                currentMapTool.mouseWheelMoved(e);
828
                                
829
                                // Si el tool actual no ha consumido el evento
830
                                // entendemos que quiere el comportamiento por defecto.
831
                                if (!e.isConsumed())
832
                                {
833
                                        // Para usar el primer punto sobre el que queremos centrar
834
                                        // el mapa, dejamos pasar un segundo para considerar el siguiente
835
                                        // punto como v?lido.
836
                                        if (t1 == 0)
837
                                        {
838
                                                t1= System.currentTimeMillis();
839
                                                pReal = vp.toMapPoint(e.getPoint());
840
                                        }
841
                                        else
842
                                        {
843
                                                long t2 = System.currentTimeMillis();
844
                                                if ((t2-t1) > 1000)
845
                                                        t1=0;
846
                                        }
847
                                        cancelDrawing();
848
                                        ViewPort vp = getViewPort();
849
                                        
850

    
851
                                        /* Point2D pReal = new Point2D.Double(vp.getAdjustedExtent().getCenterX(),
852
                                                        vp.getAdjustedExtent().getCenterY()); */
853
                                        int amount = e.getWheelRotation();
854
                                        double nuevoX;
855
                                        double nuevoY;
856
                                        double factor;
857

    
858
                                        if (amount > 0) // nos acercamos
859
                                        {
860
                                                factor = 0.9;
861
                                        } else // nos alejamos
862
                                        {
863
                                                factor = 1.2;
864
                                        }
865
                                        Rectangle2D.Double r = new Rectangle2D.Double();
866
                                        if (vp.getExtent() != null) {
867
                                                nuevoX = pReal.getX()
868
                                                                - ((vp.getExtent().getWidth() * factor) / 2.0);
869
                                                nuevoY = pReal.getY()
870
                                                                - ((vp.getExtent().getHeight() * factor) / 2.0);
871
                                                r.x = nuevoX;
872
                                                r.y = nuevoY;
873
                                                r.width = vp.getExtent().getWidth() * factor;
874
                                                r.height = vp.getExtent().getHeight() * factor;
875

    
876
                                                vp.setExtent(r);
877
                                        }
878
                                        
879
                                        
880
                                }
881
                        } catch (BehaviorException t) {
882
                                throwException(t);
883
                        }
884
                }
885

    
886
                /**
887
                 * @see java.awt.event.MouseMotionListener#mouseDragged(java.awt.event.MouseEvent)
888
                 */
889
                public void mouseDragged(MouseEvent e) {
890
                        try {
891
                                currentMapTool.mouseDragged(e);
892
                        } catch (BehaviorException t) {
893
                                throwException(t);
894
                        }
895
                }
896

    
897
                /**
898
                 * @see java.awt.event.MouseMotionListener#mouseMoved(java.awt.event.MouseEvent)
899
                 */
900
                public void mouseMoved(MouseEvent e) {
901
                        try {
902
                                currentMapTool.mouseMoved(e);
903
                        } catch (BehaviorException t) {
904
                                throwException(t);
905
                        }
906
                }
907
        }
908

    
909
        /**
910
         * Listener sobre el MapContext.
911
         *
912
         * @author Fernando Gonz?lez Cort?s
913
         */
914
        public class MapContextListener implements AtomicEventListener {
915
                /**
916
                 * @see com.iver.cit.gvsig.fmap.AtomicEventListener#atomicEvent(com.iver.cit.gvsig.fmap.AtomicEvent)
917
                 */
918
                public void atomicEvent(AtomicEvent e) {
919
                        boolean redraw = false;
920
                        LayerEvent[] layerEvents = e.getLayerEvents();
921

    
922
                        for (int i = 0; i < layerEvents.length; i++) {
923
                                if (layerEvents[i].getProperty().equals("visible")) {
924
                                        redraw = true;
925
                                }
926
                        }
927

    
928
                        if (e.getColorEvents().length > 0) {
929
                                redraw = true;
930
                        }
931

    
932
                        if (e.getExtentEvents().length > 0) {
933
                                redraw = true;
934
                        }
935
                        
936
                        if (e.getProjectionEvents().length > 0) {
937
                                //redraw = true;
938
                        }
939

    
940
                        
941
                        if (e.getLayerCollectionEvents().length > 0) {
942
                                redraw = true;
943
                        }
944

    
945
                        if (e.getLegendEvents().length > 0) {
946
                                redraw = true;
947
                        }
948

    
949
                        if (e.getSelectionEvents().length > 0) {
950
                                redraw = true;
951
                        }
952

    
953
                        if (redraw) {
954
                System.out.println("MapContextListener redraw");
955
                                MapControl.this.drawMap(false);
956
                        }
957
                }
958
        }
959
        public ViewPort getViewPort() {
960
                return vp;
961
        }
962

    
963
        /**
964
         * Returns a HashMap with the tools that have been registered
965
         * in the Mapcontrol.
966
         */
967
        public HashMap getNamesMapTools() {
968
                return namesMapTools;
969
        }
970

    
971
        public void commandRepaint() {
972
                drawMap(false);
973
        }
974

    
975
        public void commandRefresh() {
976
                // TODO Auto-generated method stub
977
        }
978

    
979
        public void setPrevTool() {
980
                setTool(prevTool);
981
        }
982

    
983
}