Statistics
| Revision:

svn-gvsig-desktop / tags / v1_1_Build_1009 / libraries / libFMap / src / com / iver / cit / gvsig / fmap / MapControl.java @ 12649

History | View | Annotate | Download (25.8 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.Component;
45
import java.awt.Dimension;
46
import java.awt.Graphics;
47
import java.awt.Graphics2D;
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.Date;
61
import java.util.HashMap;
62
import java.util.Set;
63

    
64
import javax.swing.JComponent;
65
import javax.swing.Timer;
66

    
67
import org.cresques.cts.IProjection;
68

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

    
80

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

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

    
114
        private String prevTool;
115

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

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

    
130
                //Clase usada para cancelar el dibujado
131
                canceldraw = new CancelDraw();
132

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

    
140
                //eventos
141
                this.addComponentListener(this);
142
                this.addMouseListener(mapToolListener);
143
                this.addMouseMotionListener(mapToolListener);
144
                this.addMouseWheelListener(mapToolListener);
145

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

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

    
166
                mapContext = model;
167

    
168
                if (mapContext.getViewPort() == null) {
169
                        mapContext.setViewPort(vp);
170
                } else {
171
                        vp = mapContext.getViewPort();
172

    
173
                        // vp.setImageSize(new Dimension(getWidth(), getHeight()));
174
                        //System.err.println("Viewport en setMapContext:" + vp);
175
                }
176

    
177
                mapContext.addAtomicEventListener(mapContextListener);
178

    
179
                status = DESACTUALIZADO;
180
        }
181

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

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

    
200
        /**
201
         * Devuelve el modelo.
202
         *
203
         * @return FMap.
204
         */
205
        public MapContext getMapContext() {
206
                return mapContext;
207
        }
208

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

    
220
        public void addMapTool(String name, Behavior[] tools){
221
                CompoundBehavior tool = new CompoundBehavior(tools);
222
                addMapTool(name, tool);
223
        }
224

    
225
        /**
226
         * Devuelve una herramienta (tool) registrada.
227
         *
228
         * @param name Nombre de la herramienta.
229
         * @return tool Herramienta.
230
         */
231
        public Behavior getMapTool(String name) {
232
                return (Behavior)namesMapTools.get(name);
233
        }
234

    
235
        /**
236
         * Devuelve los nombres de herramientas (tool) registradas.
237
         *
238
         * @return Set (String) nombres de las herramientas.
239
         */
240
        public Set getMapToolsKeySet() {
241
                return namesMapTools.keySet();
242
        }
243

    
244

    
245
        /**
246
         * Returns true if this map control contains a tool named with the value
247
         * passed in the toolName parameter. If you have added two tools with the
248
         * same name, the last tool will overwrite the previous ones.
249
         * @param toolName
250
         * @return true if the map control contains a tool with the same name than
251
         *                 toolName. False, otherwise.
252
         */
253
        public boolean hasTool(String toolName) {
254
                return namesMapTools.containsKey(toolName);
255
        }
256
        /**
257
         * DOCUMENT ME!
258
         *
259
         * @param toolName DOCUMENT ME!
260
         */
261
        public void setTool(String toolName) {
262
                prevTool=getCurrentTool();
263
                Behavior mapTool = (Behavior) namesMapTools.get(toolName);
264
                currentMapTool = mapTool;
265
                currentTool = toolName;
266
                this.setCursor(mapTool.getCursor());
267
        }
268
        public Behavior getCurrentMapTool(){
269
                return currentMapTool;
270
        }
271
        /**
272
         * Returns the name of the current selected tool on this MapControl
273
         *
274
         * @return A tool name.
275
         */
276
        public String getCurrentTool() {
277
                return currentTool;
278
        }
279

    
280

    
281
        /**
282
         * Cancela el dibujado. Se espera a que la cancelaci?n surta efecto
283
         */
284
        public void cancelDrawing() {
285
                /* if (drawer != null) {
286
                        if (!drawer.isAlive()) {
287
                                return;
288
                        }
289
                }
290
                */
291
                canceldraw.setCanceled(true);
292

    
293
                /* while (!isCancelled) {
294
                        if (!drawer.isAlive()) {
295
                            // Si hemos llegado aqu? con un thread vivo, seguramente
296
                            // no estamos actualizados.
297

298
                                break;
299
                        }
300

301
                }
302
                canceldraw.setCancel(false);
303
                isCancelled = false;
304
        drawerAlive = false; */
305
        }
306

    
307
    private boolean adaptToImageSize()
308
    {
309
        if ((image == null) || (vp.getImageWidth() != this.getWidth()) || (vp.getImageHeight() != this.getHeight()))
310
        {
311
            image = new BufferedImage(this.getWidth(), this.getHeight(),
312
                    BufferedImage.TYPE_INT_ARGB);
313
            // ESTILO MAC
314
//                image = GraphicsEnvironment.getLocalGraphicsEnvironment()
315
//                                .getDefaultScreenDevice().getDefaultConfiguration()
316
//                                .createCompatibleImage(this.getWidth(), this.getHeight());
317
            vp.setImageSize(new Dimension(getWidth(), getHeight()));
318
            getMapContext().getViewPort().refreshExtent();
319

    
320

    
321
            Graphics gTemp = image.createGraphics();
322
            Color theBackColor = vp.getBackColor();
323
            if (theBackColor == null)
324
                gTemp.setColor(Color.WHITE);
325
            else
326
                gTemp.setColor(theBackColor);
327

    
328
            gTemp.fillRect(0,0,getWidth(), getHeight());
329
            gTemp.dispose();
330
            status = DESACTUALIZADO;
331
            // g.drawImage(image,0,0,null);
332
            return true;
333
        }
334
        return false;
335
    }
336

    
337
        /**
338
         * @see javax.swing.JComponent#paintComponent(java.awt.Graphics)
339
         */
340
        protected void paintComponent(Graphics g) {
341
        adaptToImageSize();
342
              if (status == ACTUALIZADO) {
343
                        /*
344
                         * Si hay un behaviour y la imagen es distinta de null se delega el dibujado
345
                         * en dicho behaviour
346
                         */
347
            if (image != null)
348
            {
349
                if (currentMapTool != null)
350
                    currentMapTool.paintComponent(g);
351
                else
352
                    g.drawImage(image,0,0,null);
353
                        }
354
                } else if ((status == DESACTUALIZADO)
355
                || (status == ONLY_GRAPHICS)) {
356

    
357
                g.drawImage(image,0,0,null);
358

    
359
                drawer2.put(new PaintingRequest());
360
                timer.start();
361
       }
362
        }
363

    
364
        /**
365
         * Devuelve la imagen de la vista.
366
         *
367
         * @return imagen.
368
         */
369
        public BufferedImage getImage() {
370
                return image;
371
        }
372

    
373
        /**
374
         * Marca el mapa para que en el pr?ximo redibujado se acceda a la
375
         * cartograf?a para reobtener la imagen
376
         * @param doClear Solo deber?a ser true cuando se llama desde pan
377
         */
378
        public void drawMap(boolean doClear) {
379
                cancelDrawing();
380
                status = DESACTUALIZADO;
381
        getMapContext().getLayers().setDirty(true);
382
                if (doClear)
383
        {
384
            // image = null; // Se usa para el PAN
385
            if (image != null)
386
            {
387
                Graphics2D g = image.createGraphics();
388
                Color theBackColor = vp.getBackColor();
389
                if (theBackColor == null)
390
                    g.setColor(Color.WHITE);
391
                else
392
                    g.setColor(theBackColor);
393
                g.fillRect(0, 0, vp.getImageWidth(), vp.getImageHeight());
394
                g.dispose();
395
            }
396
        }
397
                repaint();
398
        }
399

    
400
        public void rePaintDirtyLayers()
401
        {
402
                cancelDrawing();
403
        status = DESACTUALIZADO;
404
        repaint();
405
        }
406

    
407
    public void drawGraphics() {
408
        status = ONLY_GRAPHICS;
409
        repaint();
410
    }
411

    
412
        /**
413
         * @see java.awt.event.ComponentListener#componentHidden(java.awt.event.ComponentEvent)
414
         */
415
        public void componentHidden(ComponentEvent e) {
416
        }
417

    
418
        /**
419
         * @see java.awt.event.ComponentListener#componentMoved(java.awt.event.ComponentEvent)
420
         */
421
        public void componentMoved(ComponentEvent e) {
422
        }
423

    
424
        /**
425
         * @see java.awt.event.ComponentListener#componentResized(java.awt.event.ComponentEvent)
426
         */
427
        public void componentResized(ComponentEvent e) {
428
                /* image = new BufferedImage(this.getWidth(), this.getHeight(),
429
                                BufferedImage.TYPE_INT_ARGB);
430
                Graphics gTemp = image.createGraphics();
431
                gTemp.setColor(vp.getBackColor());
432
                gTemp.fillRect(0,0,getWidth(), getHeight());
433
        System.out.println("MapControl resized");
434
            // image = null;
435
            vp.setImageSize(new Dimension(getWidth(), getHeight()));
436
                getMapContext().getViewPort().setScale(); */
437
                // drawMap(true);
438
        }
439

    
440
        /**
441
         * @see java.awt.event.ComponentListener#componentShown(java.awt.event.ComponentEvent)
442
         */
443
        public void componentShown(ComponentEvent e) {
444
        }
445

    
446
        /**
447
         * A?ade un listener de tipo ExceptionListener.
448
         *
449
         * @param o ExceptionListener.
450
         */
451
        public void addExceptionListener(ExceptionListener o) {
452
                exceptionHandlingSupport.addExceptionListener(o);
453
        }
454

    
455
        /**
456
         * Borra la ExceptioListener que se pasa como par?metro.
457
         *
458
         * @param o ExceptionListener.
459
         *
460
         * @return True si se borra correctamente.
461
         */
462
        public boolean removeExceptionListener(ExceptionListener o) {
463
                return exceptionHandlingSupport.removeExceptionListener(o);
464
        }
465

    
466
        /**
467
         * Lanza una Excepci?n.
468
         *
469
         * @param t Excepci?n.
470
         */
471
        protected void throwException(Throwable t) {
472
                exceptionHandlingSupport.throwException(t);
473
        }
474

    
475

    
476
    private class PaintingRequest
477
    {
478

    
479
        public PaintingRequest()
480
        {
481
        }
482

    
483
        public void paint()
484
        {
485
            try
486
            {
487
                    canceldraw.setCanceled(false);
488
                /* if (image == null)
489
                {
490
                    image = new BufferedImage(vp.getImageWidth(), vp.getImageHeight(),
491
                            BufferedImage.TYPE_INT_ARGB);
492
                    Graphics gTemp = image.createGraphics();
493
                    Color theBackColor = vp.getBackColor();
494
                    if (theBackColor == null)
495
                        gTemp.setColor(Color.WHITE);
496
                    else
497
                        gTemp.setColor(theBackColor);
498

499
                    gTemp.fillRect(0,0,getWidth(), getHeight());
500
                    gTemp.dispose();
501
                    // g.drawImage(image,0,0,null);
502
                    System.out.println("Imagen con null en DESACTUALIZADO. Width = " + this.getWidth());
503
                } */
504
                Graphics2D g = image.createGraphics();
505

    
506
                ViewPort viewPort = mapContext.getViewPort();
507

    
508
                if (status == DESACTUALIZADO)
509
                {
510
                        Graphics2D gTemp = image.createGraphics();
511
                    Color theBackColor = viewPort.getBackColor();
512
                    if (theBackColor == null)
513
                        gTemp.setColor(Color.WHITE);
514
                    else
515
                        gTemp.setColor(theBackColor);
516
                    gTemp.fillRect(0, 0, viewPort.getImageWidth(), viewPort.getImageHeight());
517
                    status = ACTUALIZADO;
518
                    // ESTILO MAC
519
//                    BufferedImage imgMac = new BufferedImage(vp.getImageWidth(), vp.getImageHeight(),
520
//                            BufferedImage.TYPE_INT_ARGB);
521
//
522
//                    mapContext.draw(imgMac, g, canceldraw, mapContext.getScaleView());
523
//                    g.drawImage(imgMac, 0, 0, null);
524
                    // FIN ESTILO MAC
525
                    // SIN MAC:
526
                    mapContext.draw(image, g, canceldraw, mapContext.getScaleView());
527

    
528
                }
529
                else if (status == ONLY_GRAPHICS)
530
                {
531
                    status = ACTUALIZADO;
532
                    mapContext.drawGraphics(image, g, canceldraw,mapContext.getScaleView());
533

    
534
                }
535

    
536

    
537
                // status = FAST_PAINT;
538
              //  drawerAlive = false;
539
                timer.stop();
540
                repaint();
541

    
542

    
543
            } catch (Throwable e) {
544
                timer.stop();
545
              //  isCancelled = true;
546
                e.printStackTrace();
547
                throwException(e);
548
            } finally {
549
            }
550

    
551
        }
552

    
553
    }
554

    
555
    /**
556
     * @author fjp
557
     *
558
     * Basasdo en el patr?n WorkerThread
559
     *
560
     */
561
    public class Drawer2
562
    {
563
        // Una mini cola de 2. No acumulamos peticiones de dibujado
564
        // dibujamos solo lo ?ltimo que nos han pedido.
565
        private PaintingRequest paintingRequest;
566
        private PaintingRequest waitingRequest;
567

    
568
        private boolean waiting;
569
        private boolean shutdown;
570

    
571
        public void setShutdown(boolean isShutdown)
572
        {
573
            shutdown = isShutdown;
574
        }
575

    
576
        public Drawer2()
577
        {
578
            paintingRequest = null;
579
            waitingRequest = null;
580
            waiting = false;
581
            shutdown = false;
582
            new Thread(new Worker()).start();
583
        }
584

    
585
        public void put(PaintingRequest newPaintRequest)
586
        {
587
            waitingRequest = newPaintRequest;
588
            if (waiting)
589
            {
590
                synchronized (this) {
591
                    notifyAll();
592
                }
593
            }
594
        }
595

    
596
        public PaintingRequest take()
597
        {
598
            if (waitingRequest == null)
599
            {
600
                synchronized (this) {
601
                    waiting = true;
602
                    try {
603
                        wait();
604
                    }
605
                    catch (InterruptedException ie)
606
                    {
607
                        waiting = false;
608
                    }
609
                }
610
            }
611
            paintingRequest = waitingRequest;
612
            waitingRequest = null;
613
            return paintingRequest;
614
        }
615

    
616

    
617
        private class Worker implements Runnable
618
        {
619
            public void run()
620
            {
621
                while (!shutdown)
622
                {
623
                    PaintingRequest p = take();
624
                    System.out.println("Pintando");
625
                    if (image != null){
626
                            cancelDrawing();
627
                        p.paint();
628
                    } else
629
                        status = DESACTUALIZADO;
630
                }
631
            }
632
        }
633
    }
634

    
635
        /**
636
         * Clase utilizada para dibujar las capas.
637
         *
638
         * @author Vicente Caballero Navarro
639
         */
640
        public class Drawer extends Thread {
641
                //private Graphics g;
642
                private BufferedImage image = null;
643
                private CancelDraw cancel;
644
                //private boolean threadCancel = false;
645

    
646
                /**
647
                 * Crea un nuevo Drawer.
648
                 *
649
                 */
650
                public Drawer(BufferedImage image, CancelDraw cancel)
651
        {
652
                        this.image = image;
653
                        this.cancel = cancel;
654
         //   drawerAlive = true;
655
                }
656

    
657
                /**
658
                 * @see java.lang.Runnable#run()
659
                 */
660
                public void run() {
661
                        try {
662
                                // synchronized (Drawer.class) {
663
                                    Graphics2D g = image.createGraphics();
664

    
665
                                    ViewPort viewPort = mapContext.getViewPort();
666
                    if (status == DESACTUALIZADO)
667
                    {
668
                                        Color theBackColor = viewPort.getBackColor();
669
                                        if (theBackColor == null)
670
                                            g.setColor(Color.WHITE);
671
                                        else
672
                                            g.setColor(theBackColor);
673
                                            g.fillRect(0, 0, viewPort.getImageWidth(), viewPort.getImageHeight());
674
                        status = ACTUALIZADO;
675
                        mapContext.draw(image, g, cancel,mapContext.getScaleView());
676
                    }
677
                    else if (status == ONLY_GRAPHICS)
678
                    {
679
                        status = ACTUALIZADO;
680
                        mapContext.drawGraphics(image, g, cancel,mapContext.getScaleView());
681
                    }
682

    
683
                                        timer.stop();
684
                    // status = FAST_PAINT;
685
                  //  drawerAlive = false;
686
                                        repaint();
687

    
688

    
689

    
690
                                // }
691
                        } catch (Throwable e) {
692
                            timer.stop();
693
                                //isCancelled = true;
694
                e.printStackTrace();
695
                                throwException(e);
696
                        } finally {
697
                        }
698
                }
699
        }
700

    
701
        /**
702
         * Clase para cancelar el dibujado.
703
         *
704
         * @author Fernando Gonz?lez Cort?s
705
         */
706
        public class CancelDraw implements Cancellable {
707
                private boolean cancel = false;
708

    
709
                /**
710
                 * Crea un nuevo CancelDraw.
711
                 */
712
                public CancelDraw() {
713
                }
714

    
715
                /**
716
                 * Insertar si se debe cancelar el dibujado.
717
                 *
718
                 * @param b true si se debe cancelar el dibujado.
719
                 */
720
                public void setCanceled(boolean b) {
721
                        cancel = b;
722
                }
723

    
724
                /**
725
                 * @see com.iver.utiles.swing.threads.Cancellable#isCanceled()
726
                 */
727
                public boolean isCanceled() {
728
                        return cancel;
729
                }
730
        }
731

    
732

    
733
        /**
734
         * Listener del MapTool.
735
         *
736
         * @author Fernando Gonz?lez Cort?s
737
         */
738
        public class MapToolListener implements MouseListener, MouseWheelListener,
739
                MouseMotionListener {
740

    
741
                long t1;
742
                Point2D pReal;
743
                /**
744
                 * @see java.awt.event.MouseListener#mouseClicked(java.awt.event.MouseEvent)
745
                 */
746
                public void mouseClicked(MouseEvent e) {
747
                        try {
748
                                currentMapTool.mouseClicked(e);
749
                        } catch (BehaviorException t) {
750
                                throwException(t);
751
                        }
752
                }
753

    
754
                /**
755
                 * @see java.awt.event.MouseListener#mouseEntered(java.awt.event.MouseEvent)
756
                 */
757
                public void mouseEntered(MouseEvent e) {
758
                        try {
759
                                currentMapTool.mouseEntered(e);
760
                        } catch (BehaviorException t) {
761
                                throwException(t);
762
                        }
763
                }
764

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

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

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

    
798
                /**
799
                 * @see java.awt.event.MouseWheelListener#mouseWheelMoved(java.awt.event.MouseWheelEvent)
800
                 */
801
                public void mouseWheelMoved(MouseWheelEvent e) {
802
                        try {
803
                                currentMapTool.mouseWheelMoved(e);
804

    
805
                                // Si el tool actual no ha consumido el evento
806
                                // entendemos que quiere el comportamiento por defecto.
807
                                if (!e.isConsumed())
808
                                {
809
                                        // Para usar el primer punto sobre el que queremos centrar
810
                                        // el mapa, dejamos pasar un segundo para considerar el siguiente
811
                                        // punto como v?lido.
812
                                        if (t1 == 0)
813
                                        {
814
                                                t1= System.currentTimeMillis();
815
                                                pReal = vp.toMapPoint(e.getPoint());
816
                                        }
817
                                        else
818
                                        {
819
                                                long t2 = System.currentTimeMillis();
820
                                                if ((t2-t1) > 1000)
821
                                                        t1=0;
822
                                        }
823
                                        cancelDrawing();
824
                                        ViewPort vp = getViewPort();
825

    
826

    
827
                                        /* Point2D pReal = new Point2D.Double(vp.getAdjustedExtent().getCenterX(),
828
                                                        vp.getAdjustedExtent().getCenterY()); */
829
                                        int amount = e.getWheelRotation();
830
                                        double nuevoX;
831
                                        double nuevoY;
832
                                        double factor;
833

    
834
                                        if (amount < 0) // nos acercamos
835
                                        {
836
                                                factor = 0.9;
837
                                        } else // nos alejamos
838
                                        {
839
                                                factor = 1.2;
840
                                        }
841
                                        Rectangle2D.Double r = new Rectangle2D.Double();
842
                                        if (vp.getExtent() != null) {
843
                                                nuevoX = pReal.getX()
844
                                                                - ((vp.getExtent().getWidth() * factor) / 2.0);
845
                                                nuevoY = pReal.getY()
846
                                                                - ((vp.getExtent().getHeight() * factor) / 2.0);
847
                                                r.x = nuevoX;
848
                                                r.y = nuevoY;
849
                                                r.width = vp.getExtent().getWidth() * factor;
850
                                                r.height = vp.getExtent().getHeight() * factor;
851

    
852
                                                vp.setExtent(r);
853
                                        }
854

    
855

    
856
                                }
857
                        } catch (BehaviorException t) {
858
                                throwException(t);
859
                        }
860
                }
861

    
862
                /**
863
                 * @see java.awt.event.MouseMotionListener#mouseDragged(java.awt.event.MouseEvent)
864
                 */
865
                public void mouseDragged(MouseEvent e) {
866
                        try {
867
                                currentMapTool.mouseDragged(e);
868
                        } catch (BehaviorException t) {
869
                                throwException(t);
870
                        }
871
                }
872

    
873
                /**
874
                 * @see java.awt.event.MouseMotionListener#mouseMoved(java.awt.event.MouseEvent)
875
                 */
876
                public void mouseMoved(MouseEvent e) {
877
                        try {
878
                                currentMapTool.mouseMoved(e);
879
                        } catch (BehaviorException t) {
880
                                throwException(t);
881
                        }
882
                }
883
        }
884

    
885
        /**
886
         * Listener sobre el MapContext.
887
         *
888
         * @author Fernando Gonz?lez Cort?s
889
         */
890
        public class MapContextListener implements AtomicEventListener {
891
                /**
892
                 * @see com.iver.cit.gvsig.fmap.AtomicEventListener#atomicEvent(com.iver.cit.gvsig.fmap.AtomicEvent)
893
                 */
894
                public void atomicEvent(AtomicEvent e) {
895
                        boolean redraw = false;
896
                        LayerEvent[] layerEvents = e.getLayerEvents();
897

    
898
                        for (int i = 0; i < layerEvents.length; i++) {
899
                                if (layerEvents[i].getProperty().equals("visible")) {
900
                                        redraw = true;
901
                                }
902
                        }
903

    
904
                        if (e.getColorEvents().length > 0) {
905
                                redraw = true;
906
                        }
907

    
908
                        if (e.getExtentEvents().length > 0) {
909
                                redraw = true;
910
                        }
911

    
912
                        if (e.getProjectionEvents().length > 0) {
913
                                //redraw = true;
914
                        }
915

    
916

    
917
                        LayerCollectionEvent[] aux = e.getLayerCollectionEvents();
918
                        if (aux.length > 0) {
919
                                for (int i=0; i < aux.length; i++)
920
                                {
921
                                        if (aux[i].getAffectedLayer().getFLayerStatus().isDriverLoaded())
922
                                        {
923
                                                redraw = true;
924
                                                break;
925
                                        }
926
                                }
927

    
928
                        }
929

    
930
                        if (e.getLegendEvents().length > 0) {
931
                                redraw = true;
932
                        }
933

    
934
                        if (e.getSelectionEvents().length > 0) {
935
                                redraw = true;
936
                        }
937

    
938
                        if (redraw) {
939
                System.out.println("MapContextListener redraw");
940
                                MapControl.this.drawMap(false);
941
                        }
942
                }
943
        }
944
        public ViewPort getViewPort() {
945
                return vp;
946
        }
947

    
948
        /**
949
         * Returns a HashMap with the tools that have been registered
950
         * in the Mapcontrol.
951
         */
952
        public HashMap getNamesMapTools() {
953
                return namesMapTools;
954
        }
955

    
956
        public void commandRepaint() {
957
                drawMap(false);
958
        }
959

    
960
        public void commandRefresh() {
961
                // TODO Auto-generated method stub
962
        }
963

    
964
        public void setPrevTool() {
965
                setTool(prevTool);
966
        }
967

    
968
        public void zoomIn() {
969
                getMapContext().clearAllCachingImageDrawnLayers();
970
                Behavior mapTool = (Behavior) namesMapTools.get("zoomIn");
971
                ViewPort vp=getViewPort();
972
                Rectangle2D r=getViewPort().getAdjustedExtent();
973
                Point2D pCenter=vp.fromMapPoint(r.getCenterX(),r.getCenterY());
974
                MouseEvent e=new MouseEvent((Component)this,MouseEvent.MOUSE_RELEASED,MouseEvent.ACTION_EVENT_MASK,MouseEvent.BUTTON1,(int)pCenter.getX(),(int)pCenter.getY(),1,true,MouseEvent.BUTTON1);
975
                try {
976
                        mapTool.mousePressed(e);
977
                        mapTool.mouseReleased(e);
978
                } catch (BehaviorException t) {
979
                        throwException(t);
980
                }
981
        }
982
        public void zoomOut() {
983
                getMapContext().clearAllCachingImageDrawnLayers();
984
                Behavior mapTool = (Behavior) namesMapTools.get("zoomOut");
985
                ViewPort vp=getViewPort();
986
                Rectangle2D r=getViewPort().getAdjustedExtent();
987
                Point2D pCenter=vp.fromMapPoint(r.getCenterX(),r.getCenterY());
988
                MouseEvent e=new MouseEvent((Component)this,MouseEvent.MOUSE_RELEASED,MouseEvent.ACTION_EVENT_MASK,MouseEvent.BUTTON1,(int)pCenter.getX(),(int)pCenter.getY(),1,true,MouseEvent.BUTTON1);
989
                try {
990
                        mapTool.mousePressed(e);
991
                        mapTool.mouseReleased(e);
992
                } catch (BehaviorException t) {
993
                        throwException(t);
994
                }
995
        }
996

    
997

    
998
}