/[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

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

Legend:
Removed from v.511  
changed lines
  Added in v.530

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26