Statistics
| Revision:

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

History | View | Annotate | Download (15.7 KB)

1 1223 fernando
/* 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 1282 fjp
import java.awt.Color;
44 1223 fernando
import java.awt.Dimension;
45
import java.awt.Graphics;
46
import java.awt.Graphics2D;
47
import java.awt.event.ActionEvent;
48
import java.awt.event.ActionListener;
49
import java.awt.event.ComponentEvent;
50
import java.awt.event.ComponentListener;
51
import java.awt.event.MouseEvent;
52
import java.awt.event.MouseListener;
53
import java.awt.event.MouseMotionListener;
54
import java.awt.event.MouseWheelEvent;
55
import java.awt.event.MouseWheelListener;
56
import java.awt.image.BufferedImage;
57
import java.util.HashMap;
58
59
import javax.swing.JComponent;
60
import javax.swing.Timer;
61
62
import org.cresques.cts.IProjection;
63
import org.cresques.cts.ProjectionPool;
64
65
import com.iver.cit.gvsig.fmap.layers.LayerEvent;
66
import com.iver.cit.gvsig.fmap.operations.Cancellable;
67
import com.iver.cit.gvsig.fmap.tools.BehaviorException;
68
import com.iver.cit.gvsig.fmap.tools.CompoundBehavior;
69
import com.iver.cit.gvsig.fmap.tools.Behavior.Behavior;
70
import com.iver.utiles.exceptionHandling.ExceptionHandlingSupport;
71
import com.iver.utiles.exceptionHandling.ExceptionListener;
72
73
74
/**
75
 * MapControl.
76
 *
77
 * @author Fernando Gonz?lez Cort?s
78
 */
79
public class MapControl extends JComponent implements ComponentListener {
80
        /** Cuando la vista est? actualizada. */
81
        public static final int ACTUALIZADO = 0;
82
83
        /** Cuando la vista est? desactualizada. */
84
        public static final int DESACTUALIZADO = 1;
85 2901 fjp
    public static final int ONLY_GRAPHICS = 2;
86 2531 caballero
        //private static Logger logger = Logger.getLogger(MapControl.class.getName());
87 1223 fernando
        private FMap mapContext = null;
88
        private HashMap namesMapTools = new HashMap();
89
        private Behavior currentMapTool = null;
90
        private int status = DESACTUALIZADO;
91
        private BufferedImage image = null;
92
        private String currentTool;
93
        private CancelDraw canceldraw;
94
        private boolean isCancelled = true;
95
        private Timer timer;
96
        protected ViewPort vp;
97
        private Drawer drawer;
98
        private MapToolListener mapToolListener = new MapToolListener();
99
        private MapContextListener mapContextListener = new MapContextListener();
100
        private ExceptionHandlingSupport exceptionHandlingSupport = new ExceptionHandlingSupport();
101
102
        /**
103
         * Crea un nuevo NewMapControl.
104
         */
105
        public MapControl() {
106
                setDoubleBuffered(false);
107
                setOpaque(true);
108
                status = DESACTUALIZADO;
109
110
                //Clase usada para cancelar el dibujado
111
                canceldraw = new CancelDraw();
112
113
                //Modelo de datos y ventana del mismo
114
                // TODO: Cuando creamos un mapControl, deber?amos asignar
115
                // la projecci?n por defecto con la que vayamos a trabajar.
116
                // 23030 es el c?digo EPSG del UTM30 elipsoide ED50
117
                vp = new ViewPort(ProjectionPool.get("EPSG:23030"));
118
                setMapContext(new FMap(vp));
119 1243 fjp
120 1223 fernando
                //eventos
121
                this.addComponentListener(this);
122
                this.addMouseListener(mapToolListener);
123
                this.addMouseMotionListener(mapToolListener);
124
                this.addMouseWheelListener(mapToolListener);
125
126
                //Timer para mostrar el redibujado mientras se dibuja
127
                timer = new Timer(300,
128
                                new ActionListener() {
129
                                        public void actionPerformed(ActionEvent e) {
130
                                                MapControl.this.repaint();
131
                                        }
132
                                });
133
        }
134
135
        /**
136
         * Inserta el modelo.
137
         *
138
         * @param model FMap.
139
         */
140
        public void setMapContext(FMap model) {
141
                if (mapContext != null) {
142
                        mapContext.removeAtomicEventListener(mapContextListener);
143
                }
144
145
                mapContext = model;
146
147
                if (mapContext.getViewPort() == null) {
148
                        mapContext.setViewPort(vp);
149
                } else {
150
                        vp = mapContext.getViewPort();
151
152
                        // vp.setImageSize(new Dimension(getWidth(), getHeight()));
153
                        //System.err.println("Viewport en setMapContext:" + vp);
154
                }
155
156
                mapContext.addAtomicEventListener(mapContextListener);
157
158
                status = DESACTUALIZADO;
159
        }
160
161
        /**
162
         * Devuelve la proyecci?n.
163
         *
164
         * @return Proyecci?n.
165
         */
166
        public IProjection getProjection() {
167
                return getMapContext().getProjection();
168
        }
169
170
        /**
171
         * Inserta una proyecci?n.
172
         *
173
         * @param proj Proyecci?n.
174
         */
175
        public void setProjection(IProjection proj) {
176
                getMapContext().setProjection(proj);
177
        }
178
179
        /**
180
         * Devuelve el modelo.
181
         *
182
         * @return FMap.
183
         */
184
        public FMap getMapContext() {
185
                return mapContext;
186
        }
187
188
        /**
189
         * Registra una herramienta (tool).
190
         *
191
         * @param name Nombre de la herramienta.
192
         * @param tool Herramienta.
193
         */
194
        public void addMapTool(String name, Behavior tool) {
195
                namesMapTools.put(name, tool);
196
                tool.setMapControl(this);
197
        }
198
199
        public void addMapTool(String name, Behavior[] tools){
200
                CompoundBehavior tool = new CompoundBehavior(tools);
201
                addMapTool(name, tool);
202
        }
203
204
        /**
205
         * DOCUMENT ME!
206
         *
207
         * @param toolName DOCUMENT ME!
208
         */
209
        public void setTool(String toolName) {
210
                Behavior mapTool = (Behavior) namesMapTools.get(toolName);
211
                currentMapTool = mapTool;
212
                currentTool = toolName;
213
                this.setCursor(mapTool.getCursor());
214
        }
215
216
        /**
217
         * Devuelve el nombre de la herramienta seleccionada.
218
         *
219
         * @return nombre.
220
         */
221
        public String getTool() {
222
                return currentTool;
223
        }
224
225
        /**
226
         * Cancela el dibujado. Se espera a que la cancelaci?n surta efecto
227
         */
228
        public void cancelDrawing() {
229
                if (drawer != null) {
230
                        if (!drawer.isAlive()) {
231
                                return;
232
                        }
233
                }
234
235
                canceldraw.setCancel(true);
236
237
                while (!isCancelled) {
238 1243 fjp
                        if (!drawer.isAlive()) {
239 1327 fjp
                            // Si hemos llegado aqu? con un thread vivo, seguramente
240
                            // no estamos actualizados.
241
242
                                break;
243 1243 fjp
                        }
244
245 1223 fernando
                }
246
                canceldraw.setCancel(false);
247
                isCancelled = false;
248
        }
249
250
        /**
251
         * @see javax.swing.JComponent#paintComponent(java.awt.Graphics)
252
         */
253
        protected void paintComponent(Graphics g) {
254
                if (status == ACTUALIZADO) {
255 1680 luisw
                        // LWS logger.debug("Dibujando la imagen obtenida");
256 1223 fernando
257
                        /*
258
                         * Si hay un behaviour y la imagen es distinta de null se delega el dibujado
259
                         * en dicho behaviour
260
                         */
261
                        if ((currentMapTool != null) && (image != null)) {
262
                                currentMapTool.paintComponent(g);
263 1680 luisw
                                // LWS System.out.println("Pinto ACTUALIZADO");
264 1223 fernando
                        }
265 2946 fjp
                } else if ((status == DESACTUALIZADO)
266
                || (status == ONLY_GRAPHICS)) {
267 1680 luisw
                        // LWS System.out.println("DESACTUALIZADO: Obteniendo la imagen de la cartograf?a");
268 1223 fernando
                        /* if (isOpaque())
269
                        {
270
                            if (image==null)
271
                            {
272
                                g.setColor(vp.getBackColor());
273
                                g.fillRect(0,0,getWidth(), getHeight());
274
                            }
275
                            // else g.drawImage(image,0,0,null);
276
                        } */
277
278
                        //Se crea la imagen con el color de fonde deseado
279
                        if (image == null)
280
                        {
281
                                image = new BufferedImage(this.getWidth(), this.getHeight(),
282
                                                BufferedImage.TYPE_INT_ARGB);
283
                                vp.setImageSize(new Dimension(getWidth(), getHeight()));
284
                                Graphics gTemp = image.createGraphics();
285 1303 fjp
                            Color theBackColor = vp.getBackColor();
286
                            if (theBackColor == null)
287
                                gTemp.setColor(Color.WHITE);
288
                            else
289
                                gTemp.setColor(theBackColor);
290
291 1223 fernando
                                gTemp.fillRect(0,0,getWidth(), getHeight());
292
                                gTemp.dispose();
293
                                // g.drawImage(image,0,0,null);
294
                                System.out.println("Imagen con null en DESACTUALIZADO");
295
                        }
296
                        g.drawImage(image,0,0,null);
297
298
                        Graphics imgg = image.createGraphics();
299
300 1243 fjp
                        //Se cancela el dibujado anterior
301
                        cancelDrawing();
302
303 1223 fernando
                        drawer = new Drawer(image, (Graphics2D) imgg, canceldraw);
304
                        drawer.start();
305 1327 fjp
                        //Se lanza el tread de dibujado
306
                        timer.start();
307 1243 fjp
308 2946 fjp
                        // status = ACTUALIZADO;
309 1223 fernando
                }
310
        }
311
312
        /**
313
         * Devuelve la imagen de la vista.
314
         *
315
         * @return imagen.
316
         */
317
        public BufferedImage getImage() {
318
                return image;
319
        }
320
321
        /**
322
         * Marca el mapa para que en el pr?ximo redibujado se acceda a la
323
         * cartograf?a para reobtener la imagen
324
         * @param doClear TODO
325
         */
326
        public void drawMap(boolean doClear) {
327
                status = DESACTUALIZADO;
328
                if (doClear) image = null; // Se usa para el PAN
329
                repaint();
330
        }
331 2901 fjp
    public void drawGraphics() {
332
        status = ONLY_GRAPHICS;
333
        repaint();
334
    }
335 1223 fernando
336
        /**
337
         * @see java.awt.event.ComponentListener#componentHidden(java.awt.event.ComponentEvent)
338
         */
339
        public void componentHidden(ComponentEvent e) {
340
        }
341
342
        /**
343
         * @see java.awt.event.ComponentListener#componentMoved(java.awt.event.ComponentEvent)
344
         */
345
        public void componentMoved(ComponentEvent e) {
346
        }
347
348
        /**
349
         * @see java.awt.event.ComponentListener#componentResized(java.awt.event.ComponentEvent)
350
         */
351
        public void componentResized(ComponentEvent e) {
352
                /* image = new BufferedImage(this.getWidth(), this.getHeight(),
353
                                BufferedImage.TYPE_INT_ARGB);
354
                Graphics gTemp = image.createGraphics();
355
                gTemp.setColor(vp.getBackColor());
356
                gTemp.fillRect(0,0,getWidth(), getHeight()); */
357
            image = null;
358
            vp.setImageSize(new Dimension(getWidth(), getHeight()));
359
                getMapContext().getViewPort().setScale();
360
                drawMap(false);
361
        }
362
363
        /**
364
         * @see java.awt.event.ComponentListener#componentShown(java.awt.event.ComponentEvent)
365
         */
366
        public void componentShown(ComponentEvent e) {
367
        }
368
369
        /**
370
         * A?ade un listener de tipo ExceptionListener.
371
         *
372
         * @param o ExceptionListener.
373
         */
374
        public void addExceptionListener(ExceptionListener o) {
375
                exceptionHandlingSupport.addExceptionListener(o);
376
        }
377
378
        /**
379
         * Borra la ExceptioListener que se pasa como par?metro.
380
         *
381
         * @param o ExceptionListener.
382
         *
383
         * @return True si se borra correctamente.
384
         */
385
        public boolean removeExceptionListener(ExceptionListener o) {
386
                return exceptionHandlingSupport.removeExceptionListener(o);
387
        }
388
389
        /**
390
         * Lanza una Excepci?n.
391
         *
392
         * @param t Excepci?n.
393
         */
394
        private void throwException(Throwable t) {
395
                exceptionHandlingSupport.throwException(t);
396
        }
397
398
        /**
399
         * Clase utilizada para dibujar las capas.
400
         *
401
         * @author Vicente Caballero Navarro
402
         */
403
        public class Drawer extends Thread {
404 2531 caballero
                //private Graphics g;
405 1223 fernando
                private BufferedImage image;
406
                private CancelDraw cancel;
407 2531 caballero
                //private boolean threadCancel = false;
408 1223 fernando
409
                /**
410
                 * Crea un nuevo Drawer.
411
                 *
412
                 * @param image
413
                 * @param g
414
                 * @param cancel
415
                 */
416
                public Drawer(BufferedImage image, Graphics g, CancelDraw cancel) {
417 2531 caballero
                        //this.g = g;
418 1223 fernando
                        this.image = image;
419
                        this.cancel = cancel;
420
                }
421
422
                /**
423
                 * @see java.lang.Runnable#run()
424
                 */
425
                public void run() {
426
                        try {
427 2857 jaume
                                // synchronized (Drawer.class) {
428 1282 fjp
                                    Graphics2D g = image.createGraphics();
429
                                    ViewPort viewPort = mapContext.getViewPort();
430 2946 fjp
                    if (status == DESACTUALIZADO)
431
                    {
432
                                        Color theBackColor = viewPort.getBackColor();
433
                                        if (theBackColor == null)
434
                                            g.setColor(Color.WHITE);
435
                                        else
436
                                            g.setColor(theBackColor);
437
                                            g.fillRect(0, 0, viewPort.getImageWidth(), viewPort.getImageHeight());
438
                        status = ACTUALIZADO;
439
                        mapContext.draw(image, g, cancel,mapContext.getScaleView());
440
                    }
441
                    else if (status == ONLY_GRAPHICS)
442
                    {
443 2951 fjp
                        status = ACTUALIZADO;
444 2946 fjp
                        mapContext.drawGraphics(image, g, cancel,mapContext.getScaleView());
445
                    }
446
                    // status = ACTUALIZADO;
447 1223 fernando
                                        isCancelled = true;
448 1327 fjp
                                        timer.stop();
449 1223 fernando
                                        repaint();
450 1327 fjp
451 2857 jaume
                                // }
452 1223 fernando
                        } catch (Throwable e) {
453 1266 fernando
                            timer.stop();
454
                                isCancelled = true;
455 2943 fjp
                e.printStackTrace();
456 1223 fernando
                                throwException(e);
457
                        } finally {
458
                        }
459
                }
460
        }
461
462
        /**
463
         * Clase para cancelar el dibujado.
464
         *
465
         * @author Fernando Gonz?lez Cort?s
466
         */
467
        public class CancelDraw implements Cancellable {
468
                private boolean cancel = false;
469
470
                /**
471
                 * Crea un nuevo CancelDraw.
472
                 */
473
                public CancelDraw() {
474
                }
475
476
                /**
477
                 * Insertar si se debe cancelar el dibujado.
478
                 *
479
                 * @param b true si se debe cancelar el dibujado.
480
                 */
481
                public void setCancel(boolean b) {
482
                        cancel = b;
483
                }
484
485
                /**
486
                 * @see com.iver.cit.gvsig.fmap.operations.Cancellable#isCanceled()
487
                 */
488
                public boolean isCanceled() {
489
                        return cancel;
490
                }
491
        }
492
493
        /**
494
         * Listener del MapTool.
495
         *
496
         * @author Fernando Gonz?lez Cort?s
497
         */
498
        public class MapToolListener implements MouseListener, MouseWheelListener,
499
                MouseMotionListener {
500
                /**
501
                 * @see java.awt.event.MouseListener#mouseClicked(java.awt.event.MouseEvent)
502
                 */
503
                public void mouseClicked(MouseEvent e) {
504
                        try {
505
                                currentMapTool.mouseClicked(e);
506
                        } catch (BehaviorException t) {
507
                                throwException(t);
508
                        }
509
                }
510
511
                /**
512
                 * @see java.awt.event.MouseListener#mouseEntered(java.awt.event.MouseEvent)
513
                 */
514
                public void mouseEntered(MouseEvent e) {
515
                        try {
516
                                currentMapTool.mouseEntered(e);
517
                        } catch (BehaviorException t) {
518
                                throwException(t);
519
                        }
520
                }
521
522
                /**
523
                 * @see java.awt.event.MouseListener#mouseExited(java.awt.event.MouseEvent)
524
                 */
525
                public void mouseExited(MouseEvent e) {
526
                        try {
527
                                currentMapTool.mouseExited(e);
528
                        } catch (BehaviorException t) {
529
                                throwException(t);
530
                        }
531
                }
532
533
                /**
534
                 * @see java.awt.event.MouseListener#mousePressed(java.awt.event.MouseEvent)
535
                 */
536
                public void mousePressed(MouseEvent e) {
537
                        try {
538
                                currentMapTool.mousePressed(e);
539
                        } catch (BehaviorException t) {
540
                                throwException(t);
541
                        }
542
                }
543
544
                /**
545
                 * @see java.awt.event.MouseListener#mouseReleased(java.awt.event.MouseEvent)
546
                 */
547
                public void mouseReleased(MouseEvent e) {
548
                        try {
549
                                currentMapTool.mouseReleased(e);
550
                        } catch (BehaviorException t) {
551
                                throwException(t);
552
                        }
553
                }
554
555
                /**
556
                 * @see java.awt.event.MouseWheelListener#mouseWheelMoved(java.awt.event.MouseWheelEvent)
557
                 */
558
                public void mouseWheelMoved(MouseWheelEvent e) {
559
                        try {
560
                                currentMapTool.mouseWheelMoved(e);
561
                        } catch (BehaviorException t) {
562
                                throwException(t);
563
                        }
564
                }
565
566
                /**
567
                 * @see java.awt.event.MouseMotionListener#mouseDragged(java.awt.event.MouseEvent)
568
                 */
569
                public void mouseDragged(MouseEvent e) {
570
                        try {
571
                                currentMapTool.mouseDragged(e);
572
                        } catch (BehaviorException t) {
573
                                throwException(t);
574
                        }
575
                }
576
577
                /**
578
                 * @see java.awt.event.MouseMotionListener#mouseMoved(java.awt.event.MouseEvent)
579
                 */
580
                public void mouseMoved(MouseEvent e) {
581
                        try {
582
                                currentMapTool.mouseMoved(e);
583
                        } catch (BehaviorException t) {
584
                                throwException(t);
585
                        }
586
                }
587
        }
588
589
        /**
590
         * Listener sobre el MapContext.
591
         *
592
         * @author Fernando Gonz?lez Cort?s
593
         */
594
        public class MapContextListener implements AtomicEventListener {
595
                /**
596
                 * @see com.iver.cit.gvsig.fmap.AtomicEventListener#atomicEvent(com.iver.cit.gvsig.fmap.AtomicEvent)
597
                 */
598
                public void atomicEvent(AtomicEvent e) {
599
                        boolean redraw = false;
600
                        LayerEvent[] layerEvents = e.getLayerEvents();
601
602
                        for (int i = 0; i < layerEvents.length; i++) {
603
                                if (layerEvents[i].getProperty().equals("visible")) {
604
                                        redraw = true;
605
                                }
606
                        }
607
608
                        if (e.getColorEvents().length > 0) {
609
                                redraw = true;
610
                        }
611
612
                        if (e.getExtentEvents().length > 0) {
613
                                redraw = true;
614
                        }
615
616
                        if (e.getLayerCollectionEvents().length > 0) {
617
                                redraw = true;
618
                        }
619
620
                        if (e.getLegendEvents().length > 0) {
621
                                redraw = true;
622
                        }
623
624
                        if (e.getSelectionEvents().length > 0) {
625
                                redraw = true;
626
                        }
627
628
                        if (redraw) {
629
                                MapControl.this.drawMap(false);
630
                        }
631
                }
632
        }
633
        public ViewPort getViewPort() {
634
                return vp;
635
        }
636 2877 caballero
637
        /**
638
         * Returns a HashMap with the tools that have been registered
639
         * in the Mapcontrol.
640
         */
641 2876 caballero
        public HashMap getNamesMapTools() {
642
                return namesMapTools;
643
        }
644 1223 fernando
}