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

Legend:
Removed from v.512  
changed lines
  Added in v.545

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26