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

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

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

branches/1.0-gt2-2.6/src/org/geotools/gui/swing/JMapPane.java revision 318 by alfonx, Wed Aug 26 13:33:32 2009 UTC branches/1.0-gt2-2.6/src/gtmig/org/geotools/swing/XMapPane.java revision 530 by alfonx, Thu Nov 19 09:31:14 2009 UTC
# Line 1  Line 1 
1  /*  package gtmig.org.geotools.swing;
  *    GeoTools - OpenSource mapping toolkit  
  *    http://geotools.org  
  *    (C) 2002-2006, GeoTools Project Managment Committee (PMC)  
  *  
  *    This library is free software; you can redistribute it and/or  
  *    modify it under the terms of the GNU Lesser General Public  
  *    License as published by the Free Software Foundation;  
  *    version 2.1 of the License.  
  *  
  *    This library is distributed in the hope that it will be useful,  
  *    but WITHOUT ANY WARRANTY; without even the implied warranty of  
  *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU  
  *    Lesser General Public License for more details.  
  */  
 package org.geotools.gui.swing;  
   
 /**  
  * <b>Xulu:<br>  
  *    Code taken from gt-2.4.5 to make some changes (marked with {@code xulu}),  
  *    which can not be realized in a subclass:</b>  
  *    <ul>  
  *       <li>{@link #getMapArea()} declared as {@code final}<li>  
  *       <li>some variables declared as {@code protected}</li>  
  *       <li>minimal/maximal zoom scale</li>  
  *       <li>zoom in and zoom out via mouse click realized by setMapArea(..)</li>  
  *    </ul>  
  * <br><br>  
  * A simple map container that is a JPanel with a map in. provides simple  
  * pan,zoom, highlight and selection The mappane stores an image of the map  
  * (drawn from the context) and an image of the slected feature(s) to speed up  
  * rendering of the highlights. Thus the whole map is only redrawn when the bbox  
  * changes, selection is only redrawn when the selected feature changes.  
  *  
  *  
  * @author Ian Turton  
  *  
  */  
2    
3  import java.awt.Color;  import java.awt.Color;
4  import java.awt.Cursor;  import java.awt.Cursor;
5    import java.awt.Font;
6  import java.awt.Graphics;  import java.awt.Graphics;
7  import java.awt.Graphics2D;  import java.awt.Graphics2D;
8  import java.awt.LayoutManager;  import java.awt.Image;
9    import java.awt.Point;
10  import java.awt.Rectangle;  import java.awt.Rectangle;
11    import java.awt.RenderingHints;
12    import java.awt.event.ActionEvent;
13    import java.awt.event.ActionListener;
14    import java.awt.event.ComponentAdapter;
15    import java.awt.event.ComponentEvent;
16  import java.awt.event.InputEvent;  import java.awt.event.InputEvent;
17  import java.awt.event.MouseEvent;  import java.awt.event.MouseEvent;
18  import java.awt.event.MouseListener;  import java.awt.event.MouseListener;
19  import java.awt.event.MouseMotionListener;  import java.awt.geom.AffineTransform;
20    import java.awt.geom.NoninvertibleTransformException;
21    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;
 import java.util.Date;  
24  import java.util.HashMap;  import java.util.HashMap;
25  import java.util.Map;  import java.util.Map;
26    import java.util.Vector;
27    
28  import javax.swing.JPanel;  import javax.swing.Timer;
29    
30  import org.apache.log4j.Logger;  import org.apache.log4j.Logger;
31  import org.geotools.feature.FeatureCollection;  import org.geotools.feature.FeatureCollection;
32  import org.geotools.filter.IllegalFilterException;  import org.geotools.geometry.jts.JTS;
33    import org.geotools.geometry.jts.ReferencedEnvelope;
34  import org.geotools.map.DefaultMapContext;  import org.geotools.map.DefaultMapContext;
35  import org.geotools.map.MapContext;  import org.geotools.map.MapContext;
36  import org.geotools.map.MapLayer;  import org.geotools.map.MapLayer;
37    import org.geotools.map.event.MapLayerEvent;
38  import org.geotools.map.event.MapLayerListEvent;  import org.geotools.map.event.MapLayerListEvent;
39  import org.geotools.map.event.MapLayerListListener;  import org.geotools.map.event.MapLayerListListener;
40  import org.geotools.referencing.crs.DefaultGeographicCRS;  import org.geotools.map.event.MapLayerListener;
41    import org.geotools.referencing.CRS;
42  import org.geotools.renderer.GTRenderer;  import org.geotools.renderer.GTRenderer;
43    import org.geotools.renderer.label.LabelCacheImpl;
44  import org.geotools.renderer.lite.LabelCache;  import org.geotools.renderer.lite.LabelCache;
 import org.geotools.renderer.lite.LabelCacheDefault;  
45  import org.geotools.renderer.lite.StreamingRenderer;  import org.geotools.renderer.lite.StreamingRenderer;
46  import org.geotools.renderer.shape.TransitionShapefileRenderer;  import org.geotools.swing.JMapPane;
47  import org.geotools.styling.Graphic;  import org.geotools.swing.event.MapMouseEvent;
48  import org.geotools.styling.LineSymbolizer;  import org.geotools.swing.event.MapPaneEvent;
49  import org.geotools.styling.Mark;  import org.geotools.swing.event.MapPaneListener;
50  import org.geotools.styling.PointSymbolizer;  import org.opengis.feature.simple.SimpleFeature;
51  import org.geotools.styling.PolygonSymbolizer;  import org.opengis.feature.simple.SimpleFeatureType;
52  import org.geotools.styling.Style;  import org.opengis.referencing.FactoryException;
 import org.geotools.styling.StyleBuilder;  
 import org.geotools.styling.StyleFactory;  
 import org.opengis.filter.Filter;  
 import org.opengis.filter.FilterFactory2;  
53  import org.opengis.referencing.crs.CoordinateReferenceSystem;  import org.opengis.referencing.crs.CoordinateReferenceSystem;
54    import org.opengis.referencing.operation.MathTransform;
55    import org.opengis.referencing.operation.TransformException;
56    
57    import schmitzm.geotools.GTUtil;
58    import schmitzm.geotools.JTSUtil;
59    import schmitzm.geotools.gui.SelectableXMapPane;
60    import schmitzm.geotools.map.event.JMapPaneListener;
61    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;
 import com.vividsolutions.jts.geom.GeometryFactory;  
   
 public class JMapPane extends JPanel implements MouseListener,  
                 MouseMotionListener, HighlightChangeListener, SelectionChangeListener,  
                 PropertyChangeListener, MapLayerListListener {  
         private static Logger LOGGER = Logger.getLogger(JMapPane.class.getName());  
   
         private static final long serialVersionUID = -8647971481359690499L;  
70    
71          public static final int Reset = 0;  /**
72     * The {@link XMapPane} class uses a Geotools {@link GTRenderer} to paint up to
73          public static final int ZoomIn = 1;   * 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          public static final int ZoomOut = 2;          private static final int IMAGETYPE = BufferedImage.TYPE_INT_RGB;
97            private static final int IMAGETYPE_withAlpha = BufferedImage.TYPE_INT_ARGB;
98    
99          public static final int Pan = 3;          private static Logger LOGGER = Logger.getLogger(XMapPane.class);
100    
101          public static final int Select = 4;          private boolean acceptsRepaintCalls = true;
102    
103          private static final int POLYGON = 0;          /**
104             * Main {@link MapContext} that holds all layers that are rendered into the
105             * {@link #localImage} by the {@link #localRenderer}
106             */
107            MapContext localContext;
108    
109          private static final int LINE = 1;          /**
110             * {@link MapContext} holding the background layers. Use it for layers that
111             * CAN take very long for rendering, like layer from the Internet: WMS, WFS,
112             * OSM...<br>
113             * <code>null</code> by default.
114             *
115             * @see #setBgContext(MapContext)
116             * @see #getBgContext()
117             */
118            MapContext bgContext;
119    
120          private static final int POINT = 2;          /**
121             * While threads are working, calls {@link XMapPane#updateFinalImage()}
122             * regularly and {@link #repaint()}. This {@link Timer} is stopped when all
123             * renderers have finished.
124             *
125             * @see #INITIAL_REPAINT_DELAYAL
126             * @see #REPEATING_REPAINT_DELAY
127             */
128            final private Timer repaintTimer;
129    
130          /**          /**
131           * what renders the map           * The initial delay in milliseconds until the {@link #finalImage} is
132             * updated the first time.
133           */           */
134          GTRenderer renderer;          public static final int INITIAL_REPAINT_DELAY = 1000;
135    
136          private GTRenderer highlightRenderer, selectionRenderer;          /**
137             * While the {@link #bgExecuter} and {@link #localExecuter} are rendering,
138             * the {@link #repaintTimer} is regularly updating the {@link #finalImage}
139             * with previews.
140             */
141            public static final long REPEATING_REPAINT_DELAY = 500;
142    
143          /**          /**
144           * the map context to render           * Default delay (milliseconds) before the map will be redrawn when resizing
145             * the pane. This is to avoid flickering while drag-resizing.
146           */           */
147          MapContext context;          public static final int DEFAULT_RESIZING_PAINT_DELAY = 500;
148    
149          private MapContext selectionContext;          public static final int NONE = -123;
150    
151          /**          /**
152           * the area of the map to draw           * Flag fuer Modus "Kartenausschnitt bewegen". Nicht fuer Window-Auswahl
153             * moeglich!
154             *
155             * @see #setState(int)
156           */           */
157          // xulu.sc          public static final int PAN = 1;
         // Envelope mapArea;  
         protected Envelope mapArea;  
         // xulu.ec  
158    
159          /**          /**
160           * the size of the pane last time we drew           * Flag fuer Modus "SimpleFeature-Auswahl auf allen (sichtbaren) Layern".
161             *
162             * @see #setState(int)
163             * @see #setState(int)
164           */           */
165          // xulu.sc          public static final int SELECT_ALL = 103;
         // private Rectangle oldRect = null;  
         protected Rectangle oldRect = null;  
         // xulu.ec  
   
166          /**          /**
167           * the last map area drawn.           * Flag fuer Modus
168             * "Auswahl nur eines Features, das erste sichtbare von Oben".
169             *
170             * @see #setState(int)
171             * @see #setState(int)
172           */           */
173          // xulu.sc          public static final int SELECT_ONE_FROM_TOP = 104;
         // private Envelope oldMapArea = null;  
         protected Envelope oldMapArea = null;  
         // xulu.ec  
   
174          /**          /**
175           * the base image of the map           * Flag fuer Modus
176             * "SimpleFeature-Auswahl auf dem obersten (sichtbaren) Layer".
177             *
178             * @see #setState(int)
179             * @see #setState(int)
180           */           */
181          protected BufferedImage baseImage, panningImage;          public static final int SELECT_TOP = 4;
182          // SK: private BufferedImage baseImage, panningImage;  
183            public static final Cursor WAIT_CURSOR = Cursor
184                            .getPredefinedCursor(Cursor.WAIT_CURSOR);
185    
186            final static Font waitFont = new Font("Arial", Font.BOLD, 30);
187    
188          /**          /**
189           * image of selection           * Flag fuer Modus "Heran zoomen".
190             *
191             * @see #setState(int)
192             * @see #setState(int)
193           */           */
194          private BufferedImage selectImage;          public static final int ZOOM_IN = 2;
195    
196          /**          /**
197           * style for selected items           * Flag fuer Modus "Heraus zoomen". Nicht fuer Window-Auswahl moeglich!
198             *
199             * @see #setState(int)
200           */           */
201          private Style selectionStyle;          public static final int ZOOM_OUT = 3;
202    
203          /**          /**
204           * layer that selection works on           * Konvertiert die Maus-Koordinaten (relativ zum <code>JMapPane</code>) in
205             * Karten-Koordinaten.
206             *
207             * @param e
208             *            Maus-Ereignis
209           */           */
210          private MapLayer selectionLayer;          public static Point2D getMapCoordinatesFromEvent(final MouseEvent e) {
211                    // aktuelle Geo-Position aus GeoMouseEvent ermitteln
212                    if (e != null && e instanceof MapMouseEvent)
213                            try {
214                                    return ((MapMouseEvent) e).getMapPosition().toPoint2D();
215                            } catch (final Exception err) {
216                                    LOGGER
217                                                    .error(
218                                                                    "return ((GeoMouseEvent) e).getMapCoordinate(null).toPoint2D();",
219                                                                    err);
220                            }
221    
222                    // aktuelle Geo-Position ueber Transformation des JMapPane berechnen
223                    if (e != null && e.getSource() instanceof XMapPane) {
224    
225                            final XMapPane xMapPane = (XMapPane) e.getSource();
226    
227                            if (!xMapPane.isWellDefined())
228                                    return null;
229    
230                            final AffineTransform at = xMapPane.getScreenToWorld();
231                            if (at != null)
232                                    return at.transform(e.getPoint(), null);
233                            return null;
234                    }
235                    throw new IllegalArgumentException(
236                                    "MouseEvent has to be of instance MapMouseEvent or come from an XMapPane");
237            }
238    
239          /**          /**
240           * layer that highlight works on           * Listens to changes of the "background" {@link MapContext} and triggers
241             * repaints where needed.
242           */           */
243          private MapLayer highlightLayer;          private final MapLayerListListener bgContextListener = new MapLayerListListener() {
244    
245                    @Override
246                    public void layerAdded(final MapLayerListEvent event) {
247                            event.getLayer().addMapLayerListener(bgMapLayerListener);
248    
249                            if (localContext.getLayers().length == 0
250                                            && bgContext.getLayers().length == 1) { // the first one and
251                                    // localContext is
252                                    // empty
253                                    if (!setMapArea(localContext.getAreaOfInterest()))
254                                            requestStartRendering();
255                                    return;
256                            }
257    
258                            // We need to redraw, even in case that the mapArea didn't change
259                            // mapImageInvalid = true;
260                            // repaint();
261                            requestStartRendering();
262    
263                    }
264    
265                    @Override
266                    public void layerChanged(final MapLayerListEvent event) {
267                            // mapImageInvalid = true;
268                            // repaint();
269                            requestStartRendering();
270                    }
271    
272                    @Override
273                    public void layerMoved(final MapLayerListEvent event) {
274                            // mapImageInvalid = true;
275                            // repaint();
276                            requestStartRendering();
277                    }
278    
279                    @Override
280                    public void layerRemoved(final MapLayerListEvent event) {
281                            if (event.getLayer() != null)
282                                    event.getLayer().removeMapLayerListener(bgMapLayerListener);
283                            // mapImageInvalid = true;
284                            // repaint();
285                            requestStartRendering();
286                    }
287            };
288    
289          /**          /**
290           * the object which manages highlighting           * compass and icon are rendered into this image
291           */           */
292          private HighlightManager highlightManager;          // protected BufferedImage gadgetsImage;
293    
294            protected RenderingExecutor bgExecuter;
295    
296          /**          /**
297           * is highlighting on or off           * The Renderer for the LocalLayers uses this Image. When set to null,
298             * please dispose this {@link Graphics2D}
299           */           */
300          private boolean highlight = true;          private BufferedImage localImage;
301    
302            private BufferedImage finalImage;
303          /**          /**
304           * a factory for filters           * If # {@link #bgExecuter} is using {@link #bgRenderer} for the Background
305             * uses this Image. When set to null, please dispose the {@link Graphics2D}
306           */           */
307          FilterFactory2 ff;          private BufferedImage bgImage;
308    
309          /**          /**
310           * a factory for geometries           * Optionally a transparent image to paint over the map in the lower right
311             * corner.
312             *
313             * @see #addGadgets(Graphics2D)
314             * @see #setMapImage(BufferedImage)
315             **/
316            private BufferedImage mapImage = null;
317    
318            /**
319             * Listens to each layer in the local {@link MapContext} for changes and
320             * triggers repaints.
321           */           */
322          GeometryFactory gf = new GeometryFactory(); // FactoryFinder.getGeometryFactory(null);          protected MapLayerListener bgMapLayerListener = new MapLayerAdapter() {
323    
324                    @Override
325                    public void layerChanged(final MapLayerEvent event) {
326                            // Change of SLD for example
327                            // mapImageInvalid = true;
328                            // repaint();
329                            requestStartRendering();
330                    }
331    
332                    @Override
333                    public void layerHidden(final MapLayerEvent event) {
334                            // mapImageInvalid = true;
335                            // repaint();
336                            requestStartRendering();
337                    }
338    
339                    @Override
340                    public void layerShown(final MapLayerEvent event) {
341                            // mapImageInvalid = true;
342                            // repaint();
343                            requestStartRendering();
344                    }
345            };
346    
347          /**          /**
348           * the collections of features to be selected or highlighted           * A flag indicating if dispose() was already called. If true, then further
349             * use of this {@link SelectableXMapPane} is undefined.
350           */           */
351          FeatureCollection selection;          private boolean disposed = false;
352    
353          /**          /**
354           * the collections of features to be selected or highlighted           * While dragging, the {@link #updateFinalImage()} method is translating the
355             * 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          FeatureCollection highlightFeature;          private RenderingHints java2dHints;
366    
367          private int state = ZoomIn;          protected LabelCache labelCache = new LabelCacheImpl();
368    
369          /**          /**
370           * how far to zoom in or out           * Listens to changes of the "local" {@link MapContext} and triggers
371             * repaints where needed.
372           */           */
373          private double zoomFactor = 2.0;          private final MapLayerListListener localContextListener = new MapLayerListListener() {
374    
375          Style lineHighlightStyle;                  @Override
376                    public void layerAdded(final MapLayerListEvent event) {
377                            event.getLayer().addMapLayerListener(localMapLayerListener);
378    
379          Style pointHighlightStyle;                          localRenderer.setContext(getContext());
380    
381          Style polygonHighlightStyle;                          if (localContext.getLayers().length == 1) { // the first one
382                                    // if the Area of Interest is unset, the LayerBounds are used
383                                    if (!setMapArea(localContext.getAreaOfInterest()))
384                                            repaint();
385    
386          Style polygonSelectionStyle;                                  return;
387                            }
388    
389          Style pointSelectionStyle;                          // We need to redraw, even in case that the mapArea didn't change
390                            // mapImageInvalid = true;
391                            // repaint();
392                            requestStartRendering();
393    
394          Style lineSelectionStyle;                  }
395    
396          boolean changed = true;                  @Override
397                    public void layerChanged(final MapLayerListEvent event) {
398                            // mapImageInvalid = true;
399                            // repaint();
400                            localRenderer.setContext(getContext());
401                            requestStartRendering();
402                    }
403    
404          LabelCache labelCache = new LabelCacheDefault();                  @Override
405                    public void layerMoved(final MapLayerListEvent event) {
406                            // mapImageInvalid = true;
407                            // repaint();
408                            localRenderer.setContext(getContext());
409                            requestStartRendering();
410                    }
411    
412          // xulu.sc                  @Override
413          // private boolean reset = false;                  public void layerRemoved(final MapLayerListEvent event) {
414          protected boolean reset = false;                          if (event.getLayer() != null)
415          // xulu.ec                                  event.getLayer().removeMapLayerListener(localMapLayerListener);
416                            // mapImageInvalid = true;
417                            // repaint();
418                            localRenderer.setContext(getContext());
419                            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
427             * triggers repaints.
428             */
429            protected MapLayerListener localMapLayerListener = new MapLayerAdapter() {
430    
431          int startX;                  @Override
432                    public void layerChanged(final MapLayerEvent event) {
433                            localRenderer.setContext(getContext()); // betters for SLD changes?!
434                            // Change of SLD for example
435                            // mapImageInvalid = true;
436                            // repaint();
437                            requestStartRendering();
438                    }
439    
440                    @Override
441                    public void layerHidden(final MapLayerEvent event) {
442                            // mapImageInvalid = true;
443                            // repaint();
444                            requestStartRendering();
445                    }
446    
447                    @Override
448                    public void layerShown(final MapLayerEvent event) {
449                            // mapImageInvalid = true;
450                            // repaint();
451                            requestStartRendering();
452                    }
453            };
454    
455            private final GTRenderer localRenderer = GTUtil.createGTRenderer();
456            
457            private final GTRenderer bgRenderer = GTUtil.createGTRenderer();
458    
459            /**
460             * the area of the map to draw
461             */
462            protected Envelope mapArea = null;
463    
464          int startY;          /**
465             * A flag set it {@link #setMapArea(Envelope)} to indicated the
466             * {@link #paintComponent(Graphics)} method, that the image on-screen is
467             * associated with {@link #oldMapArea} and may hence be scaled for a quick
468             * preview.<br>
469             * The flag is reset
470             **/
471            private boolean mapAreaChanged = false;
472    
473          private boolean clickable;          /**
474             * This color is used as the default background color when painting a map.
475             */
476            private Color mapBackgroundColor = Color.WHITE;
477    
478          int lastX;          /**
479             * A flag indicating that the shown image is invalid and needs to be
480             * re-rendered.
481             */
482            protected boolean mapImageInvalid = true;
483    
484          int lastY;          /**
485             * 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             * actions.
488             */
489            final protected HashMap<MapLayer, Boolean> mapLayerSelectable = new HashMap<MapLayer, Boolean>();
490    
491          private SelectionManager selectionManager;          /**
492          // xulu.sn           * List of listeners of this {@link XMapPane}
493             */
494            protected Vector<JMapPaneListener> mapPaneListeners = new Vector<JMapPaneListener>();
495            /**
496             * If not <code>null</code>, the {@link XMapPane} will not allow to zoom/pan
497             * out of that area
498             **/
499            private Envelope maxExtend = null;
500          private Double maxZoomScale = Double.MIN_VALUE;          private Double maxZoomScale = Double.MIN_VALUE;
501    
502          private Double minZoomScale = Double.MAX_VALUE;          private Double minZoomScale = Double.MAX_VALUE;
         // xulu.en  
503    
         // sk.sn  
504          /**          /**
505           * Wenn true, dann wurde PANNING via mouseDraged-Events begonnen. Dieses           * We store the old mapArea for a moment to use it for the
506           * Flag wird benutzt um nur einmal den passenden Cursor nur einmal zu           * "quick scaled preview" in case of ZoomOut
507           * setzen.           **/
508            protected Envelope oldMapArea = null;
509    
510            /**
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            /**
517             * A flag indicating, that the image size has changed and the buffered
518             * images are not big enough any more
519             **/
520            protected boolean paneResized = false;
521    
522            private BufferedImage preFinalImage;
523    
524            // if null, no quick preview will be shown
525            private int quickPreviewHint = 0;
526    
527            private Map<Object, Object> rendererHints;
528    
529            private volatile Boolean requestStartRendering = false;
530    
531            private final Timer resizeTimer;
532    
533            private final int resizingPaintDelay;
534    
535            /**
536             * Transformation zwischen Fenster-Koordinaten und Karten-Koordinaten
537             * (lat/lon)
538           */           */
539          private boolean panning_started = false;          protected AffineTransform screenToWorld = null;
540    
541          // sk.en          /**
542             * The flag {@link #requestStartRendering} can be set to true by events.
543             * This {@link Timer} checks the flag regularly and starts one renderer
544             * thread.
545             */
546            final private Timer startRenderThreadsTimer;
547    
548          public JMapPane() {          /**
549                  this(null, true, null, null);           * 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           * create a basic JMapPane           * Manuell gesetzter statischer Cursor, unabhaengig von der aktuellen
556           *           * MapPane-Funktion
          * @param render  
          *            - how to draw the map  
          * @param context  
          *            - the map context to display  
557           */           */
558          public JMapPane(final GTRenderer render, final MapContext context) {          protected Cursor staticCursor = null;
559                  this(null, true, render, context);  
560            private AffineTransform worldToScreen;
561    
562            /**
563             * This {@link MouseListener} is managing all zoom related tasks
564             */
565            public final ZoomXMapPaneMouseListener zoomMapPaneMouseListener = new ZoomXMapPaneMouseListener(
566                            this);
567    
568            // TODO doku
569            public XMapPane() {
570                    this(null, null);
571          }          }
572    
573          /**          /**
574           * full constructor extending JPanel           * full constructor extending JPanel
575           *           *
576             * @param rendererHints
577             *
578           * @param layout           * @param layout
579           *            - layout (probably shouldn't be set)           *            - layout (probably shouldn't be set)
580           * @param isDoubleBuffered           * @param isDoubleBuffered
581           *            - a Swing thing I don't really understand           *            - a Swing thing I don't really understand
582           * @param render           * @param render
583           *            - what to draw the map with           *            - what to draw the map with
584           * @param context           * @param localContext
585           *            - what to draw           *            - {@link MapContext} of layer to render.
586           */           */
587          public JMapPane(final LayoutManager layout, final boolean isDoubleBuffered,          public XMapPane(final MapContext localContext_,
588                          final GTRenderer render, final MapContext context) {                          final Map<Object, Object> rendererHints) {
589                  super(layout, isDoubleBuffered);                  super(true);
590    
591                  ff = (FilterFactory2) org.geotools.factory.CommonFactoryFinder                  setRendererHints(rendererHints);
                                 .getFilterFactory(null);  
                 setRenderer(render);  
592    
593                  setContext(context);                  setOpaque(true);
594    
595                  this.addMouseListener(this);                  localRenderer.setJava2DHints(getJava2dHints());
                 this.addMouseMotionListener(this);  
                 setHighlightManager(new HighlightManager(highlightLayer));  
                 setSelectionManager(new SelectionManager(selectionLayer));  
                 lineHighlightStyle = setupStyle(LINE, Color.red);  
596    
597                  pointHighlightStyle = setupStyle(POINT, Color.red);                  if (localContext_ != null)
598                            setLocalContext(localContext_);
599    
600                  polygonHighlightStyle = setupStyle(POLYGON, Color.red);                  /**
601                     * Adding the #zoomMapPaneMouseListener
602                     */
603                    this.addMouseListener(zoomMapPaneMouseListener);
604                    this.addMouseMotionListener(zoomMapPaneMouseListener);
605                    this.addMouseWheelListener(zoomMapPaneMouseListener);
606    
607                    /*
608                     * 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                  polygonSelectionStyle = setupStyle(POLYGON, Color.cyan);                          public void actionPerformed(final ActionEvent e) {
618                                    paneResized = true;
619    
620                  pointSelectionStyle = setupStyle(POINT, Color.cyan);                                  if (!isWellDefined())
621                                            return;
622    
623                  lineSelectionStyle = setupStyle(LINE, Color.cyan);                                  final Rectangle bounds = getVisibleRect();
                 setCursor(new Cursor(Cursor.CROSSHAIR_CURSOR));  
         }  
624    
625          /**                                  final Envelope geoMapArea = tranformWindowToGeo(bounds.x,
626           * get the renderer                                                  bounds.y, bounds.x + bounds.width, bounds.y
627           */                                                                  + bounds.height);
         public GTRenderer getRenderer() {  
                 return renderer;  
         }  
628    
629          public void setRenderer(final GTRenderer renderer) {                                  setMapArea(bestAllowedMapArea(geoMapArea));
                 Map hints = new HashMap();  
                   
                 this.renderer = renderer;  
                   
                 if (renderer instanceof StreamingRenderer || renderer instanceof TransitionShapefileRenderer) {  
                         hints = renderer.getRendererHints();  
                         if (hints == null) {  
                                 hints = new HashMap();  
630                          }                          }
631                          if (hints.containsKey(StreamingRenderer.LABEL_CACHE_KEY)) {                  });
632                                  labelCache = (LabelCache) hints                  resizeTimer.setRepeats(false);
633                                                  .get(StreamingRenderer.LABEL_CACHE_KEY);                  this.addComponentListener(new ComponentAdapter() {
634                          } else {  
635                                  hints.put(StreamingRenderer.LABEL_CACHE_KEY, labelCache);                          @Override
636                            public void componentResized(final ComponentEvent e) {
637                                    if (bgExecuter != null)
638                                            bgExecuter.cancelTask();
639                                    if (localExecuter != null)
640                                            localExecuter.cancelTask();
641                                    resizeTimer.restart();
642                          }                          }
643    
644                          hints.put("memoryPreloadingEnabled", Boolean.TRUE);                  });
                           
                         renderer.setRendererHints(hints);  
                 }  
   
 //              this.highlightRenderer = new StreamingRenderer();  
 //              this.selectionRenderer = new StreamingRenderer();  
645    
646  //              highlightRenderer.setRendererHints(hints);                  /*
647  //              selectionRenderer.setRendererHints(hints);                   * Setting up the repaintTimer. Not started automatically.
648                                     */
649  //              renderer.setRendererHints(hints);                  repaintTimer = new Timer((int) REPEATING_REPAINT_DELAY,
650                                    new ActionListener() {
                 if (this.context != null) {  
                         this.renderer.setContext(this.context);  
                 }  
         }  
   
         public MapContext getContext() {  
                 return context;  
         }  
651    
652          public void setContext(final MapContext context) {                                          @Override
653                  if (this.context != null) {                                          public void actionPerformed(final ActionEvent e) {
654                          this.context.removeMapLayerListListener(this);                                                  updateFinalImage();
655                  }                                                  XMapPane.this.repaint();
656                                            }
657                                    });
658                    repaintTimer.setInitialDelay(INITIAL_REPAINT_DELAY);
659                    repaintTimer.setRepeats(true);
660    
661                  this.context = context;                  /*
662                     * Setting up the startRenderThreadsTimer. This Timer starts
663                     * automatically.
664                     */
665                    startRenderThreadsTimer = new Timer(100, new ActionListener() {
666    
667                  if (context != null) {                          @Override
668                          this.context.addMapLayerListListener(this);                          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    
                 if (renderer != null) {  
                         renderer.setContext(this.context);  
                 }  
684          }          }
685    
686          public Envelope getMapArea() {          /**
687                  return mapArea;           * Fuegt der Map einen Listener hinzu.
688             *
689             * @param l
690             *            neuer Listener
691             */
692            public void addMapPaneListener(final JMapPaneListener l) {
693                    mapPaneListeners.add(l);
694          }          }
695    
696          public void setMapArea(final Envelope mapArea) {          /**
697                  this.mapArea = mapArea;           * Korrigiert den {@link Envelope} aka {@code mapArea} auf die beste
698          }           * erlaubte Flaeche damit die Massstabsbeschaenkungen noch eingehalten
699             * werden, FALLS der uebergeben Envelope nicht schon gueltig sein sollte.<br>
700             * Since 21. April 09: Before thecalculation starts, the aspect ratio is
701             * corrected. This change implies, that setMapArea() will most of the time
702             * not allow setting to a wrong aspectRatio.
703             *
704             * @author <a href="mailto:[email protected]">Stefan Alfons
705             *         Kr&uuml;ger</a>
706             */
707            public Envelope bestAllowedMapArea(Envelope env) {
708                    if (getWidth() == 0)
709                            return env;
710                    if (env == null)
711                            return null;
712    
713          public int getState() {                  Envelope newArea = null;
                 return state;  
         }  
714    
715          public void setState(final int state) {                  /**
716                  this.state = state;                   * Correct the aspect Ratio before we check the rest. Otherwise we might
717                     * easily fail. We allow to grow here, because we don't check against
718                     * the maxExtend
719                     */
720                    final Rectangle curPaintArea = getVisibleRect();
721    
722                  // System.out.println("State: " + state);                  env = JTSUtil.fixAspectRatio(curPaintArea, env, true);
         }  
723    
724          public double getZoomFactor() {                  final double scale = env.getWidth() / getWidth();
725                  return zoomFactor;                  final double centerX = env.getMinX() + env.getWidth() / 2.;
726          }                  final double centerY = env.getMinY() + env.getHeight() / 2.;
727                    double newWidth2 = 0;
728                    double newHeight2 = 0;
729                    if (scale < getMaxZoomScale()) {
730                            // ****************************************************************************
731                            // Wir zoomen weiter rein als erlaubt => Anpassen des envelope
732                            // ****************************************************************************
733                            newWidth2 = getMaxZoomScale() * getWidth() / 2.;
734                            newHeight2 = getMaxZoomScale() * getHeight() / 2.;
735                    } else if (scale > getMinZoomScale()) {
736                            // ****************************************************************************
737                            // Wir zoomen weiter raus als erlaubt => Anpassen des envelope
738                            // ****************************************************************************
739                            newWidth2 = getMinZoomScale() * getWidth() / 2.;
740                            newHeight2 = getMinZoomScale() * getHeight() / 2.;
741                    } else {
742                            // ****************************************************************************
743                            // Die mapArea / der Envelope ist ist gueltig! Keine Aenderungen
744                            // ****************************************************************************
745                            newArea = env;
746                    }
747    
748          public void setZoomFactor(final double zoomFactor) {                  if (newArea == null) {
                 this.zoomFactor = zoomFactor;  
         }  
749    
750          public MapLayer getSelectionLayer() {                          final Coordinate ll = new Coordinate(centerX - newWidth2, centerY
751                  return selectionLayer;                                          - newHeight2);
752          }                          final Coordinate ur = new Coordinate(centerX + newWidth2, centerY
753                                            + newHeight2);
754    
755          public void setSelectionLayer(final MapLayer selectionLayer) {                          newArea = new Envelope(ll, ur);
                 this.selectionLayer = selectionLayer;  
                 if (selectionManager != null) {  
                         selectionManager.setSelectionLayer(selectionLayer);  
756                  }                  }
         }  
757    
758          public boolean isHighlight() {                  final Envelope maxAllowedExtend = getMaxExtend();
759                  return highlight;                  while (maxAllowedExtend != null && !maxAllowedExtend.contains(newArea)
760          }                                  && newArea != null && !newArea.isNull()
761                                    && !Double.isNaN(newArea.getMinX())
762                                    && !Double.isNaN(newArea.getMaxX())
763                                    && !Double.isNaN(newArea.getMinY())
764                                    && !Double.isNaN(newArea.getMaxY())) {
765                            /*
766                             * If a maxExtend is set, we have to honour that...
767                             */
768    
769          public void setHighlight(final boolean highlight) {                          // Exceeds top? Move down and maybe cut
770                  this.highlight = highlight;                          if (newArea.getMaxY() > maxAllowedExtend.getMaxY()) {
771          }                                  final double divY = newArea.getMaxY()
772                                                    - maxAllowedExtend.getMaxY();
773                                    // LOGGER.debug("Moving area down by " + divY);
774    
775                                    newArea = new Envelope(new Coordinate(newArea.getMinX(),
776                                                    newArea.getMinY() - divY), new Coordinate(newArea
777                                                    .getMaxX(), newArea.getMaxY() - divY));
778    
779                                    if (newArea.getMinY() < maxAllowedExtend.getMinY()) {
780                                            // LOGGER.debug("Now it exeeds the bottom border.. cut!");
781                                            // And cut the bottom if it moved out of the area
782                                            newArea = new Envelope(new Coordinate(newArea.getMinX(),
783                                                            maxAllowedExtend.getMinY()), new Coordinate(newArea
784                                                            .getMaxX(), newArea.getMaxY()));
785    
786          public MapLayer getHighlightLayer() {                                          // LOGGER.debug("and fix aspect ratio");
                 return highlightLayer;  
         }  
787    
788          public void setHighlightLayer(final MapLayer highlightLayer) {                                          newArea = JTSUtil.fixAspectRatio(this.getBounds(), newArea,
789                  this.highlightLayer = highlightLayer;                                                          false);
790                                    }
791                            }
792    
793                  if (highlightManager != null) {                          // Exceeds bottom? Move up and maybe cut
794                          highlightManager.setHighlightLayer(highlightLayer);                          if (newArea.getMinY() < maxAllowedExtend.getMinY()) {
795                  }                                  final double divY = newArea.getMinY()
796          }                                                  - maxAllowedExtend.getMinY();
797                                    // LOGGER.debug("Moving area up by " + divY);
798    
799                                    newArea = new Envelope(new Coordinate(newArea.getMinX(),
800                                                    newArea.getMinY() - divY), new Coordinate(newArea
801                                                    .getMaxX(), newArea.getMaxY() - divY));
802    
803                                    if (newArea.getMaxY() > maxAllowedExtend.getMaxY()) {
804                                            // LOGGER.debug("Now it exeeds the top border.. cut!");
805                                            // And cut the bottom if it moved out of the area
806                                            newArea = new Envelope(new Coordinate(newArea.getMinX(),
807                                                            newArea.getMinY()), new Coordinate(newArea
808                                                            .getMaxX(), maxAllowedExtend.getMaxY()));
809    
810          public HighlightManager getHighlightManager() {                                          // LOGGER.debug("and fix aspect ratio");
                 return highlightManager;  
         }  
811    
812          public void setHighlightManager(final HighlightManager highlightManager) {                                          newArea = JTSUtil.fixAspectRatio(this.getBounds(), newArea,
813                  this.highlightManager = highlightManager;                                                          false);
814                  this.highlightManager.addHighlightChangeListener(this);                                  }
815                  this.addMouseMotionListener(this.highlightManager);                          }
         }  
816    
817          public Style getLineHighlightStyle() {                          // Exceeds to the right? move and maybe cut
818                  return lineHighlightStyle;                          if (newArea.getMaxX() > maxAllowedExtend.getMaxX()) {
         }  
819    
820          public void setLineHighlightStyle(final Style lineHighlightStyle) {                                  // Move left..
821                  this.lineHighlightStyle = lineHighlightStyle;                                  final double divX = newArea.getMaxX()
822          }                                                  - maxAllowedExtend.getMaxX();
823                                    // LOGGER.debug("Moving area left by " + divX);
824    
825                                    newArea = new Envelope(new Coordinate(newArea.getMinX() - divX,
826                                                    newArea.getMinY()), new Coordinate(newArea.getMaxX()
827                                                    - divX, newArea.getMaxY()));
828    
829                                    if (newArea.getMinX() < maxAllowedExtend.getMinX()) {
830                                            // LOGGER.debug("Now it exeeds the left border.. cut!");
831                                            // And cut the left if it moved out of the area
832                                            newArea = new Envelope(new Coordinate(maxAllowedExtend
833                                                            .getMinX(), newArea.getMinY()), new Coordinate(
834                                                            newArea.getMaxX(), newArea.getMaxY()));
835    
836          public Style getLineSelectionStyle() {                                          // LOGGER.debug("and fix aspect ratio");
                 return lineSelectionStyle;  
         }  
837    
838          public void setLineSelectionStyle(final Style lineSelectionStyle) {                                          newArea = JTSUtil.fixAspectRatio(this.getBounds(), newArea,
839                  this.lineSelectionStyle = lineSelectionStyle;                                                          false);
840          }                                  }
841                            }
842    
843          public Style getPointHighlightStyle() {                          // Exceeds to the left? move and maybe cut
844                  return pointHighlightStyle;                          if (newArea.getMinX() < maxAllowedExtend.getMinX()) {
         }  
845    
846          public void setPointHighlightStyle(final Style pointHighlightStyle) {                                  // Move right..
847                  this.pointHighlightStyle = pointHighlightStyle;                                  final double divX = newArea.getMinX()
848          }                                                  - maxAllowedExtend.getMinX();
849                                    // LOGGER.debug("Moving area right by " + divX);
850    
851                                    newArea = new Envelope(new Coordinate(newArea.getMinX() - divX,
852                                                    newArea.getMinY()), new Coordinate(newArea.getMaxX()
853                                                    - divX, newArea.getMaxY()));
854    
855                                    if (newArea.getMaxX() > maxAllowedExtend.getMaxX()) {
856                                            // LOGGER.debug("Now it exeeds the right border.. cut!");
857                                            // And cut the left if it moved out of the area
858                                            newArea = new Envelope(new Coordinate(newArea.getMinX(),
859                                                            newArea.getMinY()), new Coordinate(maxAllowedExtend
860                                                            .getMaxX(), newArea.getMaxY()));
861    
862          public Style getPointSelectionStyle() {                                          // LOGGER.debug("and fix aspect ratio");
                 return pointSelectionStyle;  
         }  
863    
864          public void setPointSelectionStyle(final Style pointSelectionStyle) {                                          newArea = JTSUtil.fixAspectRatio(this.getBounds(), newArea,
865                  this.pointSelectionStyle = pointSelectionStyle;                                                          false);
866          }                                  }
867                            }
868                    }
869    
870          public Style getPolygonHighlightStyle() {                  return newArea;
                 return polygonHighlightStyle;  
871          }          }
872    
873          public void setPolygonHighlightStyle(final Style polygonHighlightStyle) {          /**
874                  this.polygonHighlightStyle = polygonHighlightStyle;           * Should be called when the {@link JMapPane} is not needed no more to help
875          }           * the GarbageCollector
876             *
877             * Removes all {@link JMapPaneListener}s that are registered
878             *
879             * @author <a href="mailto:[email protected]">Stefan Alfons
880             *         Kr&uuml;ger</a>
881             */
882            public void dispose() {
883                    if (isDisposed())
884                            return;
885    
886          public Style getPolygonSelectionStyle() {                  setPainting(false);
                 return polygonSelectionStyle;  
         }  
887    
888          public void setPolygonSelectionStyle(final Style polygonSelectionStyle) {                  resizeTimer.stop();
889                  this.polygonSelectionStyle = polygonSelectionStyle;                  startRenderThreadsTimer.stop();
         }  
890    
891          protected void paintComponent(final Graphics g) {                  disposed = true;
                 super.paintComponent(g);  
892    
893                  if ((renderer == null) || (mapArea == null)) {                  if (bgExecuter != null) {
894                          return;                          bgExecuter.cancelTask();
895                            bgExecuter.dispose();
896                  }                  }
897    
898                  final Rectangle r = getBounds();                  if (localExecuter != null) {
899                  final Rectangle dr = new Rectangle(r.width, r.height);                          int i = 0;
900                            localExecuter.cancelTask();
901                  if (!r.equals(oldRect) || reset) {                          while (i++ < 10 && localExecuter.isRunning()) {
                         if (!r.equals(oldRect) && (mapArea == null)) {  
902                                  try {                                  try {
903                                          mapArea = context.getLayerBounds();                                          Thread.sleep(200);
904                                  } catch (final IOException e) {                                  } catch (final InterruptedException e) {
905                                          // TODO Auto-generated catch block                                          // TODO Auto-generated catch block
906                                          e.printStackTrace();                                          e.printStackTrace();
907                                  }                                  }
908                          }                          }
909                            if (localExecuter.isRunning()) {
910                          if (mapArea != null) {                                  System.out
911                                  /* either the viewer size has changed or we've done a reset */                                                  .println("BAD BAD BAD... still running the thread....");
                                 changed = true; /* note we need to redraw */  
                                 reset = false; /* forget about the reset */  
                                 oldRect = r; /* store what the current size is */  
   
                                 mapArea = fixAspectRatio(r, mapArea);  
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                  if (!mapArea.equals(oldMapArea)) { /* did the map extent change? */          /**
957                          changed = true;           * Draws a rectangle in XOR mode from the origin at {@link #startPos} to the
958                          oldMapArea = mapArea;           * given point. All in screen coordinates.
959                          // when we tell the context that the bounds have changed WMSLayers           */
960                          // can refresh them selves          protected void drawRectangle(final Graphics graphics, final Point startPos,
961                          context.setAreaOfInterest(mapArea, context                          final Point e) {
962                                          .getCoordinateReferenceSystem());  
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 (changed ) { /* if the map changed then redraw */                  if (width == 0 && height == 0)
975                          changed = false;                          return;
                         baseImage = new BufferedImage(dr.width, dr.height,  
                                         BufferedImage.TYPE_INT_ARGB);  
976    
977                          final Graphics2D ig = baseImage.createGraphics();                  graphics.setXORMode(Color.WHITE);
978                          /* System.out.println("rendering"); */                  graphics.drawRect(left, bottom, width, height);
979                          if (renderer.getContext() != null)          }
                                 renderer.setContext(context);  
                         labelCache.clear(); // work around anoying labelcache bug  
980    
981                          // draw the map          /**
982                          renderer.paint((Graphics2D) ig, dr, mapArea);           * Diretly paints scaled preview into the {@link SelectableXMapPane}. Used
983             * to give the user something to look at while we are rendering. Method
984             * should be called after {@link #setMapArea(Envelope)} has been set to the
985             * new mapArea and transform has been reset.<br>
986             *
987             * @param g
988             *            Graphics2D to paint the preview into
989             *
990             * @param state
991             *            Max be {@link #ZOOM_IN} or {@link #ZOOM_OUT}
992             */
993            protected boolean drawScaledPreviewImage_Zoom(final Graphics2D graphics) {
994    
995                          // TODO nur machen, wenn panning beginnt                  if (quickPreviewHint == 0)
996                          panningImage = new BufferedImage(dr.width, dr.height,                          return false;
                                         BufferedImage.TYPE_INT_RGB);  
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                  ((Graphics2D) g).drawImage(baseImage, 0, 0, this);                  if (oldMapArea == null)
1006                            return false;
1007    
1008                  if ((selection != null) && (selection.size() > 0)) {                  final Rectangle visibleArea = getVisibleRect();
                         // paint selection  
1009    
1010                          String type = selectionLayer.getFeatureSource().getSchema()                  // Calculate the oldMapArea in the current WindowCoordinates:
1011                                          .getDefaultGeometry().getType().getName();                  final Envelope oldMapWindow = tranformGeoToWindow(oldMapArea.getMinX(),
1012                          /* String type = selection.getDefaultGeometry().getGeometryType(); */                                  oldMapArea.getMinY(), oldMapArea.getMaxX(), oldMapArea
1013                          /* System.out.println(type); */                                                  .getMaxY(), null);
                         if (type == null)  
                                 type = "polygon";  
1014    
1015                          /* String type = "point"; */                  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                          if (type.toLowerCase().endsWith("polygon")) {                  graphics.drawImage(getPreFinalImage(), xx1, yy1, xx2, yy2,
1021                                  selectionStyle = polygonSelectionStyle;                                  (int) visibleArea.getMinX(), (int) visibleArea.getMinY(),
1022                          } else if (type.toLowerCase().endsWith("point")) {                                  (int) visibleArea.getMaxX(), (int) visibleArea.getMaxY(),
1023                                  selectionStyle = pointSelectionStyle;                                  getMapBackgroundColor(), null);
                         } else if (type.toLowerCase().endsWith("line")) {  
                                 selectionStyle = lineSelectionStyle;  
                         }  
1024    
1025                          selectionContext = new DefaultMapContext(DefaultGeographicCRS.WGS84);                  final Rectangle painedArea = new Rectangle(xx1, yy1, xx2 - xx1, yy2
1026                                    - yy1);
1027    
1028                          selectionContext.addLayer(selection, selectionStyle);                  SwingUtil.clearAround(graphics, painedArea, visibleArea);
                         selectionRenderer.setContext(selectionContext);  
1029    
1030                          selectImage = new BufferedImage(dr.width, dr.height,                  addGadgets(graphics);
                                         BufferedImage.TYPE_INT_ARGB);  
1031    
1032                          final Graphics2D ig = selectImage.createGraphics();                  quickPreviewHint = 0;
                         /* System.out.println("rendering selection"); */  
                         selectionRenderer.paint((Graphics2D) ig, dr, mapArea);  
1033    
1034                          ((Graphics2D) g).drawImage(selectImage, 0, 0, this);                  graphics.dispose();
                 }  
1035    
1036                  if (highlight && (highlightFeature != null)                  // Something has been drawn
1037                                  && (highlightFeature.size() > 0)) {                  return true;
1038                          /*          }
                          * String type = selection.getDefaultGeometry().getGeometryType();  
                          * System.out.println(type); if(type==null) type="polygon";  
                          */  
                         String type = highlightLayer.getFeatureSource().getSchema()  
                                         .getDefaultGeometry().getType().getName();  
                         /* String type = selection.getDefaultGeometry().getGeometryType(); */  
                         // System.out.println(type);  
                         if (type == null)  
                                 type = "polygon";  
1039    
1040                          /* String type = "point"; */          public MapContext getBgContext() {
1041                          Style highlightStyle = null;                  return bgContext;
1042                          if (type.toLowerCase().endsWith("polygon")) {          }
                                 highlightStyle = polygonHighlightStyle;  
                         } else if (type.toLowerCase().endsWith("point")) {  
                                 highlightStyle = pointHighlightStyle;  
                         } else if (type.toLowerCase().endsWith("line")) {  
                                 highlightStyle = lineHighlightStyle;  
                         }  
1043    
1044                          final MapContext highlightContext = new DefaultMapContext(          /**
1045                                          DefaultGeographicCRS.WGS84);           * Lazyly initializes a {@link BufferedImage} for the background renderer.
1046             */
1047            private Image getBgImage() {
1048                    //
1049                    // if (bgImage == null) {
1050                    // bgImage = createImage(getBounds().width, getBounds().height);
1051                    // }
1052    
1053                          highlightContext.addLayer(highlightFeature, highlightStyle);                  return bgImage;
1054                          highlightRenderer.setContext(highlightContext);          }
1055    
1056                          /* System.out.println("rendering highlight"); */          public MapContext getContext() {
1057                          highlightRenderer.paint((Graphics2D) g, dr, mapArea);                  if (localContext == null) {
1058                            setLocalContext(new DefaultMapContext());
1059                  }                  }
1060                    return localContext;
1061          }          }
1062    
1063          private Envelope fixAspectRatio(final Rectangle r, final Envelope mapArea) {          private BufferedImage getFinalImage() {
1064                    //
1065                    if (finalImage == null) {
1066                            // Rectangle curPaintArea = getVisibleRect();
1067                            finalImage = new BufferedImage(getBounds().width,
1068                                            getBounds().height, IMAGETYPE);
1069    
1070                  final double mapWidth = mapArea.getWidth(); /* get the extent of the map */                          requestStartRendering();
1071                  final double mapHeight = mapArea.getHeight();                  }
1072                  final double scaleX = r.getWidth() / mapArea.getWidth(); /*                  return finalImage;
1073                                                                                                                           * calculate the new          }
                                                                                                                          * scale  
                                                                                                                          */  
1074    
1075                  final double scaleY = r.getHeight() / mapArea.getHeight();          public RenderingHints getJava2dHints() {
1076                  double scale = 1.0; // stupid compiler!                  return java2dHints;
1077            }
1078    
1079                  if (scaleX < scaleY) { /* pick the smaller scale */          /**
1080                          scale = scaleX;           * Lazyly initializes a {@link BufferedImage} for the background renderer.
1081                  } else {           */
1082                          scale = scaleY;          private BufferedImage getLocalImage() {
1083    
1084                    if (localImage == null) {
1085                            localImage = new BufferedImage(getBounds().width,
1086                                            getBounds().height, IMAGETYPE_withAlpha);
1087                  }                  }
1088    
1089                  /* calculate the difference in width and height of the new extent */                  return localImage;
1090                  final double deltaX = /* Math.abs */((r.getWidth() / scale) - mapWidth);          }
                 final double deltaY = /* Math.abs */((r.getHeight() / scale) - mapHeight);  
1091    
1092                  /*          /**
1093                   * System.out.println("delta x " + deltaX);           * Returns a copy of the mapArea
1094                   * System.out.println("delta y " + deltaY);           *
1095                   */           * @return
1096             */
1097            public Envelope getMapArea() {
1098                    if (mapArea == null) {
1099                            ReferencedEnvelope mapArea_ = null;
1100                            try {
1101                                    mapArea_ = localContext.getLayerBounds();
1102                            } catch (final IOException e) {
1103                                    LOGGER.warn("context.getLayerBounds()", e);
1104                            }
1105    
1106                  /* create the new extent */                          if (mapArea_ != null) {
1107                  final Coordinate ll = new Coordinate(mapArea.getMinX() - (deltaX / 2.0),                                  mapImageInvalid = true; /* note we need to redraw */
1108                                  mapArea.getMinY() - (deltaY / 2.0));  //                              setMapArea(mapArea_); // results in a loop
1109                  final Coordinate ur = new Coordinate(mapArea.getMaxX() + (deltaX / 2.0),                                  mapArea = bestAllowedMapArea(mapArea_);
1110                                  mapArea.getMaxY() + (deltaY / 2.0));                          }
1111                    }
1112    
1113                    if (mapArea == null)
1114                            return null;
1115    
1116                  return new Envelope(ll, ur);                  return new Envelope(mapArea);
1117          }          }
1118    
1119          public void doSelection(final double x, final double y, final MapLayer layer) {          /**
1120             * Returns the background {@link Color} of the map pane. Default is white.
1121             **/
1122            public Color getMapBackgroundColor() {
1123                    return mapBackgroundColor;
1124            }
1125    
1126                  final Geometry geometry = gf.createPoint(new Coordinate(x, y));          /**
1127             * Get the BufferedImage to use as a flaoting icon in the lower right
1128             * corner.
1129             *
1130             * @return <code>null</code> if the feature is deactivated.
1131             */
1132            public BufferedImage getMapImage() {
1133                    return mapImage;
1134            }
1135    
1136                  // org.opengis.geometry.Geometry geometry = new Point();          /**
1137             * Returns the evelope of the viewable area. The JMapPane will never show
1138             * anything outside of this extend. If this has been set to
1139             * <code>null</code> via {@link #setMaxExtend(Envelope)}, it tries to return
1140             * quickly the context's bounds. It it takes to long to determine the
1141             * context bounds, <code>null</code> is returned.
1142             *
1143             * @param maxExtend
1144             *            <code>null</code> to not have this restriction.
1145             */
1146    
1147                  findFeature(geometry, layer);          public Envelope getMaxExtend() {
1148                    if (maxExtend == null) {
1149                            final ReferencedEnvelope layerBounds = GTUtil
1150                                            .getVisibleLayoutBounds(localContext);
1151                            if (layerBounds == null) {
1152                                    // TODO Last fallback could be the CRS valid area
1153                                    return null;
1154                            }
1155    
1156                            // Kartenbereich um 10% vergroessern
1157                            return JTSUtil.fixAspectRatio(this.getBounds(), JTSUtil
1158                                            .expandEnvelope(layerBounds, 0.1), true);
1159                    }
1160                    return maxExtend;
1161          }          }
1162    
1163          /**          /**
1164           * @param geometry           * Retuns the maximum allowed zoom scale. This is the smaller number value
1165           *            - a geometry to construct the filter with           * of the two. Defaults to {@link Double}.MIN_VALUE
1166           * @param i           *
1167           *            - the index of the layer to search           * @author <a href="mailto:[email protected]">Stefan Alfons
1168           * @throws IndexOutOfBoundsException           *         Kr&uuml;ger</a>
1169           */           */
1170          private void findFeature(final Geometry geometry, final MapLayer layer)          public Double getMaxZoomScale() {
1171                          throws IndexOutOfBoundsException {                  return maxZoomScale;
1172                  org.opengis.filter.spatial.BinarySpatialOperator f = null;          }
1173    
1174                  if ((context == null) || (layer == null)) {          /**
1175                          return;           * Retuns the minimum allowed zoom scale. This is the bigger number value of
1176                  }           * the two. Defaults to {@link Double}.MAX_VALUE
1177             *
1178             * @author <a href="mailto:[email protected]">Stefan Alfons
1179             *         Kr&uuml;ger</a>
1180             */
1181            public Double getMinZoomScale() {
1182                    return minZoomScale;
1183            }
1184    
1185                  try {          private Image getPreFinalImage() {
1186                          String name = layer.getFeatureSource().getSchema()                  // if (preFinalImage == null) {
1187                                          .getDefaultGeometry().getLocalName();                  //                      
1188                    // // Rectangle curPaintArea = getVisibleRect();
1189                    // // preFinalImage = new BufferedImage(curPaintArea.width,
1190                    // // curPaintArea.height, BufferedImage.TYPE_INT_RGB);
1191                    //                      
1192                    // preFinalImage = createImage(getBounds().width, getBounds().height);
1193                    //
1194                    // requestStartRendering();
1195                    // }
1196                    return preFinalImage;
1197            }
1198    
1199                          if (name == "") {          public Map<Object, Object> getRendererHints() {
1200                                  name = "the_geom";                  return rendererHints;
1201                          }          }
1202    
1203                          try {          /**
1204                                  f = ff.contains(ff.property(name), ff.literal(geometry));           * Liefert eine affine Transformation, um von den Fenster-Koordinaten in die
1205                                  if (selectionManager != null) {           * Karten-Koordinaten (Lat/Lon) umzurechnen.
1206  //                                      System.out.println("selection changed");           *
1207                                          selectionManager.selectionChanged(this, f);           * @return eine Kopie der aktuellen Transformation; <code>null</code> wenn
1208             *         noch keine Karte angezeigt wird
1209             */
1210            public AffineTransform getScreenToWorld() {
1211                    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                                  }          public int getState() {
1220                          } catch (final IllegalFilterException e) {                  return state;
1221                                  // TODO Auto-generated catch block          }
                                 e.printStackTrace();  
                         }  
1222    
1223                          /*          /**
1224                           * // f.addLeftGeometry(ff.property(name)); //           * Liefert den statisch eingestellten Cursor, der unabhaengig von der
1225                           * System.out.println("looking with " + f); FeatureCollection fc =           * eingestellten MapPane-Aktion (Zoom, Auswahl, ...) verwendet wird.
1226                           * layer.getFeatureSource().getFeatures(f);           *
1227                           *           * @return {@code null}, wenn kein statischer Cursor verwendet, sondern der
1228                           *           *         Cursor automatisch je nach MapPane-Aktion eingestellt wird.
1229                           *           */
1230                           * if (fcol == null) { fcol = fc;          public Cursor getStaticCursor() {
1231                           *                  return this.staticCursor;
1232                           * // here we should set the defaultgeom type } else {          }
                          * fcol.addAll(fc); }  
                          */  
1233    
1234                          /*          public AffineTransform getWorldToScreenTransform() {
1235                           * GeometryAttributeType gat =                  if (worldToScreen == null) {
1236                           * layer.getFeatureSource().getSchema().getDefaultGeometry();                          resetTransforms();
1237                           * fcol.setDefaultGeometry((Geometry)gat.createDefaultValue());                  }
1238                           */                  // nur Kopie der Transformation zurueckgeben!
1239                    return new AffineTransform(worldToScreen);
1240            }
1241    
1242                          /*          /**
1243                           * Iterator fi = fc.iterator(); while (fi.hasNext()) { SimpleFeature feat           * A flag indicating if dispose() has already been called. If true, then
1244                           * = (SimpleFeature) fi.next(); System.out.println("selected " +           * further use of this {@link SelectableXMapPane} is undefined.
1245                           * feat.getAttribute("STATE_NAME")); }           */
1246                           */          private boolean isDisposed() {
1247                  } catch (final IllegalFilterException e) {                  return disposed;
1248                          // TODO Auto-generated catch block          }
                         e.printStackTrace();  
                 }  
                 return;  
         }  
   
         public void mouseClicked(final MouseEvent e) {  
                 if (mapArea == null) return;  
                 // System.out.println("before area "+mapArea+"\nw:"+mapArea.getWidth()+"  
                 // h:"+mapArea.getHeight());  
                 final Rectangle bounds = this.getBounds();  
                 final double x = (double) (e.getX());  
                 final double y = (double) (e.getY());  
                 final double width = mapArea.getWidth();  
                 final double height = mapArea.getHeight();  
                 // xulu.sc  
                 // double width2 = mapArea.getWidth() / 2.0;  
                 // double height2 = mapArea.getHeight() / 2.0;  
                 final double width2 = width / 2.0;  
                 final double height2 = height / 2.0;  
                 // xulu.ec  
                 final double mapX = ((x * width) / (double) bounds.width) + mapArea.getMinX();  
                 final double mapY = (((bounds.getHeight() - y) * height) / (double) bounds.height)  
                                 + mapArea.getMinY();  
1249    
1250                  /*          /**
1251                   * System.out.println(""+x+"->"+mapX);           * Returns whether a layer is regarded or ignored on {@link #SELECT_TOP},
1252                   * System.out.println(""+y+"->"+mapY);           * {@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 layer
1256             *            a layer
1257             */
1258            public boolean isMapLayerSelectable(final MapLayer layer) {
1259                    final Boolean selectable = mapLayerSelectable.get(layer);
1260                    return selectable == null ? true : selectable;
1261            }
1262    
1263                  /*          /**
1264                   * Coordinate ll = new Coordinate(mapArea.getMinX(), mapArea.getMinY());           * Return <code>true</code> if a CRS and a {@link #mapArea} are set and the
1265                   * Coordinate ur = new Coordinate(mapArea.getMaxX(), mapArea.getMaxY());           * {@link XMapPane} is visible and has bounds set.
1266                   */           */
1267                  double zlevel = 1.0;          public boolean isWellDefined() {
1268    
1269                  switch (state) {                  try {
                 case Pan:  
                         zlevel = 1.0;  
                         // xulu.sc SK: return here.. a mouselistener is managing the PANNING  
                         // break;  
                         return;  
                         // xulu.ec  
                 case ZoomIn:  
                         zlevel = zoomFactor;  
1270    
1271                          break;                          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                  case ZoomOut:          public void mouseDragged(final Point startPos, final Point lastPos,
1288                          zlevel = 1.0 / zoomFactor;                          final MouseEvent event) {
1289    
1290                          break;                  if ((getState() == XMapPane.PAN)
1291                                    || ((event.getModifiersEx() & InputEvent.BUTTON3_DOWN_MASK) != 0)) {
1292    
1293                  case Select:                          if (getCursor() != SwingUtil.PANNING_CURSOR) {
1294                          doSelection(mapX, mapY, selectionLayer);                                  setCursor(SwingUtil.PANNING_CURSOR);
1295    
1296                          return;                                  // While panning, we deactivate the rendering. So the tasts are
1297                                    // ready to start when the panning os done.
1298                                    if (bgExecuter != null)
1299                                            bgExecuter.cancelTask();
1300                                    if (localExecuter != null)
1301                                            localExecuter.cancelTask();
1302                            }
1303    
1304                            if (lastPos.x > 0 && lastPos.y > 0) {
1305                                    final int dx = event.getX() - lastPos.x;
1306                                    final int dy = event.getY() - lastPos.y;
1307    
1308                                    // TODO Stop dragging when the drag would not be valid...
1309                                    // boolean dragValid = true;
1310                                    // // check if this panning results in a valid mapArea
1311                                    // {
1312                                    // Rectangle winBounds = xMapPane.getBounds();
1313                                    // winBounds.translate(xMapPane.imageOrigin.x,
1314                                    // -xMapPane.imageOrigin.y);
1315                                    // Envelope newMapAreaBefore = xMapPane.tranformWindowToGeo(
1316                                    // winBounds.x, winBounds.y, winBounds.x
1317                                    // + winBounds.width, winBounds.y
1318                                    // + winBounds.height);
1319                                    //                                      
1320                                    //
1321                                    // winBounds = xMapPane.getBounds();
1322                                    // Point testIng = new Point(xMapPane.imageOrigin);
1323                                    // testIng.translate(dx, dy);
1324                                    // winBounds.translate(testIng.x, -testIng.y);
1325                                    // Envelope newMapAreaAfter = xMapPane.tranformWindowToGeo(
1326                                    // winBounds.x, winBounds.y, winBounds.x
1327                                    // + winBounds.width, winBounds.y
1328                                    // + winBounds.height);
1329                                    //
1330                                    // // If the last drag doesn't change the MapArea anymore cancel
1331                                    // it.
1332                                    // if (xMapPane.bestAllowedMapArea(newMapAreaAfter).equals(
1333                                    // xMapPane.bestAllowedMapArea(newMapAreaBefore))){
1334                                    // dragValid = false;
1335                                    // return;
1336                                    // }
1337                                    // }
1338    
1339                                    imageOrigin.translate(dx, dy);
1340                                    updateFinalImage();
1341                                    repaint();
1342                            }
1343    
1344                    } else if ((getState() == XMapPane.ZOOM_IN)
1345                                    || (getState() == XMapPane.ZOOM_OUT)
1346                                    || (getState() == XMapPane.SELECT_ALL)
1347                                    || (getState() == XMapPane.SELECT_TOP)
1348                    // || (getState() == XMapPane.SELECT_ONE_FROM_TOP)
1349                    ) {
1350                            final Graphics graphics = getGraphics();
1351    
1352                            drawRectangle(graphics, startPos, event.getPoint());
1353    
1354                            if ((lastPos.x > 0) && (lastPos.y > 0)) {
1355                                    drawRectangle(graphics, startPos, lastPos);
1356                            }
1357    
1358                            graphics.dispose();
1359    
                 default:  
                         return;  
1360                  }                  }
1361    
1362                  final Coordinate ll = new Coordinate(mapX - (width2 / zlevel), mapY          }
                                 - (height2 / zlevel));  
                 final Coordinate ur = new Coordinate(mapX + (width2 / zlevel), mapY  
                                 + (height2 / zlevel));  
                 // xulu.sc SK: Check for min/max scale  
                 // mapArea = new Envelope(ll, ur);  
                 final Envelope newMapArea = new Envelope(ll, ur);  
                 setMapArea(bestAllowedMapArea(newMapArea));  
                 // xulu.ec  
1363    
1364                  // sk.ec          /**
1365             * Called by the {@link RenderingExecutor} when rendering was cancelled.
1366             */
1367            public void onRenderingCancelled() {
1368                    repaintTimer.stop();
1369                    LOGGER.debug("Rendering cancelled");
1370            }
1371    
1372                  // System.out.println("after area "+mapArea+"\nw:"+mapArea.getWidth()+"          /**
1373                  // h:"+mapArea.getHeight());           * Called by the {@link RenderingExecutor} when rendering has been
1374             * completed.
1375             */
1376            public void onRenderingCompleted() {
1377                    repaintTimer.stop();
1378                    updateFinalImage();
1379                  repaint();                  repaint();
1380          }          }
1381    
1382          public void mouseEntered(final MouseEvent e) {          /**
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    
         public void mouseExited(final MouseEvent e) {  
1398          }          }
1399    
1400          public void mousePressed(final MouseEvent e) {          public void onRenderingPending() {
1401                  startX = e.getX();                  // LOGGER.debug("Pending rendering updates the preview...");
1402                  startY = e.getY();                  updateFinalImage();
1403                  lastX = 0;                  repaint();
                 lastY = 0;  
1404          }          }
1405    
1406          public void mouseReleased(final MouseEvent e) {          @Override
1407                  final int endX = e.getX();          protected void paintComponent(final Graphics g) {
1408                  final int endY = e.getY();                  if (!acceptsRepaintCalls)
1409                            return;
1410    
1411                  processDrag(startX, startY, endX, endY, e);                  // Maybe update the cursor and maybe stop the repainting timer
1412                  lastX = 0;                  updateCursor();
                 lastY = 0;  
1413    
1414                  /**                  super.paintComponent(g); // candidate for removal
                  * Es wird nicht (mehr) gepannt!  
                  */  
                 panning_started = false;  
         }  
1415    
1416          public void mouseDragged(final MouseEvent e) {                  boolean paintedSomething = false;
1417                  final Graphics graphics = this.getGraphics();  
1418                  final int x = e.getX();                  if (mapImageInvalid) { /* if the map changed then redraw */
1419                  final int y = e.getY();  
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    
                 if ((state == JMapPane.Pan)  
                                 || ((e.getModifiersEx() & InputEvent.BUTTON3_DOWN_MASK) != 0)) {  
                         /**  
                          * SK: Der Cursor wird auf PANNING gesetzt.  
                          */  
                         if (panning_started == false) {  
                                 panning_started = true;  
                                 setCursor(SwingUtil.PANNING_CURSOR);  
1439                          }                          }
1440    
1441                          // move the image with the mouse                          if (paneResized) {
1442                          if ((lastX > 0) && (lastY > 0)) {                                  paneResized = false;
1443                                  final int dx = lastX - startX;                                  disposeImages();
                                 final int dy = lastY - startY;  
                                 // System.out.println("translate "+dx+","+dy);  
                                 final Graphics2D g2 = panningImage.createGraphics();  
                                 g2.setBackground(new Color(240, 240, 240)); // TODO richtige  
                                                                                                                         // farbe? am besten  
                                                                                                                         // vom L&F die  
                                                                                                                         // hintergrundfarbe  
                                                                                                                         // auslesen...  
                                   
                                 g2.clearRect(0, 0, this.getWidth(), this.getHeight());  
                                 g2.drawImage(baseImage, dx, dy, this);  
                                 graphics.drawImage(panningImage, 0, 0, this);  
                         }  
   
                         lastX = x;  
                         lastY = y;  
                 } else  
   
                 if ((state == JMapPane.ZoomIn) || (state == JMapPane.ZoomOut)) {  
   
                         graphics.setXORMode(Color.WHITE);  
   
                         if ((lastX > 0) && (lastY > 0)) {  
                                 drawRectangle(graphics);  
                         }  
   
                         // draw new box  
                         lastX = x;  
                         lastY = y;  
                         drawRectangle(graphics);  
                 } else if (state == JMapPane.Select && selectionLayer != null) {  
   
                         // construct a new bbox filter  
                         final Rectangle bounds = this.getBounds();  
   
                         final double mapWidth = mapArea.getWidth();  
                         final double mapHeight = mapArea.getHeight();  
   
                         final double x1 = ((this.startX * mapWidth) / (double) bounds.width)  
                                         + mapArea.getMinX();  
                         final double y1 = (((bounds.getHeight() - this.startY) * mapHeight) / (double) bounds.height)  
                                         + mapArea.getMinY();  
                         final double x2 = ((x * mapWidth) / (double) bounds.width)  
                                         + mapArea.getMinX();  
                         final double y2 = (((bounds.getHeight() - y) * mapHeight) / (double) bounds.height)  
                                         + mapArea.getMinY();  
                         final double left = Math.min(x1, x2);  
                         final double right = Math.max(x1, x2);  
                         final double bottom = Math.min(y1, y2);  
                         final double top = Math.max(y1, y2);  
   
                         String name = selectionLayer.getFeatureSource().getSchema()  
                                         .getDefaultGeometry().getName();  
   
                         if (name == "") {  
                                 name = "the_geom";  
                         }  
                         final Filter bb = ff.bbox(ff.property(name), left, bottom, right, top,  
                                         getContext().getCoordinateReferenceSystem().toString());  
                         if (selectionManager != null) {  
                                 selectionManager.selectionChanged(this, bb);  
1444                          }                          }
1445    
1446                          graphics.setXORMode(Color.green);                          // Start the Threads and Timers to render the image
1447                            requestStartRendering();
1448    
1449                          /*                  }
1450                           * if ((lastX > 0) && (lastY > 0)) { drawRectangle(graphics); }  
1451                           */                  if (!paintedSomething) {
1452    
1453                            g.drawImage(getFinalImage(), 0, 0, null);
1454    
1455                            g.dispose(); // cand. for removal
1456    
1457                          // draw new box                          paintedSomething = true; // cand. for removal
                         lastX = x;  
                         lastY = y;  
                         drawRectangle(graphics);  
1458                  }                  }
1459    
1460          }          }
1461    
1462          // sk.cs          /**
1463          // private void processDrag(int x1, int y1, int x2, int y2) {           * Heavily works on releasing all resources related to the four
1464          // sk.ce           * {@link Image}s used to cache the results of the different renderers.<br>
1465          protected void processDrag(final int x1, final int y1, final int x2,           * In November 2009 i had some memory leaking problems with {@link XMapPane}
1466                          final int y2, final MouseEvent e) {           * . 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                   * If no layer is availabe we dont want a NullPointerException           * times.
1470                   */           */
1471                  if (mapArea == null)          private void disposeImages() {
                         return;  
1472    
1473                  // System.out.println("processing drag from " + x1 + "," + y1 + " -> "                  // System.out.println("vorher = "
1474                  // + x2 + "," + y2);                  // + new MbDecimalFormatter().format(LangUtil.gcTotal()));
1475                  if ((x1 == x2) && (y1 == y2)) {                  // bi.flush();
1476                          if (isClickable()) {                  // return bi = null;
1477                                  mouseClicked(new MouseEvent(this, 0, new Date().getTime(), 0,                  // System.out.println("nacher = "
1478                                                  x1, y1, y2, false));                  // + new MbDecimalFormatter().format(LangUtil.gcTotal()));
1479                          }                  //
1480                    // System.out.println("\n");
1481    
1482                          return;                  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                  final Rectangle bounds = this.getBounds();          }
1504    
1505                  final double mapWidth = mapArea.getWidth();          /**
1506                  final double mapHeight = mapArea.getHeight();           * 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() {
1511    
1512                  final double startX = ((x1 * mapWidth) / (double) bounds.width)                  final Rectangle winBounds = getBounds();
1513                                  + mapArea.getMinX();                  winBounds.translate(-imageOrigin.x, -imageOrigin.y);
1514                  final double startY = (((bounds.getHeight() - y1) * mapHeight) / (double) bounds.height)                  final Envelope newMapArea = tranformWindowToGeo(winBounds.x,
1515                                  + mapArea.getMinY();                                  winBounds.y, winBounds.x + winBounds.width, winBounds.y
1516                  final double endX = ((x2 * mapWidth) / (double) bounds.width)                                                  + winBounds.height);
                                 + mapArea.getMinX();  
                 final double endY = (((bounds.getHeight() - y2) * mapHeight) / (double) bounds.height)  
                                 + mapArea.getMinY();  
   
                 if ((state == JMapPane.Pan) || (e.getButton() == MouseEvent.BUTTON3)) {  
                         // move the image with the mouse  
                         // calculate X offsets from start point to the end Point  
                         final double deltaX1 = endX - startX;  
   
                         // System.out.println("deltaX " + deltaX1);  
                         // new edges  
                         final double left = mapArea.getMinX() - deltaX1;  
                         final double right = mapArea.getMaxX() - deltaX1;  
   
                         // now for Y  
                         final double deltaY1 = endY - startY;  
   
                         // System.out.println("deltaY " + deltaY1);  
                         final double bottom = mapArea.getMinY() - deltaY1;  
                         final double top = mapArea.getMaxY() - deltaY1;  
                         final Coordinate ll = new Coordinate(left, bottom);  
                         final Coordinate ur = new Coordinate(right, top);  
                         // xulu.sc  
                         // mapArea = fixAspectRatio(this.getBounds(), new Envelope(ll, ur));  
                         setMapArea(fixAspectRatio(this.getBounds(), new Envelope(ll, ur)));  
                         // xulu.ec  
                 } else if (state == JMapPane.ZoomIn) {  
   
                         // Zu kleine Flächen sollen nicht gezoomt werden.  
                         // sk.bc  
                         if ((Math.abs(x1 - x2) * Math.abs(y2 - y1)) < 150)  
                                 return;  
                         // sk.ec  
1517    
1518                          drawRectangle(this.getGraphics());                  imageOrigin.x = 0;
1519                          // make the dragged rectangle (in map coords) the new BBOX                  imageOrigin.y = 0;
1520                          final double left = Math.min(startX, endX);  
1521                          final double right = Math.max(startX, endX);                  if (!setMapArea(newMapArea)) {
1522                          final double bottom = Math.min(startY, endY);                          /**
1523                          final double top = Math.max(startY, endY);                           * If setMapArea returns true, the finalImage is updated anyways.
1524                          final Coordinate ll = new Coordinate(left, bottom);                           * This if-case exists to ensure that we repaint a correct image
1525                          final Coordinate ur = new Coordinate(right, top);                           * even if the new panning area has been denied.
                         // xulu.sc  
   
                         // mapArea = fixAspectRatio(this.getBounds(), new Envelope(ll, ur));  
                         setMapArea(bestAllowedMapArea(new Envelope(ll, ur)));  
   
                         // sk.sc  
 //                      {  
 //                      // SK tries to paint a preview of the zoom ;-9 aha.... well  
 //                      Graphics2D graphics = (Graphics2D) JMapPane.this.getGraphics();  
 //                      graphics.setRenderingHint(RenderingHints.KEY_INTERPOLATION,  
 //                                      RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR);  
 //                      graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING,  
 //                                      RenderingHints.VALUE_ANTIALIAS_OFF);  
 //                      graphics.setRenderingHint(RenderingHints.KEY_RENDERING,  
 //                                      RenderingHints.VALUE_RENDER_SPEED);  
 //                      graphics.drawImage(baseImage, 0, 0, JMapPane.this.getWidth(),  
 //                                      JMapPane.this.getHeight(), x1, y1, x2, y2, null);  
 //                      }  
                         // xulu.ec  
                 } else if (state == JMapPane.ZoomOut) {  
                         drawRectangle(this.getGraphics());  
   
                         // make the dragged rectangle in screen coords the new map size?  
                         final double left = Math.min(startX, endX);  
                         final double right = Math.max(startX, endX);  
                         final double bottom = Math.min(startY, endY);  
                         final double top = Math.max(startY, endY);  
                         final double nWidth = (mapWidth * mapWidth) / (right - left);  
                         final double nHeight = (mapHeight * mapHeight) / (top - bottom);  
                         final double deltaX1 = left - mapArea.getMinX();  
                         final double nDeltaX1 = (deltaX1 * nWidth) / mapWidth;  
                         final double deltaY1 = bottom - mapArea.getMinY();  
                         final double nDeltaY1 = (deltaY1 * nHeight) / mapHeight;  
                         final Coordinate ll = new Coordinate(mapArea.getMinX() - nDeltaX1,  
                                         mapArea.getMinY() - nDeltaY1);  
                         final double deltaX2 = mapArea.getMaxX() - right;  
                         final double nDeltaX2 = (deltaX2 * nWidth) / mapWidth;  
                         final double deltaY2 = mapArea.getMaxY() - top;  
                         final double nDeltaY2 = (deltaY2 * nHeight) / mapHeight;  
                         final Coordinate ur = new Coordinate(mapArea.getMaxX() + nDeltaX2,  
                                         mapArea.getMaxY() + nDeltaY2);  
                         // xulu.sc  
                         // mapArea = fixAspectRatio(this.getBounds(), new Envelope(ll, ur));  
                         setMapArea(bestAllowedMapArea(new Envelope(ll, ur)));  
   
                         // xulu.ec  
                 } else if (state == JMapPane.Select && selectionLayer != null) {  
                         final double left = Math.min(startX, endX);  
                         final double right = Math.max(startX, endX);  
                         final double bottom = Math.min(startY, endY);  
                         final double top = Math.max(startY, endY);  
   
                         String name = selectionLayer.getFeatureSource().getSchema()  
                                         .getDefaultGeometry().getLocalName();  
   
                         if (name == "") {  
                                 name = "the_geom";  
                         }  
                         final Filter bb = ff.bbox(ff.property(name), left, bottom, right, top,  
                                         getContext().getCoordinateReferenceSystem().toString());  
                         // System.out.println(bb.toString());  
                         if (selectionManager != null) {  
                                 selectionManager.selectionChanged(this, bb);  
                         }  
                         /*  
                          * FeatureCollection fc; selection = null; try { fc =  
                          * selectionLayer.getFeatureSource().getFeatures(bb); selection =  
                          * fc; } catch (IOException e) { e.printStackTrace(); }  
1526                           */                           */
1527                            updateFinalImage();
1528                            repaint();
1529                  }                  }
1530    
1531                  // xulu.so                  if (getCursor() == SwingUtil.PANNING_CURSOR)
1532                  // setMapArea(mapArea);                          setCursor(SwingUtil.PAN_CURSOR);
                 // xulu.eo  
                 repaint();  
1533          }          }
1534    
1535          private boolean isClickable() {          //
1536                  return clickable;          // /**
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          private org.geotools.styling.Style setupStyle(final int type, final Color color) {          /**
1558                  final StyleFactory sf = org.geotools.factory.CommonFactoryFinder           * Entfernt einen Listener von der Map.
1559                                  .getStyleFactory(null);           *
1560                  final StyleBuilder sb = new StyleBuilder();           * @param l
1561             *            zu entfernender Listener
1562             */
1563            public void removeMapPaneListener(final JMapPaneListener l) {
1564                    mapPaneListeners.remove(l);
1565            }
1566    
1567                  org.geotools.styling.Style s = sf.createStyle();          /**
1568                  s.setTitle("selection");           * 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                  // TODO parameterise the color          }
                 final PolygonSymbolizer ps = sb.createPolygonSymbolizer(color);  
                 ps.setStroke(sb.createStroke(color));  
1580    
1581                  final LineSymbolizer ls = sb.createLineSymbolizer(color);          /**
1582                  final Graphic h = sb.createGraphic();           * Berechnet die Transformation zwischen Fenster- und Karten-Koordinaten
1583                  h.setMarks(new Mark[] { sb.createMark("square", color) });           * neu.
1584             */
1585            protected void resetTransforms() {
1586                    if (getMapArea() == null || getWidth() == 0 || getHeight() == 0)
1587                            return;
1588    
1589                  final PointSymbolizer pts = sb.createPointSymbolizer(h);                  // We store the last Transform
1590                    oldScreenToWorld = screenToWorld;
1591    
1592                  // Rule r = sb.createRule(new Symbolizer[]{ps,ls,pts});                  this.screenToWorld = new AffineTransform(
1593                  switch (type) {                  // Genauso wie die Fenster-Koordinaten, werden die Longitude-Koordinaten
1594                  case POLYGON:                                  // nach rechts (Osten) hin groesser
1595                          s = sb.createStyle(ps);                                  // --> 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                          break;                  try {
1612                            this.worldToScreen = screenToWorld.createInverse();
1613                    } catch (final NoninvertibleTransformException e) {
1614                            LOGGER.error(e);
1615                    }
1616            }
1617    
1618                  case POINT:          public void setBgContext(final MapContext context) {
                         s = sb.createStyle(pts);  
1619    
1620                          break;                  // Remove the default listener from the old context
1621                    if (this.bgContext != null) {
1622                            this.bgContext.removeMapLayerListListener(bgContextListener);
1623    
1624                  case LINE:                          // adding listener to all layers
1625                          s = sb.createStyle(ls);                          for (final MapLayer mapLayer : bgContext.getLayers()) {
1626                                    mapLayer.removeMapLayerListener(bgMapLayerListener);
1627                            }
1628                  }                  }
1629    
1630                  return s;                  this.bgContext = context;
         }  
1631    
1632          public void highlightChanged(final HighlightChangedEvent e) {                  if (context != null) {
1633                  final org.opengis.filter.Filter f = e.getFilter();                          setMapArea(bgContext.getAreaOfInterest());
1634    
1635                  try {                          this.bgContext.addMapLayerListListener(bgContextListener);
                         highlightFeature = highlightLayer.getFeatureSource().getFeatures(f);  
                 } catch (final IOException e1) {  
                         // TODO Auto-generated catch block  
                         e1.printStackTrace();  
                 }  
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();                  repaint();
1644          }          }
1645    
1646          public void propertyChange(final PropertyChangeEvent evt) {          public void setJava2dHints(final RenderingHints java2dHints) {
1647                  final String prop = evt.getPropertyName();                  this.java2dHints = java2dHints;
1648            }
1649    
1650                  if (prop.equalsIgnoreCase("crs")) {          /**
1651                          context.setAreaOfInterest(context.getAreaOfInterest(),           *
1652                                          (CoordinateReferenceSystem) evt.getNewValue());           * @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          public boolean isReset() {                  this.localContext = context;
                 return reset;  
         }  
1666    
1667          public void setReset(final boolean reset) {                  if (context != null) {
                 this.reset = reset;  
         }  
1668    
1669          public void layerAdded(final MapLayerListEvent event) {                          setMapArea(localContext.getAreaOfInterest());
                 changed = true;  
1670    
1671                  if (context.getLayers().length == 1) { // the first one                          localRenderer.setContext(localContext);
1672    
1673                          try {                          this.localContext.addMapLayerListListener(localContextListener);
                                 // xulu.sc  
                                 // mapArea = context.getLayerBounds();  
                                 mapArea = context.getAreaOfInterest();  
                                 if (mapArea == null)  
                                         mapArea = context.getLayerBounds();  
                                 // xulu.ec  
                         } catch (final IOException e) {  
                                 // TODO Auto-generated catch block  
                                 e.printStackTrace();  
                         }  
1674    
1675                          reset = true;                          // adding listener to all layers
1676                            for (final MapLayer mapLayer : localContext.getLayers()) {
1677                                    mapLayer.addMapLayerListener(localMapLayerListener);
1678                            }
1679                  }                  }
1680    
1681                    mapImageInvalid = true;
1682                  repaint();                  repaint();
1683          }          }
1684    
1685          public void layerRemoved(final MapLayerListEvent event) {          /**
1686                  changed = true;           * @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();                  repaint();
1747    
1748                    // LOGGER.debug("New maparea = " + mapArea);
1749                    return true;
1750          }          }
1751    
1752          public void layerChanged(final MapLayerListEvent event) {          /**
1753                  changed = true;           * Set the background color of the map.
1754                  // System.out.println("layer changed - repaint");           *
1755                  repaint();           * @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          public void layerMoved(final MapLayerListEvent event) {          /**
1764                  changed = true;           * Set the BufferedImage to use as a flaoting icon in the lower right corner
1765                  repaint();           *
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          protected void drawRectangle(final Graphics graphics) {          /**
1774                  // undraw last box/draw new box           * Sets whether a layer is regarded or ignored on {@link #SELECT_TOP},
1775                  final int left = Math.min(startX, lastX);           * {@link #SELECT_ALL} and {@link #SELECT_ONE_FROM_TOP} actions.
1776                  final int right = Math.max(startX, lastX);           *
1777                  final int top = Math.max(startY, lastY);           * @param layer
1778                  final int bottom = Math.min(startY, lastY);           *            a layer
1779                  final int width = right - left;           * @param selectable
1780                  final int height = top - bottom;           *            if {@code false} the layer is ignored during the upper
1781                  // System.out.println("drawing rect("+left+","+bottom+","+ width+","+           *            mentioned actions. If <code>null</code>, the default (true)
1782                  // height+")");           *            will be used.
1783                  graphics.drawRect(left, bottom, width, height);           */
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           * if clickable is set to true then a single click on the map pane will zoom           * Defines an evelope of the viwable area. The JMapPane will never show
1794           * or pan the map.           * anything outside of this extend.
1795           *           *
1796           * @param clickable           * @param maxExtend
1797             *            <code>null</code> to not have this restriction.
1798           */           */
1799          public void setClickable(final boolean clickable) {          public void setMaxExtend(final Envelope maxExtend) {
1800                  this.clickable = clickable;                  this.maxExtend = maxExtend;
1801          }          }
1802    
1803          public void mouseMoved(final MouseEvent e) {          /**
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          public FeatureCollection getSelection() {          // /** Stored the time used for the last real rendering in ms. **/
1817                  return selection;          // private long lastRenderingDuration = Long.MAX_VALUE;
         }  
1818    
1819          public void setSelection(final FeatureCollection selection) {          /**
1820                  this.selection = selection;           * Set the minimum (nearest) allowed zoom scale. This is the bigger number
1821                  repaint();           * 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          /*          /**
          * (non-Javadoc)  
1834           *           *
1835           * @see           * @param b
          * org.geotools.gui.swing.event.SelectionChangeListener#selectionChanged  
          * (org.geotools.gui.swing.event.SelectionChangedEvent)  
1836           */           */
1837          public void selectionChanged(final SelectionChangedEvent e) {          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    
                 try {  
                         selection = selectionLayer.getFeatureSource().getFeatures(  
                                         e.getFilter());  
                         repaint();  
                 } catch (final IOException e1) {  
                         e1.printStackTrace();  
                 }  
1854          }          }
1855    
1856          public SelectionManager getSelectionManager() {          private void setRendererHints(final Map<Object, Object> rendererHints) {
1857                  return selectionManager;                  this.rendererHints = rendererHints;
1858          }          }
1859    
1860          public void setSelectionManager(final SelectionManager selectionManager) {          /**
1861                  this.selectionManager = selectionManager;           * Enables/Disables the ZOOM Mouse Listener. Upates the Cursor and stops the
1862                  this.selectionManager.addSelectionChangeListener(this);           * 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    
         // xulu.sn  
1876          /**          /**
1877           * Korrigiert den {@link Envelope} aka {@code mapArea} auf die beste           * Standardmaessig wird der Cursor automatisch je nach MapPane-Aktion (Zoom,
1878           * erlaubte Flaeche damit die Massstabsbeschaenkungen noch eingehalten           * Auswahl, ...) gesetzt. Mit dieser Methode kann ein statischer Cursor
1879           * werden, FALLS der uebergeben Envelope nicht schon gueltig sein sollte.<br/>           * gesetzt werden, der unabhaengig von der aktuellen MapPanes-Aktion
1880           * Since 21. April 09: Before thecalculation starts, the aspect ratio is           * beibehalten wird. Um diesen statischen Cursor wieder zu entfernen, kann
1881           * corrected. This change implies, that setMapArea() will most of the time           * {@code null} als Parameter uebergeben werden
          * not allow setting to a wrong aspectRatio.  
1882           *           *
1883           * @author <a href="mailto:[email protected]">Stefan Alfons           * @param cursor
1884           *         Kr&uuml;ger</a>           *            Cursor
1885           */           */
1886          public Envelope bestAllowedMapArea(Envelope env) {          public void setStaticCursor(final Cursor cursor) {
1887                  if (getWidth() == 0)                  this.staticCursor = cursor;
1888                          return env;                  if (cursor != null)
1889                  if (env == null)                          super.setCursor(cursor);
1890                          return env;          }
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                   * Correct the aspect Ratio before we check the rest. Otherwise we might                   * We have to set new renderer
                  * easily fail.  
1913                   */                   */
                 env = fixAspectRatio(this.getBounds(), env);  
1914    
1915                  final double scale = env.getWidth() / getWidth();                  if (getBgContext() != null) {
1916                  final double centerX = env.getMinX() + env.getWidth() / 2.;                          // bgExecuter = new RenderingExecutor();
1917                  final double centerY = env.getMinY() + env.getHeight() / 2.;                          // LOGGER.debug("starting bg renderer:");
1918                  double newWidth2;                          // // /* System.out.println("rendering"); */
1919                  double newHeight2;                          // final GTRenderer createGTRenderer = GTUtil.createGTRenderer(
1920                  if (scale < getMaxZoomScale()) {                          // bgContext, getRendererHints());
1921                          // ****************************************************************************                          // createGTRenderer.setJava2DHints(getJava2dHints());
1922                          // Wir zoomen weiter rein als erlaubt => Anpassen des envelope                          // bgExecuter.submit(getBgContext().getAreaOfInterest(),
1923                          // ****************************************************************************                          // curPaintArea,
1924                          newWidth2 = getMaxZoomScale() * getWidth() / 2.;                          // (Graphics2D) getBgImage().getGraphics(), createGTRenderer);
1925                          newHeight2 = getMaxZoomScale() * getHeight() / 2.;                  }
1926                  } else if (scale > getMinZoomScale()) {  
1927                          // ****************************************************************************                  if (getContext() != null) {
1928                          // Wir zoomen weiter raus als erlaubt => Anpassen des envelope                          // localExecuter = new RenderingExecutor(this, 150l);
1929                          // ****************************************************************************                          // LOGGER.debug("starting local renderer:");
1930                          newWidth2 = getMinZoomScale() * getWidth() / 2.;  
1931                          newHeight2 = getMinZoomScale() * getHeight() / 2.;                          // Clear label cache
1932                  } else {                          labelCache.clear();
1933                          // ****************************************************************************                          final Map<Object, Object> rh = localRenderer.getRendererHints();
1934                          // Die mapArea / der Envelope ist ist gueltig! Keine Aenderungen                          rh.put(StreamingRenderer.LABEL_CACHE_KEY, labelCache);
1935                          // ****************************************************************************                          localRenderer.setRendererHints(rh);
1936                          return env;  
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                  final Coordinate ll = new Coordinate(centerX - newWidth2, centerY                  updateCursor();
1949                                  - newHeight2);          }
                 final Coordinate ur = new Coordinate(centerX + newWidth2, centerY  
                                 + newHeight2);  
1950    
1951                  return new Envelope(ll, ur);          /**
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           * Retuns the minimum allowed zoom scale. This is the bigger number value of           * Transformiert einen Fenster-Koordinaten-Bereich in Geo-Koordinaten.
          * the two. Defaults to {@link Double}.MAX_VALUE  
1986           *           *
1987           * @author <a href="mailto:[email protected]">Stefan Alfons           * @param ox
1988           *         Kr&uuml;ger</a>           *            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          public Double getMinZoomScale() {          private void addGadgets(final Graphics2D graphics) {
2107                  return minZoomScale;  
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           * Retuns the maximum allowed zoom scale. This is the smaller number value           * Sets the {@link #mapArea} to best possibly present the given features. If only one
2135           * of the two. Defaults to {@link Double}.MIN_VALUE           * single point is given, the window is moved over the point.
2136           *           *
2137           * @author <a href="mailto:[email protected]">Stefan Alfons           * @param features
2138           *         Kr&uuml;ger</a>           *            if <code>null</code> or size==0, the function doesn nothing.
2139           */           */
2140          public Double getMaxZoomScale() {          public void zoomTo(
2141                  return maxZoomScale;                          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           * Set the maximum allowed zoom scale. This is the smaller number value of           * Zooms towards a point.
          * the two.  
2218           *           *
2219           * @author <a href="mailto:[email protected]">Stefan Alfons           * @param center
2220           *         Kr&uuml;ger</a>           *            position in window coordinates
2221             * @param zoomFactor
2222             *            > 1 for zoom in, < 1 for zoom out. Default is 1.33
2223           */           */
2224          public void setMaxZoomScale(final Double maxZoomScale) {          public void zoomTo(final Point center) {
2225                  // System.out.println("setting max scale to "+maxZoomScale);                  zoomTo(center, null);
                 this.maxZoomScale = maxZoomScale;  
2226          }          }
2227    
2228          /**          /**
2229           * Set the minimum (nearest) allowed zoom scale. This is the bigger number           * Zooms towards a point.
          * value of the two.  
2230           *           *
2231           * @author <a href="mailto:[email protected]">Stefan Alfons           * @param center
2232           *         Kr&uuml;ger</a>           *            position in window coordinates
2233           */           * @param zoomFaktor
2234          public void setMinZoomScale(final Double minZoomScale) {           *            > 1 for zoom in, < 1 for zoom out. Default is 1.33.
2235                  this.minZoomScale = minZoomScale;           */
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          }          }
         // xulu.en  
2266    
2267  }  }

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

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26