/* gvSIG. Sistema de Información Geográfica de la Generalitat Valenciana * * Copyright (C) 2004 IVER T.I. and Generalitat Valenciana. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,USA. * * For more information, contact: * * Generalitat Valenciana * Conselleria d'Infraestructures i Transport * Av. Blasco Ibáñez, 50 * 46010 VALENCIA * SPAIN * * +34 963862235 * gvsig@gva.es * www.gvsig.gva.es * * or * * IVER T.I. S.A * Salamanca 50 * 46005 Valencia * Spain * * +34 963163400 * dac@iver.es */ package com.iver.cit.gvsig.fmap; import java.awt.Color; import java.awt.Component; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.ComponentEvent; import java.awt.event.ComponentListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.event.MouseMotionListener; import java.awt.event.MouseWheelEvent; import java.awt.event.MouseWheelListener; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; import java.awt.image.BufferedImage; import java.util.HashMap; import java.util.Set; import javax.swing.JComponent; import javax.swing.Timer; import org.cresques.cts.IProjection; import com.iver.cit.gvsig.fmap.crs.CRSFactory; import com.iver.cit.gvsig.fmap.edition.commands.CommandListener; import com.iver.cit.gvsig.fmap.layers.FLayers; import com.iver.cit.gvsig.fmap.layers.GraphicLayer; import com.iver.cit.gvsig.fmap.layers.LayerCollectionEvent; import com.iver.cit.gvsig.fmap.layers.LayerEvent; import com.iver.cit.gvsig.fmap.tools.BehaviorException; import com.iver.cit.gvsig.fmap.tools.CompoundBehavior; import com.iver.cit.gvsig.fmap.tools.Behavior.Behavior; import com.iver.cit.gvsig.fmap.tools.Listeners.ToolListener; import com.iver.utiles.exceptionHandling.ExceptionHandlingSupport; import com.iver.utiles.exceptionHandling.ExceptionListener; import com.iver.utiles.swing.threads.Cancellable; /** *

A component that includes a {@link MapContext MapContext} with support for use it as a particular {@link Behavior Behavior}.

* *

A developer can register a set of Behavior, but only one (that can be a composition of several) of them can be active. The active one * defines the way to work and access with its MapContext's layers. The active behavior, in combination with the appropriate * {@link ToolListener ToolListener} will allow user work with a particular tool.

* *

All mouse events produced on this component will be delegated to the current active behavior, the currentMapTool.

* *

Drawing process:

* *

Uses a double buffer for the drawing process of MapContext's information.

* *

If the double buffer wasn't created, creates a new one.

* *

Paints the component according the following algorithm: *
*   If status is UPDATED:
*     If there is a double buffer:
*       If there is a behavior for managing the MapControl instance, delegates * the drawing process to that behavior, calling: behavior_instance.paintComponent(g).
*       Else, repaints the current graphical information quickly calling: g.drawImage(image,0,0,null).
*   Else, (status is OUTDATED, or ONLY_GRAPHICS): executes a quickly repaint of the previous information calling g.drawImage(image,0,0,null), and creates * a painting request to delegate the heavy drawing process to the {@link Drawer2 Drawer2}'s worker thread, according the SingleWorketThread pattern, starting a timer to update * (invoking repaint()) the view every delay of 1000 / drawFrameRate ms. during that heavy drawing process, and if its enabled drawAnimationEnabled. The painting request once is being attended, invokes MapContext to * draw the layers: mapContext.draw(image, g, cancel,mapContext.getScaleView()); *
*

Some notes: *

*

* *

Tools:

* *

A developer can: *

*

* *

Exception listener:

* *

Adding an ExceptionListener, can get notification about any exception produced: *

*

* *

Other:

* *

Other useful capabilities of MapControl: *

*

* * @see CancelDraw * @see Drawer2 * @see MapContextListener * @see MapToolListener * * @author Fernando González Cortés * @author Pablo Piqueras Bartolomé (pablo.piqueras@iver.es) */ public class MapControl extends JComponent implements ComponentListener, CommandListener { /** *

One of the possible status of MapControl. Determines that all visible information has been * drawn and its updated.

*/ public static final int ACTUALIZADO = 0; /** *

One of the possible status of MapControl. Determines that not all visible information has been * drawn or isn't updated.

*/ public static final int DESACTUALIZADO = 1; /** *

One of the possible status of MapControl. Determines that only the graphical layer must * be drawn / updated.

*/ public static final int ONLY_GRAPHICS = 2; /** *

Determines the number of frames.

* *

Number of updates per second that the timer will invoke repaint this component.

*/ private static int drawFrameRate = 3; /** *

Determines if the drawer can update this MapControl instance when the timer launches an event.

*/ private static boolean drawAnimationEnabled = true; // public static final int FAST_PAINT = 3; //private static Logger logger = Logger.getLogger(MapControl.class.getName()); /** *

Inner model with the layers, event support for drawing them, and the ViewPort * with information to adapt to the bounds available in image coordinates.

* * @see #getMapContext() * @see #setMapContext(MapContext) */ private MapContext mapContext = null; //private boolean drawerAlive = false; /** *

All registered Behavior that can define a way to work with this MapControl.

* *

Only one of them can be active at a given moment.

* * @see #addMapTool(String, Behavior) * @see #addMapTool(String, Behavior[]) * @see #getMapTool(String) * @see #getMapToolsKeySet() * @see #getNamesMapTools() */ protected HashMap namesMapTools = new HashMap(); /** *

Active {@link Behavior Behavior} that will generate events according a criterion, and then, with a {@link ToolListener ToolListener} * associated, will simulate to user that works with this component as a particular tool.

* * @see #getCurrentMapTool() * @see #getCurrentTool() * @see #setTool(String) */ protected Behavior currentMapTool = null; /** *

Determines which's the current drawn status of this component: *

*

* *

The MapControl drawing process will consider the value of this parameter to decide which elements will * be updated or drawn.

*/ private int status = DESACTUALIZADO; /** *

Image with a buffer to accelerate the draw the changes of the graphical items in this component.

* *

Firstly, information will be drawn in the buffer, and, when is outright drawn, that information will be displayed. * Meanwhile, the previous image can be kept showed.

* * @see BufferedImage * * @see #getImage() */ private BufferedImage image = null; /** *

Name of the tool used currently to interact with this component.

* * @see #getCurrentTool() * @see #setTool(String) */ protected String currentTool; /** *

Object to store the flag that notifies a drawing thread task and MapContext's layers, * that must be canceled or can continue with the process.

* * @see #cancelDrawing() */ private CancelDraw canceldraw; //private boolean isCancelled = true; /** *

Fires an action events after a specified delay.

* *

MapControl will use the timer to update its visible graphical information during * a drawing process, or allowing to cancel that process.

* *

This is very useful to pretend faster interactivity to user when MapControl has * lots of layers, and / or layers with heavy graphical elements, that need a long time to finish * drawing all its data.

*/ private Timer timer; /** *

Reference to the {@link ViewPort ViewPort} of the {@link MapContext MapContext} of this component.

* *

The view port once is created an instance of MapControl, * is obtained from the EPSG:23030 projection, that's the default projection for this component.

* *

After, the view port will change adapting itself according the current projection and the extent.

* * @see #getViewPort() * * @see ViewPort */ protected ViewPort vp; //private Drawer drawer; /** *

Manager of all MapControl painting requests.

*/ private Drawer2 drawer2; // private boolean firstDraw = true; /** *

Listener of all kind of mouse events produced in this component.

* *

Delegates each mouse event to the current map tool.

* * @see #addMapTool(String, Behavior) * @see #addMapTool(String, Behavior[]) * @see #getMapTool(String) * @see #getMapToolsKeySet() * @see #getNamesMapTools() * @see #setTool(String) */ protected MapToolListener mapToolListener = new MapToolListener(); /** *

Listener of all events produced in a this component's MapContext * object during an atomic period of time.

*/ private MapContextListener mapContextListener = new MapContextListener(); /** *

Group of ExceptionListener that, in whatever moment could be notified a Throwable Java error or exception.

* * @see #addExceptionListener(ExceptionListener) * @see #removeExceptionListener(ExceptionListener) */ private ExceptionHandlingSupport exceptionHandlingSupport = new ExceptionHandlingSupport(); /** *

Name of the previous tool used.

*/ protected String prevTool; /** *

Tool that will be used combined with the current tool of this MapControl.

*/ private Behavior combinedTool = null; /** * We need this to avoid not wanted refresh. REMEMBER TO SET TO TRUE!! */ // private boolean paintEnabled = false; /** *

Creates a new MapControl instance with the following characteristics: *

*

*/ public MapControl() { this.setName("MapControl"); setDoubleBuffered(false); setOpaque(true); status = DESACTUALIZADO; //Clase usada para cancelar el dibujado canceldraw = new CancelDraw(); //Modelo de datos y ventana del mismo // TODO: Cuando creamos un mapControl, deberíamos asignar // la projección por defecto con la que vayamos a trabajar. // 23030 es el código EPSG del UTM30 elipsoide ED50 vp = new ViewPort(CRSFactory.getCRS("EPSG:23030")); setMapContext(new MapContext(vp)); //eventos this.addComponentListener(this); this.addMouseListener(mapToolListener); this.addMouseMotionListener(mapToolListener); this.addMouseWheelListener(mapToolListener); this.drawer2 = new Drawer2(); //Timer para mostrar el redibujado mientras se dibuja timer = new Timer(1000/drawFrameRate, new ActionListener() { public void actionPerformed(ActionEvent e) { if (drawAnimationEnabled) { MapControl.this.repaint(); } } }); } /** *

Sets a MapContext to this component.

* *

The MapContext has the model, and most of the view, * and control logic of the layers of this component, including a {@link ViewPort ViewPort} to adapt the * information to the projection, and to display it in the available area.

* *

If model hadn't a ViewPort, assigns the current one to it, otherwise, use its ViewPort.

* *

After assigning the MapContext and ViewPort, sets the same {@link MapContextListener MapContextListener} * that was using, and changes the status to OUTDATED.

* * @param model this component's MapContext, that includes the ViewPort. * * @see MapContext * * @see #getMapContext() */ public void setMapContext(MapContext model) { if (mapContext != null) { mapContext.removeAtomicEventListener(mapContextListener); } mapContext = model; if (mapContext.getViewPort() == null) { mapContext.setViewPort(vp); } else { vp = mapContext.getViewPort(); // vp.setImageSize(new Dimension(getWidth(), getHeight())); //System.err.println("Viewport en setMapContext:" + vp); } mapContext.addAtomicEventListener(mapContextListener); status = DESACTUALIZADO; } /** *

Gets this component's {@link MapContext MapContext} projection.

* * @return this component's {@link MapContext MapContext} projection * * @see MapContext#getProjection() * @see MapControl#setProjection(IProjection) */ public IProjection getProjection() { return getMapContext().getProjection(); } /** *

Sets the projection to this component's {@link MapContext MapContext}.

* * @param proj the kind of projection to this component's {@link MapContext MapContext} * * @see MapContext#setProjection(IProjection) * @see MapControl#getProjection() */ public void setProjection(IProjection proj) { getMapContext().setProjection(proj); } /** *

Gets this component's MapContext, with the model, and most of the view, * and control logic of the layers of this component, including a {@link ViewPort ViewPort} to adapt the * information to the projection, and display it in the available area.

* * @return this component's MapContext, that includes the ViewPort used to project the * graphical information, and display it in the available area * * @see MapContext * * @see MapControl#setMapContext(MapContext) */ public MapContext getMapContext() { return mapContext; } /** *

Registers a new behavior to this component.

* *

According the nature of the {@link Behavior Behavior}, different events will be generated. Those * events can be caught by a particular {@link ToolListener ToolListener}, allowing user to interact with this * MapControl object as a tool.

* * @param name name to identify the behavior to add * @param tool the behavior to add * * @see #addMapTool(String, Behavior[]) * @see #getNamesMapTools() * @see #getMapToolsKeySet() * @see #hasTool(String) */ public void addMapTool(String name, Behavior tool) { namesMapTools.put(name, tool); tool.setMapControl(this); } /** *

Registers a new behavior to this component as a {@link CompoundBehavior CompoundBehavior} made up of tools.

* *

According the nature of the behaviors registered, different events will be generated. Those * events can be caught by a particular {@link ToolListener ToolListener}, allowing user to interact with this * MapControl object as a tool.

* * @param name name to identify the compound behavior to add * @param tools the compound behavior to add * * @see #addMapTool(String, Behavior) * @see #getNamesMapTools() * @see #getMapToolsKeySet() * @see #hasTool(String) */ public void addMapTool(String name, Behavior[] tools){ CompoundBehavior tool = new CompoundBehavior(tools); addMapTool(name, tool); } /** *

Gets the Behavior registered in this component, identified * by name.

* * @param name name of a registered behavior * * @return tool the registered behavior in this component as name, or null if * no one has that identifier * * @see #addMapTool(String, Behavior) * @see #addMapTool(String, Behavior[]) * @see #hasTool(String) */ public Behavior getMapTool(String name) { return (Behavior)namesMapTools.get(name); } /** *

Returns a set view of the keys that identified the tools * registered.

* * @return a set view of the keys that identified the tools registered * * @see HashMap#keySet() * * @see #getNamesMapTools() * @see #addMapTool(String, Behavior) * @see #addMapTool(String, Behavior[]) */ public Set getMapToolsKeySet() { return namesMapTools.keySet(); } /** *

Returns true if this component contains a tool identified by toolName.

* * @param toolName identifier of the tool * * @return true if this component contains a tool identified by toolName; otherwise false * * @see #addMapTool(String, Behavior) * @see #addMapTool(String, Behavior[]) */ public boolean hasTool(String toolName) { return namesMapTools.containsKey(toolName); } /** *

Sets as current active Behavior associated to this component, that one which * is registered and identified by toolName.

* *

Changing the current active behavior for this MapControl, implies also updating the * previous behavior tool, and the current cursor.

* * @param toolName name of a registered behavior * * @see #getCurrentMapTool() * @see #getCurrentTool() */ public void setTool(String toolName) { prevTool=getCurrentTool(); Behavior mapTool = (Behavior) namesMapTools.get(toolName); currentMapTool = mapTool; currentTool = toolName; if (combinedTool != null) { if (mapTool instanceof CompoundBehavior) { ((CompoundBehavior)mapTool).addMapBehavior(combinedTool, true); } else { currentMapTool = new CompoundBehavior(new Behavior[] {currentMapTool}); ((CompoundBehavior)currentMapTool).addMapBehavior(combinedTool, true); } } this.setCursor(mapTool.getCursor()); } /** *

Gets as current active Behavior associated to this component, that one which * is registered and identified by toolName.

* *

Changing the current active behavior for this MapControl, implies also updating the * previous behavior tool, and the current cursor.

* * @param toolName name of a registered behavior * * @see #getCurrentTool() * @see #setTool(String) */ public Behavior getCurrentMapTool(){ return currentMapTool; } /** *

Returns the name of the current selected tool on this MapControl

* * @return the name of the current's behavior tool associated to this component * * @see #getCurrentMapTool() * @see #setTool(String) */ public String getCurrentTool() { return currentTool; } /** *

Determines that current drawing process of MapControl's MapContext's data must be canceled.

* *

It has no effects if now isn't drawing that graphical information.

* *

At last resort, the particular implementation of each layer in this MapControl's MapContrext * will be that one which will draw the graphical information, and, if supports, which could cancel its drawing subprocess.

*/ public void cancelDrawing() { /* if (drawer != null) { if (!drawer.isAlive()) { return; } } */ canceldraw.setCanceled(true); /* while (!isCancelled) { if (!drawer.isAlive()) { // Si hemos llegado aquí con un thread vivo, seguramente // no estamos actualizados. break; } } canceldraw.setCancel(false); isCancelled = false; drawerAlive = false; */ } /** *

Creates a {@link BufferedImage BufferedImage} image if there was no buffered image, or if * its viewport's image height or width is different from this component's size. Once has created * a double-buffer, fills it with the vieport's background color, or with white if it had no background color.

* *

If no double-buffered existed, creates a {@link BufferedImage BufferedImage} with the size of this component, * and as an image with 8-bit RGBA color components packed into integer pixels. That image has a DirectColorModel with alpha. * The color data in that image is considered not to be premultiplied with alpha.

* *

Once has created and filled the new inner MapControl's double-buffer, changes the status to * OUTDATED.

* * @return true if has created and filled a new double-buffer for this MapControl instance; otherwise false */ private boolean adaptToImageSize() { if ((image == null) || (vp.getImageWidth() != this.getWidth()) || (vp.getImageHeight() != this.getHeight())) { image = new BufferedImage(this.getWidth(), this.getHeight(), BufferedImage.TYPE_INT_ARGB); // ESTILO MAC // image = GraphicsEnvironment.getLocalGraphicsEnvironment() // .getDefaultScreenDevice().getDefaultConfiguration() // .createCompatibleImage(this.getWidth(), this.getHeight()); vp.setImageSize(new Dimension(getWidth(), getHeight())); getMapContext().getViewPort().refreshExtent(); Graphics gTemp = image.createGraphics(); Color theBackColor = vp.getBackColor(); if (theBackColor == null) gTemp.setColor(Color.WHITE); else gTemp.setColor(theBackColor); gTemp.fillRect(0,0,getWidth(), getHeight()); gTemp.dispose(); status = DESACTUALIZADO; // g.drawImage(image,0,0,null); return true; } return false; } /** *

Paints the graphical information of this component using a double buffer.

* *

If the double buffer wasn't created, creates a new one.

* *

Paints the component according the following algorithm: *
*   If status is UPDATED:
*     If there is no double buffer:
*       If there is a behavior for managing the MapControl instance, delegates * the drawing process to that behavior, calling: behavior_instance.paintComponent(g)   .
*       Else, repaints the current graphical information quickly calling: g.drawImage(image,0,0,null)   .
*   Else, (status is OUTDATED, or ONLY_GRAPHICS): executes a quickly repaint of the previous information calling g.drawImage(image,0,0,null), and creates * a painting request to delegate the heavy drawing process to the {@link Drawer2 Drawer2}'s worker thread, according the SingleWorketThread pattern, starting a timer to update * (invoking repaint() that comprises invoke this method) the view every delay of 360 ms. during the the process drawing.

* * @see javax.swing.JComponent#paintComponent(java.awt.Graphics) * @see Drawer2 */ protected void paintComponent(Graphics g) { adaptToImageSize(); /* if (status == FAST_PAINT) { System.out.println("FAST_PAINT"); g.drawImage(image,0,0,null); status = ACTUALIZADO; return; } */ // System.out.println("PINTANDO MAPCONTROL" + this); if (status == ACTUALIZADO) { // LWS logger.debug("Dibujando la imagen obtenida"); /* * Si hay un behaviour y la imagen es distinta de null se delega el dibujado * en dicho behaviour */ if (image != null) { if (currentMapTool != null) currentMapTool.paintComponent(g); else g.drawImage(image,0,0,null); // System.out.println("Pinto ACTUALIZADO"); } } else if ((status == DESACTUALIZADO) || (status == ONLY_GRAPHICS)) { // LWS System.out.println("DESACTUALIZADO: Obteniendo la imagen de la cartografía"); /* if (isOpaque()) { if (image==null) { g.setColor(vp.getBackColor()); g.fillRect(0,0,getWidth(), getHeight()); } // else g.drawImage(image,0,0,null); } */ // cancelDrawing(); //Se crea la imagen con el color de fonde deseado /* if (image == null) { image = new BufferedImage(this.getWidth(), this.getHeight(), BufferedImage.TYPE_INT_ARGB); vp.setImageSize(new Dimension(getWidth(), getHeight())); Graphics gTemp = image.createGraphics(); Color theBackColor = vp.getBackColor(); if (theBackColor == null) gTemp.setColor(Color.WHITE); else gTemp.setColor(theBackColor); gTemp.fillRect(0,0,getWidth(), getHeight()); gTemp.dispose(); // g.drawImage(image,0,0,null); System.out.println("Imagen con null en DESACTUALIZADO. Width = " + this.getWidth()); } */ // else // { // if (image != null) // { g.drawImage(image,0,0,null); drawer2.put(new PaintingRequest()); timer.start(); /* } else return; */ // } /* if (drawerAlive == false) { drawer = new Drawer(image, canceldraw); drawer.start(); //Se lanza el tread de dibujado } */ // status = ACTUALIZADO; } } /** *

Gets the {@link BufferedImage BufferedImage} used to accelerate the draw of new ''frames'' with changes, * or new graphical items in this component.

* * @return double buffered image used by this component to accelerate the draw of its graphical information, or * null if isn't already created * * @see BufferedImage */ public BufferedImage getImage() { return image; } /** *

Forces repaint all visible graphical information in this component.

* *

If doClear == true, before repainting, clears the background color, with the * inner viewport's background color.

* * @param doClear true if needs clearing the background color before drawing the map * * @see #cancelDrawing() * @see FLayers#setDirty(boolean) */ public void drawMap(boolean doClear) { cancelDrawing(); //System.out.println("drawMap con doClear=" + doClear); status = DESACTUALIZADO; // getMapContext().getLayers().setDirty(true); if (doClear) { // image = null; // Se usa para el PAN if (image != null) { Graphics2D g = image.createGraphics(); Color theBackColor = vp.getBackColor(); if (theBackColor == null) g.setColor(Color.WHITE); else g.setColor(theBackColor); g.fillRect(0, 0, vp.getImageWidth(), vp.getImageHeight()); g.dispose(); } } repaint(); } /** *

Cancels any current drawing process, changing the status to OUTDATED, and forcing * repaint only the layers dirty.

* * @see #cancelDrawing() */ public void rePaintDirtyLayers() { cancelDrawing(); status = DESACTUALIZADO; repaint(); } /** *

Cancels any current drawing process, changing the status to ONLY_GRAPHICS, and forcing * repaint only the graphical layer of the MapContext.

*/ public void drawGraphics() { status = ONLY_GRAPHICS; repaint(); } /** * @see java.awt.event.ComponentListener#componentHidden(java.awt.event.ComponentEvent) */ public void componentHidden(ComponentEvent e) { } /** * @see java.awt.event.ComponentListener#componentMoved(java.awt.event.ComponentEvent) */ public void componentMoved(ComponentEvent e) { } /** * @see java.awt.event.ComponentListener#componentResized(java.awt.event.ComponentEvent) */ public void componentResized(ComponentEvent e) { /* image = new BufferedImage(this.getWidth(), this.getHeight(), BufferedImage.TYPE_INT_ARGB); Graphics gTemp = image.createGraphics(); gTemp.setColor(vp.getBackColor()); gTemp.fillRect(0,0,getWidth(), getHeight()); System.out.println("MapControl resized"); // image = null; vp.setImageSize(new Dimension(getWidth(), getHeight())); getMapContext().getViewPort().setScale(); */ // drawMap(true); } /** * @see java.awt.event.ComponentListener#componentShown(java.awt.event.ComponentEvent) */ public void componentShown(ComponentEvent e) { } /** * @see ExceptionHandlingSupport#addExceptionListener(ExceptionListener) */ public void addExceptionListener(ExceptionListener o) { exceptionHandlingSupport.addExceptionListener(o); } /** * @see ExceptionHandlingSupport#removeExceptionListener(ExceptionListener) */ public boolean removeExceptionListener(ExceptionListener o) { return exceptionHandlingSupport.removeExceptionListener(o); } /** * @see ExceptionHandlingSupport#throwException(Throwable) */ protected void throwException(Throwable t) { exceptionHandlingSupport.throwException(t); } /** *

Represents each MapControl's data painting request.

* *

The request will be attended by a Drawer2, which will hold it since the Drawer2's worker * takes it, or arrives a new painting request, which will replace it.

*/ private class PaintingRequest { /** *

Creates a new PaintingRequest

instance.

*/ public PaintingRequest() { } /** *

MapControl paint process:

* *

*

*

* * @see #cancelDrawing() * @see MapContext#draw(BufferedImage, Graphics2D, Cancellable, double) * @see MapContext#drawGraphics(BufferedImage, Graphics2D, Cancellable, double) * * @see ViewPort */ public void paint() { try { canceldraw.setCanceled(false); /* if (image == null) { image = new BufferedImage(vp.getImageWidth(), vp.getImageHeight(), BufferedImage.TYPE_INT_ARGB); Graphics gTemp = image.createGraphics(); Color theBackColor = vp.getBackColor(); if (theBackColor == null) gTemp.setColor(Color.WHITE); else gTemp.setColor(theBackColor); gTemp.fillRect(0,0,getWidth(), getHeight()); gTemp.dispose(); // g.drawImage(image,0,0,null); System.out.println("Imagen con null en DESACTUALIZADO. Width = " + this.getWidth()); } */ Graphics2D g = image.createGraphics(); ViewPort viewPort = mapContext.getViewPort(); if (status == DESACTUALIZADO) { Graphics2D gTemp = image.createGraphics(); Color theBackColor = viewPort.getBackColor(); if (theBackColor == null) gTemp.setColor(Color.WHITE); else gTemp.setColor(theBackColor); gTemp.fillRect(0, 0, viewPort.getImageWidth(), viewPort.getImageHeight()); // ESTILO MAC // BufferedImage imgMac = new BufferedImage(vp.getImageWidth(), vp.getImageHeight(), // BufferedImage.TYPE_INT_ARGB); // // mapContext.draw(imgMac, g, canceldraw, mapContext.getScaleView()); // g.drawImage(imgMac, 0, 0, null); // FIN ESTILO MAC // SIN MAC: mapContext.draw(image, g, canceldraw, mapContext.getScaleView()); if (!canceldraw.isCanceled()){ status=ACTUALIZADO; }else{ status=DESACTUALIZADO; // getMapContext().getLayers().setDirty(true); } } else if (status == ONLY_GRAPHICS) { status = ACTUALIZADO; mapContext.drawGraphics(image, g, canceldraw,mapContext.getScaleView()); } // status = FAST_PAINT; // drawerAlive = false; timer.stop(); repaint(); } catch (Throwable e) { timer.stop(); // isCancelled = true; e.printStackTrace(); throwException(e); } finally { } } } /** *

An instance of Drawer2 could manage all MapControl painting requests.

* *

Based on the WorkerThread software pattern, creates a worker thread that will attend sequentially * the current waiting painting request, after finishing the previous (that could be by a cancel action).

* *

All new {@link PaintingRequest PaintingRequest} generated will be stored as waiting requests since the worker * attends it.

* *

If a worker finished and there was no painting request, the worker would be set to wait until any * painting request would be put.

* * @author fjp */ public class Drawer2 { // Una mini cola de 2. No acumulamos peticiones de dibujado // dibujamos solo lo último que nos han pedido. /** *

Painting request that's been attended by the Drawer2's worker.

* * @see #put(com.iver.cit.gvsig.fmap.MapControl.PaintingRequest) * @see #take() */ private PaintingRequest paintingRequest; /** *

Painting request waiting to be attended by the Drawer2's worker.

* * @see #put(com.iver.cit.gvsig.fmap.MapControl.PaintingRequest) * @see #take() */ private PaintingRequest waitingRequest; /** *

Determines that the Drawer2's worker is busy attending a painting request.

* * @see #put(com.iver.cit.gvsig.fmap.MapControl.PaintingRequest) * @see #take() */ private boolean waiting; /** *

Notifies the Drawer2's worker to finish or continue with its process.

* * @see #setShutdown(boolean) */ private boolean shutdown; /** *

Sets this Drawer2's worker to finish or continue with its process.

* * @param isShutdown a boolean value */ public void setShutdown(boolean isShutdown) { shutdown = isShutdown; } /** *

Creates a new drawer for managing all data painting requests in MapControl.

* *

Includes the following steps: *

*

*/ public Drawer2() { paintingRequest = null; waitingRequest = null; waiting = false; shutdown = false; new Thread(new Worker()).start(); } /** *

Sets a PaintingRequest to be attended by the worker thread of this object. If * this one was waiting, wakes up.

* *

All waiting threads will be notified synchronized.

* * @param newPaintRequest * * @see #take() */ public void put(PaintingRequest newPaintRequest) { waitingRequest = newPaintRequest; if (waiting) { synchronized (this) { notifyAll(); } } } /** *

Used by this object's worker, returns the current waiting drawing request, causing current thread * to wait until another thread invokes {@link #put(com.iver.cit.gvsig.fmap.MapControl.PaintingRequest) #put(com.iver.cit.gvsig.fmap.MapControl.PaintingRequest)}, * if there was no waiting request.

* *

All threads will access synchronized to the waiting request.

* * @return PaintingRequest that was waiting to be attended * * @see #put(com.iver.cit.gvsig.fmap.MapControl.PaintingRequest) */ public PaintingRequest take() { if (waitingRequest == null) { synchronized (this) { waiting = true; try { wait(); } catch (InterruptedException ie) { waiting = false; } } } paintingRequest = waitingRequest; waitingRequest = null; return paintingRequest; } /** *

Thread for attending painting requests.

* *

If there was no double buffer, sets the status to OUTDATED and finishes, otherwise * takes the painting request (it's probably that would wait some time), cancel the previous drawing * process, and starts processing the request.

* * @see Thread */ private class Worker implements Runnable { /* * (non-Javadoc) * @see java.lang.Runnable#run() */ public void run() { while (!shutdown) { PaintingRequest p = take(); //System.out.println("Pintando"); if (image != null){ cancelDrawing(); p.paint(); } else{ status = DESACTUALIZADO; } } } } } /** *

Drawer is implemented for drawing the layers of a MapControl's MapContext instance * as a thread of execution.

* *

Draws MapControl according its status: *