Statistics
| Revision:

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

History | View | Annotate | Download (27.3 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 6266 fjp
import java.awt.Component;
45 1223 fernando
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 5874 fjp
import java.awt.geom.Point2D;
58
import java.awt.geom.Rectangle2D;
59 1223 fernando
import java.awt.image.BufferedImage;
60
import java.util.HashMap;
61 6777 jmvivo
import java.util.Set;
62 1223 fernando
63
import javax.swing.JComponent;
64
import javax.swing.Timer;
65
66
import org.cresques.cts.IProjection;
67
68 6164 luisw2
import com.iver.cit.gvsig.fmap.crs.CRSFactory;
69 4120 caballero
import com.iver.cit.gvsig.fmap.edition.commands.CommandListener;
70 1223 fernando
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 5317 fjp
import com.iver.utiles.swing.threads.Cancellable;
77 1223 fernando
78
79
/**
80
 * MapControl.
81
 *
82
 * @author Fernando Gonz?lez Cort?s
83
 */
84 5874 fjp
public class MapControl extends JComponent implements ComponentListener,
85
                        CommandListener {
86 1223 fernando
        /** 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 2901 fjp
    public static final int ONLY_GRAPHICS = 2;
92 3346 fjp
    // public static final int FAST_PAINT = 3;
93 2531 caballero
        //private static Logger logger = Logger.getLogger(MapControl.class.getName());
94 6878 cesar
        private MapContext mapContext = null;
95 3719 caballero
    //private boolean drawerAlive = false;
96 1223 fernando
        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 3719 caballero
        //private boolean isCancelled = true;
103 1223 fernando
        private Timer timer;
104
        protected ViewPort vp;
105 3719 caballero
        //private Drawer drawer;
106 3368 fjp
    private Drawer2 drawer2;
107 3372 fjp
    // private boolean firstDraw = true;
108 9142 ldiaz
        protected MapToolListener mapToolListener = new MapToolListener();
109 1223 fernando
        private MapContextListener mapContextListener = new MapContextListener();
110
        private ExceptionHandlingSupport exceptionHandlingSupport = new ExceptionHandlingSupport();
111 4619 caballero
112 4888 caballero
        private String prevTool;
113
114 3719 caballero
        /**
115 3331 fjp
     * We need this to avoid not wanted refresh. REMEMBER TO SET TO TRUE!!
116
     */
117
    // private boolean paintEnabled = false;
118 1223 fernando
119
        /**
120
         * Crea un nuevo NewMapControl.
121
         */
122
        public MapControl() {
123 5787 jaume
                this.setName("MapControl");
124 1223 fernando
                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 6164 luisw2
                vp = new ViewPort(CRSFactory.getCRS("EPSG:23030"));
136 6878 cesar
                setMapContext(new MapContext(vp));
137 3719 caballero
138 1223 fernando
                //eventos
139
                this.addComponentListener(this);
140
                this.addMouseListener(mapToolListener);
141
                this.addMouseMotionListener(mapToolListener);
142
                this.addMouseWheelListener(mapToolListener);
143
144 3368 fjp
        this.drawer2 = new Drawer2();
145 1223 fernando
                //Timer para mostrar el redibujado mientras se dibuja
146 7679 fjp
                timer = new Timer(360,
147 1223 fernando
                                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 6878 cesar
        public void setMapContext(MapContext model) {
160 1223 fernando
                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 6878 cesar
        public MapContext getMapContext() {
204 1223 fernando
                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 10837 caballero
223 6777 jmvivo
        /**
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 3719 caballero
233 1223 fernando
        /**
234 6777 jmvivo
         * Devuelve los nombres de herramientas (tool) registradas.
235 10837 caballero
         *
236 6777 jmvivo
         * @return Set (String) nombres de las herramientas.
237
         */
238
        public Set getMapToolsKeySet() {
239
                return namesMapTools.keySet();
240
        }
241
242 10837 caballero
243 6777 jmvivo
        /**
244 6378 jaume
         * 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 1223 fernando
         * DOCUMENT ME!
256
         *
257
         * @param toolName DOCUMENT ME!
258
         */
259
        public void setTool(String toolName) {
260 6378 jaume
                prevTool=getCurrentTool();
261 1223 fernando
                Behavior mapTool = (Behavior) namesMapTools.get(toolName);
262
                currentMapTool = mapTool;
263
                currentTool = toolName;
264
                this.setCursor(mapTool.getCursor());
265
        }
266 3719 caballero
        public Behavior getCurrentMapTool(){
267
                return currentMapTool;
268
        }
269 1223 fernando
        /**
270 6378 jaume
         * Returns the name of the current selected tool on this MapControl
271 1223 fernando
         *
272 6378 jaume
         * @return A tool name.
273 1223 fernando
         */
274 6378 jaume
        public String getCurrentTool() {
275 1223 fernando
                return currentTool;
276
        }
277
278 10837 caballero
279 1223 fernando
        /**
280
         * Cancela el dibujado. Se espera a que la cancelaci?n surta efecto
281
         */
282
        public void cancelDrawing() {
283 3368 fjp
                /* if (drawer != null) {
284 1223 fernando
                        if (!drawer.isAlive()) {
285
                                return;
286
                        }
287
                }
288 3368 fjp
                */
289 4832 fjp
                canceldraw.setCanceled(true);
290 1223 fernando
291 3368 fjp
                /* while (!isCancelled) {
292 1243 fjp
                        if (!drawer.isAlive()) {
293 1327 fjp
                            // Si hemos llegado aqu? con un thread vivo, seguramente
294
                            // no estamos actualizados.
295

296
                                break;
297 1243 fjp
                        }
298 3719 caballero

299 1223 fernando
                }
300
                canceldraw.setCancel(false);
301
                isCancelled = false;
302 3368 fjp
        drawerAlive = false; */
303 1223 fernando
        }
304 3719 caballero
305 3375 fjp
    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 6212 fjp
            // ESTILO MAC
312
//                image = GraphicsEnvironment.getLocalGraphicsEnvironment()
313
//                                .getDefaultScreenDevice().getDefaultConfiguration()
314
//                                .createCompatibleImage(this.getWidth(), this.getHeight());
315 3375 fjp
            vp.setImageSize(new Dimension(getWidth(), getHeight()));
316 6630 caballero
            getMapContext().getViewPort().refreshExtent();
317 3719 caballero
318
319 3375 fjp
            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 3719 caballero
326 3375 fjp
            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 1223 fernando
335
        /**
336
         * @see javax.swing.JComponent#paintComponent(java.awt.Graphics)
337
         */
338
        protected void paintComponent(Graphics g) {
339 3375 fjp
        adaptToImageSize();
340 3346 fjp
        /* if (status == FAST_PAINT) {
341 3331 fjp
            System.out.println("FAST_PAINT");
342
            g.drawImage(image,0,0,null);
343
            status = ACTUALIZADO;
344
            return;
345 3346 fjp
        } */
346 4568 fjp
        // System.out.println("PINTANDO MAPCONTROL" + this);
347 1223 fernando
                if (status == ACTUALIZADO) {
348 1680 luisw
                        // LWS logger.debug("Dibujando la imagen obtenida");
349 1223 fernando
350
                        /*
351
                         * Si hay un behaviour y la imagen es distinta de null se delega el dibujado
352
                         * en dicho behaviour
353
                         */
354 3372 fjp
            if (image != null)
355
            {
356
                if (currentMapTool != null)
357
                    currentMapTool.paintComponent(g);
358
                else
359
                    g.drawImage(image,0,0,null);
360 3719 caballero
361 3372 fjp
                                // System.out.println("Pinto ACTUALIZADO");
362 1223 fernando
                        }
363 3719 caballero
                } else if ((status == DESACTUALIZADO)
364 2946 fjp
                || (status == ONLY_GRAPHICS)) {
365 1680 luisw
                        // LWS System.out.println("DESACTUALIZADO: Obteniendo la imagen de la cartograf?a");
366 1223 fernando
                        /* if (isOpaque())
367
                        {
368
                            if (image==null)
369
                            {
370
                                g.setColor(vp.getBackColor());
371 3719 caballero
                                g.fillRect(0,0,getWidth(), getHeight());
372
                            }
373 1223 fernando
                            // else g.drawImage(image,0,0,null);
374
                        } */
375 3368 fjp
            // cancelDrawing();
376 1223 fernando
                        //Se crea la imagen con el color de fonde deseado
377 3375 fjp
                        /* if (image == null)
378 1223 fernando
                        {
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 1303 fjp
                            Color theBackColor = vp.getBackColor();
384
                            if (theBackColor == null)
385
                                gTemp.setColor(Color.WHITE);
386
                            else
387
                                gTemp.setColor(theBackColor);
388 3719 caballero

389 1223 fernando
                                gTemp.fillRect(0,0,getWidth(), getHeight());
390
                                gTemp.dispose();
391
                                // g.drawImage(image,0,0,null);
392 3174 ldiaz
                                System.out.println("Imagen con null en DESACTUALIZADO. Width = " + this.getWidth());
393 3375 fjp
                        } */
394 3331 fjp
            // else
395
            // {
396 3719 caballero
397
398 3372 fjp
            // if (image != null)
399
            //  {
400 3331 fjp
                g.drawImage(image,0,0,null);
401 3719 caballero
402 3372 fjp
                drawer2.put(new PaintingRequest());
403
                timer.start();
404
            /* }
405
            else
406
                return; */
407 3331 fjp
            // }
408 3719 caballero
409 3368 fjp
            /* if (drawerAlive == false)
410 3331 fjp
            {
411
                drawer = new Drawer(image, canceldraw);
412
                drawer.start();
413 3719 caballero
                        //Se lanza el tread de dibujado
414 3368 fjp
            } */
415 3719 caballero
416 2946 fjp
                        // status = ACTUALIZADO;
417 1223 fernando
                }
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 3422 fjp
         * @param doClear Solo deber?a ser true cuando se llama desde pan
433 1223 fernando
         */
434
        public void drawMap(boolean doClear) {
435 3979 caballero
                cancelDrawing();
436
                System.out.println("drawMap con doClear=" + doClear);
437 3346 fjp
        status = DESACTUALIZADO;
438 5923 fjp
        getMapContext().getLayers().setDirty(true);
439 3331 fjp
                if (doClear)
440
        {
441 3372 fjp
            // 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 3719 caballero
            }
453 3331 fjp
        }
454 1223 fernando
                repaint();
455
        }
456 6306 caballero
457 5923 fjp
        public void rePaintDirtyLayers()
458
        {
459
                cancelDrawing();
460
        status = DESACTUALIZADO;
461
        repaint();
462
        }
463 6306 caballero
464 2901 fjp
    public void drawGraphics() {
465
        status = ONLY_GRAPHICS;
466
        repaint();
467
    }
468 1223 fernando
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 3375 fjp
                /* image = new BufferedImage(this.getWidth(), this.getHeight(),
486 3719 caballero
                                BufferedImage.TYPE_INT_ARGB);
487 1223 fernando
                Graphics gTemp = image.createGraphics();
488
                gTemp.setColor(vp.getBackColor());
489 3372 fjp
                gTemp.fillRect(0,0,getWidth(), getHeight());
490
        System.out.println("MapControl resized");
491
            // image = null;
492 1223 fernando
            vp.setImageSize(new Dimension(getWidth(), getHeight()));
493 3375 fjp
                getMapContext().getViewPort().setScale(); */
494 3372 fjp
                // drawMap(true);
495 1223 fernando
        }
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 9079 ldiaz
        protected void throwException(Throwable t) {
529 1223 fernando
                exceptionHandlingSupport.throwException(t);
530
        }
531
532 3719 caballero
533 3368 fjp
    private class PaintingRequest
534
    {
535 3719 caballero
536 3372 fjp
        public PaintingRequest()
537 3368 fjp
        {
538
        }
539 3719 caballero
540 3368 fjp
        public void paint()
541
        {
542 3719 caballero
            try
543
            {
544 4832 fjp
                    canceldraw.setCanceled(false);
545 3372 fjp
                /* 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 3719 caballero

556 3372 fjp
                    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 3368 fjp
                Graphics2D g = image.createGraphics();
562 3719 caballero
563 3368 fjp
                ViewPort viewPort = mapContext.getViewPort();
564 3719 caballero
565 3368 fjp
                if (status == DESACTUALIZADO)
566
                {
567 5874 fjp
                        Graphics2D gTemp = image.createGraphics();
568 3368 fjp
                    Color theBackColor = viewPort.getBackColor();
569
                    if (theBackColor == null)
570 5874 fjp
                        gTemp.setColor(Color.WHITE);
571 3368 fjp
                    else
572 5874 fjp
                        gTemp.setColor(theBackColor);
573
                    gTemp.fillRect(0, 0, viewPort.getImageWidth(), viewPort.getImageHeight());
574 3368 fjp
                    status = ACTUALIZADO;
575 6261 fjp
                    // ESTILO MAC
576
//                    BufferedImage imgMac = new BufferedImage(vp.getImageWidth(), vp.getImageHeight(),
577
//                            BufferedImage.TYPE_INT_ARGB);
578 6306 caballero
//
579 6261 fjp
//                    mapContext.draw(imgMac, g, canceldraw, mapContext.getScaleView());
580
//                    g.drawImage(imgMac, 0, 0, null);
581
                    // FIN ESTILO MAC
582
                    // SIN MAC:
583 3372 fjp
                    mapContext.draw(image, g, canceldraw, mapContext.getScaleView());
584 3719 caballero
585 3368 fjp
                }
586
                else if (status == ONLY_GRAPHICS)
587
                {
588 3719 caballero
                    status = ACTUALIZADO;
589 3372 fjp
                    mapContext.drawGraphics(image, g, canceldraw,mapContext.getScaleView());
590 3719 caballero
591 3368 fjp
                }
592 3719 caballero
593
594 3368 fjp
                // status = FAST_PAINT;
595 3719 caballero
              //  drawerAlive = false;
596 3372 fjp
                timer.stop();
597 3368 fjp
                repaint();
598 3719 caballero
599
600 3368 fjp
            } catch (Throwable e) {
601
                timer.stop();
602 3719 caballero
              //  isCancelled = true;
603 3368 fjp
                e.printStackTrace();
604
                throwException(e);
605
            } finally {
606
            }
607 3719 caballero
608 3368 fjp
        }
609 3719 caballero
610 3368 fjp
    }
611 3719 caballero
612 3368 fjp
    /**
613
     * @author fjp
614 3719 caballero
     *
615 3368 fjp
     * 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 3719 caballero
625 3368 fjp
        private boolean waiting;
626
        private boolean shutdown;
627 3719 caballero
628 3368 fjp
        public void setShutdown(boolean isShutdown)
629
        {
630
            shutdown = isShutdown;
631
        }
632 3719 caballero
633
        public Drawer2()
634 3368 fjp
        {
635
            paintingRequest = null;
636
            waitingRequest = null;
637
            waiting = false;
638
            shutdown = false;
639
            new Thread(new Worker()).start();
640
        }
641 3719 caballero
642 3368 fjp
        public void put(PaintingRequest newPaintRequest)
643
        {
644
            waitingRequest = newPaintRequest;
645
            if (waiting)
646
            {
647
                synchronized (this) {
648
                    notifyAll();
649
                }
650
            }
651
        }
652 3719 caballero
653 3368 fjp
        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 3719 caballero
673
674 3368 fjp
        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 4120 caballero
                    if (image != null){
683
                            cancelDrawing();
684 3372 fjp
                        p.paint();
685 4120 caballero
                    } else
686 3372 fjp
                        status = DESACTUALIZADO;
687 3368 fjp
                }
688
            }
689
        }
690
    }
691 3719 caballero
692 1223 fernando
        /**
693
         * Clase utilizada para dibujar las capas.
694
         *
695
         * @author Vicente Caballero Navarro
696
         */
697
        public class Drawer extends Thread {
698 2531 caballero
                //private Graphics g;
699 3331 fjp
                private BufferedImage image = null;
700 1223 fernando
                private CancelDraw cancel;
701 2531 caballero
                //private boolean threadCancel = false;
702 1223 fernando
703
                /**
704
                 * Crea un nuevo Drawer.
705
                 *
706
                 */
707 3331 fjp
                public Drawer(BufferedImage image, CancelDraw cancel)
708
        {
709 1223 fernando
                        this.image = image;
710
                        this.cancel = cancel;
711 3719 caballero
         //   drawerAlive = true;
712 1223 fernando
                }
713
714
                /**
715
                 * @see java.lang.Runnable#run()
716
                 */
717
                public void run() {
718
                        try {
719 2857 jaume
                                // synchronized (Drawer.class) {
720 1282 fjp
                                    Graphics2D g = image.createGraphics();
721 3719 caballero
722 1282 fjp
                                    ViewPort viewPort = mapContext.getViewPort();
723 2946 fjp
                    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 2951 fjp
                        status = ACTUALIZADO;
737 2946 fjp
                        mapContext.drawGraphics(image, g, cancel,mapContext.getScaleView());
738
                    }
739 3719 caballero
740 1327 fjp
                                        timer.stop();
741 3346 fjp
                    // status = FAST_PAINT;
742 3719 caballero
                  //  drawerAlive = false;
743 1223 fernando
                                        repaint();
744 3719 caballero
745
746
747 2857 jaume
                                // }
748 1223 fernando
                        } catch (Throwable e) {
749 1266 fernando
                            timer.stop();
750 3719 caballero
                                //isCancelled = true;
751 2943 fjp
                e.printStackTrace();
752 1223 fernando
                                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 4832 fjp
                public void setCanceled(boolean b) {
778 1223 fernando
                        cancel = b;
779
                }
780
781
                /**
782 5317 fjp
                 * @see com.iver.utiles.swing.threads.Cancellable#isCanceled()
783 1223 fernando
                 */
784
                public boolean isCanceled() {
785
                        return cancel;
786
                }
787
        }
788
789 6306 caballero
790 1223 fernando
        /**
791
         * Listener del MapTool.
792
         *
793
         * @author Fernando Gonz?lez Cort?s
794
         */
795
        public class MapToolListener implements MouseListener, MouseWheelListener,
796
                MouseMotionListener {
797 5881 fjp
798
                long t1;
799
                Point2D pReal;
800 1223 fernando
                /**
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 6306 caballero
862 5874 fjp
                                // Si el tool actual no ha consumido el evento
863
                                // entendemos que quiere el comportamiento por defecto.
864
                                if (!e.isConsumed())
865
                                {
866 5881 fjp
                                        // 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 5874 fjp
                                        cancelDrawing();
881
                                        ViewPort vp = getViewPort();
882
883 6306 caballero
884 5874 fjp
                                        /* 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 6306 caballero
                                        if (amount < 0) // nos acercamos
892 5874 fjp
                                        {
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 6306 caballero
912
913 5874 fjp
                                }
914 1223 fernando
                        } 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 6306 caballero
969 5941 jmvivo
                        if (e.getProjectionEvents().length > 0) {
970
                                //redraw = true;
971
                        }
972 1223 fernando
973 6306 caballero
974 1223 fernando
                        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 3331 fjp
                System.out.println("MapContextListener redraw");
988 3422 fjp
                                MapControl.this.drawMap(false);
989 1223 fernando
                        }
990
                }
991
        }
992
        public ViewPort getViewPort() {
993
                return vp;
994
        }
995 3719 caballero
996 2877 caballero
        /**
997 3719 caballero
         * Returns a HashMap with the tools that have been registered
998 2877 caballero
         * in the Mapcontrol.
999
         */
1000 2876 caballero
        public HashMap getNamesMapTools() {
1001
                return namesMapTools;
1002
        }
1003 4120 caballero
1004 4142 caballero
        public void commandRepaint() {
1005 4127 caballero
                drawMap(false);
1006 4120 caballero
        }
1007 4127 caballero
1008
        public void commandRefresh() {
1009
                // TODO Auto-generated method stub
1010
        }
1011 4888 caballero
1012
        public void setPrevTool() {
1013
                setTool(prevTool);
1014
        }
1015 6306 caballero
1016 10837 caballero
        public void zoomIn() {
1017
                getMapContext().clearAllCachingImageDrawnLayers();
1018 6264 fjp
                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 10837 caballero
                getMapContext().clearAllCachingImageDrawnLayers();
1032 6264 fjp
                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 6261 fjp
1045 6306 caballero
1046 1223 fernando
}