/[schmitzm]/trunk/src/skrueger/geotools/XMapPane.java
ViewVC logotype

Diff of /trunk/src/skrueger/geotools/XMapPane.java

Parent Directory Parent Directory | Revision Log Revision Log | View Patch Patch

branches/1.0-gt2-2.6/src/gtmig/org/geotools/swing/XMapPane.java revision 516 by alfonx, Wed Nov 11 21:17:33 2009 UTC branches/1.0-gt2-2.6/src/skrueger/geotools/XMapPane.java revision 536 by alfonx, Fri Nov 20 15:38:34 2009 UTC
# Line 1  Line 1 
1  /*  package skrueger.geotools;
  *    GeoTools - OpenSource mapping toolkit  
  *    http://geotools.org  
  *    (C) 2002-2006, GeoTools Project Managment Committee (PMC)  
  *  
  *    This library is free software; you can redistribute it and/or  
  *    modify it under the terms of the GNU Lesser General Public  
  *    License as published by the Free Software Foundation;  
  *    version 2.1 of the License.  
  *  
  *    This library 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  
  *    Lesser General Public License for more details.  
  */  
 package gtmig.org.geotools.swing;  
2    
 /**  
  * This class is 50% copied from GeoTools 2.6.x JMapPane. GeoTools is LGPL, SCHMITZM also.<br/>  
  * In addition to  
  */  
   
 import java.awt.AlphaComposite;  
3  import java.awt.Color;  import java.awt.Color;
4  import java.awt.Cursor;  import java.awt.Cursor;
5  import java.awt.Font;  import java.awt.Font;
# Line 41  import java.awt.geom.AffineTransform; Line 20  import java.awt.geom.AffineTransform;
20  import java.awt.geom.NoninvertibleTransformException;  import java.awt.geom.NoninvertibleTransformException;
21  import java.awt.geom.Point2D;  import java.awt.geom.Point2D;
22  import java.awt.image.BufferedImage;  import java.awt.image.BufferedImage;
 import java.beans.PropertyChangeEvent;  
 import java.beans.PropertyChangeListener;  
23  import java.io.IOException;  import java.io.IOException;
24    import java.util.ArrayList;
25  import java.util.HashMap;  import java.util.HashMap;
26  import java.util.Map;  import java.util.Map;
27  import java.util.Vector;  import java.util.Vector;
28    
 import javax.swing.JFrame;  
 import javax.swing.JPanel;  
29  import javax.swing.Timer;  import javax.swing.Timer;
30    
31  import org.apache.log4j.Logger;  import org.apache.log4j.Logger;
32  import org.geotools.feature.FeatureCollection;  import org.geotools.feature.FeatureCollection;
33    import org.geotools.geometry.Envelope2D;
34  import org.geotools.geometry.jts.JTS;  import org.geotools.geometry.jts.JTS;
35  import org.geotools.geometry.jts.ReferencedEnvelope;  import org.geotools.geometry.jts.ReferencedEnvelope;
36  import org.geotools.map.DefaultMapContext;  import org.geotools.map.DefaultMapContext;
# Line 67  import org.geotools.referencing.CRS; Line 44  import org.geotools.referencing.CRS;
44  import org.geotools.renderer.GTRenderer;  import org.geotools.renderer.GTRenderer;
45  import org.geotools.renderer.label.LabelCacheImpl;  import org.geotools.renderer.label.LabelCacheImpl;
46  import org.geotools.renderer.lite.LabelCache;  import org.geotools.renderer.lite.LabelCache;
47    import org.geotools.renderer.lite.StreamingRenderer;
48  import org.geotools.swing.JMapPane;  import org.geotools.swing.JMapPane;
49  import org.geotools.swing.event.MapMouseEvent;  import org.geotools.swing.event.MapMouseEvent;
50  import org.geotools.swing.event.MapPaneEvent;  import org.geotools.swing.event.MapPaneEvent;
# Line 81  import org.opengis.referencing.operation Line 59  import org.opengis.referencing.operation
59  import schmitzm.geotools.GTUtil;  import schmitzm.geotools.GTUtil;
60  import schmitzm.geotools.JTSUtil;  import schmitzm.geotools.JTSUtil;
61  import schmitzm.geotools.gui.SelectableXMapPane;  import schmitzm.geotools.gui.SelectableXMapPane;
62    import schmitzm.geotools.io.GeoImportUtil;
63  import schmitzm.geotools.map.event.JMapPaneListener;  import schmitzm.geotools.map.event.JMapPaneListener;
64  import schmitzm.geotools.map.event.MapLayerAdapter;  import schmitzm.geotools.map.event.MapLayerAdapter;
65    import schmitzm.lang.LangUtil;
66    import schmitzm.swing.JPanel;
67  import schmitzm.swing.SwingUtil;  import schmitzm.swing.SwingUtil;
 import skrueger.geotools.RenderingExecutor;  
68    
69  import com.vividsolutions.jts.geom.Coordinate;  import com.vividsolutions.jts.geom.Coordinate;
70  import com.vividsolutions.jts.geom.Envelope;  import com.vividsolutions.jts.geom.Envelope;
71  import com.vividsolutions.jts.geom.Geometry;  import com.vividsolutions.jts.geom.Geometry;
72    
73  public class XMapPane extends JPanel implements PropertyChangeListener {  /**
74     * The {@link XMapPane} class uses a Geotools {@link GTRenderer} to paint up to
75     * two {@link MapContext}s: a "local" {@link MapContext} and a "background"
76     * {@link MapContext}. The idea is, that rendering a background layer made up of
77     * e.g. OSM data, may take much longer than rendering local data.<br>
78     * Every {@link MapContext} is rendered on a {@link Thread} of it's own.
79     * Starting/ cancelling these threads is done by the {@link RenderingExecutor}.<br>
80     * <br>
81     * While the renderers are rending the map, a <br>
82     * The {@link XMapPane} is based on schmitzm {@link JPanel}, so
83     * {@link #print(Graphics)} will automatically set the background of components
84     * to pure white.
85     *
86     * The XMapPane has a {@link MouseListener} that manages zooming.<br>
87     * A logo/icon to float in the lower left corner may be set with
88     * {@link #setMapImage(BufferedImage)}<br>
89     *
90     * @see SelectableXMapPane - an extension of {@link XMapPane} that supports
91     *      selecting features.
92     *
93     * @author stefan
94     *
95     */
96    public class XMapPane extends JPanel {
97    
98            private static final int IMAGETYPE = BufferedImage.TYPE_INT_RGB;
99            private static final int IMAGETYPE_withAlpha = BufferedImage.TYPE_INT_ARGB;
100    
101          private static Logger LOGGER = Logger.getLogger(XMapPane.class);          private static Logger LOGGER = Logger.getLogger(XMapPane.class);
102    
103            private boolean acceptsRepaintCalls = true;
104    
105          /**          /**
106           * Sets whether a layer is regarded or ignored on {@link #SELECT_TOP},           * Main {@link MapContext} that holds all layers that are rendered into the
107           * {@link #SELECT_ALL} and {@link #SELECT_ONE_FROM_TOP} actions.           * {@link #localImage} by the {@link #localRenderer}
          *  
          * @param layer  
          *            a layer  
          * @param selectable  
          *            if {@code false} the layer is ignored during the upper  
          *            mentioned actions. If <code>null</code>, the default (true)  
          *            will be used.  
108           */           */
109          public void setMapLayerSelectable(MapLayer layer, Boolean selectable) {          MapContext localContext;
                 if (selectable == null)  
                         mapLayerSelectable.remove(layer);  
                 else  
                         mapLayerSelectable.put(layer, selectable);  
         }  
110    
111          /**          /**
112           * Holds a flag for each layer, whether it is regarded or ignored on           * {@link MapContext} holding the background layers. Use it for layers that
113           * {@link #SELECT_TOP}, {@link #SELECT_ALL} and {@link #SELECT_ONE_FROM_TOP}           * CAN take very long for rendering, like layer from the Internet: WMS, WFS,
114           * actions.           * OSM...<br>
115             * <code>null</code> by default.
116             *
117             * @see #setBgContext(MapContext)
118             * @see #getBgContext()
119           */           */
120          final protected HashMap<MapLayer, Boolean> mapLayerSelectable = new HashMap<MapLayer, Boolean>();          MapContext bgContext;
121    
122          /**          /**
123           * Returns whether a layer is regarded or ignored on {@link #SELECT_TOP},           * While threads are working, calls {@link XMapPane#updateFinalImage()}
124           * {@link #SELECT_ALL} and {@link #SELECT_ONE_FROM_TOP} actions. Returns           * regularly and {@link #repaint()}. This {@link Timer} is stopped when all
125           * <code>true</code> if the selectability has not been defined.           * renderers have finished.
126           *           *
127           * @param layer           * @see #INITIAL_REPAINT_DELAYAL
128           *            a layer           * @see #REPEATING_REPAINT_DELAY
129           */           */
130          public boolean isMapLayerSelectable(MapLayer layer) {          final private Timer repaintTimer;
                 Boolean selectable = mapLayerSelectable.get(layer);  
                 return selectable == null ? true : selectable;  
         }  
131    
132          /**          /**
133           * Flag fuer Modus "Kartenausschnitt bewegen". Nicht fuer Window-Auswahl           * The initial delay in milliseconds until the {@link #finalImage} is
134           * moeglich!           * updated the first time.
          *  
          * @see #setState(int)  
135           */           */
136          public static final int PAN = 1;          public static final int INITIAL_REPAINT_DELAY = 1000;
137    
138          /**          /**
139           * Flag fuer Modus "Heran zoomen".           * While the {@link #bgExecuter} and {@link #localExecuter} are rendering,
140           *           * the {@link #repaintTimer} is regularly updating the {@link #finalImage}
141           * @see #setState(int)           * with previews.
          * @see #setState(int)  
142           */           */
143          public static final int ZOOM_IN = 2;          public static final long REPEATING_REPAINT_DELAY = 500;
144    
145          /**          /**
146           * Flag fuer Modus "Heraus zoomen". Nicht fuer Window-Auswahl moeglich!           * Default delay (milliseconds) before the map will be redrawn when resizing
147           *           * the pane. This is to avoid flickering while drag-resizing.
          * @see #setState(int)  
148           */           */
149          public static final int ZOOM_OUT = 3;          public static final int DEFAULT_RESIZING_PAINT_DELAY = 500;
150    
151            public static final int NONE = -123;
152    
153          /**          /**
154           * Flag fuer Modus           * Flag fuer Modus "Kartenausschnitt bewegen". Nicht fuer Window-Auswahl
155           * "SimpleFeature-Auswahl auf dem obersten (sichtbaren) Layer".           * moeglich!
156           *           *
157           * @see #setState(int)           * @see #setState(int)
          * @see #setState(int)  
158           */           */
159          public static final int SELECT_TOP = 4;          public static final int PAN = 1;
160    
161          /**          /**
162           * Flag fuer Modus "SimpleFeature-Auswahl auf allen (sichtbaren) Layern".           * Flag fuer Modus "SimpleFeature-Auswahl auf allen (sichtbaren) Layern".
163           *           *
# Line 174  public class XMapPane extends JPanel imp Line 173  public class XMapPane extends JPanel imp
173           * @see #setState(int)           * @see #setState(int)
174           */           */
175          public static final int SELECT_ONE_FROM_TOP = 104;          public static final int SELECT_ONE_FROM_TOP = 104;
 //  
 //      /**  
 //       * While threads are working, we call {@link XMapPane#updateFinalImage()}  
 //       * regularly and repaint(). This {@link Timer} is stopped when all renderers  
 //       * have finished.  
 //       */  
 //      final private Timer repainterTimer;  
 //  
 //      /**  
 //       * While the {@link #bgExecuter} and {@link #localExecuter} are rendering,  
 //       * the {@link #repainterTimer} is regularly updating the {@link #finalImage}  
 //       * with previews.  
 //       */  
 //      public static final long REPEATING_REPAINT_DELAY = 500;  
 //        
 //      /**  
 //       * The initial delay in milliseconds until the {@link #finalImage} is updated the first time.    
 //       */  
 //      public static final long INITIAL_REPAINT_DELAY = 333;  
   
         protected RenderingExecutor bgExecuter;  
   
         /**  
          * the map context to render  
          */  
         MapContext localContext;  
176          /**          /**
177           * the map context to render           * Flag fuer Modus
178           */           * "SimpleFeature-Auswahl auf dem obersten (sichtbaren) Layer".
179          MapContext bgContext;           *
180             * @see #setState(int)
181          /**           * @see #setState(int)
          * the area of the map to draw  
182           */           */
183          protected Envelope mapArea = null;          public static final int SELECT_TOP = 4;
         /**  
          * We store the old mapArea for a moment to use it for the  
          * "quick scaled preview" in case of ZoomOut  
          **/  
         protected Envelope oldMapArea = null;  
184    
185          /**          public static final Cursor WAIT_CURSOR = Cursor
186           * the size of the pane last time we drew                          .getPredefinedCursor(Cursor.WAIT_CURSOR);
          */  
         protected Rectangle oldRect = null;  
187    
188          /**          final static Font waitFont = new Font("Arial", Font.BOLD, 30);
189           * The Renderer for the Background uses this Image. When set to null, please          final String waitMsg = SwingUtil.R("WaitMess");
190           * dispose the {@link Graphics2D}          final static Font errorFont = new Font("Arial", Font.BOLD, 13);
          */  
         protected BufferedImage bgImage;  
191    
192          /**          /**
193           * The Renderer for the LocalLayers uses this Image. When set to null,           * Flag fuer Modus "Heran zoomen".
194           * please dispose this {@link Graphics2D}           *
195             * @see #setState(int)
196             * @see #setState(int)
197           */           */
198          volatile protected BufferedImage localImage;          public static final int ZOOM_IN = 2;
199    
200          /**          /**
201           * compass and icon are rendered into this image           * Flag fuer Modus "Heraus zoomen". Nicht fuer Window-Auswahl moeglich!
202             *
203             * @see #setState(int)
204           */           */
205          // protected BufferedImage gadgetsImage;          public static final int ZOOM_OUT = 3;
   
         /**  
          * The default state is ZOOM_IN, hence by default the  
          * {@link #zoomMapPaneMouseListener} is also enabled.  
          **/  
         private int state = ZOOM_IN;  
206    
207          /**          /**
208           * Konvertiert die Maus-Koordinaten (relativ zum <code>JMapPane</code>) in           * Konvertiert die Maus-Koordinaten (relativ zum <code>JMapPane</code>) in
# Line 250  public class XMapPane extends JPanel imp Line 211  public class XMapPane extends JPanel imp
211           * @param e           * @param e
212           *            Maus-Ereignis           *            Maus-Ereignis
213           */           */
214          public static Point2D getMapCoordinatesFromEvent(MouseEvent e) {          public static Point2D getMapCoordinatesFromEvent(final MouseEvent e) {
215                  // aktuelle Geo-Position aus GeoMouseEvent ermitteln                  // aktuelle Geo-Position aus GeoMouseEvent ermitteln
216                  if (e != null && e instanceof MapMouseEvent)                  if (e != null && e instanceof MapMouseEvent)
217                          try {                          try {
218                                  return ((MapMouseEvent) e).getMapPosition().toPoint2D();                                  return ((MapMouseEvent) e).getMapPosition().toPoint2D();
219                          } catch (Exception err) {                          } catch (final Exception err) {
220                                  LOGGER                                  LOGGER
221                                                  .error(                                                  .error(
222                                                                  "return ((GeoMouseEvent) e).getMapCoordinate(null).toPoint2D();",                                                                  "return ((GeoMouseEvent) e).getMapCoordinate(null).toPoint2D();",
# Line 270  public class XMapPane extends JPanel imp Line 231  public class XMapPane extends JPanel imp
231                          if (!xMapPane.isWellDefined())                          if (!xMapPane.isWellDefined())
232                                  return null;                                  return null;
233    
234                          AffineTransform at = xMapPane.getScreenToWorld();                          final AffineTransform at = xMapPane.getScreenToWorld();
235                          if (at != null)                          if (at != null)
236                                  return at.transform(e.getPoint(), null);                                  return at.transform(e.getPoint(), null);
237                          return null;                          return null;
# Line 280  public class XMapPane extends JPanel imp Line 241  public class XMapPane extends JPanel imp
241          }          }
242    
243          /**          /**
244           * A flag indicating that the shown image is invalid and needs to be           * Listens to changes of the "background" {@link MapContext} and triggers
245           * re-rendered.           * repaints where needed.
          */  
         protected boolean mapImageInvalid = true;  
   
         protected LabelCache labelCache = new LabelCacheImpl();  
   
         /**  
          * If not <code>null</code>, the {@link XMapPane} will not allow to zoom/pan  
          * out of that area  
          **/  
         private Envelope maxExtend = null;  
   
         private Double maxZoomScale = Double.MIN_VALUE;  
         private Double minZoomScale = Double.MAX_VALUE;  
   
         /**  
          * This color is used as the default background color when painting a map.  
          */  
         private Color mapBackgroundColor = Color.WHITE;  
   
         /**  
          * This {@link MouseListener} is managing all zoom related tasks  
          */  
         public final ZoomXMapPaneMouseListener zoomMapPaneMouseListener = new ZoomXMapPaneMouseListener(  
                         this);  
   
         /**  
          * A flag indicating, that the image size has changed and the buffered  
          * images are not big enough any more  
          **/  
         protected boolean paneResized = false;  
   
         /**  
          * The flag {@link #requestStartRendering} can be set to true by events.  
          * This {@link Timer} checks the flag regularly and starts one renderer  
          * thread.  
          */  
         final private Timer startRenderThreadsTimer;  
   
         private Map<Object, Object> rendererHints;  
   
         public Map<Object, Object> getRendererHints() {  
                 return rendererHints;  
         }  
   
         /**  
          * Nuetzlich wenn die Componente gedruckt (z.B. wenn ein Screenshot gemacht  
          * wird) wird. Dann werden wird der Hintergrund auf WEISS gesetzt.  
          *  
          * @author <a href="mailto:[email protected]">Stefan Alfons  
          *         Kr&uuml;ger</a>  
          */  
         @Override  
         public void print(Graphics g) {  
                 Color orig = getBackground();  
                 setBackground(Color.WHITE);  
   
                 // wrap in try/finally so that we always restore the state  
                 try {  
                         super.print(g);  
                 } finally {  
                         setBackground(orig);  
                 }  
         }  
   
         /**  
          * full constructor extending JPanel  
          *  
          * @param rendererHints  
          *  
          * @param layout  
          *            - layout (probably shouldn't be set)  
          * @param isDoubleBuffered  
          *            - a Swing thing I don't really understand  
          * @param render  
          *            - what to draw the map with  
          * @param localContext  
          *            - {@link MapContext} of layer to render.  
          */  
         public XMapPane(final MapContext localContext,  
                         Map<Object, Object> rendererHints) {  
                 super(true);  
   
                 setRendererHints(rendererHints);  
   
                 setOpaque(true);  
   
                 setLocalContext(localContext);  
   
                 /**  
                  * Adding the #zoomMapPaneMouseListener  
                  */  
                 this.addMouseListener(zoomMapPaneMouseListener);  
                 this.addMouseMotionListener(zoomMapPaneMouseListener);  
                 this.addMouseWheelListener(zoomMapPaneMouseListener);  
   
                 /*  
                  * We use a Timer object to avoid rendering delays and flickering when  
                  * the user is drag-resizing the parent container of this map pane.  
                  *  
                  * Using a ComponentListener doesn't work because, unlike a JFrame, the  
                  * pane receives a stream of events during drag-resizing.  
                  */  
                 resizingPaintDelay = DEFAULT_RESIZING_PAINT_DELAY;  
                 resizeTimer = new Timer(resizingPaintDelay, new ActionListener() {  
   
                         public void actionPerformed(ActionEvent e) {  
                                 paneResized = true;  
   
                                 if (!isWellDefined())  
                                         return;  
   
                                 Rectangle bounds = getVisibleRect();  
   
                                 Envelope geoMapArea = tranformWindowToGeo(bounds.x, bounds.y,  
                                                 bounds.x + bounds.width, bounds.y + bounds.height);  
   
                                 setMapArea(bestAllowedMapArea(geoMapArea));  
                         }  
                 });  
                 resizeTimer.setRepeats(false);  
                 this.addComponentListener(new ComponentAdapter() {  
   
                         @Override  
                         public void componentResized(ComponentEvent e) {  
                                 if (bgExecuter != null)  
                                         bgExecuter.cancelTask();  
                                 if (localExecuter != null)  
                                         localExecuter.cancelTask();  
                                 resizeTimer.restart();  
                         }  
   
                 });  
   
 //              repainterTimer = new Timer((int) REPEATING_REPAINT_DELAY,  
 //                              new ActionListener() {  
 //  
 //                                      @Override  
 //                                      public void actionPerformed(ActionEvent e) {  
 //                                              updateFinalImage();  
 //                                              XMapPane.this.repaint();  
 //                                      }  
 //                              });  
 //              repainterTimer.setInitialDelay(300);  
 //              repainterTimer.setRepeats(true);  
   
                 startRenderThreadsTimer = new Timer(200, new ActionListener() {  
   
                         @Override  
                         public void actionPerformed(ActionEvent e) {  
                                 synchronized (requestStartRendering) {  
                                         if (requestStartRendering && isValid())  
                                                 startRendering();  
                                         requestStartRendering = false;  
                                 }  
                         }  
                 });  
                 startRenderThreadsTimer.start();  
   
         }  
   
         // TODO doku  
         public XMapPane() {  
                 this(null, null);  
         }  
   
         /**  
          * Sets the mapArea to best possibly present the given features. If only one  
          * single point is given, the window is moved over the point.  
          *  
          * Note: The method does not call {@link #repaint()} on the  
          * {@link SelectableXMapPane} .  
          *  
          * @param features  
          *            if <code>null</code> or size==0, the function doesn nothing.  
246           */           */
247          public void zoomTo(          private final MapLayerListListener bgContextListener = new MapLayerListListener() {
                         FeatureCollection<SimpleFeatureType, SimpleFeature> features) {  
   
                 CoordinateReferenceSystem mapCRS = getContext()  
                                 .getCoordinateReferenceSystem();  
                 CoordinateReferenceSystem fCRS = features.getSchema()  
                                 .getGeometryDescriptor().getCoordinateReferenceSystem();  
   
                 double width = mapArea.getWidth();  
                 double height = mapArea.getHeight();  
                 double ratio = height / width;  
   
                 if (features == null || features.size() == 0) {  
                         // feature count == 0 Zoom to the full extend  
                         return;  
                 } else if (features.size() == 1) {  
   
                         // feature count == 1 Just move the window to the point and zoom 'a  
                         // bit'  
                         SimpleFeature singleFeature = (SimpleFeature) features.iterator()  
                                         .next();  
   
                         if (((Geometry) singleFeature.getDefaultGeometry())  
                                         .getCoordinates().length > 1) {  
                                 // System.out.println("Zoomed to only pne poylgon");  
                                 // Poly  
                                 // TODO max width vs. height  
                                 width = features.getBounds().getWidth() * 3;  
                                 height = ratio * width;  
                         } else {  
                                 // System.out.println("Zoomed in a bit becasue only one point");  
                                 // width *= .9;  
                                 // height *= .9;  
                         }  
248    
249                          Coordinate centre = features.getBounds().centre();                  @Override
250                          if (!mapCRS.equals(fCRS)) {                  public void layerAdded(final MapLayerListEvent event) {
                                 // only to calculations if the CRS differ  
                                 try {  
                                         MathTransform fToMap;  
                                         fToMap = CRS.findMathTransform(fCRS, mapCRS);  
                                         // centre is transformed to the mapCRS  
                                         centre = JTS.transform(centre, null, fToMap);  
                                 } catch (FactoryException e) {  
                                         LOGGER.error("Looking for a Math transform", e);  
                                 } catch (TransformException e) {  
                                         LOGGER.error("Looking for a Math transform", e);  
                                 }  
                         }  
   
                         Coordinate newLeftBottom = new Coordinate(centre.x - width / 2.,  
                                         centre.y - height / 2.);  
                         Coordinate newTopRight = new Coordinate(centre.x + width / 2.,  
                                         centre.y + height / 2.);  
   
                         Envelope newMapArea = new Envelope(newLeftBottom, newTopRight);  
251    
252                          setMapArea(newMapArea);                          MapLayer layer = event.getLayer();
253    
254                  } else {                          layer.addMapLayerListener(bgMapLayerListener);
                         ReferencedEnvelope fBounds = features.getBounds();  
255    
256                          Envelope bounds;                          if (localContext.getLayers().length == 0
257                          if (!mapCRS.equals(fCRS)) {                                          && bgContext.getLayers().length == 1) { // the first one and
258                                  bounds = JTSUtil.transformEnvelope(fBounds, fCRS, mapCRS);                                  // localContext is
259                          } else {                                  // empty
260                                  bounds = fBounds;                                  if (!setMapArea(localContext.getAreaOfInterest()))
261                                            requestStartRendering();
262                                    return;
263                          }                          }
                         // BB umrechnen von Layer-CRS in Map-CRS  
264    
265                          // Expand a bit                          // We need to redraw, even in case that the mapArea didn't change
266                          bounds.expandBy(bounds.getWidth() / 6., bounds.getHeight() / 6.);                          // mapImageInvalid = true;
267                            // repaint();
268                            requestStartRendering();
269    
                         setMapArea(bounds);  
270                  }                  }
         }  
271    
272          private void setRendererHints(Map<Object, Object> rendererHints) {                  @Override
273                  this.rendererHints = rendererHints;                  public void layerChanged(final MapLayerListEvent event) {
274          }                          // mapImageInvalid = true;
275                            // repaint();
276          /**                          requestStartRendering();
277           * Return <code>true</code> if a CRS and a {@link #mapArea} are set and the                  }
          * {@link XMapPane} is visible and has bounds set.  
          */  
         public boolean isWellDefined() {  
278    
279                  try {                  @Override
280                    public void layerMoved(final MapLayerListEvent event) {
281                            // mapImageInvalid = true;
282                            // repaint();
283                            requestStartRendering();
284                    }
285    
286                          if (getContext() == null)                  @Override
287                                  return false;                  public void layerRemoved(final MapLayerListEvent event) {
288                          if (getContext().getLayerCount() <= 0)                          if (event.getLayer() != null)
289                                  return false;                                  event.getLayer().removeMapLayerListener(bgMapLayerListener);
290                          if (getMapArea() == null)                          // mapImageInvalid = true;
291                                  return false;                          // repaint();
292                          if (getBounds().getWidth() == 0)                          requestStartRendering();
                                 return false;  
                         if (getBounds().getHeight() == 0)  
                                 return false;  
                 } catch (Exception e) {  
                         return false;  
293                  }                  }
294                  return true;          };
         }  
295    
296          /**          /**
297           * Default delay (milliseconds) before the map will be redrawn when resizing           * compass and icon are rendered into this image
          * the pane. This is to avoid flickering while drag-resizing.  
298           */           */
299          public static final int DEFAULT_RESIZING_PAINT_DELAY = 500; // delay in          // protected BufferedImage gadgetsImage;
         // milliseconds  
300    
301          private Timer resizeTimer;          protected RenderingExecutor bgExecuter;
         private int resizingPaintDelay;  
         /**  
          * We store the old transform for a moment to use it for the  
          * "quick scaled preview" in case of ZoomIn  
          **/  
         protected AffineTransform oldScreenToWorld = null;  
302    
303          /**          /**
304           * Manuell gesetzter statischer Cursor, unabhaengig von der aktuellen           * The Renderer for the LocalLayers uses this Image. When set to null,
305           * MapPane-Funktion           * please dispose this {@link Graphics2D}
306           */           */
307          protected Cursor staticCursor = null;          private BufferedImage localImage;
308    
309            private BufferedImage finalImage;
310          /**          /**
311           * Standardmaessig wird der Cursor automatisch je nach MapPane-Aktion (Zoom,           * If # {@link #bgExecuter} is using {@link #bgRenderer} for the Background
312           * Auswahl, ...) gesetzt. Mit dieser Methode kann ein statischer Cursor           * uses this Image. When set to null, please dispose the {@link Graphics2D}
          * gesetzt werden, der unabhaengig von der aktuellen MapPanes-Aktion  
          * beibehalten wird. Um diesen statischen Cursor wieder zu entfernen, kann  
          * {@code null} als Parameter uebergeben werden  
          *  
          * @param cursor  
          *            Cursor  
313           */           */
314          public void setStaticCursor(Cursor cursor) {          private BufferedImage bgImage;
                 this.staticCursor = cursor;  
                 if (cursor != null)  
                         super.setCursor(cursor);  
         }  
315    
316          /**          /**
317           * Liefert den statisch eingestellten Cursor, der unabhaengig von der           * Optionally a transparent image to paint over the map in the lower right
318           * eingestellten MapPane-Aktion (Zoom, Auswahl, ...) verwendet wird.           * corner.
319           *           *
320           * @return {@code null}, wenn kein statischer Cursor verwendet, sondern der           * @see #addGadgets(Graphics2D)
321           *         Cursor automatisch je nach MapPane-Aktion eingestellt wird.           * @see #setMapImage(BufferedImage)
322           */           **/
323          public Cursor getStaticCursor() {          private BufferedImage mapImage = null;
                 return this.staticCursor;  
         }  
324    
325          /**          /**
326           * Abhaengig von selState wird der Cursor gesetzt           * Listens to each layer in the local {@link MapContext} for changes and
327             * triggers repaints.
328           */           */
329          public void updateCursor() {          protected MapLayerListener bgMapLayerListener = new MapLayerAdapter() {
330    
331                  if (bgExecuter != null && bgExecuter.isRunning()                  @Override
332                                  || localExecuter != null && localExecuter.isRunning()) {                  public void layerChanged(final MapLayerEvent event) {
333                          setCursor(WAIT_CURSOR);                          // Change of SLD for example
334                          return;                          // mapImageInvalid = true;
335                  } else {                          // repaint();
336  //                      // Allow one last rendering                          requestStartRendering();
 //                      if (repainterTimer.isRunning()) {  
 //                              repainterTimer.stop();  
 //                              updateFinalImage();  
 //                              repaint();  
 //                      }  
337                  }                  }
338    
339                  // wenn manueller Cursor gesetzt ist, dann diesen verwenden (unabhaengig                  @Override
340                  // von der aktuellen Aktion                  public void layerHidden(final MapLayerEvent event) {
341                  if (this.staticCursor != null) {                          // mapImageInvalid = true;
342                          setCursor(staticCursor);                          // repaint();
343                          return;                          requestStartRendering();
                 }  
                 if (getCursor() == SwingUtil.PANNING_CURSOR) {  
                         // This cursor will reset itself  
                         return;  
344                  }                  }
345    
346                  // Je nach Aktion den Cursor umsetzen                  @Override
347                  switch (state) {                  public void layerShown(final MapLayerEvent event) {
348                  case SELECT_TOP:                          // mapImageInvalid = true;
349                  case SELECT_ONE_FROM_TOP:                          // repaint();
350                  case SELECT_ALL:                          requestStartRendering();
                         setCursor(SwingUtil.CROSSHAIR_CURSOR);  
                         break;  
                 case ZOOM_IN:  
                         setCursor(SwingUtil.ZOOMIN_CURSOR);  
                         break;  
                 case ZOOM_OUT:  
                         setCursor(SwingUtil.ZOOMOUT_CURSOR);  
                         break;  
                 case PAN:  
                         setCursor(SwingUtil.PAN_CURSOR);  
                         break;  
                 default:  
                         setCursor(normalCursor);  
                         break;  
351                  }                  }
352          }          };
   
         //  
         // /**  
         // * Gibt den "normalen" Cursor zurueck. Dieser kann neben dem "pointer"  
         // auch  
         // * ein Sanduhr-Wartecursor sein.  
         // *  
         // * @author <a href="mailto:[email protected]">Stefan Alfons  
         // * Kr&uuml;ger</a>  
         // */  
         // public Cursor getNormalCursor() {  
         // return normalCursor;  
         // }  
         //  
         // /**  
         // * Setzt den "normalen" Cursor. Dieser kann neben dem default "pointer"  
         // z.B.  
         // * auch ein Sanduhr-Wartecursor sein.  
         // *  
         // * @author <a href="mailto:[email protected]">Stefan Alfons  
         // * Kr&uuml;ger</a>  
         // */  
         // public void setNormalCursor(Cursor normalCursor) {  
         // this.normalCursor = normalCursor;  
         // }  
353    
354          /**          /**
355           * Berechnet die Transformation zwischen Fenster- und Karten-Koordinaten           * A flag indicating if dispose() was already called. If true, then further
356           * neu.           * use of this {@link SelectableXMapPane} is undefined.
357           */           */
358          protected void resetTransforms() {          private boolean disposed = false;
                 if (getMapArea() == null || getWidth() == 0 || getHeight() == 0)  
                         return;  
   
                 // We store the last Transform  
                 oldScreenToWorld = screenToWorld;  
   
                 this.screenToWorld = new AffineTransform(  
                 // Genauso wie die Fenster-Koordinaten, werden die Longitude-Koordinaten  
                                 // nach rechts (Osten) hin groesser  
                                 // --> positive Verschiebung  
                                 getMapArea().getWidth() / getWidth(),  
                                 // keine Verzerrung  
                                 0.0, 0.0,  
                                 // Waehrend die Fenster-Koordinaten nach unten hin groesser  
                                 // werden,  
                                 // werden Latitude-Koordinaten nach Sueden hin keiner  
                                 // --> negative Verschiebung  
                                 -getMapArea().getHeight() / getHeight(),  
                                 // Die Longitude-Koordinaten werden nach Osten hin groesser  
                                 // --> obere linke Ecke des Fensters hat also den Minimalwert  
                                 getMapArea().getMinX(),  
                                 // Die Latitude-Koordinaten werden nach Norden hin groesser  
                                 // --> obere linke Ecke des Fensters hat also den Maximalwert  
                                 getMapArea().getMaxY());  
   
                 try {  
                         this.worldToScreen = screenToWorld.createInverse();  
                 } catch (NoninvertibleTransformException e) {  
                         LOGGER.error(e);  
                 }  
         }  
359    
360          /**          /**
361           * Transformation zwischen Fenster-Koordinaten und Karten-Koordinaten           * While dragging, the {@link #updateFinalImage()} method is translating the
362           * (lat/lon)           * cached images while setting it together.
363             **/
364            Point imageOrigin = new Point(0, 0);
365            /**
366             * For every rendering thread started,
367             * {@link GTUtil#createGTRenderer(MapContext)} is called to create a new
368             * renderer. These Java2D rendering hints are passed to the
369             * {@link GTRenderer}. The java2dHints are the same for all renderers (bg
370             * and local).
371           */           */
372          protected AffineTransform screenToWorld = null;          private RenderingHints java2dHints;
373    
374          private AffineTransform worldToScreen;          protected LabelCache labelCache = new LabelCacheImpl();
375    
376          /**          /**
377           * Listens to changes of the "local" {@link MapContext} and triggers           * Listens to changes of the "local" {@link MapContext} and triggers
378           * repaints where needed.           * repaints where needed.
379           */           */
380          private MapLayerListListener localContextListener = new MapLayerListListener() {          private final MapLayerListListener localContextListener = new MapLayerListListener() {
381    
382                  @Override                  @Override
383                  public void layerAdded(final MapLayerListEvent event) {                  public void layerAdded(final MapLayerListEvent event) {
384                          event.getLayer().addMapLayerListener(localMapLayerListener);                          event.getLayer().addMapLayerListener(localMapLayerListener);
385    
386                            localRenderer.setContext(getContext());
387    
388                          if (localContext.getLayers().length == 1) { // the first one                          if (localContext.getLayers().length == 1) { // the first one
389                                  // if the Area of Interest is unset, the LayerBounds are used                                  // if the Area of Interest is unset, the LayerBounds are used
390                                  if (!setMapArea(localContext.getAreaOfInterest()))                                  if (!setMapArea(localContext.getAreaOfInterest()))
# Line 757  public class XMapPane extends JPanel imp Line 401  public class XMapPane extends JPanel imp
401                  }                  }
402    
403                  @Override                  @Override
                 public void layerRemoved(final MapLayerListEvent event) {  
                         if (event.getLayer() != null)  
                                 event.getLayer().removeMapLayerListener(localMapLayerListener);  
                         // mapImageInvalid = true;  
                         // repaint();  
                         requestStartRendering();  
                 }  
   
                 @Override  
404                  public void layerChanged(final MapLayerListEvent event) {                  public void layerChanged(final MapLayerListEvent event) {
405                          // mapImageInvalid = true;                          // mapImageInvalid = true;
406                          // repaint();                          // repaint();
407                            localRenderer.setContext(getContext());
408                          requestStartRendering();                          requestStartRendering();
409                  }                  }
410    
# Line 776  public class XMapPane extends JPanel imp Line 412  public class XMapPane extends JPanel imp
412                  public void layerMoved(final MapLayerListEvent event) {                  public void layerMoved(final MapLayerListEvent event) {
413                          // mapImageInvalid = true;                          // mapImageInvalid = true;
414                          // repaint();                          // repaint();
415                            localRenderer.setContext(getContext());
416                          requestStartRendering();                          requestStartRendering();
417                  }                  }
         };  
   
         /**  
          * Listens to changes of the "background" {@link MapContext} and triggers  
          * repaints where needed.  
          */  
         private MapLayerListListener bgContextListener = new MapLayerListListener() {  
   
                 @Override  
                 public void layerAdded(final MapLayerListEvent event) {  
                         event.getLayer().addMapLayerListener(bgMapLayerListener);  
   
                         if (localContext.getLayers().length == 0  
                                         && bgContext.getLayers().length == 1) { // the first one and  
                                 // localContext is  
                                 // empty  
                                 if (!setMapArea(localContext.getAreaOfInterest()))  
                                         requestStartRendering();  
                                 return;  
                         }  
   
                         // We need to redraw, even in case that the mapArea didn't change  
                         // mapImageInvalid = true;  
                         // repaint();  
                         requestStartRendering();  
   
                 }  
418    
419                  @Override                  @Override
420                  public void layerRemoved(final MapLayerListEvent event) {                  public void layerRemoved(final MapLayerListEvent event) {
421                          if (event.getLayer() != null)                          if (event.getLayer() != null)
422                                  event.getLayer().removeMapLayerListener(bgMapLayerListener);                                  event.getLayer().removeMapLayerListener(localMapLayerListener);
                         // mapImageInvalid = true;  
                         // repaint();  
                         requestStartRendering();  
                 }  
   
                 @Override  
                 public void layerChanged(final MapLayerListEvent event) {  
                         // mapImageInvalid = true;  
                         // repaint();  
                         requestStartRendering();  
                 }  
   
                 @Override  
                 public void layerMoved(final MapLayerListEvent event) {  
423                          // mapImageInvalid = true;                          // mapImageInvalid = true;
424                          // repaint();                          // repaint();
425                            localRenderer.setContext(getContext());
426                          requestStartRendering();                          requestStartRendering();
427                  }                  }
428          };          };
429    
430            private final RenderingExecutor localExecuter = new RenderingExecutor(this);
431    
432          /**          /**
433           * Listens to each layer in the local {@link MapContext} for changes and           * Listens to each layer in the local {@link MapContext} for changes and
434           * triggers repaints.           * triggers repaints.
# Line 837  public class XMapPane extends JPanel imp Line 436  public class XMapPane extends JPanel imp
436          protected MapLayerListener localMapLayerListener = new MapLayerAdapter() {          protected MapLayerListener localMapLayerListener = new MapLayerAdapter() {
437    
438                  @Override                  @Override
439                  public void layerShown(MapLayerEvent event) {                  public void layerChanged(final MapLayerEvent event) {
440                          // mapImageInvalid = true;                          localRenderer.setContext(getContext()); // betters for SLD changes?!
                         // repaint();  
                         requestStartRendering();  
                 }  
   
                 @Override  
                 public void layerHidden(MapLayerEvent event) {  
                         // mapImageInvalid = true;  
                         // repaint();  
                         requestStartRendering();  
                 }  
   
                 @Override  
                 public void layerChanged(MapLayerEvent event) {  
441                          // Change of SLD for example                          // Change of SLD for example
442                          // mapImageInvalid = true;                          // mapImageInvalid = true;
443                          // repaint();                          // repaint();
444                          requestStartRendering();                          requestStartRendering();
445                  }                  }
         };  
   
         /**  
          * Listens to each layer in the local {@link MapContext} for changes and  
          * triggers repaints.  
          */  
         protected MapLayerListener bgMapLayerListener = new MapLayerAdapter() {  
   
                 @Override  
                 public void layerShown(MapLayerEvent event) {  
                         // mapImageInvalid = true;  
                         // repaint();  
                         requestStartRendering();  
                 }  
446    
447                  @Override                  @Override
448                  public void layerHidden(MapLayerEvent event) {                  public void layerHidden(final MapLayerEvent event) {
449                          // mapImageInvalid = true;                          // mapImageInvalid = true;
450                          // repaint();                          // repaint();
451                          requestStartRendering();                          requestStartRendering();
452                  }                  }
453    
454                  @Override                  @Override
455                  public void layerChanged(MapLayerEvent event) {                  public void layerShown(final MapLayerEvent event) {
                         // Change of SLD for example  
456                          // mapImageInvalid = true;                          // mapImageInvalid = true;
457                          // repaint();                          // repaint();
458                          requestStartRendering();                          requestStartRendering();
459                  }                  }
460          };          };
461    
462          /**          private final GTRenderer localRenderer = GTUtil.createGTRenderer();
          * Liefert eine affine Transformation, um von den Fenster-Koordinaten in die  
          * Karten-Koordinaten (Lat/Lon) umzurechnen.  
          *  
          * @return eine Kopie der aktuellen Transformation; <code>null</code> wenn  
          *         noch keine Karte angezeigt wird  
          */  
         public AffineTransform getScreenToWorld() {  
                 if (screenToWorld == null)  
                         resetTransforms();  
                 // nur Kopie der Transformation zurueckgeben!  
                 if (screenToWorld == null)  
                         return null;  
                 return new AffineTransform(screenToWorld);  
         }  
   
         public AffineTransform getWorldToScreenTransform() {  
                 if (worldToScreen == null) {  
                         resetTransforms();  
                 }  
                 // nur Kopie der Transformation zurueckgeben!  
                 return new AffineTransform(worldToScreen);  
         }  
   
         public MapContext getContext() {  
                 if (localContext == null) {  
                         this.localContext = new DefaultMapContext();  
                         this.localContext.addMapLayerListListener(localContextListener);  
                 }  
                 return localContext;  
         }  
463    
464          public MapContext getBgContext() {          private final GTRenderer bgRenderer = GTUtil.createGTRenderer();
                 return bgContext;  
         }  
465    
466          /**          /**
467           *           * the area of the map to draw
          * @param context  
          */  
         public void setLocalContext(final MapContext context) {  
                 // Remove the default listener from the old context  
                 if (this.localContext != null) {  
                         this.localContext.removeMapLayerListListener(localContextListener);  
   
                         // adding listener to all layers  
                         for (MapLayer mapLayer : localContext.getLayers()) {  
                                 mapLayer.removeMapLayerListener(localMapLayerListener);  
                         }  
                 }  
   
                 this.localContext = context;  
   
                 if (context != null) {  
                         setMapArea(localContext.getAreaOfInterest());  
   
                         this.localContext.addMapLayerListListener(localContextListener);  
   
                         // adding listener to all layers  
                         for (MapLayer mapLayer : localContext.getLayers()) {  
                                 mapLayer.addMapLayerListener(localMapLayerListener);  
                         }  
                 }  
   
                 mapImageInvalid = true;  
                 repaint();  
         }  
   
         public void setBgContext(final MapContext context) {  
   
                 // Remove the default listener from the old context  
                 if (this.bgContext != null) {  
                         this.bgContext.removeMapLayerListListener(bgContextListener);  
   
                         // adding listener to all layers  
                         for (MapLayer mapLayer : bgContext.getLayers()) {  
                                 mapLayer.removeMapLayerListener(bgMapLayerListener);  
                         }  
                 }  
   
                 this.bgContext = context;  
   
                 if (context != null) {  
                         setMapArea(bgContext.getAreaOfInterest());  
   
                         this.bgContext.addMapLayerListListener(bgContextListener);  
   
                         // adding listener to all layers  
                         for (MapLayer mapLayer : bgContext.getLayers()) {  
                                 mapLayer.addMapLayerListener(bgMapLayerListener);  
                         }  
                 }  
                 mapImageInvalid = true;  
                 repaint();  
         }  
   
         /**  
          * Returns a copy of the mapArea  
          *  
          * @return  
          */  
         public Envelope getMapArea() {  
                 if (mapArea == null) {  
                         final Rectangle paneBounds = getBounds();  
   
                         try {  
                                 mapArea = localContext.getLayerBounds();  
                         } catch (final IOException e) {  
                                 LOGGER.warn("context.getLayerBounds()", e);  
                         }  
   
                         if (mapArea != null) {  
                                 /* either the viewer size has changed or we've done a reset */  
                                 mapImageInvalid = true; /* note we need to redraw */  
                                 oldRect = paneBounds; /* store what the current size is */  
                                 mapArea = bestAllowedMapArea(mapArea);  
                         }  
                 }  
   
                 if (mapArea == null)  
                         return null;  
   
                 return new Envelope(mapArea);  
         }  
   
         /**  
          * @param newMapArea  
          * @return <code>true</code> if the mapArea has been changed and a repaint  
          *         has been triggered.  
          */  
         public boolean setMapArea(final Envelope newMapArea) {  
   
                 if (newMapArea == null  
                                 || bestAllowedMapArea(newMapArea).equals(mapArea)) {  
                         // No change.. no need to repaint  
                         return false;  
                 }  
   
                 // Testing, whether NaN or Infinity are used in the newMapArea  
                 if (newMapArea.isNull() || Double.isInfinite(newMapArea.getMaxX())  
                                 || Double.isInfinite(newMapArea.getMaxY())  
                                 || Double.isInfinite(newMapArea.getMinX())  
                                 || Double.isInfinite(newMapArea.getMinY())) {  
                         // No change.. ugly new values  
                         LOGGER.warn("setMapArea has been called with newArea = "  
                                         + newMapArea);  
                         return false;  
                 }  
   
                 // Testing, whether the difference if just minimal  
                 if (mapArea != null) {  
                         Envelope candNew = bestAllowedMapArea(newMapArea);  
                         double tolX = mapArea.getWidth() / 1000.;  
                         double tolY = mapArea.getHeight() / 1000.;  
                         if ((candNew.getMinX() - tolX < mapArea.getMinX())  
                                         && (mapArea.getMinX() < candNew.getMinX() + tolX)  
                                         && (candNew.getMaxX() - tolX < mapArea.getMaxX())  
                                         && (mapArea.getMaxX() < candNew.getMaxX() + tolX)  
   
                                         && (candNew.getMinY() - tolY < mapArea.getMinY())  
                                         && (mapArea.getMinY() < candNew.getMinY() + tolY)  
                                         && (candNew.getMaxY() - tolY < mapArea.getMaxY())  
                                         && (mapArea.getMaxY() < candNew.getMaxY() + tolY)  
   
                         ) {  
                                 // The two mapAreas only differ my 1/1000th.. ignore  
   
                                 return false;  
                         }  
                 }  
   
                 oldMapArea = mapArea;  
   
                 this.mapArea = bestAllowedMapArea(newMapArea);  
   
                 if (localContext != null) {  
                         localContext.setAreaOfInterest(mapArea, localContext  
                                         .getCoordinateReferenceSystem());  
                 }  
                 if (bgContext != null) {  
                         bgContext.setAreaOfInterest(mapArea, localContext  
                                         .getCoordinateReferenceSystem());  
                 }  
                 resetTransforms();  
                 mapImageInvalid = true;  
                 mapAreaChanged = true;  
                 repaint();  
   
 //              LOGGER.debug("New maparea = " + mapArea);  
                 return true;  
         }  
   
         public int getState() {  
                 return state;  
         }  
   
         /**  
          * Enables/Disables the ZOOM Mouse Listener. Upates the Cursor and stops the  
          * repaint Timer if  
          *  
          * @param state  
468           */           */
469          public void setState(final int state) {          protected Envelope mapArea = null;
                 this.state = state;  
   
                 zoomMapPaneMouseListener.setEnabled((state == ZOOM_IN  
                                 || state == ZOOM_OUT || state == PAN));  
   
                 // Je nach Aktion den Cursor umsetzen  
                 updateCursor();  
         }  
   
         /** Cursor wenn kein Mausbutton gedrueckt wird. default oder SwingUtil.PAN **/  
         protected static Cursor normalCursor = Cursor  
                         .getPredefinedCursor(Cursor.DEFAULT_CURSOR);  
   
         public static final Cursor WAIT_CURSOR = Cursor  
                         .getPredefinedCursor(Cursor.WAIT_CURSOR);  
   
         public static final int NONE = -123;  
   
         private RenderingExecutor localExecuter;  
   
         private BufferedImage finalImage;  
470    
471          /**          /**
472           * A flag set it {@link #setMapArea(Envelope)} to indicated the           * A flag set it {@link #setMapArea(Envelope)} to indicated the
473           * {@link #paintComponent(Graphics)} method, that the image on-screen is           * {@link #paintComponent(Graphics)} method, that the image on-screen is
474           * associated with {@link #oldMapArea} and may hence be scaled for a quick           * associated with {@link #oldMapArea} and may hence be scaled for a quick
475           * preview.<br/>           * preview.<br>
476           * The flag is reset           * The flag is reset
477           **/           **/
478          private boolean mapAreaChanged = false;          private boolean mapAreaChanged = false;
479    
         private JFrame finalImageFrame;  
   
         private volatile Boolean requestStartRendering = false;  
         private BufferedImage preFinalImage;  
   
         protected void paintComponent(final Graphics g) {  
                 // Maybe update the cursor  
                 updateCursor();  
   
                 if (!acceptsRepaintCalls)  
                         return;  
   
                 boolean paintedSomething = false;  
   
                 if (mapImageInvalid) { /* if the map changed then redraw */  
   
                         mapImageInvalid = false; // Reset for next round  
   
                         // If the new mapArea and the oldMapArea intersect, we can draw some  
                         // quick scaled preview to make the user feel that something is  
                         // happening.  
                         if (mapAreaChanged && oldMapArea != null  
                                         && getMapArea().intersects(oldMapArea)  
                                         & !getMapArea().equals(oldMapArea)) {  
   
                                 mapAreaChanged = false;  
   
                                 if (getMapArea().covers(oldMapArea)) {  
                                         setQuickPreviewHint(ZOOM_OUT);  
                                         paintedSomething = drawScaledPreviewImage_Zoom((Graphics2D) g);  
                                 } else if (oldMapArea.covers(getMapArea())) {  
                                         setQuickPreviewHint(ZOOM_IN);  
                                         paintedSomething = drawScaledPreviewImage_Zoom((Graphics2D) g);  
                                 }  
   
                         }  
   
                         if (paneResized) {  
                                 paneResized = false;  
                                 preFinalImage = null;  
                                 finalImage = null;  
                                 localImage = null;  
                                 bgImage = null;  
                                 // gadgetsImage = null;  
                         }  
   
                         // Start the Threads and Timers to render the image  
                         requestStartRendering();  
   
                 }  
   
                 if (!paintedSomething) {  
   
                         // TODO Should just paint the getFinalImage(). Update should be  
                         // called by timer every 300ms, and the repaint() until all threads  
                         // are done.  
                         g.drawImage(getFinalImage(), 0, 0, this);  
   
                         paintedSomething = true;  
                 }  
   
         }  
   
480          /**          /**
481           * Cancels all running renderers and sets the flag to start new ones. <br/>           * This color is used as the default background color when painting a map.
          *  
          * @see #startRenderThreadsTimer  
482           */           */
483          private void requestStartRendering() {          private Color mapBackgroundColor = Color.WHITE;
                 if (bgExecuter != null)  
                         bgExecuter.cancelTask();  
                 if (localExecuter != null)  
                         localExecuter.cancelTask();  
                 requestStartRendering = true;  
         }  
484    
485          /**          /**
486           * Transformiert einen Fenster-Koordinaten-Bereich in Geo-Koordinaten.           * A flag indicating that the shown image is invalid and needs to be
487           *           * re-rendered.
          * @param ox  
          *            X-Koordinate der VON-Position  
          * @param oy  
          *            Y-Koordinate der VON-Position  
          * @param px  
          *            X-Koordinate der BIS-Position  
          * @param py  
          *            Y-Koordinate der BIS-Position  
488           */           */
489          public Envelope tranformWindowToGeo(int ox, int oy, int px, int py) {          protected boolean mapImageInvalid = true;
                 AffineTransform at = getScreenToWorld();  
                 Point2D geoO = at.transform(new Point2D.Double(ox, oy), null);  
                 Point2D geoP = at.transform(new Point2D.Double(px, py), null);  
                 return new Envelope(geoO.getX(), geoP.getX(), geoO.getY(), geoP.getY());  
         }  
490    
491          /**          /**
492           * Transformiert einen Geo-Koordinaten-Bereich in Fenster-Koordinaten.           * Holds a flag for each layer, whether it is regarded or ignored on
493           *           * {@link #SELECT_TOP}, {@link #SELECT_ALL} and {@link #SELECT_ONE_FROM_TOP}
494           * @param ox           * actions.
          *            X-Koordinate der VON-Position  
          * @param oy  
          *            Y-Koordinate der VON-Position  
          * @param px  
          *            X-Koordinate der BIS-Position  
          * @param py  
          *            Y-Koordinate der BIS-Position  
          * @param winToGeotransform  
          *            Eine Window to Geo transform. If <code>null</code>,  
          *            {@link #getScreenToWorld()} is used.  
495           */           */
496          public Envelope tranformGeoToWindow(double ox, double oy, double px,          final protected HashMap<MapLayer, Boolean> mapLayerSelectable = new HashMap<MapLayer, Boolean>();
                         double py, AffineTransform winToGeotransform) {  
                 AffineTransform at = winToGeotransform == null ? getScreenToWorld()  
                                 : winToGeotransform;  
                 Point2D geoO;  
                 try {  
                         geoO = at.inverseTransform(new Point2D.Double(ox, oy), null);  
                         Point2D geoP = at  
                                         .inverseTransform(new Point2D.Double(px, py), null);  
                         return new Envelope(geoO.getX(), geoP.getX(), geoO.getY(), geoP  
                                         .getY());  
                 } catch (NoninvertibleTransformException e) {  
                         LOGGER.error(e);  
                         return new Envelope(ox, oy, px, py);  
                 }  
         }  
497    
498          /**          /**
499           * Diretly paints scaled preview into the {@link SelectableXMapPane}. Used           * List of listeners of this {@link XMapPane}
          * to give the user something to look at while we are rendering. Method  
          * should be called after {@link #setMapArea(Envelope)} has been set to the  
          * new mapArea and transform has been reset.<br/>  
          * This method does nothing if the {@link #lastRenderingDuration} is smaller  
          * then a trashhold.  
          *  
          * @param g  
          *            Graphics2D to paint the preview into  
          *  
          * @param state  
          *            Max be {@link #ZOOM_IN} or {@link #ZOOM_OUT}  
500           */           */
501          protected boolean drawScaledPreviewImage_Zoom(Graphics2D graphics) {          protected Vector<JMapPaneListener> mapPaneListeners = new Vector<JMapPaneListener>();
502            /**
503                  if (quickPreviewHint == 0)           * If not <code>null</code>, the {@link XMapPane} will not allow to zoom/pan
504                          return false;           * out of that area
505             **/
506                  graphics.setRenderingHint(RenderingHints.KEY_INTERPOLATION,          private Envelope maxExtend = null;
507                                  RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR);          private Double maxZoomScale = Double.MIN_VALUE;
                 graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING,  
                                 RenderingHints.VALUE_ANTIALIAS_OFF);  
                 graphics.setRenderingHint(RenderingHints.KEY_RENDERING,  
                                 RenderingHints.VALUE_RENDER_SPEED);  
   
                 if (oldMapArea == null)  
                         return false;  
508    
509                  Rectangle visibleArea = getVisibleRect();          private Double minZoomScale = Double.MAX_VALUE;
510    
511                  // Calculate the oldMapArea in the current WindowCoordinates:          /**
512                  Envelope oldMapWindow = tranformGeoToWindow(oldMapArea.getMinX(),           * We store the old mapArea for a moment to use it for the
513                                  oldMapArea.getMinY(), oldMapArea.getMaxX(), oldMapArea           * "quick scaled preview" in case of ZoomOut
514                                                  .getMaxY(), null);           **/
515            protected Envelope oldMapArea = null;
516    
517                  int xx1 = (int) Math.round(oldMapWindow.getMinX());          /**
518                  int yy1 = (int) Math.round(oldMapWindow.getMinY());           * We store the old transform for a moment to use it for the
519                  int xx2 = (int) Math.round(oldMapWindow.getMaxX());           * "quick scaled preview" in case of ZoomIn
520                  int yy2 = (int) Math.round(oldMapWindow.getMaxY());           **/
521            protected AffineTransform oldScreenToWorld = null;
522    
523                  graphics.drawImage(getPreFinalImage(), xx1, yy1, xx2, yy2,          /**
524                                  (int) visibleArea.getMinX(), (int) visibleArea.getMinY(),           * A flag indicating, that the image size has changed and the buffered
525                                  (int) visibleArea.getMaxX(), (int) visibleArea.getMaxY(),           * images are not big enough any more
526                                  getMapBackgroundColor(), null);           **/
527            protected boolean paneResized = false;
528    
529                  Rectangle painedArea = new Rectangle(xx1, yy1, xx2 - xx1, yy2 - yy1);          private BufferedImage preFinalImage;
530    
531                  SwingUtil.clearAround(graphics, painedArea, visibleArea);          // if null, no quick preview will be shown
532            private int quickPreviewHint = 0;
533    
534                  addGadgets(graphics);          private Map<Object, Object> rendererHints = GTUtil
535                  // graphics.drawImage(getGadgetsImage(), 0,0, (int)                          .getDefaultGTRendererHints(localRenderer);
                 // visibleArea.getMaxX(), (int) visibleArea.getMaxY(),null);  
536    
537                  quickPreviewHint = 0;          private volatile Boolean requestStartRendering = false;
538    
539                  graphics.dispose();          private final Timer resizeTimer;
                 // Something has been drawn  
                 return true;  
         }  
540    
541          final static Font waitFont = new Font("Arial", Font.BOLD, 30);          private final int resizingPaintDelay;
542    
543          /**          /**
544           * Paints some optinal stuff into the given {@link Graphics2D}. Usually           * Transformation zwischen Fenster-Koordinaten und Karten-Koordinaten
545           * called as the last paint on the mapImage.           * (lat/lon)
546           */           */
547          private void addGadgets(Graphics2D graphics) {          protected AffineTransform screenToWorld = null;
   
                 if (mapImage != null)  
                         graphics.drawImage(mapImage, getBounds().width  
                                         - mapImage.getWidth() - 10, getBounds().height  
                                         - mapImage.getHeight() - 10, this);  
   
                 // If still rendering, paint a gray shadow or so...  
                 if (bgExecuter != null && bgExecuter.isRunning()  
                                 || localExecuter != null && localExecuter.isRunning()) {  
                         graphics.setColor(Color.BLACK);  
   
                         graphics.setFont(waitFont);  
                         graphics.drawString("Wait...", 40, 70);  
                 }  
   
         }  
548    
549          /**          /**
550           * Accumulates all three images           * The flag {@link #requestStartRendering} can be set to true by events.
551           *           * This {@link Timer} checks the flag regularly and starts one renderer
552           * @return           * thread.
553           */           */
554          synchronized protected BufferedImage updateFinalImage() {          final private Timer startRenderThreadsTimer;
   
                 final Graphics2D finalG = (Graphics2D) getFinalImage().getGraphics();  
                 finalG.setBackground(getMapBackgroundColor());  
   
                 // Render the two map images first, into the preFinalImage  
                 {  
                         final Graphics2D preFinalG = (Graphics2D) getPreFinalImage()  
                                         .getGraphics();  
                         preFinalG.setBackground(getMapBackgroundColor());  
   
                         preFinalG.drawImage(getBgImage(), 0, 0, getMapBackgroundColor(),  
                                         null);  
                         // // Draw the local layers image  
                         preFinalG.drawImage(getLocalImage(), 0, 0, null);  
                         preFinalG.dispose();  
                 }  
   
                 finalG.drawImage(getPreFinalImage(), imageOrigin.x, imageOrigin.y,  
                                 getMapBackgroundColor(), null);  
   
                 // System.out.println(new Date().getTime() - startTime +  
                 // "ms for update");  
                 //  
                 // if (finalImageFrame == null) {  
                 // finalImageFrame = new JFrame();  
                 // finalImageFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);  
                 // SwingUtil.setRelativeFramePosition(finalImageFrame, 0, 0);  
                 // }  
                 // finalImageFrame.setContentPane(new JLabel(new  
                 // ImageIcon(finalImage)));  
                 // finalImageFrame.pack();  
                 // finalImageFrame.setVisible(true);  
   
                 final int finalImageHeight = getFinalImage().getHeight(null);  
                 final int finalImageWidth = getFinalImage().getWidth(null);  
   
                 Rectangle painedArea = new Rectangle(imageOrigin.x, imageOrigin.y,  
                                 finalImageWidth, finalImageHeight);  
                 SwingUtil.clearAround(finalG, painedArea, getVisibleRect());  
   
                 addGadgets(finalG);  
                 // finalG.drawImage(getGadgetsImage(), 0, 0, null);  
   
                 finalG.dispose();  
555    
556                  return finalImage;          /**
557          }           * The default state is ZOOM_IN, hence by default the
558             * {@link #zoomMapPaneMouseListener} is also enabled.
559             **/
560            private int state = ZOOM_IN;
561    
562          /*          /**
563           * Set alpha composite. For example, pass in 1.0f to have 100% opacity pass           * Manuell gesetzter statischer Cursor, unabhaengig von der aktuellen
564           * in 0.25f to have 25% opacity.           * MapPane-Funktion
565           */           */
566          private AlphaComposite makeComposite(float alpha) {          protected Cursor staticCursor = null;
                 int type = AlphaComposite.SRC_OVER;  
                 return (AlphaComposite.getInstance(type, alpha));  
         }  
   
         private Image getFinalImage() {  
   
                 if (finalImage == null) {  
                         finalImage = null;  
                         Rectangle curPaintArea = getVisibleRect();  
                         finalImage = new BufferedImage(curPaintArea.width,  
                                         curPaintArea.height, BufferedImage.TYPE_INT_RGB);  
   
                         requestStartRendering();  
                 }  
                 return finalImage;  
         }  
567    
568          private Image getPreFinalImage() {          private AffineTransform worldToScreen;
569    
570                  if (preFinalImage == null) {          /**
571                          preFinalImage = null;           * This {@link MouseListener} is managing all zoom related tasks
572                          Rectangle curPaintArea = getVisibleRect();           */
573            public final ZoomXMapPaneMouseListener zoomMapPaneMouseListener = new ZoomXMapPaneMouseListener(
574                            this);
575    
576                          preFinalImage = new BufferedImage(curPaintArea.width,          /** Is set if a renderer has an error **/
577                                          curPaintArea.height, BufferedImage.TYPE_INT_RGB);          protected ArrayList<Exception> renderingErrors = new ArrayList<Exception>();
578    
579                          requestStartRendering();          // TODO doku
580                  }          public XMapPane() {
581                  return preFinalImage;                  this(null, null);
582          }          }
583    
584          /**          /**
585           * While dragging, the {@link #updateFinalImage()} method is translating the           * full constructor extending JPanel
586           * cached images while setting it together.           *
587           **/           * @param rendererHints
588          Point imageOrigin = new Point(0, 0);           *
589             * @param layout
590          /**           *            - layout (probably shouldn't be set)
591           * Starts rendering on one or two threads           * @param isDoubleBuffered
592             *            - a Swing thing I don't really understand
593             * @param render
594             *            - what to draw the map with
595             * @param localContext
596             *            - {@link MapContext} of layer to render.
597           */           */
598          private void startRendering() {          public XMapPane(final MapContext localContext_,
599                            final Map<Object, Object> rendererHints) {
600                  if (!isWellDefined())                  super(true);
                         return;  
   
                 if (bgExecuter != null)  
                         // Stop all renderers  
                         bgExecuter.cancelTask();  
   
                 if (localExecuter != null)  
                         localExecuter.cancelTask();  
                 //  
                 //  
                 // LOGGER.debug("stopping any running renderes:");  
                 // int count = 0;  
                 // while (bgExecuter.isRunning() || localExecuter.isRunning()) {  
                 // LOGGER.debug("waiting for threads to stop");  
                 //  
                 // bgExecuter.cancelTask();  
                 // localExecuter.cancelTask();  
                 //  
                 // count++;  
                 //  
                 // try {  
                 // Thread.sleep(100);  
                 // } catch (InterruptedException e) {  
                 // LOGGER.error(e);  
                 // }  
                 //  
                 // if (count > 100) {  
                 // throw new RuntimeException(  
                 // "Unable to stop rendering thread for 10secs");  
                 // }  
                 // }  
                 // LOGGER.debug(" threads stopped after " + count / 10. + "secs");  
601    
602                  Rectangle curPaintArea = getVisibleRect();                  setRendererHints(rendererHints);
603    
604                  // allow a single pixel margin at the right and bottom edges                  setOpaque(true);
                 curPaintArea.width -= 1;  
                 curPaintArea.height -= 1;  
605    
606                  labelCache.clear();                  if (localContext_ != null)
607                            setLocalContext(localContext_);
608    
609                  /**                  /**
610                     * Adding the #zoomMapPaneMouseListener
611                   */                   */
612                    this.addMouseListener(zoomMapPaneMouseListener);
613                    this.addMouseMotionListener(zoomMapPaneMouseListener);
614                    this.addMouseWheelListener(zoomMapPaneMouseListener);
615    
616                  /**                  /*
617                   * We have to set new renderer                   * We use a Timer object to avoid rendering delays and flickering when
618                     * the user is drag-resizing the parent container of this map pane.
619                     *
620                     * Using a ComponentListener doesn't work because, unlike a JFrame, the
621                     * pane receives a stream of events during drag-resizing.
622                   */                   */
623                    resizingPaintDelay = DEFAULT_RESIZING_PAINT_DELAY;
624                    resizeTimer = new Timer(resizingPaintDelay, new ActionListener() {
625    
626                  if (getBgContext() != null) {                          public void actionPerformed(final ActionEvent e) {
627                          bgExecuter = new RenderingExecutor(this, 333l);                                  paneResized = true;
                         LOGGER.debug("starting bg renderer:");  
                         // /* System.out.println("rendering"); */  
                         final GTRenderer createGTRenderer = GTUtil.createGTRenderer(  
                                         localContext, getRendererHints());  
                         createGTRenderer.setJava2DHints(getJava2dHints());  
                         bgExecuter.submit(getBgContext().getAreaOfInterest(), curPaintArea,  
                                         (Graphics2D) getBgImage().getGraphics(), createGTRenderer);  
                 }  
   
                 if (getContext() != null) {  
                         localExecuter = new RenderingExecutor(this, 150l);  
                         LOGGER.debug("starting local renderer:");  
                         final GTRenderer createGTRenderer = GTUtil.createGTRenderer(  
                                         localContext, getRendererHints());  
                         createGTRenderer.setJava2DHints(getJava2dHints());  
                         localExecuter.submit(getContext().getAreaOfInterest(),  
                                         curPaintArea, (Graphics2D) getLocalImage().getGraphics(),  
                                         createGTRenderer);  
                 }  
   
                 updateCursor();  
 //  
 //              // start regular repaints until all renderers are done.  
 //              repainterTimer.setRepeats(true);  
 //              repainterTimer.restart();  
   
         }  
   
         /**  
          * Lazyly initializes a {@link BufferedImage} for the background renderer.  
          */  
         private BufferedImage getBgImage() {  
   
                 if (bgImage == null) {  
 //                      LOGGER.debug("creating a new background image");  
   
                         Rectangle curPaintArea = getVisibleRect();  
                         // allow a single pixel margin at the right and bottom edges  
                         curPaintArea.width -= 1;  
                         curPaintArea.height -= 1;  
   
                         bgImage = new BufferedImage(curPaintArea.width + 1,  
                                         curPaintArea.height + 1, BufferedImage.TYPE_INT_ARGB);  
                 }  
   
                 return bgImage;  
         }  
628    
629          /** An (transparent) image to paint over the map in the lower right corner **/                                  if (!isWellDefined())
630          private BufferedImage mapImage = null;                                          return;
631    
632          private boolean acceptsRepaintCalls = true;                                  final Rectangle bounds = getVisibleRect();
633    
634          /**                                  final Envelope geoMapArea = tranformWindowToGeo(bounds.x,
635           * Get the BufferedImage to use as a flaoting icon in the lower right                                                  bounds.y, bounds.x + bounds.width, bounds.y
636           * corner.                                                                  + bounds.height);
          *  
          * @return <code>null</code> if the feature is deactivated.  
          */  
         public BufferedImage getMapImage() {  
                 return mapImage;  
         }  
637    
638          /**                                  setMapArea(bestAllowedMapArea(geoMapArea));
639           * Set the BufferedImage to use as a flaoting icon in the lower right corner                          }
640           *                  });
641           * @param mapImageIcon                  resizeTimer.setRepeats(false);
642           *            <code>null</code> is allowed and deactivates this icon.                  this.addComponentListener(new ComponentAdapter() {
          */  
         public void setMapImage(BufferedImage mapImage) {  
                 this.mapImage = mapImage;  
                 // gadgetsImage = null;  
         }  
643    
644          /**                          @Override
645           * Lazyly initializes a {@link BufferedImage} for the background renderer.                          public void componentResized(final ComponentEvent e) {
646           */                                  if (bgExecuter != null)
647          private BufferedImage getLocalImage() {                                          bgExecuter.cancelTask();
648                                    if (localExecuter != null)
649                                            localExecuter.cancelTask();
650                                    resizeTimer.restart();
651                            }
652    
653                  if (localImage == null) {                  });
 //                      LOGGER.debug("creating a new local image");  
654    
655                          Rectangle curPaintArea = getVisibleRect();                  /*
656                          // allow a single pixel margin at the right and bottom edges                   * Setting up the repaintTimer. Not started automatically.
657                          curPaintArea.width -= 1;                   */
658                          curPaintArea.height -= 1;                  repaintTimer = new Timer((int) REPEATING_REPAINT_DELAY,
659                                    new ActionListener() {
660    
661                          localImage = new BufferedImage(curPaintArea.width + 1,                                          @Override
662                                          curPaintArea.height + 1, BufferedImage.TYPE_INT_ARGB);                                          public void actionPerformed(final ActionEvent e) {
663                  }                                                  updateFinalImage();
664                                                    XMapPane.this.repaint();
665                                            }
666                                    });
667                    repaintTimer.setInitialDelay(INITIAL_REPAINT_DELAY);
668                    repaintTimer.setRepeats(true);
669    
670                  return localImage;                  /*
671          }                   * Setting up the startRenderThreadsTimer. This Timer starts
672                     * automatically.
673                     */
674                    startRenderThreadsTimer = new Timer(100, new ActionListener() {
675    
676          //                          @Override
677          // /**                          public void actionPerformed(final ActionEvent e) {
678          // * Lazyly initializes a {@link BufferedImage} for the background renderer.                                  synchronized (requestStartRendering) {
679          // */                                          if (requestStartRendering && isWellDefined()) {
         // private BufferedImage getGadgetsImage() {  
         //  
         // if (gadgetsImage == null) {  
         // LOGGER.debug("creating a new gadgets image");  
         //  
         // Rectangle curPaintArea = getVisibleRect();  
         // // allow a single pixel margin at the right and bottom edges  
         // curPaintArea.width -= 1;  
         // curPaintArea.height -= 1;  
         //  
         // gadgetsImage = new BufferedImage(curPaintArea.width + 1,  
         // curPaintArea.height + 1, BufferedImage.TYPE_INT_ARGB);  
         //  
         // if (mapImage != null)  
         // gadgetsImage.getGraphics().drawImage(mapImage,  
         // curPaintArea.width - mapImage.getWidth() - 10,  
         // curPaintArea.height - mapImage.getHeight() - 10, this);  
         //                        
         // }  
         //  
         // return gadgetsImage;  
         // }  
680    
681          /**                                                  if (localExecuter.isRunning()) {
682           * Called by the {@linkplain XMapPane.RenderingTask} when rendering has been                                                          localExecuter.cancelTask();
683           * completed Publishes a {@linkplain MapPaneEvent} of type {@code                                                  } else {
684           * MapPaneEvent.Type.RENDERING_STOPPED} to listeners.                                                          requestStartRendering = false;
685           *                                                          startRendering();
686           * @see MapPaneListener#onRenderingStopped(org.geotools.swing.event.MapPaneEvent)                                                  }
687           */                                          }
688          public void onRenderingCompleted() {                                  }
689                  updateFinalImage();                          }
690                  repaint();                  });
691          }                  startRenderThreadsTimer.start();
692    
         /**  
          * Called by the {@linkplain XMapPane.RenderingTask} when rendering was  
          * cancelled. Publishes a {@linkplain MapPaneEvent} of type {@code  
          * MapPaneEvent.Type.RENDERING_STOPPED} to listeners.  
          *  
          * @see MapPaneListener#onRenderingStopped(org.geotools.swing.event.MapPaneEvent)  
          */  
         public void onRenderingCancelled() {  
                 LOGGER.debug("Rendering cancelled");  
693          }          }
694    
695          /**          /**
696           * Called by the {@linkplain XMapPane.RenderingTask} when rendering failed.           * Fuegt der Map einen Listener hinzu.
          * Publishes a {@linkplain MapPaneEvent} of type {@code  
          * MapPaneEvent.Type.RENDERING_STOPPED} to listeners.  
          *  
          * @param renderingError  
          *            The error that occured during rendering  
697           *           *
698           * @see MapPaneListener#onRenderingStopped(org.geotools.swing.event.MapPaneEvent)           * @param l
699           */           *            neuer Listener
         public void onRenderingFailed(Exception renderingError) {  
                 // MapPaneEvent ev = new MapPaneEvent(this,  
                 // MapPaneEvent.Type.RENDERING_STOPPED);  
                 // publishEvent(ev);  
                 LOGGER.warn("Rendering failed", renderingError);  
                 updateFinalImage();  
                 repaint();  
   
         }  
   
         /**  
          * Called when a rendering request has been rejected. This will be common,  
          * such as when the user pauses during drag-resizing fo the map pane. The  
          * base implementation does nothing. It is provided for sub-classes to  
          * override if required.  
700           */           */
701          public void onRenderingRejected() {          public void addMapPaneListener(final JMapPaneListener l) {
702                  LOGGER.warn("Rendering rejected");                  mapPaneListeners.add(l);
                 repaint();  
         }  
   
         @Override  
         public void propertyChange(final PropertyChangeEvent evt) {  
                 final String prop = evt.getPropertyName();  
   
                 if (prop.equalsIgnoreCase("crs")) {  
                         localContext.setAreaOfInterest(localContext.getAreaOfInterest(),  
                                         (CoordinateReferenceSystem) evt.getNewValue());  
                 }  
703          }          }
704    
         // xulu.sn  
705          /**          /**
706           * Korrigiert den {@link Envelope} aka {@code mapArea} auf die beste           * Korrigiert den {@link Envelope} aka {@code mapArea} auf die beste
707           * erlaubte Flaeche damit die Massstabsbeschaenkungen noch eingehalten           * erlaubte Flaeche damit die Massstabsbeschaenkungen noch eingehalten
708           * werden, FALLS der uebergeben Envelope nicht schon gueltig sein sollte.<br/>           * werden, FALLS der uebergeben Envelope nicht schon gueltig sein sollte.<br>
709           * Since 21. April 09: Before thecalculation starts, the aspect ratio is           * Since 21. April 09: Before thecalculation starts, the aspect ratio is
710           * corrected. This change implies, that setMapArea() will most of the time           * corrected. This change implies, that setMapArea() will most of the time
711           * not allow setting to a wrong aspectRatio.           * not allow setting to a wrong aspectRatio.
# Line 1696  public class XMapPane extends JPanel imp Line 726  public class XMapPane extends JPanel imp
726                   * easily fail. We allow to grow here, because we don't check against                   * easily fail. We allow to grow here, because we don't check against
727                   * the maxExtend                   * the maxExtend
728                   */                   */
729                  Rectangle curPaintArea = getVisibleRect();                  final Rectangle curPaintArea = getVisibleRect();
730    
731                  env = JTSUtil.fixAspectRatio(curPaintArea, env, true);                  env = JTSUtil.fixAspectRatio(curPaintArea, env, true);
732    
# Line 1734  public class XMapPane extends JPanel imp Line 764  public class XMapPane extends JPanel imp
764                          newArea = new Envelope(ll, ur);                          newArea = new Envelope(ll, ur);
765                  }                  }
766    
767                  Envelope maxAllowedExtend = getMaxExtend();                  final Envelope maxAllowedExtend = getMaxExtend();
768                  while (maxAllowedExtend != null && !maxAllowedExtend.contains(newArea)                  while (maxAllowedExtend != null && !maxAllowedExtend.contains(newArea)
769                                  && newArea != null && !newArea.isNull()                                  && newArea != null && !newArea.isNull()
770                                  && !Double.isNaN(newArea.getMinX())                                  && !Double.isNaN(newArea.getMinX())
# Line 1747  public class XMapPane extends JPanel imp Line 777  public class XMapPane extends JPanel imp
777    
778                          // Exceeds top? Move down and maybe cut                          // Exceeds top? Move down and maybe cut
779                          if (newArea.getMaxY() > maxAllowedExtend.getMaxY()) {                          if (newArea.getMaxY() > maxAllowedExtend.getMaxY()) {
780                                  double divY = newArea.getMaxY() - maxAllowedExtend.getMaxY();                                  final double divY = newArea.getMaxY()
781                                                    - maxAllowedExtend.getMaxY();
782                                  // LOGGER.debug("Moving area down by " + divY);                                  // LOGGER.debug("Moving area down by " + divY);
783    
784                                  newArea = new Envelope(new Coordinate(newArea.getMinX(),                                  newArea = new Envelope(new Coordinate(newArea.getMinX(),
# Line 1770  public class XMapPane extends JPanel imp Line 801  public class XMapPane extends JPanel imp
801    
802                          // Exceeds bottom? Move up and maybe cut                          // Exceeds bottom? Move up and maybe cut
803                          if (newArea.getMinY() < maxAllowedExtend.getMinY()) {                          if (newArea.getMinY() < maxAllowedExtend.getMinY()) {
804                                  double divY = newArea.getMinY() - maxAllowedExtend.getMinY();                                  final double divY = newArea.getMinY()
805                                                    - maxAllowedExtend.getMinY();
806                                  // LOGGER.debug("Moving area up by " + divY);                                  // LOGGER.debug("Moving area up by " + divY);
807    
808                                  newArea = new Envelope(new Coordinate(newArea.getMinX(),                                  newArea = new Envelope(new Coordinate(newArea.getMinX(),
# Line 1795  public class XMapPane extends JPanel imp Line 827  public class XMapPane extends JPanel imp
827                          if (newArea.getMaxX() > maxAllowedExtend.getMaxX()) {                          if (newArea.getMaxX() > maxAllowedExtend.getMaxX()) {
828    
829                                  // Move left..                                  // Move left..
830                                  double divX = newArea.getMaxX() - maxAllowedExtend.getMaxX();                                  final double divX = newArea.getMaxX()
831                                                    - maxAllowedExtend.getMaxX();
832                                  // LOGGER.debug("Moving area left by " + divX);                                  // LOGGER.debug("Moving area left by " + divX);
833    
834                                  newArea = new Envelope(new Coordinate(newArea.getMinX() - divX,                                  newArea = new Envelope(new Coordinate(newArea.getMinX() - divX,
# Line 1820  public class XMapPane extends JPanel imp Line 853  public class XMapPane extends JPanel imp
853                          if (newArea.getMinX() < maxAllowedExtend.getMinX()) {                          if (newArea.getMinX() < maxAllowedExtend.getMinX()) {
854    
855                                  // Move right..                                  // Move right..
856                                  double divX = newArea.getMinX() - maxAllowedExtend.getMinX();                                  final double divX = newArea.getMinX()
857                                                    - maxAllowedExtend.getMinX();
858                                  // LOGGER.debug("Moving area right by " + divX);                                  // LOGGER.debug("Moving area right by " + divX);
859    
860                                  newArea = new Envelope(new Coordinate(newArea.getMinX() - divX,                                  newArea = new Envelope(new Coordinate(newArea.getMinX() - divX,
# Line 1840  public class XMapPane extends JPanel imp Line 874  public class XMapPane extends JPanel imp
874                                                          false);                                                          false);
875                                  }                                  }
876                          }                          }
   
877                  }                  }
878    
879                  return newArea;                  return newArea;
880          }          }
881    
882          /**          /**
883           * Retuns the minimum allowed zoom scale. This is the bigger number value of           * Should be called when the {@link JMapPane} is not needed no more to help
884           * the two. Defaults to {@link Double}.MAX_VALUE           * the GarbageCollector
885             *
886             * Removes all {@link JMapPaneListener}s that are registered
887           *           *
888           * @author <a href="mailto:[email protected]">Stefan Alfons           * @author <a href="mailto:[email protected]">Stefan Alfons
889           *         Kr&uuml;ger</a>           *         Kr&uuml;ger</a>
890           */           */
891          public Double getMinZoomScale() {          public void dispose() {
892                  return minZoomScale;                  if (isDisposed())
893                            return;
894    
895                    setPainting(false);
896    
897                    resizeTimer.stop();
898                    startRenderThreadsTimer.stop();
899    
900                    disposed = true;
901    
902                    if (bgExecuter != null) {
903                            bgExecuter.cancelTask();
904                            bgExecuter.dispose();
905                    }
906    
907                    if (localExecuter != null) {
908                            int i = 0;
909                            localExecuter.cancelTask();
910                            while (i++ < 10 && localExecuter.isRunning()) {
911                                    try {
912                                            Thread.sleep(100);
913                                    } catch (final InterruptedException e) {
914                                            // TODO Auto-generated catch block
915                                            e.printStackTrace();
916                                    }
917                            }
918                            if (localExecuter.isRunning()) {
919                                    System.out
920                                                    .println("BAD BAD BAD... still running the thread....");
921                            }
922                            localExecuter.dispose();
923                    }
924                    //
925                    // if (bgImage != null) {
926                    // bgImage = dispose(bgImage);
927                    // bgImage = null;
928                    // // LangUtil.gcTotal();
929                    // }
930                    //
931                    // if (localImage != null) {
932                    // localImage = dispose(localImage);
933                    // localImage = null;
934                    // // LangUtil.gcTotal();
935                    // }
936                    //
937                    // if (finalImage != null) {
938                    // finalImage = dispose(finalImage);
939                    // finalImage = null;
940                    // // LangUtil.gcTotal();
941                    // }
942                    //
943                    // if (preFinalImage != null) {
944                    // preFinalImage = dispose(preFinalImage);
945                    // preFinalImage = null;
946                    // }
947                    disposeImages();
948    
949                    // LangUtil.gcTotal();
950    
951                    // Alle mapPaneListener entfernen
952                    mapPaneListeners.clear();
953    
954                    removeMouseMotionListener(zoomMapPaneMouseListener);
955                    removeMouseListener(zoomMapPaneMouseListener);
956    
957                    if (localContext != null)
958                            getContext().clearLayerList();
959                    if (bgContext != null)
960                            getBgContext().clearLayerList();
961    
962                    removeAll();
963          }          }
964    
965          /**          /**
966           * Retuns the maximum allowed zoom scale. This is the smaller number value           * Draws a rectangle in XOR mode from the origin at {@link #startPos} to the
967           * of the two. Defaults to {@link Double}.MIN_VALUE           * given point. All in screen coordinates.
          *  
          * @author <a href="mailto:[email protected]">Stefan Alfons  
          *         Kr&uuml;ger</a>  
968           */           */
969          public Double getMaxZoomScale() {          protected void drawRectangle(final Graphics graphics, final Point startPos,
970                  return maxZoomScale;                          final Point e) {
971    
972                    if (!isWellDefined())
973                            return;
974    
975                    // undraw last box/draw new box
976                    final int left = Math.min(startPos.x, e.x);
977                    final int right = Math.max(startPos.x, e.x);
978                    final int top = Math.max(startPos.y, e.y);
979                    final int bottom = Math.min(startPos.y, e.y);
980                    final int width = right - left;
981                    final int height = top - bottom;
982    
983                    if (width == 0 && height == 0)
984                            return;
985    
986                    graphics.setXORMode(Color.WHITE);
987                    graphics.drawRect(left, bottom, width, height);
988          }          }
989    
990          /**          /**
991           * Set the maximum allowed zoom scale. This is the smaller number value of           * Diretly paints scaled preview into the {@link SelectableXMapPane}. Used
992           * the two. If <code>null</code> is passed, Double.MINVALUE are used which           * to give the user something to look at while we are rendering. Method
993           * mean there is no restriction.           * should be called after {@link #setMapArea(Envelope)} has been set to the
994             * new mapArea and transform has been reset.<br>
995           *           *
996           * @author <a href="mailto:[email protected]">Stefan Alfons           * @param g
997           *         Kr&uuml;ger</a>           *            Graphics2D to paint the preview into
998             *
999             * @param state
1000             *            Max be {@link #ZOOM_IN} or {@link #ZOOM_OUT}
1001           */           */
1002          public void setMaxZoomScale(final Double maxZoomScale) {          protected boolean drawScaledPreviewImage_Zoom(final Graphics2D graphics) {
1003                  this.maxZoomScale = maxZoomScale == null ? Double.MIN_VALUE  
1004                                  : maxZoomScale;                  if (quickPreviewHint == 0)
1005                            return false;
1006    
1007                    graphics.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
1008                                    RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR);
1009                    graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
1010                                    RenderingHints.VALUE_ANTIALIAS_OFF);
1011                    graphics.setRenderingHint(RenderingHints.KEY_RENDERING,
1012                                    RenderingHints.VALUE_RENDER_SPEED);
1013    
1014                    if (oldMapArea == null)
1015                            return false;
1016    
1017                    final Rectangle visibleArea = getVisibleRect();
1018    
1019                    // Calculate the oldMapArea in the current WindowCoordinates:
1020                    final Envelope oldMapWindow = tranformGeoToWindow(oldMapArea.getMinX(),
1021                                    oldMapArea.getMinY(), oldMapArea.getMaxX(), oldMapArea
1022                                                    .getMaxY(), null);
1023    
1024                    final int xx1 = (int) Math.round(oldMapWindow.getMinX());
1025                    final int yy1 = (int) Math.round(oldMapWindow.getMinY());
1026                    final int xx2 = (int) Math.round(oldMapWindow.getMaxX());
1027                    final int yy2 = (int) Math.round(oldMapWindow.getMaxY());
1028    
1029                    graphics.drawImage(getPreFinalImage(), xx1, yy1, xx2, yy2,
1030                                    (int) visibleArea.getMinX(), (int) visibleArea.getMinY(),
1031                                    (int) visibleArea.getMaxX(), (int) visibleArea.getMaxY(),
1032                                    getMapBackgroundColor(), null);
1033    
1034                    final Rectangle painedArea = new Rectangle(xx1, yy1, xx2 - xx1, yy2
1035                                    - yy1);
1036    
1037                    SwingUtil.clearAround(graphics, painedArea, visibleArea);
1038    
1039                    addGadgets(graphics, true);
1040    
1041                    quickPreviewHint = 0;
1042    
1043                    repaintTimer.restart();
1044    
1045                    graphics.dispose();
1046    
1047                    // Something has been drawn
1048                    return true;
1049            }
1050    
1051            public MapContext getBgContext() {
1052                    return bgContext;
1053          }          }
1054    
1055          /**          /**
1056           * Set the minimum (nearest) allowed zoom scale. This is the bigger number           * Lazyly initializes a {@link BufferedImage} for the background renderer.
1057           * value of the two. If <code>null</code> is passed, Double.MAXVALUE are           */
1058           * used which mean there is no restriction.          private Image getBgImage() {
1059           *                  //
1060                    // if (bgImage == null) {
1061                    // bgImage = createImage(getBounds().width, getBounds().height);
1062                    // }
1063    
1064                    return bgImage;
1065            }
1066    
1067            public MapContext getContext() {
1068                    if (localContext == null) {
1069                            setLocalContext(new DefaultMapContext());
1070                    }
1071                    return localContext;
1072            }
1073    
1074            private BufferedImage getFinalImage() {
1075                    //
1076                    if (finalImage == null) {
1077                            // Rectangle curPaintArea = getVisibleRect();
1078                            finalImage = new BufferedImage(getBounds().width,
1079                                            getBounds().height, IMAGETYPE);
1080    
1081                            requestStartRendering();
1082                    }
1083                    return finalImage;
1084            }
1085    
1086            public RenderingHints getJava2dHints() {
1087                    return java2dHints;
1088            }
1089    
1090            /**
1091             * Lazyly initializes a {@link BufferedImage} for the background renderer.
1092             */
1093            private BufferedImage getLocalImage() {
1094    
1095                    if (localImage == null) {
1096                            localImage = new BufferedImage(getBounds().width,
1097                                            getBounds().height, IMAGETYPE_withAlpha);
1098                    }
1099    
1100                    return localImage;
1101            }
1102    
1103            /**
1104             * Returns a copy of the mapArea
1105           *           *
1106           * @author <a href="mailto:[email protected]">Stefan Alfons           * @return
          *         Kr&uuml;ger</a>  
1107           */           */
1108          public void setMinZoomScale(final Double minZoomScale) {          public ReferencedEnvelope getMapArea() {
1109                  this.minZoomScale = minZoomScale == null ? Double.MAX_VALUE                  if (mapArea == null) {
1110                                  : minZoomScale;                          ReferencedEnvelope mapArea_ = null;
1111                            try {
1112                                    mapArea_ = localContext.getLayerBounds();
1113                            } catch (final IOException e) {
1114                                    LOGGER.warn("context.getLayerBounds()", e);
1115                            }
1116    
1117                            if (mapArea_ != null) {
1118                                    mapImageInvalid = true; /* note we need to redraw */
1119                                    // setMapArea(mapArea_); // results in a loop
1120                                    mapArea = bestAllowedMapArea(mapArea_);
1121                            }
1122                    }
1123    
1124                    if (mapArea == null)
1125                            return null;
1126    
1127                    if (localContext.getCoordinateReferenceSystem() == null)
1128                            try {
1129                                    localContext.setCoordinateReferenceSystem(GeoImportUtil
1130                                                    .getDefaultCRS());
1131                            } catch (TransformException e) {
1132                                    // TODO Auto-generated catch block
1133                                    e.printStackTrace();
1134                            } catch (FactoryException e) {
1135                                    // TODO Auto-generated catch block
1136                                    e.printStackTrace();
1137                            }
1138    
1139                    return new ReferencedEnvelope(mapArea, localContext
1140                                    .getCoordinateReferenceSystem());
1141          }          }
1142    
1143          /**          /**
1144           * Defines an evelope of the viwable area. The JMapPane will never show           * Returns the background {@link Color} of the map pane. Default is white.
1145           * anything outside of this extend.           **/
1146            public Color getMapBackgroundColor() {
1147                    return mapBackgroundColor;
1148            }
1149    
1150            /**
1151             * Get the BufferedImage to use as a flaoting icon in the lower right
1152             * corner.
1153           *           *
1154           * @param maxExtend           * @return <code>null</code> if the feature is deactivated.
          *            <code>null</code> to not have this restriction.  
1155           */           */
1156          public void setMaxExtend(Envelope maxExtend) {          public BufferedImage getMapImage() {
1157                  this.maxExtend = maxExtend;                  return mapImage;
1158          }          }
1159    
1160          /**          /**
# Line 1934  public class XMapPane extends JPanel imp Line 1185  public class XMapPane extends JPanel imp
1185          }          }
1186    
1187          /**          /**
1188           * Set the background color of the map.           * Retuns the maximum allowed zoom scale. This is the smaller number value
1189             * of the two. Defaults to {@link Double}.MIN_VALUE
1190           *           *
1191           * @param if <code>null</code>, white is used.           * @author <a href="mailto:[email protected]">Stefan Alfons
1192             *         Kr&uuml;ger</a>
1193           */           */
1194          public void setMapBackgroundColor(Color bgColor) {          public Double getMaxZoomScale() {
1195                  if (bgColor == null)                  return maxZoomScale;
                         bgColor = Color.WHITE;  
                 this.mapBackgroundColor = bgColor;  
         }  
   
         /**  
          * Returns the background {@link Color} of the map pane. Default is white.  
          **/  
         public Color getMapBackgroundColor() {  
                 return mapBackgroundColor;  
1196          }          }
1197    
1198          /**          /**
1199             * Retuns the minimum allowed zoom scale. This is the bigger number value of
1200             * the two. Defaults to {@link Double}.MAX_VALUE
1201           *           *
1202           * @param b           * @author <a href="mailto:[email protected]">Stefan Alfons
1203             *         Kr&uuml;ger</a>
1204           */           */
1205          public void setPainting(boolean b) {          public Double getMinZoomScale() {
1206                  acceptsRepaintCalls = b;                  return minZoomScale;
1207          }          }
1208    
1209          /**          private Image getPreFinalImage() {
1210           * Fuegt der Map einen Listener hinzu.                  // if (preFinalImage == null) {
1211           *                  //                      
1212           * @param l                  // // Rectangle curPaintArea = getVisibleRect();
1213           *            neuer Listener                  // // preFinalImage = new BufferedImage(curPaintArea.width,
1214           */                  // // curPaintArea.height, BufferedImage.TYPE_INT_RGB);
1215          public void addMapPaneListener(JMapPaneListener l) {                  //                      
1216                  mapPaneListeners.add(l);                  // preFinalImage = createImage(getBounds().width, getBounds().height);
1217                    //
1218                    // requestStartRendering();
1219                    // }
1220                    return preFinalImage;
1221          }          }
1222    
1223          /**          public Map<Object, Object> getRendererHints() {
1224           * Liste der angeschlossenen Listener, die auf Aktionen des MapPanes                  // Clear label cache
1225           * lauschen.                  labelCache.clear();
1226           */                  rendererHints.put(StreamingRenderer.LABEL_CACHE_KEY, labelCache);
         protected Vector<JMapPaneListener> mapPaneListeners = new Vector<JMapPaneListener>();  
1227    
1228          /**                  return rendererHints;
1229           * A flag indicating if dispose() was already called. If true, then further          }
          * use of this {@link SelectableXMapPane} is undefined.  
          */  
         private boolean disposed = false;  
1230    
1231          /**          /**
1232           * Entfernt einen Listener von der Map.           * Liefert eine affine Transformation, um von den Fenster-Koordinaten in die
1233             * Karten-Koordinaten (Lat/Lon) umzurechnen.
1234           *           *
1235           * @param l           * @return eine Kopie der aktuellen Transformation; <code>null</code> wenn
1236           *            zu entfernender Listener           *         noch keine Karte angezeigt wird
1237           */           */
1238          public void removeMapPaneListener(JMapPaneListener l) {          public AffineTransform getScreenToWorld() {
1239                  mapPaneListeners.remove(l);                  if (screenToWorld == null)
1240                            resetTransforms();
1241                    // nur Kopie der Transformation zurueckgeben!
1242                    if (screenToWorld == null)
1243                            return null;
1244                    return new AffineTransform(screenToWorld);
1245          }          }
1246    
1247          /** Stored the time used for the last real rendering in ms. **/          public int getState() {
1248          private long lastRenderingDuration = Long.MAX_VALUE;                  return state;
   
         // if null, no quick preview will be shown  
         private int quickPreviewHint = 0;  
   
         /**  
          * For every rendering thread started,  
          * {@link GTUtil#createGTRenderer(MapContext)} is called to create a new  
          * renderer. These Java2D rendering hints are passed to the  
          * {@link GTRenderer}. The java2dHints are the same for all renderers (bg  
          * and local).  
          */  
         private RenderingHints java2dHints;  
   
         /**  
          * Returns in milli seconds the time the last rending of the  
          * {@link SelectableXMapPane} took. #Long.MAX_VALUE if the JMapPane has not  
          * been rendered yet.  
          */  
         public long getLastRenderingDuration() {  
                 return lastRenderingDuration;  
1249          }          }
1250    
1251          /**          /**
1252           * Should be called when the {@link JMapPane} is not needed no more to help           * Liefert den statisch eingestellten Cursor, der unabhaengig von der
1253           * the GarbageCollector           * eingestellten MapPane-Aktion (Zoom, Auswahl, ...) verwendet wird.
          *  
          * Removes all {@link JMapPaneListener}s that are registered  
1254           *           *
1255           * @author <a href="mailto:[email protected]">Stefan Alfons           * @return {@code null}, wenn kein statischer Cursor verwendet, sondern der
1256           *         Kr&uuml;ger</a>           *         Cursor automatisch je nach MapPane-Aktion eingestellt wird.
1257           */           */
1258          public void dispose() {          public Cursor getStaticCursor() {
1259                  if (isDisposed())                  return this.staticCursor;
1260                          return;          }
                   
                 setPainting(false);  
   
                 disposed = true;  
   
                 if (bgExecuter != null) {  
                         bgExecuter.cancelTask();  
                 }  
1261    
1262                  if (localExecuter != null) {          public AffineTransform getWorldToScreenTransform() {
1263                          localExecuter.cancelTask();                  if (worldToScreen == null) {
1264                            resetTransforms();
1265                  }                  }
1266                    // nur Kopie der Transformation zurueckgeben!
1267                  startRenderThreadsTimer.stop();                  return new AffineTransform(worldToScreen);
 //              repainterTimer.stop();  
   
                 if (bgImage != null)  
                         bgImage.flush();  
                 if (localImage != null)  
                         localImage.flush();  
                 // if (gadgetsImage != null)  
                 // gadgetsImage.flush();  
                 if (finalImage != null)  
                         finalImage.flush();  
                 if (preFinalImage != null)  
                         preFinalImage.flush();  
   
                 // if (dragWaitCursorListener != null)  
                 // this.removeMouseListener(dragWaitCursorListener);  
                 // if (mouseWheelZoomListener != null)  
                 // this.removeMouseWheelListener(mouseWheelZoomListener);  
   
                 // Alle mapPaneListener entfernen  
                 mapPaneListeners.clear();  
   
                 removeMouseMotionListener(zoomMapPaneMouseListener);  
                 removeMouseListener(zoomMapPaneMouseListener);  
   
                 if (localContext != null)  
                         getContext().clearLayerList();  
                 if (bgContext != null)  
                         getBgContext().clearLayerList();  
   
                 removeAll();  
1268          }          }
1269    
1270          /**          /**
# Line 2081  public class XMapPane extends JPanel imp Line 1275  public class XMapPane extends JPanel imp
1275                  return disposed;                  return disposed;
1276          }          }
1277    
         public void setQuickPreviewHint(int quickPreviewHint) {  
                 this.quickPreviewHint = quickPreviewHint;  
   
         }  
   
         public void setJava2dHints(RenderingHints java2dHints) {  
                 this.java2dHints = java2dHints;  
         }  
   
         public RenderingHints getJava2dHints() {  
                 return java2dHints;  
         }  
   
1278          /**          /**
1279           * Zooms towards a point.           * Returns whether a layer is regarded or ignored on {@link #SELECT_TOP},
1280             * {@link #SELECT_ALL} and {@link #SELECT_ONE_FROM_TOP} actions. Returns
1281             * <code>true</code> if the selectability has not been defined.
1282           *           *
1283           * @param center           * @param layer
1284           *            position in window coordinates           *            a layer
          * @param zoomFaktor  
          *            > 1 for zoom in, < 1 for zoom out. Default is 1.33.  
1285           */           */
1286          public void zoomTo(Point center, Double zoomFaktor) {          public boolean isMapLayerSelectable(final MapLayer layer) {
1287                  if (zoomFaktor == null || zoomFaktor == 0.)                  final Boolean selectable = mapLayerSelectable.get(layer);
1288                          zoomFaktor = 2.;                  return selectable == null ? true : selectable;
   
                 Point2D gcenter = getScreenToWorld().transform(center, null);  
                 center = null;  
   
                 if (Double.isNaN(gcenter.getX()) || Double.isNaN(gcenter.getY())  
                                 || Double.isInfinite(gcenter.getX())  
                                 || Double.isInfinite(gcenter.getY())  
   
                 ) {  
                         // Not inside valid CRS area! cancel  
                         return;  
                 }  
   
                 final Envelope mapArea = getMapArea();  
   
                 Envelope newMapArea = new Envelope(mapArea);  
                 newMapArea.expandBy((mapArea.getWidth() * zoomFaktor - mapArea  
                                 .getWidth()) / 2., (mapArea.getHeight() * zoomFaktor - mapArea  
                                 .getHeight()) / 2.);  
   
                 // Move the newMapArea above the new center  
                 newMapArea.translate(gcenter.getX() - mapArea.centre().x, gcenter  
                                 .getY()  
                                 - mapArea.centre().y);  
   
                 setMapArea(newMapArea);  
1289          }          }
1290    
1291          /**          /**
1292           * Zooms towards a point.           * Return <code>true</code> if a CRS and a {@link #mapArea} are set and the
1293           *           * {@link XMapPane} is visible and has bounds set.
          * @param center  
          *            position in window coordinates  
          * @param zoomFactor  
          *            > 1 for zoom in, < 1 for zoom out. Default is 1.33  
1294           */           */
1295          public void zoomTo(Point center) {          public boolean isWellDefined() {
1296                  zoomTo(center, null);  
1297                    try {
1298    
1299                            if (getContext() == null)
1300                                    return false;
1301                            if (getContext().getLayerCount() <= 0)
1302                                    return false;
1303                            if (getMapArea() == null)
1304                                    return false;
1305                            if (getBounds().getWidth() == 0)
1306                                    return false;
1307                            if (getBounds().getHeight() == 0)
1308                                    return false;
1309                    } catch (final Exception e) {
1310                            return false;
1311                    }
1312                    return true;
1313          }          }
1314    
1315          public void mouseDragged(Point startPos, Point lastPos, MouseEvent event) {          public void mouseDragged(final Point startPos, final Point lastPos,
1316                            final MouseEvent event) {
1317    
1318                  if ((getState() == XMapPane.PAN)                  if ((getState() == XMapPane.PAN)
1319                                  || ((event.getModifiersEx() & InputEvent.BUTTON3_DOWN_MASK) != 0)) {                                  || ((event.getModifiersEx() & InputEvent.BUTTON3_DOWN_MASK) != 0)) {
# Line 2215  public class XMapPane extends JPanel imp Line 1383  public class XMapPane extends JPanel imp
1383                                  drawRectangle(graphics, startPos, lastPos);                                  drawRectangle(graphics, startPos, lastPos);
1384                          }                          }
1385    
1386                            graphics.dispose();
1387    
1388                  }                  }
1389    
1390          }          }
1391    
1392          /**          /**
1393           * Draws a rectangle in XOR mode from the origin at {@link #startPos} to the           * Called by the {@link RenderingExecutor} when rendering was cancelled.
          * given point. All in screen coordinates.  
1394           */           */
1395          protected void drawRectangle(final Graphics graphics, Point startPos,          public void onRenderingCancelled() {
1396                          Point e) {                  repaintTimer.stop();
1397                  // undraw last box/draw new box                  LOGGER.debug("Rendering cancelled");
1398                  final int left = Math.min(startPos.x, e.x);          }
                 final int right = Math.max(startPos.x, e.x);  
                 final int top = Math.max(startPos.y, e.y);  
                 final int bottom = Math.min(startPos.y, e.y);  
                 final int width = right - left;  
                 final int height = top - bottom;  
1399    
1400                  if (width == 0 && height == 0)          /**
1401             * Called by the {@link RenderingExecutor} when rendering has been
1402             * completed.
1403             */
1404            public void onRenderingCompleted() {
1405                    repaintTimer.stop();
1406                    updateFinalImage();
1407                    repaint();
1408                    if (renderingErrors.size() > 0)
1409                            renderingErrors.remove(0);
1410            }
1411    
1412            /**
1413             * Called by the {@linkplain XMapPane.RenderingTask} when rendering failed.
1414             * Publishes a {@linkplain MapPaneEvent} of type {@code
1415             * MapPaneEvent.Type.RENDERING_STOPPED} to listeners.
1416             *
1417             * @param renderingError
1418             *            The error that occured during rendering
1419             *
1420             * @see MapPaneListener#onRenderingStopped(org.geotools.swing.event.MapPaneEvent)
1421             */
1422            public void onRenderingFailed(final Exception renderingError) {
1423                    this.renderingErrors.add(renderingError);
1424                    if (renderingErrors.size() > 3)
1425                            renderingErrors.remove(0);
1426                    repaintTimer.stop();
1427                    LOGGER.warn("Rendering failed", renderingError);
1428                    updateFinalImage();
1429                    repaint();
1430    
1431            }
1432    
1433            public void onRenderingPending() {
1434                    // LOGGER.debug("Pending rendering updates the preview...");
1435                    updateFinalImage();
1436                    repaint();
1437            }
1438    
1439            @Override
1440            protected void paintComponent(final Graphics g) {
1441                    if (!acceptsRepaintCalls)
1442                          return;                          return;
1443    
1444                  graphics.setXORMode(Color.WHITE);                  // Maybe update the cursor and maybe stop the repainting timer
1445                  graphics.drawRect(left, bottom, width, height);                  updateCursor();
1446    
1447                    // super.paintComponent(g); // candidate for removal
1448    
1449                    boolean paintedSomething = false;
1450    
1451                    if (mapImageInvalid) { /* if the map changed then redraw */
1452    
1453                            mapImageInvalid = false; // Reset for next round
1454    
1455                            // If the new mapArea and the oldMapArea intersect, we can draw some
1456                            // quick scaled preview to make the user feel that something is
1457                            // happening.
1458                            if (mapAreaChanged && oldMapArea != null
1459                                            && getMapArea().intersects(oldMapArea)
1460                                            & !getMapArea().equals(oldMapArea)) {
1461    
1462                                    mapAreaChanged = false;
1463    
1464                                    if (getMapArea().covers(oldMapArea)) {
1465                                            setQuickPreviewHint(ZOOM_OUT);
1466                                            paintedSomething = drawScaledPreviewImage_Zoom((Graphics2D) g);
1467                                    } else if (oldMapArea.covers(getMapArea())) {
1468                                            setQuickPreviewHint(ZOOM_IN);
1469                                            paintedSomething = drawScaledPreviewImage_Zoom((Graphics2D) g);
1470                                    }
1471    
1472                            }
1473    
1474                            if (paneResized) {
1475                                    paneResized = false;
1476                                    disposeImages();
1477                            }
1478    
1479                            // Start the Threads and Timers to render the image
1480                            requestStartRendering();
1481    
1482                    }
1483    
1484                    if (!paintedSomething) {
1485    
1486                            g.drawImage(getFinalImage(), 0, 0, null);
1487    
1488                            g.dispose(); // cand. for removal
1489    
1490                            paintedSomething = true; // cand. for removal
1491                    }
1492    
1493            }
1494    
1495            /**
1496             * Heavily works on releasing all resources related to the four
1497             * {@link Image}s used to cache the results of the different renderers.<br>
1498             * In November 2009 i had some memory leaking problems with {@link XMapPane}
1499             * . The resources of the buffered images were never released. It seem to be
1500             * important to call the GC right after flushing the images.<br>
1501             * Hence this method may take a while, because it calls the GC up to four
1502             * times.
1503             */
1504            private void disposeImages() {
1505    
1506                    // System.out.println("vorher = "
1507                    // + new MbDecimalFormatter().format(LangUtil.gcTotal()));
1508                    // bi.flush();
1509                    // return bi = null;
1510                    // System.out.println("nacher = "
1511                    // + new MbDecimalFormatter().format(LangUtil.gcTotal()));
1512                    //
1513                    // System.out.println("\n");
1514    
1515                    if (preFinalImage != null) {
1516                            preFinalImage.flush();
1517                            preFinalImage = null;
1518                            LangUtil.gc();
1519                    }
1520                    if (finalImage != null) {
1521                            finalImage.flush();
1522                            finalImage = null;
1523                            LangUtil.gc();
1524                    }
1525                    if (localImage != null) {
1526                            localImage.flush();
1527                            localImage = null;
1528                            LangUtil.gc();
1529                    }
1530                    if (bgImage != null) {
1531                            bgImage.flush();
1532                            bgImage = null;
1533                            LangUtil.gc();
1534                    }
1535    
1536          }          }
1537    
1538          /**          /**
1539           * Finalizes a PAN action           * Performs a {@value #PAN} action. During panning, the displacement is
1540             * stored in {@link #imageOrigin} object. Calling {@link #performPan()} will
1541             * reset the offset and call {@link #setMapArea(Envelope)}.
1542           */           */
1543          public void performPan() {          public void performPan() {
1544                  Rectangle winBounds = getBounds();  
1545                    final Rectangle winBounds = getBounds();
1546                  winBounds.translate(-imageOrigin.x, -imageOrigin.y);                  winBounds.translate(-imageOrigin.x, -imageOrigin.y);
1547                  Envelope newMapArea = tranformWindowToGeo(winBounds.x, winBounds.y,                  final Envelope newMapArea = tranformWindowToGeo(winBounds.x,
1548                                  winBounds.x + winBounds.width, winBounds.y + winBounds.height);                                  winBounds.y, winBounds.x + winBounds.width, winBounds.y
1549                                                    + winBounds.height);
1550    
1551                  imageOrigin.x = 0;                  imageOrigin.x = 0;
1552                  imageOrigin.y = 0;                  imageOrigin.y = 0;
1553    
1554                  if (!setMapArea(newMapArea)) {                  if (!setMapArea(newMapArea)) {
1555                            /**
1556                             * If setMapArea returns true, the finalImage is updated anyways.
1557                             * This if-case exists to ensure that we repaint a correct image
1558                             * even if the new panning area has been denied.
1559                             */
1560                          updateFinalImage();                          updateFinalImage();
1561                          repaint();                          repaint();
1562                  }                  }
# Line 2261  public class XMapPane extends JPanel imp Line 1565  public class XMapPane extends JPanel imp
1565                          setCursor(SwingUtil.PAN_CURSOR);                          setCursor(SwingUtil.PAN_CURSOR);
1566          }          }
1567    
1568          public void onRenderingPending() {          //
1569                  LOGGER.debug("Pending rendering updates the preview...");          // /**
1570                  updateFinalImage();          // * Nuetzlich wenn die Componente gedruckt (z.B. wenn ein Screenshot
1571                  XMapPane.this.repaint();          // gemacht
1572            // * wird) wird. Dann werden wird der Hintergrund auf WEISS gesetzt.
1573            // *
1574            // * @author <a href="mailto:[email protected]">Stefan Alfons
1575            // * Kr&uuml;ger</a>
1576            // */
1577            // @Override
1578            // public void print(final Graphics g) {
1579            // final Color orig = getBackground();
1580            // setBackground(Color.WHITE);
1581            //
1582            // // wrap in try/finally so that we always restore the state
1583            // try {
1584            // super.print(g);
1585            // } finally {
1586            // setBackground(orig);
1587            // }
1588            // }
1589    
1590            /**
1591             * Entfernt einen Listener von der Map.
1592             *
1593             * @param l
1594             *            zu entfernender Listener
1595             */
1596            public void removeMapPaneListener(final JMapPaneListener l) {
1597                    mapPaneListeners.remove(l);
1598            }
1599    
1600            /**
1601             * Cancels all running renderers and sets the flag to start new ones. <br>
1602             *
1603             * @see #startRenderThreadsTimer
1604             */
1605            private void requestStartRendering() {
1606                    if (bgExecuter != null)
1607                            bgExecuter.cancelTask();
1608                    if (localExecuter != null)
1609                            localExecuter.cancelTask();
1610                    requestStartRendering = true;
1611    
1612            }
1613    //
1614    //      /**
1615    //       * Berechnet die Transformation zwischen Fenster- und Karten-Koordinaten
1616    //       * neu.
1617    //       */
1618    //      protected void resetTransforms() {
1619    //              if (getMapArea() == null || getWidth() == 0 || getHeight() == 0)
1620    //                      return;
1621    //
1622    //              // We store the last Transform
1623    //              oldScreenToWorld = screenToWorld;
1624    //
1625    //              this.screenToWorld = new AffineTransform(
1626    //              // Genauso wie die Fenster-Koordinaten, werden die Longitude-Koordinaten
1627    //                              // nach rechts (Osten) hin groesser
1628    //                              // --> positive Verschiebung
1629    //                              getMapArea().getWidth() / getWidth(),
1630    //                              // keine Verzerrung
1631    //                              0.0, 0.0,
1632    //                              // Waehrend die Fenster-Koordinaten nach unten hin groesser
1633    //                              // werden,
1634    //                              // werden Latitude-Koordinaten nach Sueden hin keiner
1635    //                              // --> negative Verschiebung
1636    //                              -getMapArea().getHeight() / getHeight(),
1637    //                              // Die Longitude-Koordinaten werden nach Osten hin groesser
1638    //                              // --> obere linke Ecke des Fensters hat also den Minimalwert
1639    //                              getMapArea().getMinX(),
1640    //                              // Die Latitude-Koordinaten werden nach Norden hin groesser
1641    //                              // --> obere linke Ecke des Fensters hat also den Maximalwert
1642    //                              getMapArea().getMaxY());
1643    //
1644    //              try {
1645    //                      this.worldToScreen = screenToWorld.createInverse();
1646    //              } catch (final NoninvertibleTransformException e) {
1647    //                      LOGGER.error(e);
1648    //              }
1649    //      }
1650            
1651            
1652    
1653        /**
1654         * Calculate the affine transforms used to convert between
1655         * world and pixel coordinates. The calculations here are very
1656         * basic and assume a cartesian reference system.
1657         * <p>
1658         * Tne transform is calculated such that {@code envelope} will
1659         * be centred in the display
1660         *
1661         * @param envelope the current map extent (world coordinates)
1662         * @param paintArea the current map pane extent (screen units)
1663         */
1664        private void resetTransforms() {
1665            ReferencedEnvelope refEnv = new ReferencedEnvelope(mapArea, getContext().getCoordinateReferenceSystem());
1666    
1667            Rectangle paintArea = getBounds();
1668            
1669            double xscale = paintArea.getWidth() / refEnv.getWidth();
1670            double yscale = paintArea.getHeight() / refEnv.getHeight();
1671    
1672            double scale = Math.min(xscale, yscale);
1673    
1674            double xoff = refEnv.getMedian(0) * scale - paintArea.getCenterX();
1675            double yoff = refEnv.getMedian(1) * scale + paintArea.getCenterY();
1676    
1677            worldToScreen = new AffineTransform(scale, 0, 0, -scale, -xoff, yoff);
1678            try {
1679                screenToWorld = worldToScreen.createInverse();
1680    
1681            } catch (NoninvertibleTransformException ex) {
1682                ex.printStackTrace();
1683            }
1684        }
1685            
1686            
1687    
1688            public void setBgContext(final MapContext context) {
1689    
1690                    // Remove the default listener from the old context
1691                    if (this.bgContext != null) {
1692                            this.bgContext.removeMapLayerListListener(bgContextListener);
1693    
1694                            // adding listener to all layers
1695                            for (final MapLayer mapLayer : bgContext.getLayers()) {
1696                                    mapLayer.removeMapLayerListener(bgMapLayerListener);
1697                            }
1698                    }
1699    
1700                    this.bgContext = context;
1701    
1702                    if (context != null) {
1703                            setMapArea(bgContext.getAreaOfInterest());
1704    
1705                            this.bgContext.addMapLayerListListener(bgContextListener);
1706    
1707                            // adding listener to all layers
1708                            for (final MapLayer mapLayer : bgContext.getLayers()) {
1709                                    mapLayer.addMapLayerListener(bgMapLayerListener);
1710                            }
1711                    }
1712                    mapImageInvalid = true;
1713                    repaint();
1714            }
1715    
1716            public void setJava2dHints(final RenderingHints java2dHints) {
1717                    this.java2dHints = java2dHints;
1718            }
1719    
1720            /**
1721             *
1722             * @param context
1723             */
1724            public void setLocalContext(final MapContext context) {
1725                    // Remove the default listener from the old context
1726                    if (this.localContext != null) {
1727                            this.localContext.removeMapLayerListListener(localContextListener);
1728    
1729                            // adding listener to all layers
1730                            for (final MapLayer mapLayer : localContext.getLayers()) {
1731                                    mapLayer.removeMapLayerListener(localMapLayerListener);
1732                            }
1733                    }
1734    
1735                    this.localContext = context;
1736    
1737                    if (context != null) {
1738    
1739                            setMapArea(localContext.getAreaOfInterest());
1740    
1741                            localRenderer.setContext(localContext);
1742    
1743                            this.localContext.addMapLayerListListener(localContextListener);
1744    
1745                            // adding listener to all layers
1746                            for (final MapLayer mapLayer : localContext.getLayers()) {
1747                                    mapLayer.addMapLayerListener(localMapLayerListener);
1748                            }
1749                    }
1750    
1751                    mapImageInvalid = true;
1752                    repaint();
1753            }
1754    
1755            /**
1756             * @param newMapArea
1757             * @return <code>true</code> if the mapArea has been changed and a repaint
1758             *         has been triggered.
1759             */
1760            public boolean setMapArea(final Envelope newMapArea) {
1761    
1762                    if (newMapArea == null
1763                                    || bestAllowedMapArea(newMapArea).equals(mapArea)) {
1764                            // No change.. no need to repaint
1765                            return false;
1766                    }
1767    
1768                    // Testing, whether NaN or Infinity are used in the newMapArea
1769                    if (newMapArea.isNull() || Double.isInfinite(newMapArea.getMaxX())
1770                                    || Double.isInfinite(newMapArea.getMaxY())
1771                                    || Double.isInfinite(newMapArea.getMinX())
1772                                    || Double.isInfinite(newMapArea.getMinY())) {
1773                            // No change.. ugly new values
1774                            LOGGER.warn("setMapArea has been called with newArea = "
1775                                            + newMapArea);
1776                            return false;
1777                    }
1778    
1779                    // Testing, whether the difference if just minimal
1780                    if (mapArea != null) {
1781                            final Envelope candNew = bestAllowedMapArea(newMapArea);
1782                            final double tolX = mapArea.getWidth() / 1000.;
1783                            final double tolY = mapArea.getHeight() / 1000.;
1784                            if ((candNew.getMinX() - tolX < mapArea.getMinX())
1785                                            && (mapArea.getMinX() < candNew.getMinX() + tolX)
1786                                            && (candNew.getMaxX() - tolX < mapArea.getMaxX())
1787                                            && (mapArea.getMaxX() < candNew.getMaxX() + tolX)
1788    
1789                                            && (candNew.getMinY() - tolY < mapArea.getMinY())
1790                                            && (mapArea.getMinY() < candNew.getMinY() + tolY)
1791                                            && (candNew.getMaxY() - tolY < mapArea.getMaxY())
1792                                            && (mapArea.getMaxY() < candNew.getMaxY() + tolY)
1793    
1794                            ) {
1795                                    // The two mapAreas only differ my 1/1000th.. ignore
1796    
1797                                    return false;
1798                            }
1799                    }
1800    
1801                    oldMapArea = mapArea;
1802    
1803                    this.mapArea = bestAllowedMapArea(newMapArea);
1804    
1805                    if (localContext != null) {
1806                            localContext.setAreaOfInterest(mapArea, localContext
1807                                            .getCoordinateReferenceSystem());
1808                    }
1809                    if (bgContext != null) {
1810                            bgContext.setAreaOfInterest(mapArea, localContext
1811                                            .getCoordinateReferenceSystem());
1812                    }
1813                    resetTransforms();
1814                    mapImageInvalid = true;
1815                    mapAreaChanged = true;
1816                    repaint();
1817    
1818                    // LOGGER.debug("New maparea = " + mapArea);
1819                    return true;
1820            }
1821    
1822            /**
1823             * Set the background color of the map.
1824             *
1825             * @param if <code>null</code>, white is used.
1826             */
1827            public void setMapBackgroundColor(Color bgColor) {
1828                    if (bgColor == null)
1829                            bgColor = Color.WHITE;
1830                    this.mapBackgroundColor = bgColor;
1831            }
1832    
1833            /**
1834             * Set the BufferedImage to use as a flaoting icon in the lower right corner
1835             *
1836             * @param mapImageIcon
1837             *            <code>null</code> is allowed and deactivates this icon.
1838             */
1839            public void setMapImage(final BufferedImage mapImage) {
1840                    this.mapImage = mapImage;
1841            }
1842    
1843            /**
1844             * Sets whether a layer is regarded or ignored on {@link #SELECT_TOP},
1845             * {@link #SELECT_ALL} and {@link #SELECT_ONE_FROM_TOP} actions.
1846             *
1847             * @param layer
1848             *            a layer
1849             * @param selectable
1850             *            if {@code false} the layer is ignored during the upper
1851             *            mentioned actions. If <code>null</code>, the default (true)
1852             *            will be used.
1853             */
1854            public void setMapLayerSelectable(final MapLayer layer,
1855                            final Boolean selectable) {
1856                    if (selectable == null)
1857                            mapLayerSelectable.remove(layer);
1858                    else
1859                            mapLayerSelectable.put(layer, selectable);
1860            }
1861    
1862            /**
1863             * Defines an evelope of the viwable area. The JMapPane will never show
1864             * anything outside of this extend.
1865             *
1866             * @param maxExtend
1867             *            <code>null</code> to not have this restriction.
1868             */
1869            public void setMaxExtend(final Envelope maxExtend) {
1870                    this.maxExtend = maxExtend;
1871            }
1872    
1873            /**
1874             * Set the maximum allowed zoom scale. This is the smaller number value of
1875             * the two. If <code>null</code> is passed, Double.MINVALUE are used which
1876             * mean there is no restriction.
1877             *
1878             * @author <a href="mailto:[email protected]">Stefan Alfons
1879             *         Kr&uuml;ger</a>
1880             */
1881            public void setMaxZoomScale(final Double maxZoomScale) {
1882                    this.maxZoomScale = maxZoomScale == null ? Double.MIN_VALUE
1883                                    : maxZoomScale;
1884            }
1885    
1886            // /** Stored the time used for the last real rendering in ms. **/
1887            // private long lastRenderingDuration = Long.MAX_VALUE;
1888    
1889            /**
1890             * Set the minimum (nearest) allowed zoom scale. This is the bigger number
1891             * value of the two. If <code>null</code> is passed, Double.MAXVALUE are
1892             * used which mean there is no restriction.
1893             *
1894             *
1895             * @author <a href="mailto:[email protected]">Stefan Alfons
1896             *         Kr&uuml;ger</a>
1897             */
1898            public void setMinZoomScale(final Double minZoomScale) {
1899                    this.minZoomScale = minZoomScale == null ? Double.MAX_VALUE
1900                                    : minZoomScale;
1901            }
1902    
1903            /**
1904             *
1905             * @param b
1906             */
1907            public void setPainting(final boolean b) {
1908                    acceptsRepaintCalls = b;
1909            }
1910    
1911            // /**
1912            // * Returns in milli seconds the time the last rending of the
1913            // * {@link SelectableXMapPane} took. #Long.MAX_VALUE if the JMapPane has
1914            // not
1915            // * been rendered yet.
1916            // */
1917            // public long getLastRenderingDuration() {
1918            // return lastRenderingDuration;
1919            // }
1920    
1921            public void setQuickPreviewHint(final int quickPreviewHint) {
1922                    this.quickPreviewHint = quickPreviewHint;
1923    
1924            }
1925    
1926            private void setRendererHints(final Map<Object, Object> rendererHints) {
1927                    if (rendererHints != null)
1928                            this.rendererHints = rendererHints;
1929            }
1930    
1931            /**
1932             * Enables/Disables the ZOOM Mouse Listener. Upates the Cursor and stops the
1933             * repaint Timer if
1934             *
1935             * @param state
1936             */
1937            public void setState(final int state) {
1938                    this.state = state;
1939    
1940                    zoomMapPaneMouseListener.setEnabled((state == ZOOM_IN
1941                                    || state == ZOOM_OUT || state == PAN));
1942    
1943                    // Je nach Aktion den Cursor umsetzen
1944                    updateCursor();
1945            }
1946    
1947            /**
1948             * Standardmaessig wird der Cursor automatisch je nach MapPane-Aktion (Zoom,
1949             * Auswahl, ...) gesetzt. Mit dieser Methode kann ein statischer Cursor
1950             * gesetzt werden, der unabhaengig von der aktuellen MapPanes-Aktion
1951             * beibehalten wird. Um diesen statischen Cursor wieder zu entfernen, kann
1952             * {@code null} als Parameter uebergeben werden
1953             *
1954             * @param cursor
1955             *            Cursor
1956             */
1957            public void setStaticCursor(final Cursor cursor) {
1958                    this.staticCursor = cursor;
1959                    if (cursor != null)
1960                            super.setCursor(cursor);
1961            }
1962    
1963            /**
1964             * Starts rendering on one or two threads
1965             */
1966            private void startRendering() {
1967    
1968                    if (!isWellDefined())
1969                            return;
1970    
1971                    if (bgExecuter != null) {
1972                            // Stop all renderers
1973                            bgExecuter.cancelTask();
1974                    }
1975    
1976                    if (localExecuter != null) {
1977                            localExecuter.cancelTask();
1978                    }
1979    
1980                    final Rectangle curPaintArea = getVisibleRect();
1981    
1982                    /**
1983                     * We have to set new renderer
1984                     */
1985    
1986                    if (getBgContext() != null) {
1987                            bgRenderer.setJava2DHints(getJava2dHints());
1988                            bgRenderer.setRendererHints(getRendererHints());
1989    
1990                            // bgExecuter = new RenderingExecutor();
1991                            // LOGGER.debug("starting bg renderer:");
1992                            // // /* System.out.println("rendering"); */
1993                            // final GTRenderer createGTRenderer = GTUtil.createGTRenderer(
1994                            // bgContext, getRendererHints());
1995                            // createGTRenderer.setJava2DHints(getJava2dHints());
1996                            // bgExecuter.submit(getBgContext().getAreaOfInterest(),
1997                            // curPaintArea,
1998                            // (Graphics2D) getBgImage().getGraphics(), createGTRenderer);
1999                    }
2000    
2001                    if (getContext() != null) {
2002                            // localExecuter = new RenderingExecutor(this, 150l);
2003                            // LOGGER.debug("starting local renderer:");
2004    
2005                            localRenderer.setJava2DHints(getJava2dHints());
2006                            localRenderer.setRendererHints(getRendererHints());
2007    
2008                            ReferencedEnvelope areaOfInterest = getMapArea();
2009                            final boolean submitted = localExecuter.submit(areaOfInterest,
2010                                            curPaintArea, (Graphics2D) getLocalImage().getGraphics(),
2011                                            localRenderer, getWorldToScreenTransform());
2012                            if (submitted)
2013                                    repaintTimer.restart();
2014                            else
2015                                    requestStartRendering = true; // Try to start rendering again in
2016                            // a moment
2017                    }
2018    
2019                    updateCursor();
2020            }
2021    
2022            /**
2023             * Transformiert einen Geo-Koordinaten-Bereich in Fenster-Koordinaten.
2024             *
2025             * @param ox
2026             *            X-Koordinate der VON-Position
2027             * @param oy
2028             *            Y-Koordinate der VON-Position
2029             * @param px
2030             *            X-Koordinate der BIS-Position
2031             * @param py
2032             *            Y-Koordinate der BIS-Position
2033             * @param winToGeotransform
2034             *            Eine Window to Geo transform. If <code>null</code>,
2035             *            {@link #getScreenToWorld()} is used.
2036             */
2037            public Envelope tranformGeoToWindow(final double ox, final double oy,
2038                            final double px, final double py,
2039                            final AffineTransform winToGeotransform) {
2040                    final AffineTransform at = winToGeotransform == null ? getScreenToWorld()
2041                                    : winToGeotransform;
2042                    Point2D geoO;
2043                    try {
2044                            geoO = at.inverseTransform(new Point2D.Double(ox, oy), null);
2045                            final Point2D geoP = at.inverseTransform(
2046                                            new Point2D.Double(px, py), null);
2047                            return new Envelope(geoO.getX(), geoP.getX(), geoO.getY(), geoP
2048                                            .getY());
2049                    } catch (final NoninvertibleTransformException e) {
2050                            LOGGER.error(e);
2051                            return new Envelope(ox, oy, px, py);
2052                    }
2053            }
2054    
2055            /**
2056             * Transformiert einen Fenster-Koordinaten-Bereich in Geo-Koordinaten.
2057             *
2058             * @param ox
2059             *            X-Koordinate der VON-Position
2060             * @param oy
2061             *            Y-Koordinate der VON-Position
2062             * @param px
2063             *            X-Koordinate der BIS-Position
2064             * @param py
2065             *            Y-Koordinate der BIS-Position
2066             */
2067            public Envelope tranformWindowToGeo(final int ox, final int oy,
2068                            final int px, final int py) {
2069                    final AffineTransform at = getScreenToWorld();
2070                    final Point2D geoO = at.transform(new Point2D.Double(ox, oy), null);
2071                    final Point2D geoP = at.transform(new Point2D.Double(px, py), null);
2072                    return new Envelope(geoO.getX(), geoP.getX(), geoO.getY(), geoP.getY());
2073            }
2074    
2075            /**
2076             * Will update the cursor. If all rendering is finished also stops the
2077             * {@link #repaintTimer}
2078             */
2079            public void updateCursor() {
2080    
2081                    // if the renderers have stopped, also stop the timer that is updating
2082                    // the final image
2083                    if (bgExecuter != null && bgExecuter.isRunning()
2084                                    || localExecuter != null && localExecuter.isRunning()) {
2085                            setCursor(WAIT_CURSOR);
2086                            return;
2087                    } else {
2088                            // Allow one last rendering
2089                            if (repaintTimer.isRunning()) {
2090                                    System.out.println("one last rendering....");
2091                                    repaintTimer.stop();
2092                                    updateFinalImage();
2093                                    repaint();
2094                            }
2095                    }
2096    
2097                    // wenn manueller Cursor gesetzt ist, dann diesen verwenden (unabhaengig
2098                    // von der aktuellen Aktion
2099                    if (this.staticCursor != null) {
2100                            setCursor(staticCursor);
2101                            return;
2102                    }
2103                    if (getCursor() == SwingUtil.PANNING_CURSOR) {
2104                            // This cursor will reset itself
2105                            return;
2106                    }
2107    
2108                    // Set the cursor depending on what tool is in use...
2109                    switch (state) {
2110                    case SELECT_TOP:
2111                    case SELECT_ONE_FROM_TOP:
2112                    case SELECT_ALL:
2113                            setCursor(SwingUtil.CROSSHAIR_CURSOR);
2114                            break;
2115                    case ZOOM_IN:
2116                            setCursor(SwingUtil.ZOOMIN_CURSOR);
2117                            break;
2118                    case ZOOM_OUT:
2119                            setCursor(SwingUtil.ZOOMOUT_CURSOR);
2120                            break;
2121                    case PAN:
2122                            setCursor(SwingUtil.PAN_CURSOR);
2123                            break;
2124                    default:
2125                            setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
2126                            break;
2127                    }
2128            }
2129    
2130            /**
2131             * The renderers are all rendering into their own {@link Image}s. This
2132             * method combines all images to one {@link #finalImage}. The
2133             * {@link #repaintTimer} is calling this method regularely to update the
2134             * {@link #finalImage} even if the renderers are still working.
2135             */
2136            synchronized protected Image updateFinalImage() {
2137    
2138                    // Render the two map images first, into the preFinalImage
2139                    if (bgExecuter != null) {
2140                            final Graphics2D preFinalG = (Graphics2D) getPreFinalImage()
2141                                            .getGraphics();
2142                            preFinalG.setBackground(getMapBackgroundColor());
2143    
2144                            preFinalG.drawImage(getBgImage(), 0, 0, getMapBackgroundColor(),
2145                                            null);
2146    
2147                            // // Draw the local layers image
2148                            preFinalG.drawImage(getLocalImage(), 0, 0, null);
2149                            preFinalG.dispose();
2150    
2151                    } else {
2152                            preFinalImage = getLocalImage();
2153                    }
2154    
2155                    final Graphics2D finalG = getFinalImage().createGraphics();
2156                    finalG.setBackground(getMapBackgroundColor());
2157                    finalG.drawImage(getPreFinalImage(), imageOrigin.x, imageOrigin.y,
2158                                    getMapBackgroundColor(), null);
2159    
2160                    final int finalImageHeight = getFinalImage().getHeight(null);
2161                    final int finalImageWidth = getFinalImage().getWidth(null);
2162    
2163                    final Rectangle painedArea = new Rectangle(imageOrigin.x,
2164                                    imageOrigin.y, finalImageWidth, finalImageHeight);
2165                    SwingUtil.clearAround(finalG, painedArea, getVisibleRect());
2166    
2167                    addGadgets(finalG, false);
2168    
2169                    finalG.dispose();
2170    
2171                    return finalImage;
2172            }
2173    
2174            /**
2175             * Paints some optional stuff into the given {@link Graphics2D}. Usually
2176             * called as the last layer when {@link #updateFinalImage()}
2177             *
2178             * @param forceWait
2179             *            if <code>true</code>, a Wait-message will be painted even
2180             *            though the rendering threads may not yet have started. If
2181             *            <code>false</code>, it will only depend on
2182             *            {@link #localExecuter.isRunning} and #bgExecuter.isRunning
2183             */
2184            private void addGadgets(final Graphics2D graphics, boolean forceWait) {
2185    
2186                    // Paint a logo to the bottom right if available
2187                    if (mapImage != null) {
2188                            graphics.drawImage(mapImage, getBounds().width
2189                                            - mapImage.getWidth() - 10, getBounds().height
2190                                            - mapImage.getHeight() - 10, null);
2191                    }
2192                    
2193                    
2194                    int y = 17;
2195    
2196                    // If the rendering process is still running, indicate this is the image
2197                    if (forceWait || bgExecuter != null && bgExecuter.isRunning()
2198                                    || localExecuter != null && localExecuter.isRunning()) {
2199                            
2200                            y+=8;
2201    
2202                            final Color c = graphics.getColor();
2203                            graphics.setFont(waitFont);
2204    //                      String waitStr = "Wait..."; // i8n
2205    
2206                            graphics.setColor(getMapBackgroundColor());
2207                            graphics.drawString(waitMsg, 5, y);
2208                            graphics.setColor(getMapBackgroundColor());
2209                            graphics.drawString(waitMsg, 7, y+2);
2210                            graphics.setColor(Color.BLACK);
2211                            graphics.drawString(waitMsg, 6, y+1);
2212    
2213                            graphics.setColor(c);
2214                            
2215                            y += 24;
2216                    }
2217    
2218                    if (renderingErrors != null) {
2219    
2220                            final Color c = graphics.getColor();
2221                            graphics.setFont(errorFont);
2222    
2223                            for (Exception ex : renderingErrors) {
2224    
2225                                    if (ex instanceof java.lang.IllegalArgumentException
2226                                                    && ex.getMessage().equals(
2227                                                                    "Argument \"sourceCRS\" should not be null."))
2228                                            continue;
2229    
2230                                    String errStr = ex.getLocalizedMessage();
2231    
2232                                    graphics.setColor(Color.WHITE);
2233                                    graphics.drawString(errStr, 5, y);
2234                                    graphics.setColor(Color.RED);
2235                                    graphics.drawString(errStr, 6, y + 1);
2236    
2237                                    y += 19;
2238                            }
2239    
2240                            graphics.setColor(c);
2241                    }
2242    
2243            }
2244    
2245            /**
2246             * Sets the {@link #mapArea} to best possibly present the given features. If
2247             * only one single point is given, the window is moved over the point.
2248             *
2249             * @param features
2250             *            if <code>null</code> or size==0, the function doesn nothing.
2251             */
2252            public void zoomTo(
2253                            final FeatureCollection<SimpleFeatureType, SimpleFeature> features) {
2254    
2255                    final CoordinateReferenceSystem mapCRS = getContext()
2256                                    .getCoordinateReferenceSystem();
2257                    final CoordinateReferenceSystem fCRS = features.getSchema()
2258                                    .getGeometryDescriptor().getCoordinateReferenceSystem();
2259    
2260                    double width = mapArea.getWidth();
2261                    double height = mapArea.getHeight();
2262                    final double ratio = height / width;
2263    
2264                    if (features == null || features.size() == 0) {
2265                            // feature count == 0 Zoom to the full extend
2266                            return;
2267                    } else if (features.size() == 1) {
2268    
2269                            // feature count == 1 Just move the window to the point and zoom 'a
2270                            // bit'
2271                            final SimpleFeature singleFeature = features.iterator().next();
2272    
2273                            if (((Geometry) singleFeature.getDefaultGeometry())
2274                                            .getCoordinates().length > 1) {
2275                                    // System.out.println("Zoomed to only pne poylgon");
2276                                    // Poly
2277                                    // TODO max width vs. height
2278                                    width = features.getBounds().getWidth() * 3;
2279                                    height = ratio * width;
2280                            } else {
2281                                    // System.out.println("Zoomed in a bit becasue only one point");
2282                                    // width *= .9;
2283                                    // height *= .9;
2284                            }
2285    
2286                            Coordinate centre = features.getBounds().centre();
2287                            if (!mapCRS.equals(fCRS)) {
2288                                    // only to calculations if the CRS differ
2289                                    try {
2290                                            MathTransform fToMap;
2291                                            fToMap = CRS.findMathTransform(fCRS, mapCRS);
2292                                            // centre is transformed to the mapCRS
2293                                            centre = JTS.transform(centre, null, fToMap);
2294                                    } catch (final FactoryException e) {
2295                                            LOGGER.error("Looking for a Math transform", e);
2296                                    } catch (final TransformException e) {
2297                                            LOGGER.error("Looking for a Math transform", e);
2298                                    }
2299                            }
2300    
2301                            final Coordinate newLeftBottom = new Coordinate(centre.x - width
2302                                            / 2., centre.y - height / 2.);
2303                            final Coordinate newTopRight = new Coordinate(
2304                                            centre.x + width / 2., centre.y + height / 2.);
2305    
2306                            final Envelope newMapArea = new Envelope(newLeftBottom, newTopRight);
2307    
2308                            setMapArea(newMapArea);
2309    
2310                    } else {
2311                            final ReferencedEnvelope fBounds = features.getBounds();
2312    
2313                            Envelope bounds;
2314                            if (!mapCRS.equals(fCRS)) {
2315                                    bounds = JTSUtil.transformEnvelope(fBounds, fCRS, mapCRS);
2316                            } else {
2317                                    bounds = fBounds;
2318                            }
2319                            // BB umrechnen von Layer-CRS in Map-CRS
2320    
2321                            // Expand a bit
2322                            bounds.expandBy(bounds.getWidth() / 6., bounds.getHeight() / 6.);
2323    
2324                            setMapArea(bounds);
2325                    }
2326            }
2327    
2328            /**
2329             * Zooms towards a point.
2330             *
2331             * @param center
2332             *            position in window coordinates
2333             * @param zoomFactor
2334             *            > 1 for zoom in, < 1 for zoom out. Default is 1.33
2335             */
2336            public void zoomTo(final Point center) {
2337                    zoomTo(center, null);
2338            }
2339    
2340            /**
2341             * Zooms towards a point.
2342             *
2343             * @param center
2344             *            position in window coordinates
2345             * @param zoomFaktor
2346             *            > 1 for zoom in, < 1 for zoom out. Default is 1.33.
2347             */
2348            public void zoomTo(Point center, Double zoomFaktor) {
2349                    if (zoomFaktor == null || zoomFaktor == 0.)
2350                            zoomFaktor = 2.;
2351    
2352                    final Point2D gcenter = getScreenToWorld().transform(center, null);
2353                    center = null;
2354    
2355                    if (Double.isNaN(gcenter.getX()) || Double.isNaN(gcenter.getY())
2356                                    || Double.isInfinite(gcenter.getX())
2357                                    || Double.isInfinite(gcenter.getY())
2358    
2359                    ) {
2360                            // Not inside valid CRS area! cancel
2361                            return;
2362                    }
2363    
2364                    final Envelope mapArea = getMapArea();
2365    
2366                    final Envelope newMapArea = new Envelope(mapArea);
2367                    newMapArea.expandBy((mapArea.getWidth() * zoomFaktor - mapArea
2368                                    .getWidth()) / 2., (mapArea.getHeight() * zoomFaktor - mapArea
2369                                    .getHeight()) / 2.);
2370    
2371                    // Move the newMapArea above the new center
2372                    newMapArea.translate(gcenter.getX() - mapArea.centre().x, gcenter
2373                                    .getY()
2374                                    - mapArea.centre().y);
2375    
2376                    setMapArea(newMapArea);
2377          }          }
2378    
2379  }  }

Legend:
Removed from v.516  
changed lines
  Added in v.536

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26