Statistics
| Revision:

root / trunk / libraries / libFMap / src / com / iver / cit / gvsig / fmap / MapControl.java @ 12173

History | View | Annotate | Download (27.4 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.HashMap;
61
import java.util.Set;
62

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

    
66
import org.cresques.cts.IProjection;
67

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

    
78

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

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

    
112
        private String prevTool;
113

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

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

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

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

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

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

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

    
164
                mapContext = model;
165

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

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

    
175
                mapContext.addAtomicEventListener(mapContextListener);
176

    
177
                status = DESACTUALIZADO;
178
        }
179

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

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

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

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

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

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

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

    
242

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

    
278

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

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

296
                                break;
297
                        }
298

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

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

    
318

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

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

    
335
        /**
336
         * @see javax.swing.JComponent#paintComponent(java.awt.Graphics)
337
         */
338
        protected void paintComponent(Graphics g) {
339
        adaptToImageSize();
340
        /* if (status == FAST_PAINT) {
341
            System.out.println("FAST_PAINT");
342
            g.drawImage(image,0,0,null);
343
            status = ACTUALIZADO;
344
            return;
345
        } */
346
        // System.out.println("PINTANDO MAPCONTROL" + this);
347
                if (status == ACTUALIZADO) {
348
                        // LWS logger.debug("Dibujando la imagen obtenida");
349

    
350
                        /*
351
                         * Si hay un behaviour y la imagen es distinta de null se delega el dibujado
352
                         * en dicho behaviour
353
                         */
354
            if (image != null)
355
            {
356
                if (currentMapTool != null)
357
                    currentMapTool.paintComponent(g);
358
                else
359
                    g.drawImage(image,0,0,null);
360

    
361
                                // System.out.println("Pinto ACTUALIZADO");
362
                        }
363
                } else if ((status == DESACTUALIZADO)
364
                || (status == ONLY_GRAPHICS)) {
365
                        // LWS System.out.println("DESACTUALIZADO: Obteniendo la imagen de la cartograf?a");
366
                        /* if (isOpaque())
367
                        {
368
                            if (image==null)
369
                            {
370
                                g.setColor(vp.getBackColor());
371
                                g.fillRect(0,0,getWidth(), getHeight());
372
                            }
373
                            // else g.drawImage(image,0,0,null);
374
                        } */
375
            // cancelDrawing();
376
                        //Se crea la imagen con el color de fonde deseado
377
                        /* if (image == null)
378
                        {
379
                                image = new BufferedImage(this.getWidth(), this.getHeight(),
380
                                                BufferedImage.TYPE_INT_ARGB);
381
                                vp.setImageSize(new Dimension(getWidth(), getHeight()));
382
                                Graphics gTemp = image.createGraphics();
383
                            Color theBackColor = vp.getBackColor();
384
                            if (theBackColor == null)
385
                                gTemp.setColor(Color.WHITE);
386
                            else
387
                                gTemp.setColor(theBackColor);
388

389
                                gTemp.fillRect(0,0,getWidth(), getHeight());
390
                                gTemp.dispose();
391
                                // g.drawImage(image,0,0,null);
392
                                System.out.println("Imagen con null en DESACTUALIZADO. Width = " + this.getWidth());
393
                        } */
394
            // else
395
            // {
396

    
397

    
398
            // if (image != null)
399
            //  {
400
                g.drawImage(image,0,0,null);
401

    
402
                drawer2.put(new PaintingRequest());
403
                timer.start();
404
            /* }
405
            else
406
                return; */
407
            // }
408

    
409
            /* if (drawerAlive == false)
410
            {
411
                drawer = new Drawer(image, canceldraw);
412
                drawer.start();
413
                        //Se lanza el tread de dibujado
414
            } */
415

    
416
                        // status = ACTUALIZADO;
417
                }
418
        }
419

    
420
        /**
421
         * Devuelve la imagen de la vista.
422
         *
423
         * @return imagen.
424
         */
425
        public BufferedImage getImage() {
426
                return image;
427
        }
428

    
429
        /**
430
         * Marca el mapa para que en el pr?ximo redibujado se acceda a la
431
         * cartograf?a para reobtener la imagen
432
         * @param doClear Solo deber?a ser true cuando se llama desde pan
433
         */
434
        public void drawMap(boolean doClear) {
435
                cancelDrawing();
436
                //System.out.println("drawMap con doClear=" + doClear);
437
        status = DESACTUALIZADO;
438
        getMapContext().getLayers().setDirty(true);
439
                if (doClear)
440
        {
441
            // image = null; // Se usa para el PAN
442
            if (image != null)
443
            {
444
                Graphics2D g = image.createGraphics();
445
                Color theBackColor = vp.getBackColor();
446
                if (theBackColor == null)
447
                    g.setColor(Color.WHITE);
448
                else
449
                    g.setColor(theBackColor);
450
                g.fillRect(0, 0, vp.getImageWidth(), vp.getImageHeight());
451
                g.dispose();
452
            }
453
        }
454
                repaint();
455
        }
456

    
457
        public void rePaintDirtyLayers()
458
        {
459
                cancelDrawing();
460
        status = DESACTUALIZADO;
461
        repaint();
462
        }
463

    
464
    public void drawGraphics() {
465
        status = ONLY_GRAPHICS;
466
        repaint();
467
    }
468

    
469
        /**
470
         * @see java.awt.event.ComponentListener#componentHidden(java.awt.event.ComponentEvent)
471
         */
472
        public void componentHidden(ComponentEvent e) {
473
        }
474

    
475
        /**
476
         * @see java.awt.event.ComponentListener#componentMoved(java.awt.event.ComponentEvent)
477
         */
478
        public void componentMoved(ComponentEvent e) {
479
        }
480

    
481
        /**
482
         * @see java.awt.event.ComponentListener#componentResized(java.awt.event.ComponentEvent)
483
         */
484
        public void componentResized(ComponentEvent e) {
485
                /* image = new BufferedImage(this.getWidth(), this.getHeight(),
486
                                BufferedImage.TYPE_INT_ARGB);
487
                Graphics gTemp = image.createGraphics();
488
                gTemp.setColor(vp.getBackColor());
489
                gTemp.fillRect(0,0,getWidth(), getHeight());
490
        System.out.println("MapControl resized");
491
            // image = null;
492
            vp.setImageSize(new Dimension(getWidth(), getHeight()));
493
                getMapContext().getViewPort().setScale(); */
494
                // drawMap(true);
495
        }
496

    
497
        /**
498
         * @see java.awt.event.ComponentListener#componentShown(java.awt.event.ComponentEvent)
499
         */
500
        public void componentShown(ComponentEvent e) {
501
        }
502

    
503
        /**
504
         * A?ade un listener de tipo ExceptionListener.
505
         *
506
         * @param o ExceptionListener.
507
         */
508
        public void addExceptionListener(ExceptionListener o) {
509
                exceptionHandlingSupport.addExceptionListener(o);
510
        }
511

    
512
        /**
513
         * Borra la ExceptioListener que se pasa como par?metro.
514
         *
515
         * @param o ExceptionListener.
516
         *
517
         * @return True si se borra correctamente.
518
         */
519
        public boolean removeExceptionListener(ExceptionListener o) {
520
                return exceptionHandlingSupport.removeExceptionListener(o);
521
        }
522

    
523
        /**
524
         * Lanza una Excepci?n.
525
         *
526
         * @param t Excepci?n.
527
         */
528
        protected void throwException(Throwable t) {
529
                exceptionHandlingSupport.throwException(t);
530
        }
531

    
532

    
533
    private class PaintingRequest
534
    {
535

    
536
        public PaintingRequest()
537
        {
538
        }
539

    
540
        public void paint()
541
        {
542
            try
543
            {
544
                    canceldraw.setCanceled(false);
545
                /* if (image == null)
546
                {
547
                    image = new BufferedImage(vp.getImageWidth(), vp.getImageHeight(),
548
                            BufferedImage.TYPE_INT_ARGB);
549
                    Graphics gTemp = image.createGraphics();
550
                    Color theBackColor = vp.getBackColor();
551
                    if (theBackColor == null)
552
                        gTemp.setColor(Color.WHITE);
553
                    else
554
                        gTemp.setColor(theBackColor);
555

556
                    gTemp.fillRect(0,0,getWidth(), getHeight());
557
                    gTemp.dispose();
558
                    // g.drawImage(image,0,0,null);
559
                    System.out.println("Imagen con null en DESACTUALIZADO. Width = " + this.getWidth());
560
                } */
561
                Graphics2D g = image.createGraphics();
562

    
563
                ViewPort viewPort = mapContext.getViewPort();
564

    
565
                if (status == DESACTUALIZADO)
566
                {
567
                        Graphics2D gTemp = image.createGraphics();
568
                    Color theBackColor = viewPort.getBackColor();
569
                    if (theBackColor == null)
570
                        gTemp.setColor(Color.WHITE);
571
                    else
572
                        gTemp.setColor(theBackColor);
573
                    gTemp.fillRect(0, 0, viewPort.getImageWidth(), viewPort.getImageHeight());
574
                    status = ACTUALIZADO;
575
                    // ESTILO MAC
576
//                    BufferedImage imgMac = new BufferedImage(vp.getImageWidth(), vp.getImageHeight(),
577
//                            BufferedImage.TYPE_INT_ARGB);
578
//
579
//                    mapContext.draw(imgMac, g, canceldraw, mapContext.getScaleView());
580
//                    g.drawImage(imgMac, 0, 0, null);
581
                    // FIN ESTILO MAC
582
                    // SIN MAC:
583
                    mapContext.draw(image, g, canceldraw, mapContext.getScaleView());
584

    
585
                }
586
                else if (status == ONLY_GRAPHICS)
587
                {
588
                    status = ACTUALIZADO;
589
                    mapContext.drawGraphics(image, g, canceldraw,mapContext.getScaleView());
590

    
591
                }
592

    
593

    
594
                // status = FAST_PAINT;
595
              //  drawerAlive = false;
596
                timer.stop();
597
                repaint();
598

    
599

    
600
            } catch (Throwable e) {
601
                timer.stop();
602
              //  isCancelled = true;
603
                e.printStackTrace();
604
                throwException(e);
605
            } finally {
606
            }
607

    
608
        }
609

    
610
    }
611

    
612
    /**
613
     * @author fjp
614
     *
615
     * Basasdo en el patr?n WorkerThread
616
     *
617
     */
618
    public class Drawer2
619
    {
620
        // Una mini cola de 2. No acumulamos peticiones de dibujado
621
        // dibujamos solo lo ?ltimo que nos han pedido.
622
        private PaintingRequest paintingRequest;
623
        private PaintingRequest waitingRequest;
624

    
625
        private boolean waiting;
626
        private boolean shutdown;
627

    
628
        public void setShutdown(boolean isShutdown)
629
        {
630
            shutdown = isShutdown;
631
        }
632

    
633
        public Drawer2()
634
        {
635
            paintingRequest = null;
636
            waitingRequest = null;
637
            waiting = false;
638
            shutdown = false;
639
            new Thread(new Worker()).start();
640
        }
641

    
642
        public void put(PaintingRequest newPaintRequest)
643
        {
644
            waitingRequest = newPaintRequest;
645
            if (waiting)
646
            {
647
                synchronized (this) {
648
                    notifyAll();
649
                }
650
            }
651
        }
652

    
653
        public PaintingRequest take()
654
        {
655
            if (waitingRequest == null)
656
            {
657
                synchronized (this) {
658
                    waiting = true;
659
                    try {
660
                        wait();
661
                    }
662
                    catch (InterruptedException ie)
663
                    {
664
                        waiting = false;
665
                    }
666
                }
667
            }
668
            paintingRequest = waitingRequest;
669
            waitingRequest = null;
670
            return paintingRequest;
671
        }
672

    
673

    
674
        private class Worker implements Runnable
675
        {
676
            public void run()
677
            {
678
                while (!shutdown)
679
                {
680
                    PaintingRequest p = take();
681
                    //System.out.println("Pintando");
682
                    if (image != null){
683
                            cancelDrawing();
684
                        p.paint();
685
                    } else
686
                        status = DESACTUALIZADO;
687
                }
688
            }
689
        }
690
    }
691

    
692
        /**
693
         * Clase utilizada para dibujar las capas.
694
         *
695
         * @author Vicente Caballero Navarro
696
         */
697
        public class Drawer extends Thread {
698
                //private Graphics g;
699
                private BufferedImage image = null;
700
                private CancelDraw cancel;
701
                //private boolean threadCancel = false;
702

    
703
                /**
704
                 * Crea un nuevo Drawer.
705
                 *
706
                 */
707
                public Drawer(BufferedImage image, CancelDraw cancel)
708
        {
709
                        this.image = image;
710
                        this.cancel = cancel;
711
         //   drawerAlive = true;
712
                }
713

    
714
                /**
715
                 * @see java.lang.Runnable#run()
716
                 */
717
                public void run() {
718
                        try {
719
                                // synchronized (Drawer.class) {
720
                                    Graphics2D g = image.createGraphics();
721

    
722
                                    ViewPort viewPort = mapContext.getViewPort();
723
                    if (status == DESACTUALIZADO)
724
                    {
725
                                        Color theBackColor = viewPort.getBackColor();
726
                                        if (theBackColor == null)
727
                                            g.setColor(Color.WHITE);
728
                                        else
729
                                            g.setColor(theBackColor);
730
                                            g.fillRect(0, 0, viewPort.getImageWidth(), viewPort.getImageHeight());
731
                        status = ACTUALIZADO;
732
                        mapContext.draw(image, g, cancel,mapContext.getScaleView());
733
                    }
734
                    else if (status == ONLY_GRAPHICS)
735
                    {
736
                        status = ACTUALIZADO;
737
                        mapContext.drawGraphics(image, g, cancel,mapContext.getScaleView());
738
                    }
739

    
740
                                        timer.stop();
741
                    // status = FAST_PAINT;
742
                  //  drawerAlive = false;
743
                                        repaint();
744

    
745

    
746

    
747
                                // }
748
                        } catch (Throwable e) {
749
                            timer.stop();
750
                                //isCancelled = true;
751
                e.printStackTrace();
752
                                throwException(e);
753
                        } finally {
754
                        }
755
                }
756
        }
757

    
758
        /**
759
         * Clase para cancelar el dibujado.
760
         *
761
         * @author Fernando Gonz?lez Cort?s
762
         */
763
        public class CancelDraw implements Cancellable {
764
                private boolean cancel = false;
765

    
766
                /**
767
                 * Crea un nuevo CancelDraw.
768
                 */
769
                public CancelDraw() {
770
                }
771

    
772
                /**
773
                 * Insertar si se debe cancelar el dibujado.
774
                 *
775
                 * @param b true si se debe cancelar el dibujado.
776
                 */
777
                public void setCanceled(boolean b) {
778
                        cancel = b;
779
                }
780

    
781
                /**
782
                 * @see com.iver.utiles.swing.threads.Cancellable#isCanceled()
783
                 */
784
                public boolean isCanceled() {
785
                        return cancel;
786
                }
787
        }
788

    
789

    
790
        /**
791
         * Listener del MapTool.
792
         *
793
         * @author Fernando Gonz?lez Cort?s
794
         */
795
        public class MapToolListener implements MouseListener, MouseWheelListener,
796
                MouseMotionListener {
797

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

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

    
822
                /**
823
                 * @see java.awt.event.MouseListener#mouseExited(java.awt.event.MouseEvent)
824
                 */
825
                public void mouseExited(MouseEvent e) {
826
                        try {
827
                                currentMapTool.mouseExited(e);
828
                        } catch (BehaviorException t) {
829
                                throwException(t);
830
                        }
831
                }
832

    
833
                /**
834
                 * @see java.awt.event.MouseListener#mousePressed(java.awt.event.MouseEvent)
835
                 */
836
                public void mousePressed(MouseEvent e) {
837
                        try {
838
                                currentMapTool.mousePressed(e);
839
                        } catch (BehaviorException t) {
840
                                throwException(t);
841
                        }
842
                }
843

    
844
                /**
845
                 * @see java.awt.event.MouseListener#mouseReleased(java.awt.event.MouseEvent)
846
                 */
847
                public void mouseReleased(MouseEvent e) {
848
                        try {
849
                                currentMapTool.mouseReleased(e);
850
                        } catch (BehaviorException t) {
851
                                throwException(t);
852
                        }
853
                }
854

    
855
                /**
856
                 * @see java.awt.event.MouseWheelListener#mouseWheelMoved(java.awt.event.MouseWheelEvent)
857
                 */
858
                public void mouseWheelMoved(MouseWheelEvent e) {
859
                        try {
860
                                currentMapTool.mouseWheelMoved(e);
861

    
862
                                // Si el tool actual no ha consumido el evento
863
                                // entendemos que quiere el comportamiento por defecto.
864
                                if (!e.isConsumed())
865
                                {
866
                                        // Para usar el primer punto sobre el que queremos centrar
867
                                        // el mapa, dejamos pasar un segundo para considerar el siguiente
868
                                        // punto como v?lido.
869
                                        if (t1 == 0)
870
                                        {
871
                                                t1= System.currentTimeMillis();
872
                                                pReal = vp.toMapPoint(e.getPoint());
873
                                        }
874
                                        else
875
                                        {
876
                                                long t2 = System.currentTimeMillis();
877
                                                if ((t2-t1) > 1000)
878
                                                        t1=0;
879
                                        }
880
                                        cancelDrawing();
881
                                        ViewPort vp = getViewPort();
882

    
883

    
884
                                        /* Point2D pReal = new Point2D.Double(vp.getAdjustedExtent().getCenterX(),
885
                                                        vp.getAdjustedExtent().getCenterY()); */
886
                                        int amount = e.getWheelRotation();
887
                                        double nuevoX;
888
                                        double nuevoY;
889
                                        double factor;
890

    
891
                                        if (amount < 0) // nos acercamos
892
                                        {
893
                                                factor = 0.9;
894
                                        } else // nos alejamos
895
                                        {
896
                                                factor = 1.2;
897
                                        }
898
                                        Rectangle2D.Double r = new Rectangle2D.Double();
899
                                        if (vp.getExtent() != null) {
900
                                                nuevoX = pReal.getX()
901
                                                                - ((vp.getExtent().getWidth() * factor) / 2.0);
902
                                                nuevoY = pReal.getY()
903
                                                                - ((vp.getExtent().getHeight() * factor) / 2.0);
904
                                                r.x = nuevoX;
905
                                                r.y = nuevoY;
906
                                                r.width = vp.getExtent().getWidth() * factor;
907
                                                r.height = vp.getExtent().getHeight() * factor;
908

    
909
                                                vp.setExtent(r);
910
                                        }
911

    
912

    
913
                                }
914
                        } catch (BehaviorException t) {
915
                                throwException(t);
916
                        }
917
                }
918

    
919
                /**
920
                 * @see java.awt.event.MouseMotionListener#mouseDragged(java.awt.event.MouseEvent)
921
                 */
922
                public void mouseDragged(MouseEvent e) {
923
                        try {
924
                                currentMapTool.mouseDragged(e);
925
                        } catch (BehaviorException t) {
926
                                throwException(t);
927
                        }
928
                }
929

    
930
                /**
931
                 * @see java.awt.event.MouseMotionListener#mouseMoved(java.awt.event.MouseEvent)
932
                 */
933
                public void mouseMoved(MouseEvent e) {
934
                        try {
935
                                currentMapTool.mouseMoved(e);
936
                        } catch (BehaviorException t) {
937
                                throwException(t);
938
                        }
939
                }
940
        }
941

    
942
        /**
943
         * Listener sobre el MapContext.
944
         *
945
         * @author Fernando Gonz?lez Cort?s
946
         */
947
        public class MapContextListener implements AtomicEventListener {
948
                /**
949
                 * @see com.iver.cit.gvsig.fmap.AtomicEventListener#atomicEvent(com.iver.cit.gvsig.fmap.AtomicEvent)
950
                 */
951
                public void atomicEvent(AtomicEvent e) {
952
                        boolean redraw = false;
953
                        LayerEvent[] layerEvents = e.getLayerEvents();
954

    
955
                        for (int i = 0; i < layerEvents.length; i++) {
956
                                if (layerEvents[i].getProperty().equals("visible")) {
957
                                        redraw = true;
958
                                }
959
                        }
960

    
961
                        if (e.getColorEvents().length > 0) {
962
                                redraw = true;
963
                        }
964

    
965
                        if (e.getExtentEvents().length > 0) {
966
                                redraw = true;
967
                        }
968

    
969
                        if (e.getProjectionEvents().length > 0) {
970
                                //redraw = true;
971
                        }
972

    
973

    
974
                        if (e.getLayerCollectionEvents().length > 0) {
975
                                redraw = true;
976
                        }
977

    
978
                        if (e.getLegendEvents().length > 0) {
979
                                redraw = true;
980
                        }
981

    
982
                        if (e.getSelectionEvents().length > 0) {
983
                                redraw = true;
984
                        }
985

    
986
                        if (redraw) {
987
                //System.out.println("MapContextListener redraw");
988
                                MapControl.this.drawMap(false);
989
                        }
990
                }
991
        }
992
        public ViewPort getViewPort() {
993
                return vp;
994
        }
995

    
996
        /**
997
         * Returns a HashMap with the tools that have been registered
998
         * in the Mapcontrol.
999
         */
1000
        public HashMap getNamesMapTools() {
1001
                return namesMapTools;
1002
        }
1003

    
1004
        public void commandRepaint() {
1005
                drawMap(false);
1006
        }
1007

    
1008
        public void commandRefresh() {
1009
                // TODO Auto-generated method stub
1010
        }
1011

    
1012
        public void setPrevTool() {
1013
                setTool(prevTool);
1014
        }
1015

    
1016
        public void zoomIn() {
1017
                getMapContext().clearAllCachingImageDrawnLayers();
1018
                Behavior mapTool = (Behavior) namesMapTools.get("zoomIn");
1019
                ViewPort vp=getViewPort();
1020
                Rectangle2D r=getViewPort().getAdjustedExtent();
1021
                Point2D pCenter=vp.fromMapPoint(r.getCenterX(),r.getCenterY());
1022
                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);
1023
                try {
1024
                        mapTool.mousePressed(e);
1025
                        mapTool.mouseReleased(e);
1026
                } catch (BehaviorException t) {
1027
                        throwException(t);
1028
                }
1029
        }
1030
        public void zoomOut() {
1031
                getMapContext().clearAllCachingImageDrawnLayers();
1032
                Behavior mapTool = (Behavior) namesMapTools.get("zoomOut");
1033
                ViewPort vp=getViewPort();
1034
                Rectangle2D r=getViewPort().getAdjustedExtent();
1035
                Point2D pCenter=vp.fromMapPoint(r.getCenterX(),r.getCenterY());
1036
                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);
1037
                try {
1038
                        mapTool.mousePressed(e);
1039
                        mapTool.mouseReleased(e);
1040
                } catch (BehaviorException t) {
1041
                        throwException(t);
1042
                }
1043
        }
1044

    
1045

    
1046
}