/[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 341 by alfonx, Mon Aug 31 10:16:40 2009 UTC trunk/src/skrueger/geotools/XMapPane.java revision 695 by alfonx, Fri Feb 12 20:46:08 2010 UTC
# Line 1  Line 1 
1  /*  package skrueger.geotools;
  *    GeoTools - OpenSource mapping toolkit  
  *    http://geotools.org  
  *    (C) 2002-2006, GeoTools Project Managment Committee (PMC)  
  *  
  *    This library is free software; you can redistribute it and/or  
  *    modify it under the terms of the GNU Lesser General Public  
  *    License as published by the Free Software Foundation;  
  *    version 2.1 of the License.  
  *  
  *    This library is distributed in the hope that it will be useful,  
  *    but WITHOUT ANY WARRANTY; without even the implied warranty of  
  *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU  
  *    Lesser General Public License for more details.  
  */  
 package 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.event.InputEvent;  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.MouseEvent;  import java.awt.event.MouseEvent;
17  import java.awt.event.MouseListener;  import java.awt.event.MouseListener;
18  import java.awt.event.MouseMotionListener;  import java.awt.geom.AffineTransform;
19    import java.awt.geom.NoninvertibleTransformException;
20    import java.awt.geom.Point2D;
21  import java.awt.image.BufferedImage;  import java.awt.image.BufferedImage;
 import java.beans.PropertyChangeEvent;  
 import java.beans.PropertyChangeListener;  
22  import java.io.IOException;  import java.io.IOException;
23  import java.util.Date;  import java.util.ArrayList;
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.JList;
29    import javax.swing.Timer;
30    import javax.swing.border.Border;
31    
32  import org.apache.log4j.Logger;  import org.apache.log4j.Logger;
33    import org.geotools.factory.GeoTools;
34    import org.geotools.feature.FeatureCollection;
35    import org.geotools.geometry.DirectPosition2D;
36    import org.geotools.geometry.jts.JTS;
37    import org.geotools.geometry.jts.ReferencedEnvelope;
38    import org.geotools.map.DefaultMapContext;
39    import org.geotools.map.DefaultMapLayer;
40  import org.geotools.map.MapContext;  import org.geotools.map.MapContext;
41    import org.geotools.map.MapLayer;
42    import org.geotools.map.event.MapLayerEvent;
43  import org.geotools.map.event.MapLayerListEvent;  import org.geotools.map.event.MapLayerListEvent;
44  import org.geotools.map.event.MapLayerListListener;  import org.geotools.map.event.MapLayerListListener;
45    import org.geotools.map.event.MapLayerListener;
46    import org.geotools.referencing.CRS;
47  import org.geotools.renderer.GTRenderer;  import org.geotools.renderer.GTRenderer;
48  import org.geotools.renderer.label.LabelCacheImpl;  import org.geotools.renderer.label.LabelCacheImpl;
49  import org.geotools.renderer.lite.LabelCache;  import org.geotools.renderer.lite.LabelCache;
50    import org.geotools.renderer.lite.RendererUtilities;
51  import org.geotools.renderer.lite.StreamingRenderer;  import org.geotools.renderer.lite.StreamingRenderer;
52  import org.geotools.renderer.shape.TransitionShapefileRenderer;  import org.geotools.resources.image.ImageUtilities;
53  import org.geotools.styling.Graphic;  import org.geotools.styling.Style;
54  import org.geotools.styling.LineSymbolizer;  import org.geotools.swing.JMapPane;
55  import org.geotools.styling.Mark;  import org.geotools.swing.event.MapMouseEvent;
56  import org.geotools.styling.PointSymbolizer;  import org.geotools.swing.event.MapPaneEvent;
57  import org.geotools.styling.PolygonSymbolizer;  import org.geotools.swing.event.MapPaneListener;
58  import org.geotools.styling.StyleBuilder;  import org.opengis.feature.simple.SimpleFeature;
59  import org.geotools.styling.StyleFactory;  import org.opengis.feature.simple.SimpleFeatureType;
60  import org.opengis.filter.FilterFactory2;  import org.opengis.referencing.FactoryException;
61  import org.opengis.referencing.crs.CoordinateReferenceSystem;  import org.opengis.referencing.crs.CoordinateReferenceSystem;
62    import org.opengis.referencing.operation.MathTransform;
63    import org.opengis.referencing.operation.TransformException;
64    
65    import schmitzm.geotools.GTUtil;
66    import schmitzm.geotools.JTSUtil;
67    import schmitzm.geotools.gui.SelectableXMapPane;
68    import schmitzm.geotools.io.GeoImportUtil;
69    import schmitzm.geotools.map.event.JMapPaneListener;
70    import schmitzm.geotools.map.event.MapLayerAdapter;
71    import schmitzm.geotools.styling.StylingUtil;
72    import schmitzm.lang.LangUtil;
73    import schmitzm.swing.JPanel;
74  import schmitzm.swing.SwingUtil;  import schmitzm.swing.SwingUtil;
75    import schmitzm.swing.event.MouseInputType;
76    
77  import com.vividsolutions.jts.geom.Coordinate;  import com.vividsolutions.jts.geom.Coordinate;
78  import com.vividsolutions.jts.geom.Envelope;  import com.vividsolutions.jts.geom.Envelope;
79  import com.vividsolutions.jts.geom.GeometryFactory;  import com.vividsolutions.jts.geom.Geometry;
80    
81  public class JMapPane extends JPanel implements MouseListener,  /**
82                  MouseMotionListener, PropertyChangeListener, MapLayerListListener {   * The {@link XMapPane} class uses a Geotools {@link GTRenderer} to paint up to
83          private static Logger LOGGER = Logger.getLogger(JMapPane.class.getName());   * two {@link MapContext}s: a "local" {@link MapContext} and a "background"
84     * {@link MapContext}. The idea is, that rendering a background layer made up of
85     * e.g. OSM data, may take much longer than rendering local data.<br>
86     * Every {@link MapContext} is rendered on a {@link Thread} of it's own.
87     * Starting/ cancelling these threads is done by the {@link RenderingExecutor}.<br>
88     * <br>
89     * While the renderers are rending the map, a <br>
90     * The {@link XMapPane} is based on schmitzm {@link JPanel}, so
91     * {@link #print(Graphics)} will automatically set the background of components
92     * to pure white.
93     *
94     * The XMapPane has a {@link MouseListener} that manages zooming.<br>
95     * A logo/icon to float in the lower left corner may be set with
96     * {@link #setMapImage(BufferedImage)}<br>
97     *
98     * @see SelectableXMapPane - an extension of {@link XMapPane} that supports
99     *      selecting features.
100     *
101     * @author stefan
102     *
103     */
104    public class XMapPane extends JPanel {
105    
106          private static final long serialVersionUID = -8647971481359690499L;          /**
107             * If {@link #maxExtend} is <code>null</code> the following rules are used
108             * to create a default maximum.
109             * <ul>
110             * <li>Values &lt; 0 : don't grow to fit the monitors aspect ratio, no
111             * margin</li>
112             * <li>Values 0 : grow to fit the monitors aspect ratio, no margin</li>
113             * <li>Values &gt; 0 : grow to fit the monitors aspect ratio, and add a
114             * relative margin</li>
115             * </ul>
116             * **/
117            private double defaultMaxMapExtendMode = .05;
118    
119            // private static final int IMAGETYPE = BufferedImage.TYPE_INT_RGB;
120            // private static final int IMAGETYPE_withAlpha =
121            // BufferedImage.TYPE_INT_ARGB;
122            private static final int IMAGETYPE = BufferedImage.TYPE_3BYTE_BGR;
123    
124          public static final int Reset = 0;          public XMapPaneTool getTool() {
125                    return tool;
126            }
127    
128          public static final int ZoomIn = 1;          /**
129             * If the {@link JPanel} is disabled, it shows nothing and the images are disposed.
130             */
131            @Override
132            public void setEnabled(boolean enabled) {
133                    super.setEnabled(enabled);
134                    if (enabled == false)
135                            disposeImages();
136                    else
137                            requestStartRendering();
138            }
139    
140          public static final int ZoomOut = 2;          private static final int IMAGETYPE_withAlpha = BufferedImage.TYPE_4BYTE_ABGR;
141    
142          public static final int Pan = 3;          private final static Logger LOGGER = Logger.getLogger(XMapPane.class);
143    
144          public static final int Select = 4;          /**
145             * A flag indicating whether the {@link XMapPane} is accepting repaints from
146             * the EDT. @see {@link XMapPane#setPainting(boolean))
147             **/
148            private boolean acceptsRepaintCalls = true;
149    
150          private static final int POLYGON = 0;          /**
151             * Main {@link MapContext} that holds all layers that are rendered into the
152             * {@link #localImage} by the {@link #localRenderer}
153             */
154            MapContext localContext;
155    
156          private static final int LINE = 1;          /**
157             * {@link MapContext} holding the background layers. Use it for layers that
158             * CAN take very long for rendering, like layer from the Internet: WMS, WFS,
159             * OSM...<br>
160             * <code>null</code> by default.
161             *
162             * @see #setBgContext(MapContext)
163             * @see #getBgContext()
164             */
165            MapContext bgContext;
166    
167          private static final int POINT = 2;          /**
168             * While threads are working, calls {@link XMapPane#updateFinalImage()}
169             * regularly and {@link #repaint()}. This {@link Timer} is stopped when all
170             * renderers have finished.
171             *
172             * @see INITIAL_REPAINT_DELAYAL
173             * @see #REPEATING_REPAINT_DELAY
174             */
175            final private Timer repaintTimer;
176    
177          /**          /**
178           * what renders the map           * The initial delay in milliseconds until the {@link #finalImage} is
179             * updated the first time.
180           */           */
181          GTRenderer renderer;          public static final int INITIAL_REPAINT_DELAY = 900;
182    
183          private GTRenderer highlightRenderer, selectionRenderer;          /**
184             * While the {@link #bgExecuter} and {@link #localExecuter} are rendering,
185             * the {@link #repaintTimer} is regularly updating the {@link #finalImage}
186             * with previews.
187             */
188            public static final int REPEATING_REPAINT_DELAY = 500;
189    
190          /**          /**
191           * the map context to render           * Default delay (milliseconds) before the map will be redrawn when resizing
192             * the pane. This is to avoid flickering while drag-resizing.
193             *
194             * @see #resizeTimer
195           */           */
196          MapContext context;          public static final int DEFAULT_RESIZING_PAINT_DELAY = 600;
197    
198          private MapContext selectionContext;          /**
199             * This not-repeating {@link Timer} is re-started whenever the component is
200             * resized. That means => only if the component is not resizing for
201             * {@link #DEFAULT_RESIZING_PAINT_DELAY} milliseconds, does the
202             * {@link XMapPane} react.
203             */
204            private final Timer resizeTimer;
205    
206          /**          /**
207           * the area of the map to draw           * Flag for no-tool.
208           */           */
209          // xulu.sc          public static final int NONE = -123;
210          // Envelope mapArea;          //
211          protected Envelope mapArea;          // /**
212          // xulu.ec          // * Flag fuer Modus "Kartenausschnitt bewegen". Nicht fuer Window-Auswahl
213            // * moeglich!
214            // *
215            // * @see #setState(int)
216            // */
217            // public static final int PAN = 1;
218            //
219            // /**
220            // * Flag fuer Modus "Heran zoomen".
221            // *
222            // * @see #setState(int)
223            // * @see #setState(int)
224            // */
225            // public static final int ZOOM_IN = 2;
226            //
227            // /**
228            // * Flag fuer Modus "Heraus zoomen". Nicht fuer Window-Auswahl moeglich!
229            // *
230            // * @see #setState(int)
231            // */
232            // public static final int ZOOM_OUT = 3;
233    
234          /**          /**
235           * the size of the pane last time we drew           * {@link Font} used to paint the wait messages into the map
236             *
237             * @see #addGadgets(Graphics2D, boolean)
238           */           */
239          // xulu.sc          final static Font waitFont = new Font("Arial", Font.BOLD, 28);
         // private Rectangle oldRect = null;  
         protected Rectangle oldRect = null;  
         // xulu.ec  
240    
241          /**          /**
242           * the last map area drawn.           * {@link Font} used to paint error messages into the map
243             *
244             * @see #addGadgets(Graphics2D, boolean)
245           */           */
246          // xulu.sc          final static Font errorFont = new Font("Arial", Font.BOLD, 13);
247          // private Envelope oldMapArea = null;  
248          protected Envelope oldMapArea = null;          /**
249          // xulu.ec           * If last average last two renderings took more than that many ms, show the
250             * user a scaled preview
251             **/
252            private static final long PRESCALE_MINTIME = 230;
253    
254          /**          /**
255           * the base image of the map           * The wait message painted into the map while rendering is going on on
256             * another thread.
257             *
258             * @see #addGadgets(Graphics2D, boolean)
259           */           */
260          protected BufferedImage baseImage, panningImage;          final String waitMsg = SwingUtil.R("WaitMess");
         // SK: private BufferedImage baseImage, panningImage;  
261    
262          /**          /**
263           * a factory for filters           * Konvertiert die Maus-Koordinaten (relativ zum <code>JMapPane</code>) in
264             * Karten-Koordinaten.
265             *
266             * @param e
267             *            Maus-Ereignis
268           */           */
269          FilterFactory2 ff;          public static DirectPosition2D getMapCoordinatesFromEvent(final MouseEvent e) {
270                    // aktuelle Geo-Position aus GeoMouseEvent ermitteln
271                    if (e != null && e instanceof MapMouseEvent)
272                            try {
273                                    return ((MapMouseEvent) e).getMapPosition();
274                            } catch (final Exception err) {
275                                    LOGGER
276                                                    .error(
277                                                                    "return ((GeoMouseEvent) e).getMapCoordinate(null).toPoint2D();",
278                                                                    err);
279                            }
280    
281                    // aktuelle Geo-Position ueber Transformation des JMapPane berechnen
282                    if (e != null && e.getSource() instanceof XMapPane) {
283    
284                            final XMapPane xMapPane = (XMapPane) e.getSource();
285    
286                            if (!xMapPane.isWellDefined())
287                                    return null;
288    
289                            final AffineTransform at = xMapPane.getScreenToWorld();
290                            if (at != null) {
291                                    Point2D transformed = at.transform(e.getPoint(), null);
292                                    return new DirectPosition2D(xMapPane.getMapContext()
293                                                    .getCoordinateReferenceSystem(), transformed.getX(),
294                                                    transformed.getY());
295                            }
296                            return null;
297                    }
298                    throw new IllegalArgumentException(
299                                    "MouseEvent has to be of instance MapMouseEvent or come from an XMapPane");
300            }
301    
302          /**          /**
303           * a factory for geometries           * Listens to changes of the "background" {@link MapContext} and triggers
304             * repaints where needed.
305           */           */
306          GeometryFactory gf = new GeometryFactory(); // FactoryFinder.getGeometryFactory(null);          private final MapLayerListListener bgContextListener = new MapLayerListListener() {
307    
308                    @Override
309                    public void layerAdded(final MapLayerListEvent event) {
310                            final MapLayer layer = event.getLayer();
311                            layer.addMapLayerListener(bgMapLayerListener);
312                            requestStartRendering();
313                    }
314    
315                    @Override
316                    public void layerChanged(final MapLayerListEvent event) {
317                            requestStartRendering();
318                    }
319    
320                    @Override
321                    public void layerMoved(final MapLayerListEvent event) {
322                            requestStartRendering();
323                    }
324    
325                    @Override
326                    public void layerRemoved(final MapLayerListEvent event) {
327                            if (event.getLayer() != null)
328                                    event.getLayer().removeMapLayerListener(bgMapLayerListener);
329                            requestStartRendering();
330                    }
331            };
332    
333            /**
334             * This {@link RenderingExecutor} manages the creation and cancellation of
335             * up to one {@link Thread} for rendering the {@link #localContext}.
336             */
337            private final RenderingExecutor localExecuter = new RenderingExecutor(this);
338    
339            /**
340             * This {@link RenderingExecutor} manages the creation and cancellation of
341             * up to one {@link Thread} for rendering the {@link #bgContext}.
342             */
343            protected RenderingExecutor bgExecuter;
344    
345            /**
346             * The {@link #localRenderer} for the {@link #localContext} uses this
347             * {@link Image}.
348             */
349            private BufferedImage localImage;
350    
351            /**
352             * The {@link #bgRenderer} for the {@link #bgContext} uses this
353             * {@link Image}.
354             */
355            private BufferedImage bgImage;
356    
357            /**
358             * This {@link Image} is a merge of the {@link #bgImage},
359             * {@link #localImage} and {@link #addGadgets(Graphics2D, boolean)}. It is
360             * updated with {@link #updateFinalImage()} and used for painting in
361             * {@link #paintComponent(Graphics)}
362             */
363            private BufferedImage finalImage;
364    
365            /**
366             * Optionally a transparent image to paint over the map in the lower right
367             * corner.
368             *
369             * @see #addGadgets(Graphics2D)
370             * @see #setMapImage(BufferedImage)
371             **/
372            private BufferedImage mapImage = null;
373    
374            /**
375             * Listens to each layer in the local {@link MapContext} for changes and
376             * triggers repaints.
377             */
378            protected MapLayerListener bgMapLayerListener = new MapLayerAdapter() {
379    
380                    @Override
381                    public void layerChanged(final MapLayerEvent event) {
382                            requestStartRendering();
383                    }
384    
385                    @Override
386                    public void layerHidden(final MapLayerEvent event) {
387                            requestStartRendering();
388                    }
389    
390                    @Override
391                    public void layerShown(final MapLayerEvent event) {
392                            requestStartRendering();
393                    }
394            };
395    
396            /**
397             * A flag indicating if dispose() was already called. If true, then further
398             * use of this {@link SelectableXMapPane} is undefined.
399             */
400            private boolean disposed = false;
401    
402            /**
403             * While dragging, the {@link #updateFinalImage()} method is translating the
404             * cached images while setting it together.
405             **/
406            private final Point imageOrigin = new Point(0, 0);
407            /**
408             * For every rendering thread started,
409             * {@link GTUtil#createGTRenderer(MapContext)} is called to create a new
410             * renderer. These Java2D rendering hints are passed to the
411             * {@link GTRenderer}. The java2dHints are the same for all renderers (bg
412             * and local).
413             */
414            private RenderingHints java2dHints;
415    
416            protected LabelCache labelCache = new LabelCacheImpl();
417    
418            /**
419             * Listens to changes of the "local" {@link MapContext} and triggers
420             * repaints where needed.
421             */
422            private final MapLayerListListener localContextListener = new MapLayerListListener() {
423    
424                    @Override
425                    public void layerAdded(final MapLayerListEvent event) {
426                            event.getLayer().addMapLayerListener(localMapLayerListener);
427    
428                            getLocalRenderer().setContext(getMapContext());
429                            requestStartRendering();
430    
431                    }
432    
433                    @Override
434                    public void layerChanged(final MapLayerListEvent event) {
435                            // getLocalRenderer().setContext(getMapContext()); geht doch auch
436                            // ohne?!?!? wow...
437                            requestStartRendering();
438                    }
439    
440                    @Override
441                    public void layerMoved(final MapLayerListEvent event) {
442                            getLocalRenderer().setContext(getMapContext());
443                            requestStartRendering();
444                    }
445    
446          private int state = ZoomIn;                  @Override
447                    public void layerRemoved(final MapLayerListEvent event) {
448                            if (event.getLayer() != null)
449                                    event.getLayer().removeMapLayerListener(localMapLayerListener);
450                            getLocalRenderer().setContext(getMapContext());
451                            requestStartRendering();
452                    }
453            };
454    
455          /**          /**
456           * how far to zoom in or out           * Listens to each layer in the local {@link MapContext} for changes and
457             * triggers repaints. We don't have to listen layerChanged, because that is
458             * already done in {@link #localContextListener}
459           */           */
460          private double zoomFactor = 2.0;          protected MapLayerListener localMapLayerListener = new MapLayerAdapter() {
461    
462                    // @Override
463                    // public void layerChanged(final MapLayerEvent event) {
464                    // // getLocalRenderer().setContext(getMapContext()); // betters for SLD
465                    // // // changes?!
466                    // // requestStartRendering();
467                    // }
468    
469                    @Override
470                    public void layerHidden(final MapLayerEvent event) {
471                            requestStartRendering();
472                    }
473    
474          boolean changed = true;                  @Override
475                    public void layerShown(final MapLayerEvent event) {
476                            requestStartRendering();
477                    }
478            };
479    
480          LabelCache labelCache = new LabelCacheImpl();          final private GTRenderer localRenderer = GTUtil.createGTRenderer();
481    
482          // xulu.sc          private final GTRenderer bgRenderer = GTUtil.createGTRenderer();
         // private boolean reset = false;  
         protected boolean reset = false;  
         // xulu.ec  
483    
484          int startX;          /**
485             * the area of the map to draw
486             */
487            protected Envelope mapArea = null;
488    
489          int startY;          /**
490             * A flag set it {@link #setMapArea(Envelope)} to indicated the
491             * {@link #paintComponent(Graphics)} method, that the image on-screen is
492             * associated with {@link #oldMapArea} and may hence be scaled for a quick
493             * preview.<br>
494             * The flag is reset
495             **/
496            private boolean mapAreaChanged = false;
497    
498          private boolean clickable;          /**
499             * This color is used as the default background color when painting a map.
500             */
501            private Color mapBackgroundColor = null;
502    
503          int lastX;          /**
504             * A flag indicating that the shown image is invalid and needs to be
505             * re-rendered.
506             */
507            protected boolean mapImageInvalid = true;
508    
509          int lastY;          /**
510             * Holds a flag for each layer, whether it is regarded or ignored on
511             * {@link #SELECT_TOP}, {@link #SELECT_ALL} and {@link #SELECT_ONE_FROM_TOP}
512             * actions.
513             */
514            final protected HashMap<MapLayer, Boolean> mapLayerSelectable = new HashMap<MapLayer, Boolean>();
515    
516          // xulu.sn          /**
517             * List of listeners of this {@link XMapPane}
518             */
519            protected Vector<JMapPaneListener> mapPaneListeners = new Vector<JMapPaneListener>();
520            /**
521             * If not <code>null</code>, the {@link XMapPane} will not allow to zoom/pan
522             * out of that area
523             **/
524            private Envelope maxExtend = null;
525          private Double maxZoomScale = Double.MIN_VALUE;          private Double maxZoomScale = Double.MIN_VALUE;
526    
527          private Double minZoomScale = Double.MAX_VALUE;          private Double minZoomScale = Double.MAX_VALUE;
         // xulu.en  
528    
         // sk.sn  
529          /**          /**
530           * Wenn true, dann wurde PANNING via mouseDraged-Events begonnen. Dieses           * We store the old mapArea for a moment to use it for the
531           * Flag wird benutzt um nur einmal den passenden Cursor nur einmal zu           * "quick scaled preview" in case of ZoomOut
532           * setzen.           **/
533            protected Envelope oldMapArea = null;
534    
535            /**
536             * We store the old transform for a moment to use it for the
537             * "quick scaled preview" in case of ZoomIn
538             **/
539            protected AffineTransform oldScreenToWorld = null;
540    
541            /**
542             * A flag indicating, that the image size has changed and the buffered
543             * images are not big enough any more
544             **/
545            protected boolean paneResized = true;
546    
547            private BufferedImage preFinalImage;
548    
549            // ** if 0, no quick preview will be shown **/
550            // private int quickPreviewHint = 0;
551    
552            private Map<Object, Object> rendererHints = GTUtil
553                            .getDefaultGTRendererHints(getLocalRenderer());
554    
555            /**
556             * If set to <code>true</code>, the {@link #startRenderThreadsTimer} will
557             * start rendering {@link Thread}s
558             **/
559            private volatile Boolean requestStartRendering = false;
560    
561            /**
562             * Transformation zwischen Fenster-Koordinaten und Karten-Koordinaten
563             * (lat/lon)
564           */           */
565          private boolean panning_started = false;          protected AffineTransform screenToWorld = null;
566    
567          // sk.en          /**
568             * The flag {@link #requestStartRendering} can be set to true by events.
569             * This {@link Timer} checks the flag regularly and starts one renderer
570             * thread.
571             */
572            final private Timer startRenderThreadsTimer;
573            //
574            // /**
575            // * The default state is ZOOM_IN, hence by default the
576            // * {@link #xMapPaneMouseListener} is also enabled.
577            // **/
578            // private int state = ZOOM_IN;
579            //
580            // /**
581            // * Manuell gesetzter statischer Cursor, unabhaengig von der aktuellen
582            // * MapPane-Funktion
583            // */
584            // protected Cursor staticCursor = null;
585    
586            private AffineTransform worldToScreen;
587    
588            // /**
589            // * This {@link MouseListener} is managing all zoom related tasks
590            // */
591            // private final ZoomXMapPaneMouseListener zoomMapPaneMouseListener = new
592            // ZoomXMapPaneMouseListener(
593            // this);
594    
595          public JMapPane() {          /**
596                  this(null, true, null, null);           * This {@link MouseListener} is managing all zoom related tasks
597             */
598            private final XMapPaneMouseListener xMapPaneMouseListener = new XMapPaneMouseListener(
599                            this);
600    
601            /** Is set if a renderer has an error **/
602            protected ArrayList<Exception> renderingErrors = new ArrayList<Exception>();
603    
604            /**
605             * If <code>true</code>, then rendering exceptions are rendererd into the
606             * map pane
607             **/
608            private boolean showExceptions = false;
609    
610            public XMapPane() {
611                    this(null, null);
612          }          }
613    
614          /**          /**
615           * create a basic JMapPane           * full constructor extending JPanel
616           *           *
617           * @param render           * @param rendererHints
618           *            - how to draw the map           *            may be <code>null</code>. Otherwise a {@link Map<Object,
619           * @param context           *            Object>} of {@link RenderingHints} to override the default
620           *            - the map context to display           *            from {@link GTUtil#getDefaultGTRendererHints(GTRenderer)}
621             *
622             * @param localContext
623             *            The main {@link MapContext} to use. If <code>null</code>, an
624             *            empty {@link DefaultMapContext} will be created.
625           */           */
626          public JMapPane(final GTRenderer render, final MapContext context) {          public XMapPane(final MapContext localContext_,
627                  this(null, true, render, context);                          final Map<Object, Object> rendererHints) {
628    
629                    super(true);
630    
631                    blinkTimer = initBlinkTimer();
632    
633                    // A default setting
634                    RenderingHints hintsJava2d = ImageUtilities.NN_INTERPOLATION_HINT;
635                    setJava2dHints(hintsJava2d);
636    
637                    setRendererHints(rendererHints);
638    
639                    setOpaque(true);
640    
641                    if (localContext_ != null)
642                            setLocalContext(localContext_);
643    
644                    /**
645                     * Adding the #zoomMapPaneMouseListener
646                     */
647                    this.addMouseListener(xMapPaneMouseListener);
648                    this.addMouseMotionListener(xMapPaneMouseListener);
649                    this.addMouseWheelListener(xMapPaneMouseListener);
650    
651                    // By default the XMapPAne uses the ZOOM_IN tool.
652                    setTool(XMapPaneTool.ZOOM_IN);
653    
654                    /*
655                     * We use a Timer object to avoid rendering delays and flickering when
656                     * the user is drag-resizing the parent container of this map pane.
657                     *
658                     * Using a ComponentListener doesn't work because, unlike a JFrame, the
659                     * pane receives a stream of events during drag-resizing.
660                     */
661                    resizeTimer = new Timer(DEFAULT_RESIZING_PAINT_DELAY,
662                                    new ActionListener() {
663    
664                                            public void actionPerformed(final ActionEvent e) {
665                                                    if (!isWellDefined())
666                                                            return;
667    
668                                                    // LOGGER.debug("resizeTimer performed");
669    
670                                                    // final Rectangle bounds = getVisibleRect();
671                                                    //
672                                                    // System.out.println("\n\ntimer performs with bounds = "
673                                                    // + bounds);
674    
675                                                    // final Envelope geoMapArea = tranformWindowToGeo(
676                                                    // bounds.x, bounds.y, bounds.x + bounds.width,
677                                                    // bounds.y + bounds.height);
678    
679                                                    paneResized = true;
680                                                    if (!setMapArea(getMapArea())) {
681                                                            // It's important to request new rendering here.
682                                                            // setMapArea only returns true and only calls
683                                                            // requestStartRendering if the maparea has changed.
684                                                            // But if the component is resized, the maparea
685                                                            // doesn't have to change.
686                                                            requestStartRendering();
687                                                    }
688    
689                                            }
690                                    });
691                    resizeTimer.setRepeats(false);
692    
693                    this.addComponentListener(new ComponentAdapter() {
694    
695                            private Rectangle oldVisibleRect;
696    
697                            @Override
698                            public void componentResized(final ComponentEvent e) {
699    
700                                    // Seems to be called twice with the same size..
701                                    if (oldVisibleRect != null
702                                                    && oldVisibleRect.equals(getVisibleRect())) {
703                                            // LOGGER.debug("skipping resize.");
704                                            return;
705                                    }
706    
707                                    // LOGGER.debug("resized: " + getVisibleRect());
708                                    resizeTimer.restart();
709                                    oldVisibleRect = getVisibleRect();
710                            }
711    
712                    });
713    
714                    /*
715                     * Setting up the repaintTimer. Not started automatically.
716                     */
717                    repaintTimer = new Timer(REPEATING_REPAINT_DELAY, new ActionListener() {
718    
719                            @Override
720                            public void actionPerformed(final ActionEvent e) {
721                                    if ((!localExecuter.isRunning())
722                                                    && (bgExecuter != null && !bgExecuter.isRunning())) {
723                                            repaintTimer.stop();
724                                    } else {
725                                            updateFinalImage();
726                                            XMapPane.this.repaint(100);
727    
728                                    }
729                            }
730                    });
731    
732                    repaintTimer.setInitialDelay(INITIAL_REPAINT_DELAY);
733                    repaintTimer.setRepeats(true);
734    
735                    /*
736                     * Setting up the startRenderThreadsTimer. This Timer starts
737                     * automatically.
738                     */
739                    startRenderThreadsTimer = new Timer(100, new ActionListener() {
740    
741                            @Override
742                            public void actionPerformed(final ActionEvent e) {
743                                    synchronized (requestStartRendering) {
744                                            if (requestStartRendering && isWellDefined() && isEnabled()) {
745    
746                                                    if (localExecuter.isRunning()) {
747                                                            localExecuter.cancelTask();
748                                                    } else {
749                                                            // Stupidly, but we have to recheck the
750                                                            setMapArea(getMapArea());
751                                                            requestStartRendering = false;
752                                                            startRendering();
753                                                    }
754                                            }
755                                    }
756                            }
757                    });
758                    startRenderThreadsTimer.start();
759    
760          }          }
761    
762          /**          /**
763           * full constructor extending JPanel           * Fuegt der Map einen Listener hinzu.
764           *           *
765           * @param layout           * @param l
766           *            - layout (probably shouldn't be set)           *            neuer Listener
767           * @param isDoubleBuffered           */
768           *            - a Swing thing I don't really understand          public void addMapPaneListener(final JMapPaneListener l) {
769           * @param render                  mapPaneListeners.add(l);
          *            - what to draw the map with  
          * @param context  
          *            - what to draw  
          */  
         public JMapPane(final LayoutManager layout, final boolean isDoubleBuffered,  
                         final GTRenderer render, final MapContext context) {  
                 super(layout, isDoubleBuffered);  
   
                 ff = (FilterFactory2) org.geotools.factory.CommonFactoryFinder  
                                 .getFilterFactory(null);  
                 setRenderer(render);  
   
                 setContext(context);  
   
                 this.addMouseListener(this);  
                 this.addMouseMotionListener(this);  
                 setCursor(new Cursor(Cursor.CROSSHAIR_CURSOR));  
770          }          }
771    
772          /**          /**
773           * get the renderer           * Korrigiert den {@link Envelope} aka {@code mapArea} auf die beste
774           */           * erlaubte Flaeche damit die Massstabsbeschaenkungen noch eingehalten
775          public GTRenderer getRenderer() {           * werden, FALLS der uebergeben Envelope nicht schon gueltig sein sollte.<br>
776                  return renderer;           * Since 21. April 09: Before thecalculation starts, the aspect ratio is
777          }           * corrected. This change implies, that setMapArea() will most of the time
778             * not allow setting to a wrong aspectRatio.
779          public void setRenderer(final GTRenderer renderer) {           *
780                  Map hints = new HashMap();           * @author <a href="mailto:[email protected]">Stefan Alfons
781                             *         Kr&uuml;ger</a>
782                  this.renderer = renderer;           */
783                            public ReferencedEnvelope bestAllowedMapArea(ReferencedEnvelope env) {
                 if (renderer instanceof StreamingRenderer || renderer instanceof TransitionShapefileRenderer) {  
                         hints = renderer.getRendererHints();  
                         if (hints == null) {  
                                 hints = new HashMap();  
                         }  
                         if (hints.containsKey(StreamingRenderer.LABEL_CACHE_KEY)) {  
                                 labelCache = (LabelCache) hints  
                                                 .get(StreamingRenderer.LABEL_CACHE_KEY);  
                         } else {  
                                 hints.put(StreamingRenderer.LABEL_CACHE_KEY, labelCache);  
                         }  
784    
785                          hints.put("memoryPreloadingEnabled", Boolean.TRUE);                  if (getWidth() == 0)
786                                                    return env;
787                          renderer.setRendererHints(hints);  
788                    if (env == null)
789                            return null;
790    
791                    Envelope newArea = null;
792    
793                    /**
794                     * Correct the aspect Ratio before we check the rest. Otherwise we might
795                     * easily fail. We allow to grow here, because we don't check against
796                     * the maxExtend
797                     */
798                    final Rectangle curPaintArea = getVisibleRect();
799    
800                    env = JTSUtil.fixAspectRatio(curPaintArea, env, true);
801    
802                    final double scale = env.getWidth() / getWidth();
803                    final double centerX = env.getMinX() + env.getWidth() / 2.;
804                    final double centerY = env.getMinY() + env.getHeight() / 2.;
805                    double newWidth2 = 0;
806                    double newHeight2 = 0;
807                    if (scale < getMaxZoomScale()) {
808                            // ****************************************************************************
809                            // Wir zoomen weiter rein als erlaubt => Anpassen des envelope
810                            // ****************************************************************************
811                            newWidth2 = getMaxZoomScale() * getWidth() / 2.;
812                            newHeight2 = getMaxZoomScale() * getHeight() / 2.;
813                    } else if (scale > getMinZoomScale()) {
814                            // ****************************************************************************
815                            // Wir zoomen weiter raus als erlaubt => Anpassen des envelope
816                            // ****************************************************************************
817                            newWidth2 = getMinZoomScale() * getWidth() / 2.;
818                            newHeight2 = getMinZoomScale() * getHeight() / 2.;
819                    } else {
820                            // ****************************************************************************
821                            // Die mapArea / der Envelope ist ist gueltig! Keine Aenderungen
822                            // ****************************************************************************
823                            newArea = env;
824                  }                  }
825    
826  //              this.highlightRenderer = new StreamingRenderer();                  if (newArea == null) {
 //              this.selectionRenderer = new StreamingRenderer();  
827    
828  //              highlightRenderer.setRendererHints(hints);                          final Coordinate ll = new Coordinate(centerX - newWidth2, centerY
829  //              selectionRenderer.setRendererHints(hints);                                          - newHeight2);
830                                            final Coordinate ur = new Coordinate(centerX + newWidth2, centerY
831  //              renderer.setRendererHints(hints);                                          + newHeight2);
832    
833                  if (this.context != null) {                          newArea = new Envelope(ll, ur);
                         this.renderer.setContext(this.context);  
834                  }                  }
         }  
835    
836          public MapContext getContext() {                  final Envelope maxAllowedExtend = getMaxExtend();
837                  return context;  
838          }                  // This variable is used to break the loop if it runs forever...
839                    Envelope lastCalculatedArea = null;
840                    /*
841                     * If a maxAllowedExtend is set, we have to honour that...
842                     */
843                    while (maxAllowedExtend != null && !maxAllowedExtend.contains(newArea)
844                                    && newArea != null && !newArea.isNull()
845                                    && !Double.isNaN(newArea.getMinX())
846                                    && !Double.isNaN(newArea.getMaxX())
847                                    && !Double.isNaN(newArea.getMinY())
848                                    && !Double.isNaN(newArea.getMaxY())) // Due to Double precision
849                    // problems, this may
850                    // iterate for ever
851                    {
852    
853                            if (newArea.equals(lastCalculatedArea))
854                                    break;
855                            // Check that we are not iterating for ever due to double precision
856                            // rounding errors
857                            lastCalculatedArea = newArea;
858    
859                            // Exceeds top? Move down and maybe cut
860                            if (newArea.getMaxY() > maxAllowedExtend.getMaxY()) {
861                                    final double divY = newArea.getMaxY()
862                                                    - maxAllowedExtend.getMaxY();
863                                    // LOGGER.debug("Moving area down by " + divY);
864    
865                                    newArea = new Envelope(new Coordinate(newArea.getMinX(),
866                                                    newArea.getMinY() - divY), new Coordinate(newArea
867                                                    .getMaxX(), newArea.getMaxY() - divY));
868    
869                                    if (newArea.getMinY() < maxAllowedExtend.getMinY()) {
870                                            // LOGGER.debug("Now it exeeds the bottom border.. cut!");
871                                            // And cut the bottom if it moved out of the area
872                                            newArea = new Envelope(new Coordinate(newArea.getMinX(),
873                                                            maxAllowedExtend.getMinY()), new Coordinate(newArea
874                                                            .getMaxX(), newArea.getMaxY()));
875    
876                                            // LOGGER.debug("and fix aspect ratio");
877    
878                                            newArea = JTSUtil.fixAspectRatio(getVisibleRect(),
879                                                            new ReferencedEnvelope(newArea, env
880                                                                            .getCoordinateReferenceSystem()), false);
881                                    }
882                            }
883    
884                            // Exceeds bottom? Move up and maybe cut
885                            if (newArea.getMinY() < maxAllowedExtend.getMinY()) {
886                                    final double divY = newArea.getMinY()
887                                                    - maxAllowedExtend.getMinY();
888                                    // LOGGER.debug("Moving area up by " + divY);
889    
890                                    newArea = new Envelope(new Coordinate(newArea.getMinX(),
891                                                    newArea.getMinY() - divY), new Coordinate(newArea
892                                                    .getMaxX(), newArea.getMaxY() - divY));
893    
894                                    if (newArea.getMaxY() > maxAllowedExtend.getMaxY()) {
895                                            // LOGGER.debug("Now it exeeds the top border.. cut!");
896                                            // And cut the bottom if it moved out of the area
897                                            newArea = new Envelope(new Coordinate(newArea.getMinX(),
898                                                            newArea.getMinY()), new Coordinate(newArea
899                                                            .getMaxX(), maxAllowedExtend.getMaxY()));
900    
901                                            // LOGGER.debug("and fix aspect ratio");
902    
903                                            newArea = JTSUtil.fixAspectRatio(getVisibleRect(),
904                                                            new ReferencedEnvelope(newArea, env
905                                                                            .getCoordinateReferenceSystem()), false);
906                                    }
907                            }
908    
909                            // Exceeds to the right? move and maybe cut
910                            if (newArea.getMaxX() > maxAllowedExtend.getMaxX()) {
911    
912                                    // Move left..
913                                    final double divX = newArea.getMaxX()
914                                                    - maxAllowedExtend.getMaxX();
915                                    // LOGGER.debug("Moving area left by " + divX);
916    
917                                    newArea = new Envelope(new Coordinate(newArea.getMinX() - divX,
918                                                    newArea.getMinY()), new Coordinate(newArea.getMaxX()
919                                                    - divX, newArea.getMaxY()));
920    
921                                    if (newArea.getMinX() < maxAllowedExtend.getMinX()) {
922                                            // LOGGER.debug("Now it exeeds the left border.. cut!");
923                                            // And cut the left if it moved out of the area
924                                            newArea = new Envelope(new Coordinate(maxAllowedExtend
925                                                            .getMinX(), newArea.getMinY()), new Coordinate(
926                                                            newArea.getMaxX(), newArea.getMaxY()));
927    
928                                            // LOGGER.debug("and fix aspect ratio");
929    
930                                            newArea = JTSUtil.fixAspectRatio(getVisibleRect(),
931                                                            new ReferencedEnvelope(newArea, env
932                                                                            .getCoordinateReferenceSystem()), false);
933                                    }
934                            }
935    
936                            // Exceeds to the left? move and maybe cut
937                            if (newArea.getMinX() < maxAllowedExtend.getMinX()) {
938    
939                                    // Move right..
940                                    final double divX = newArea.getMinX()
941                                                    - maxAllowedExtend.getMinX();
942                                    // LOGGER.debug("Moving area right by " + divX);
943    
944                                    newArea = new Envelope(new Coordinate(newArea.getMinX() - divX,
945                                                    newArea.getMinY()), new Coordinate(newArea.getMaxX()
946                                                    - divX, newArea.getMaxY()));
947    
948                                    if (newArea.getMaxX() > maxAllowedExtend.getMaxX()) {
949                                            // LOGGER.debug("Now it exeeds the right border.. cut!");
950                                            // And cut the left if it moved out of the area
951                                            newArea = new Envelope(new Coordinate(newArea.getMinX(),
952                                                            newArea.getMinY()), new Coordinate(maxAllowedExtend
953                                                            .getMaxX(), newArea.getMaxY()));
954    
955                                            // LOGGER.debug("and fix aspect ratio");
956    
957                                            newArea = JTSUtil.fixAspectRatio(getVisibleRect(),
958                                                            new ReferencedEnvelope(newArea, env
959                                                                            .getCoordinateReferenceSystem()), false);
960                                    }
961                            }
962    
         public void setContext(final MapContext context) {  
                 if (this.context != null) {  
                         this.context.removeMapLayerListListener(this);  
963                  }                  }
964    
965                  this.context = context;                  return new ReferencedEnvelope(newArea, env
966                                    .getCoordinateReferenceSystem());
967            }
968    
969                  if (context != null) {          /**
970                          this.context.addMapLayerListListener(this);           * Should be called when the {@link JMapPane} is not needed no more to help
971             * the GarbageCollector
972             *
973             * Removes all {@link JMapPaneListener}s that are registered
974             *
975             * @author <a href="mailto:[email protected]">Stefan Alfons
976             *         Kr&uuml;ger</a>
977             */
978            public void dispose() {
979                    if (isDisposed())
980                            return;
981    
982                    setPainting(false);
983    
984                    resizeTimer.stop();
985                    startRenderThreadsTimer.stop();
986    
987                    disposed = true;
988    
989                    if (bgExecuter != null) {
990                            bgExecuter.cancelTask();
991                            bgExecuter.dispose();
992                  }                  }
993    
994                  if (renderer != null) {                  if (localExecuter.isRunning()) {
995                          renderer.setContext(this.context);                          int i = 0;
996                            localExecuter.cancelTask();
997                            while (i++ < 10 && localExecuter.isRunning()) {
998                                    try {
999                                            Thread.sleep(200);
1000                                    } catch (final InterruptedException e) {
1001                                            LOGGER
1002                                                            .warn(
1003                                                                            "while XMapPane we are waiting for the localExcutor to stop",
1004                                                                            e);
1005                                    }
1006                            }
1007                            if (localExecuter.isRunning()) {
1008                                    LOGGER
1009                                                    .warn("localExecutor Thread still running after 2s! Continuing anyways...");
1010                            }
1011                            localExecuter.dispose();
1012                  }                  }
         }  
1013    
1014          public Envelope getMapArea() {                  disposeImages();
1015                  return mapArea;  
1016                    // Remove all mapPaneListeners that have registered with us
1017                    mapPaneListeners.clear();
1018    
1019                    removeMouseMotionListener(xMapPaneMouseListener);
1020                    removeMouseListener(xMapPaneMouseListener);
1021    
1022                    if (localContext != null)
1023                            getMapContext().clearLayerList();
1024                    if (bgContext != null)
1025                            getBgContext().clearLayerList();
1026    
1027                    removeAll();
1028          }          }
1029    
1030          public void setMapArea(final Envelope mapArea) {          /**
1031                  this.mapArea = mapArea;           * Draws a rectangle in XOR mode from the origin at {@link #startPos} to the
1032             * given point. All in screen coordinates.
1033             */
1034            protected void drawRectangle(final Graphics graphics, final Point startPos,
1035                            final Point e) {
1036                    drawRectangle(graphics, startPos, e, Color.WHITE, false);
1037          }          }
1038    
1039          public int getState() {          /**
1040                  return state;           * Draws a rectangle in XOR mode from the origin at {@link #startPos} to the
1041             * given point. All in screen coordinates.
1042             */
1043            protected void drawRectangle(final Graphics graphics, final Point startPos,
1044                            final Point e, Color color, boolean fill) {
1045    
1046                    if (!isWellDefined())
1047                            return;
1048    
1049                    // undraw last box/draw new box
1050                    final int left = Math.min(startPos.x, e.x);
1051                    final int right = Math.max(startPos.x, e.x);
1052                    final int top = Math.max(startPos.y, e.y);
1053                    final int bottom = Math.min(startPos.y, e.y);
1054                    final int width = right - left;
1055                    final int height = top - bottom;
1056    
1057                    if (width == 0 && height == 0)
1058                            return;
1059    
1060                    graphics.setXORMode(color);
1061    
1062                    if (fill) {
1063                            graphics.fillRect(left, bottom, width, height);
1064                            graphics.setXORMode(Color.WHITE);
1065                    }
1066    
1067                    graphics.drawRect(left, bottom, width, height);
1068          }          }
1069    
1070          public void setState(final int state) {          /**
1071                  this.state = state;           * Diretly paints scaled preview into the {@link SelectableXMapPane}. Used
1072             * to give the user something to look at while we are rendering. Method
1073             * should be called after {@link #setMapArea(Envelope)} has been set to the
1074             * new mapArea and transform has been reset.<br>
1075             *
1076             * @param g
1077             *            Graphics2D to paint the preview into
1078             */
1079            protected boolean drawScaledPreviewImage_Zoom(final Graphics2D graphics) {
1080    
1081                    // if (1 == 1)return false;
1082                    // if (quickPreviewHint == 0)
1083                    // return false;
1084    
1085                    if (oldMapArea == null)
1086                            return false;
1087    
1088                    if (getPreFinalImage() == null)
1089                            return false;
1090    
1091                    final Rectangle visibleArea = getVisibleRect();
1092    
1093                    // Calculate the oldMapArea in the current WindowCoordinates:
1094                    final Envelope oldMapWindow = tranformGeoToWindow(oldMapArea.getMinX(),
1095                                    oldMapArea.getMinY(), oldMapArea.getMaxX(), oldMapArea
1096                                                    .getMaxY());
1097    
1098                    final int xx1 = (int) Math.round(oldMapWindow.getMinX());
1099                    final int yy1 = (int) Math.round(oldMapWindow.getMinY());
1100                    final int xx2 = (int) Math.round(oldMapWindow.getMaxX());
1101                    final int yy2 = (int) Math.round(oldMapWindow.getMaxY());
1102    
1103                  // System.out.println("State: " + state);                  graphics.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
1104                                    RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR);
1105                    graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
1106                                    RenderingHints.VALUE_ANTIALIAS_OFF);
1107                    graphics.setRenderingHint(RenderingHints.KEY_RENDERING,
1108                                    RenderingHints.VALUE_RENDER_SPEED);
1109    
1110                    graphics.drawImage(getPreFinalImage(), xx1, yy1, xx2, yy2,
1111                                    (int) visibleArea.getMinX(), (int) visibleArea.getMinY(),
1112                                    (int) visibleArea.getMaxX(), (int) visibleArea.getMaxY(),
1113                                    getMapBackgroundColor(), null);
1114    
1115                    final Rectangle painedArea = new Rectangle(xx1, yy1, xx2 - xx1, yy2
1116                                    - yy1);
1117    
1118                    SwingUtil.clearAround(graphics, painedArea, visibleArea,
1119                                    getMapBackgroundColor());
1120    
1121                    addGadgets(graphics, true);
1122    
1123                    // quickPreviewHint = 0;
1124    
1125                    repaintTimer.restart();
1126    
1127                    // Something has been drawn
1128                    return true;
1129          }          }
1130    
1131          public double getZoomFactor() {          public MapContext getBgContext() {
1132                  return zoomFactor;                  return bgContext;
1133          }          }
1134    
1135          public void setZoomFactor(final double zoomFactor) {          /**
1136                  this.zoomFactor = zoomFactor;           * Lazyly initializes a {@link BufferedImage} for the background renderer.
1137             */
1138            private Image getBgImage() {
1139                    if (bgImage == null) {
1140                            bgImage = new BufferedImage(getVisibleRect().width,
1141                                            getVisibleRect().height, IMAGETYPE);
1142                            SwingUtil.clearImage(finalImage, getMapBackgroundColor());
1143                    }
1144    
1145                    return bgImage;
1146          }          }
1147    
1148            public MapContext getMapContext() {
1149                    if (localContext == null) {
1150                            setLocalContext(new DefaultMapContext());
1151                    }
1152                    return localContext;
1153            }
1154    
1155          protected void paintComponent(final Graphics g) {          private BufferedImage getFinalImage() {
1156                  super.paintComponent(g);                  //
1157                    if (finalImage == null) {
1158                            // Rectangle curPaintArea = getVisibleRect();
1159                            finalImage = new BufferedImage(getVisibleRect().width,
1160                                            getVisibleRect().height, IMAGETYPE);
1161                            SwingUtil.clearImage(finalImage, getMapBackgroundColor());
1162    
1163                  if ((renderer == null) || (mapArea == null)) {                          // requestStartRendering();
                         return;  
1164                  }                  }
1165                    return finalImage;
1166            }
1167    
1168            /**
1169             * Lazyly initializes a {@link BufferedImage} for the background renderer.
1170             */
1171            private BufferedImage getLocalImage() {
1172    
1173                    if (localImage == null) {
1174                            localImage = new BufferedImage(getVisibleRect().width,
1175                                            getVisibleRect().height, IMAGETYPE_withAlpha);
1176                            SwingUtil.clearImage(localImage, getMapBackgroundColor());
1177                    }
1178    
1179                    return localImage;
1180            }
1181    
1182                  final Rectangle r = getBounds();          /**
1183                  final Rectangle dr = new Rectangle(r.width, r.height);           * Returns a copy of the mapArea
1184             *
1185             * @return
1186             */
1187            public ReferencedEnvelope getMapArea() {
1188                    if (mapArea == null) {
1189                            ReferencedEnvelope mapArea_ = null;
1190                            try {
1191                                    mapArea_ = localContext.getLayerBounds();
1192                            } catch (final Exception e) {
1193                                    LOGGER.warn("localContext.getLayerBounds()", e);
1194                            }
1195    
1196                  if (!r.equals(oldRect) || reset) {                          if (mapArea_ == null && bgContext != null) {
                         if (!r.equals(oldRect) && (mapArea == null)) {  
1197                                  try {                                  try {
1198                                          mapArea = context.getLayerBounds();                                          mapArea_ = bgContext.getLayerBounds();
1199                                  } catch (final IOException e) {                                  } catch (final IOException e) {
1200                                          LOGGER.warn("context.getLayerBounds()", e);                                          LOGGER.warn("bgContext.getLayerBounds()", e);
1201                                  }                                  }
1202                          }                          }
1203    
1204                          if (mapArea != null) {                          if (mapArea_ != null) {
1205                                  /* either the viewer size has changed or we've done a reset */                                  mapArea = bestAllowedMapArea(mapArea_);
1206                                  changed = true; /* note we need to redraw */                                  requestStartRendering();
                                 reset = false; /* forget about the reset */  
                                 oldRect = r; /* store what the current size is */  
   
                                 mapArea = fixAspectRatio(r, mapArea);  
1207                          }                          }
1208                  }                  }
1209    
1210                  if (!mapArea.equals(oldMapArea)) { /* did the map extent change? */                  if (mapArea == null)
1211                          changed = true;                          return null;
                         oldMapArea = mapArea;  
                         // when we tell the context that the bounds have changed WMSLayers  
                         // can refresh them selves  
                         context.setAreaOfInterest(mapArea, context  
                                         .getCoordinateReferenceSystem());  
                 }  
   
                 if (changed ) { /* if the map changed then redraw */  
                         changed = false;  
                         baseImage = new BufferedImage(dr.width, dr.height,  
                                         BufferedImage.TYPE_INT_ARGB);  
   
                         final Graphics2D ig = baseImage.createGraphics();  
                         /* System.out.println("rendering"); */  
                         if (renderer.getContext() != null)  
                                 renderer.setContext(context);  
                         labelCache.clear(); // work around anoying labelcache bug  
1212    
1213                          // draw the map                  // TODO is needed at all, this should go to setMapArea maybe
1214                          renderer.paint((Graphics2D) ig, dr, mapArea);                  if (localContext.getCoordinateReferenceSystem() == null)
1215                            try {
1216                                    localContext.setCoordinateReferenceSystem(GeoImportUtil
1217                                                    .getDefaultCRS());
1218                            } catch (final Exception e) {
1219                                    throw new RuntimeException("setting context CRS:", e);
1220                            }
1221    
1222                          // TODO nur machen, wenn panning beginnt                  return new ReferencedEnvelope(mapArea, localContext
1223                          panningImage = new BufferedImage(dr.width, dr.height,                                  .getCoordinateReferenceSystem());
1224                                          BufferedImage.TYPE_INT_RGB);          }
1225    
1226            /**
1227             * Returns the background {@link Color} of the map pane. If not set, the
1228             * methods looks for a parent component and will use its background color.
1229             * If no parent component is available, WHITE is returned.
1230             **/
1231            public Color getMapBackgroundColor() {
1232                    if (mapBackgroundColor == null) {
1233                            if (getParent() != null)
1234                                    return getParent().getBackground();
1235                            else
1236                                    return Color.WHITE;
1237                  }                  }
1238                    return mapBackgroundColor;
1239            }
1240    
1241                  ((Graphics2D) g).drawImage(baseImage, 0, 0, this);          /**
1242             * Get the BufferedImage to use as a flaoting icon in the lower right
1243             * corner.
1244             *
1245             * @return <code>null</code> if the feature is deactivated.
1246             */
1247            public BufferedImage getMapImage() {
1248                    return mapImage;
1249          }          }
1250    
1251          private Envelope fixAspectRatio(final Rectangle r, final Envelope mapArea) {          /**
1252             * Returns the evelope of the viewable area. The JMapPane will never show
1253             * anything outside of this extend. If this has been set to
1254             * <code>null</code> via {@link #setMaxExtend(Envelope)}, it tries to return
1255             * quickly the context's bounds. It it takes to long to determine the
1256             * context bounds, <code>null</code> is returned.
1257             *
1258             * @param maxExtend
1259             *            <code>null</code> to not have this restriction.
1260             */
1261    
1262                  final double mapWidth = mapArea.getWidth(); /* get the extent of the map */          public Envelope getMaxExtend() {
1263                  final double mapHeight = mapArea.getHeight();                  if (maxExtend == null) {
                 final double scaleX = r.getWidth() / mapArea.getWidth(); /*  
                                                                                                                          * calculate the new  
                                                                                                                          * scale  
                                                                                                                          */  
1264    
1265                  final double scaleY = r.getHeight() / mapArea.getHeight();                          // The next command may take long time!
1266                  double scale = 1.0; // stupid compiler!                          // long start = System.currentTimeMillis();
1267                            final ReferencedEnvelope layerBounds = GTUtil
1268                                            .getVisibleLayoutBounds(localContext);
1269                            //                      
1270                            // LOGGER.info(
1271                            // (System.currentTimeMillis()-start)+"m to get maxExtend");
1272                            //                      
1273                            if (layerBounds == null) {
1274                                    // // TODO Last fallback could be the CRS valid area
1275                                    return null;
1276                            }
1277    
1278                            return JTSUtil.fixAspectRatio(getVisibleRect(),
1279                                            addDefaultMargin(layerBounds), true);
1280    
                 if (scaleX < scaleY) { /* pick the smaller scale */  
                         scale = scaleX;  
                 } else {  
                         scale = scaleY;  
1281                  }                  }
1282                    return maxExtend;
1283            }
1284    
1285                  /* calculate the difference in width and height of the new extent */          /**
1286                  final double deltaX = /* Math.abs */((r.getWidth() / scale) - mapWidth);           * Retuns the maximum allowed zoom scale. This is the smaller number value
1287                  final double deltaY = /* Math.abs */((r.getHeight() / scale) - mapHeight);           * of the two. Defaults to {@link Double}.MIN_VALUE
1288             *
1289             * @author <a href="mailto:[email protected]">Stefan Alfons
1290             *         Kr&uuml;ger</a>
1291             */
1292            public Double getMaxZoomScale() {
1293                    return maxZoomScale;
1294            }
1295    
1296                  /*          /**
1297                   * System.out.println("delta x " + deltaX);           * Retuns the minimum allowed zoom scale. This is the bigger number value of
1298                   * System.out.println("delta y " + deltaY);           * the two. Defaults to {@link Double}.MAX_VALUE
1299                   */           *
1300             * @author <a href="mailto:[email protected]">Stefan Alfons
1301             *         Kr&uuml;ger</a>
1302             */
1303            public Double getMinZoomScale() {
1304                    return minZoomScale;
1305            }
1306    
1307                  /* create the new extent */          private Image getPreFinalImage() {
1308                  final Coordinate ll = new Coordinate(mapArea.getMinX() - (deltaX / 2.0),                  return preFinalImage;
1309                                  mapArea.getMinY() - (deltaY / 2.0));          }
                 final Coordinate ur = new Coordinate(mapArea.getMaxX() + (deltaX / 2.0),  
                                 mapArea.getMaxY() + (deltaY / 2.0));  
   
                 return new Envelope(ll, ur);  
         }  
   
 //      public void doSelection(final double x, final double y, final MapLayer layer) {  
 //  
 //              final Geometry geometry = gf.createPoint(new Coordinate(x, y));  
 //  
 //              // org.opengis.geometry.Geometry geometry = new Point();  
 //  
 //              findFeature(geometry, layer);  
 //  
 //      }  
 //  
 //      /**  
 //       * @param geometry  
 //       *            - a geometry to construct the filter with  
 //       * @param i  
 //       *            - the index of the layer to search  
 //       * @throws IndexOutOfBoundsException  
 //       */  
 //      private void findFeature(final Geometry geometry, final MapLayer layer)  
 //                      throws IndexOutOfBoundsException {  
 //              org.opengis.filter.spatial.BinarySpatialOperator f = null;  
 //  
 //              if ((context == null) || (layer == null)) {  
 //                      return;  
 //              }  
 //  
 //              try {  
 //                      String name = layer.getFeatureSource().getSchema()  
 //                                      .getDefaultGeometry().getLocalName();  
 //  
 //                      if (name == "") {  
 //                              name = "the_geom";  
 //                      }  
 //  
 //                      try {  
 //                              f = ff.contains(ff.property(name), ff.literal(geometry));  
 //                              if (selectionManager != null) {  
 ////                                    System.out.println("selection changed");  
 //                                      selectionManager.selectionChanged(this, f);  
 //  
 //                              }  
 //                      } catch (final IllegalFilterException e) {  
 //                              // TODO Auto-generated catch block  
 //                              e.printStackTrace();  
 //                      }  
 //  
 //                      /*  
 //                       * // f.addLeftGeometry(ff.property(name)); //  
 //                       * System.out.println("looking with " + f); FeatureCollection fc =  
 //                       * layer.getFeatureSource().getFeatures(f);  
 //                       *  
 //                       *  
 //                       *  
 //                       * if (fcol == null) { fcol = fc;  
 //                       *  
 //                       * // here we should set the defaultgeom type } else {  
 //                       * fcol.addAll(fc); }  
 //                       */  
 //  
 //                      /*  
 //                       * GeometryAttributeType gat =  
 //                       * layer.getFeatureSource().getSchema().getDefaultGeometry();  
 //                       * fcol.setDefaultGeometry((Geometry)gat.createDefaultValue());  
 //                       */  
 //  
 //                      /*  
 //                       * Iterator fi = fc.iterator(); while (fi.hasNext()) { SimpleFeature feat  
 //                       * = (SimpleFeature) fi.next(); System.out.println("selected " +  
 //                       * feat.getAttribute("STATE_NAME")); }  
 //                       */  
 //              } catch (final IllegalFilterException e) {  
 //                      // 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();  
1310    
1311                  /*          public Map<Object, Object> getRendererHints() {
1312                   * System.out.println(""+x+"->"+mapX);                  // Clear label cache
1313                   * System.out.println(""+y+"->"+mapY);                  labelCache.clear();
1314                   */                  rendererHints.put(StreamingRenderer.LABEL_CACHE_KEY, labelCache);
1315    
1316                  /*                  return rendererHints;
1317                   * Coordinate ll = new Coordinate(mapArea.getMinX(), mapArea.getMinY());          }
                  * Coordinate ur = new Coordinate(mapArea.getMaxX(), mapArea.getMaxY());  
                  */  
                 double zlevel = 1.0;  
1318    
1319                  switch (state) {          /**
1320                  case Pan:           * Liefert eine affine Transformation, um von den Fenster-Koordinaten in die
1321                          zlevel = 1.0;           * Karten-Koordinaten (Lat/Lon) umzurechnen.
1322                          // xulu.sc SK: return here.. a mouselistener is managing the PANNING           *
1323                          // break;           * @return eine Kopie der aktuellen Transformation; <code>null</code> wenn
1324                          return;           *         noch keine Karte angezeigt wird
1325                          // xulu.ec           */
1326                  case ZoomIn:          public AffineTransform getScreenToWorld() {
1327                          zlevel = zoomFactor;                  if (screenToWorld == null)
1328                            resetTransforms();
1329                          break;                  // nur Kopie der Transformation zurueckgeben!
1330                    if (screenToWorld == null)
1331                  case ZoomOut:                          return null;
1332                          zlevel = 1.0 / zoomFactor;                  return new AffineTransform(screenToWorld);
1333            }
1334                          break;  
1335  //          // public int getState() {
1336  //              case Select:          // return state;
1337  //                      doSelection(mapX, mapY, selectionLayer);          // }
1338  //          //
1339  //                      return;          // /**
1340            // * Liefert den statisch eingestellten Cursor, der unabhaengig von der
1341            // * eingestellten MapPane-Aktion (Zoom, Auswahl, ...) verwendet wird.
1342            // *
1343            // * @return {@code null}, wenn kein statischer Cursor verwendet, sondern
1344            // der
1345            // * Cursor automatisch je nach MapPane-Aktion eingestellt wird.
1346            // */
1347            // public Cursor getStaticCursor() {
1348            // return this.staticCursor;
1349            // }
1350    
1351            public AffineTransform getWorldToScreenTransform() {
1352                    if (worldToScreen == null) {
1353                            resetTransforms();
1354                    }
1355                    // nur Kopie der Transformation zurueckgeben!
1356                    return new AffineTransform(worldToScreen);
1357            }
1358    
1359                  default:          /**
1360                          return;           * A flag indicating if dispose() has already been called. If true, then
1361             * further use of this {@link SelectableXMapPane} is undefined.
1362             */
1363            private boolean isDisposed() {
1364                    return disposed;
1365            }
1366    
1367            /**
1368             * Returns whether a layer is regarded or ignored on {@link #SELECT_TOP},
1369             * {@link #SELECT_ALL} and {@link #SELECT_ONE_FROM_TOP} actions. Returns
1370             * <code>true</code> if the selectability has not been defined.
1371             *
1372             * @param layer
1373             *            a layer
1374             */
1375            public boolean isMapLayerSelectable(final MapLayer layer) {
1376                    final Boolean selectable = mapLayerSelectable.get(layer);
1377                    return selectable == null ? true : selectable;
1378            }
1379    
1380            /**
1381             * Return <code>true</code> if a CRS and a {@link #mapArea} are set and the
1382             * {@link XMapPane} is visible and has bounds set.
1383             */
1384            public boolean isWellDefined() {
1385                    try {
1386                            if (getMapContext() == null)
1387                                    return false;
1388                            if (getMapContext().getLayerCount() <= 0)
1389                                    return false;
1390                            if (getVisibleRect().getWidth() == 0)
1391                                    return false;
1392                            if (getVisibleRect().getHeight() == 0)
1393                                    return false;
1394                            // if (getMapArea() == null)
1395                            // return false;
1396                    } catch (final Exception e) {
1397                            return false;
1398                  }                  }
1399                    return true;
1400            }
1401    
1402                  final Coordinate ll = new Coordinate(mapX - (width2 / zlevel), mapY          /**
1403                                  - (height2 / zlevel));           * Usually called from {@link XMapPaneAction_Pan} to pan the image.
1404                  final Coordinate ur = new Coordinate(mapX + (width2 / zlevel), mapY           *
1405                                  + (height2 / zlevel));           * @param startPos
1406                  // xulu.sc SK: Check for min/max scale           *            in screen coordinates
1407                  // mapArea = new Envelope(ll, ur);           * @param lastPos
1408                  final Envelope newMapArea = new Envelope(ll, ur);           *            in screen coordinates
1409                  setMapArea(bestAllowedMapArea(newMapArea));           */
1410                  // xulu.ec          public void pan(final int dX, final int dY) {
1411    
1412                  // sk.ec                  // Panning needs a panning coursor
1413                    if (getCursor() != SwingUtil.PANNING_CURSOR) {
1414                            setCursor(SwingUtil.PANNING_CURSOR);
1415    
1416                            // While panning, we deactivate the rendering. So the tasks are
1417                            // ready to start when the panning is finished.
1418                            if (bgExecuter != null && bgExecuter.isRunning())
1419                                    bgExecuter.cancelTask();
1420                            if (localExecuter.isRunning())
1421                                    localExecuter.cancelTask();
1422                    }
1423                    //
1424                    // if (lastPos.x > 0 && lastPos.y > 0) {
1425                    // final int dx = event.getX() - lastPos.x;
1426                    // final int dy = event.getY() - lastPos.y;
1427    
1428                    // TODO Stop dragging when the drag would not be valid...
1429                    // boolean dragValid = true;
1430                    // // check if this panning results in a valid mapArea
1431                    // {
1432                    // Rectangle winBounds = xMapPane.getBounds();
1433                    // winBounds.translate(xMapPane.imageOrigin.x,
1434                    // -xMapPane.imageOrigin.y);
1435                    // Envelope newMapAreaBefore = xMapPane.tranformWindowToGeo(
1436                    // winBounds.x, winBounds.y, winBounds.x
1437                    // + winBounds.width, winBounds.y
1438                    // + winBounds.height);
1439                    //                                      
1440                    //
1441                    // winBounds = xMapPane.getBounds();
1442                    // Point testIng = new Point(xMapPane.imageOrigin);
1443                    // testIng.translate(dx, dy);
1444                    // winBounds.translate(testIng.x, -testIng.y);
1445                    // Envelope newMapAreaAfter = xMapPane.tranformWindowToGeo(
1446                    // winBounds.x, winBounds.y, winBounds.x
1447                    // + winBounds.width, winBounds.y
1448                    // + winBounds.height);
1449                    //
1450                    // // If the last drag doesn't change the MapArea anymore cancel
1451                    // it.
1452                    // if (xMapPane.bestAllowedMapArea(newMapAreaAfter).equals(
1453                    // xMapPane.bestAllowedMapArea(newMapAreaBefore))){
1454                    // dragValid = false;
1455                    // return;
1456                    // }
1457                    // }
1458    
1459                  // System.out.println("after area "+mapArea+"\nw:"+mapArea.getWidth()+"                  getImageOrigin().translate(dX, dY);
1460                  // h:"+mapArea.getHeight());                  updateFinalImage();
1461                  repaint();                  repaint();
1462          }                  // }
1463    
1464          public void mouseEntered(final MouseEvent e) {                  // } else if ((getState() == XMapPane.ZOOM_IN)
1465                    // || (getState() == XMapPane.ZOOM_OUT)
1466                    // || (getState() == XMapPane.SELECT_ALL)
1467                    // || (getState() == XMapPane.SELECT_TOP)) {
1468                    //
1469                    // // Draws a rectangle
1470                    // final Graphics2D graphics = (Graphics2D) getGraphics();
1471                    // drawRectangle(graphics, startPos, event.getPoint());
1472                    // if ((lastPos.x > 0) && (lastPos.y > 0))
1473                    // drawRectangle(graphics, startPos, lastPos);
1474                    // graphics.dispose();
1475                    // }
1476          }          }
1477    
1478          public void mouseExited(final MouseEvent e) {          /**
1479             * Called by the {@link RenderingExecutor} when rendering was cancelled.
1480             */
1481            public void onRenderingCancelled() {
1482                    // LOGGER.debug("Rendering cancelled");
1483                    repaintTimer.stop();
1484          }          }
1485    
1486          public void mousePressed(final MouseEvent e) {          /**
1487                  startX = e.getX();           * Called by the {@link RenderingExecutor} when rendering has been
1488                  startY = e.getY();           * completed.
1489                  lastX = 0;           *
1490                  lastY = 0;           * @param l
1491             *            long ms the rendering took
1492             */
1493            public void onRenderingCompleted(final long l) {
1494                    lastRenderingDuration = (lastRenderingDuration + l) / 2;
1495                    // LOGGER
1496                    // .debug("complete rendering after " + lastRenderingDuration
1497                    // + "ms");
1498    
1499                    repaintTimer.stop();
1500    
1501                    // We "forget" about an exception every time we complete a rendering
1502                    // thread successfully
1503                    if (renderingErrors.size() > 0)
1504                            renderingErrors.remove(0);
1505    
1506                    updateFinalImage();
1507                    repaint();
1508          }          }
1509    
1510          public void mouseReleased(final MouseEvent e) {          /**
1511                  final int endX = e.getX();           * Called by the {@linkplain XMapPane.RenderingTask} when rendering failed.
1512                  final int endY = e.getY();           * Publishes a {@linkplain MapPaneEvent} of type {@code
1513             * MapPaneEvent.Type.RENDERING_STOPPED} to listeners.
1514             *
1515             * @param renderingError
1516             *            The error that occured during rendering
1517             *
1518             * @see MapPaneListener#onRenderingStopped(org.geotools.swing.event.MapPaneEvent)
1519             */
1520            public void onRenderingFailed(final Exception renderingError) {
1521    
1522                    // Store the exceptions so we can show it to the user:
1523                    if (!(renderingError instanceof java.lang.IllegalArgumentException && renderingError
1524                                    .getMessage().equals(
1525                                                    "Argument \"sourceCRS\" should not be null.")))
1526                            this.renderingErrors.add(renderingError);
1527                    if (renderingErrors.size() > 3)
1528                            renderingErrors.remove(0);
1529    
1530                  processDrag(startX, startY, endX, endY, e);                  repaintTimer.stop();
1531                  lastX = 0;  
1532                  lastY = 0;                  LOGGER.warn("Rendering failed", renderingError);
1533                    updateFinalImage();
1534                    repaint();
1535    
                 /**  
                  * Es wird nicht (mehr) gepannt!  
                  */  
                 panning_started = false;  
1536          }          }
1537    
1538          public void mouseDragged(final MouseEvent e) {          @Override
1539                  final Graphics graphics = this.getGraphics();          protected void paintComponent(final Graphics g) {
                 final int x = e.getX();  
                 final int y = e.getY();  
   
                 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);  
                         }  
   
                         // move the image with the mouse  
                         if ((lastX > 0) && (lastY > 0)) {  
                                 final int dx = lastX - startX;  
                                 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  
1540    
1541                  if ((state == JMapPane.ZoomIn) || (state == JMapPane.ZoomOut)) {                  // Maybe update the cursor and maybe stop the repainting timer
1542                    updateCursor();
1543    
1544                          graphics.setXORMode(Color.WHITE);                  if (!acceptsRepaintCalls)
1545                            return;
1546    
1547                          if ((lastX > 0) && (lastY > 0)) {                  if (!isWellDefined())
1548                                  drawRectangle(graphics);                          return;
1549                    //
1550                    // if (paneResized) {
1551                    // // ((Graphics2D) g).setBackground(getMapBackgroundColor());
1552                    // // g.clearRect(0, 0, getVisibleRect().width,
1553                    // getVisibleRect().height);
1554                    // return;
1555                    // }
1556    
1557                    // super.paintComponent(g); // candidate for removal
1558    
1559                    boolean paintedSomething = false;
1560    
1561                    if (mapImageInvalid) { /* if the map changed then redraw */
1562    
1563                            mapImageInvalid = false; // Reset for next round
1564    
1565                            // If the new mapArea and the oldMapArea intersect, we can draw some
1566                            // quick scaled preview to make the user feel that something is
1567                            // happening.
1568                            if (lastRenderingDuration > PRESCALE_MINTIME && mapAreaChanged
1569                                            && oldMapArea != null
1570                                            && getMapArea().intersects(oldMapArea)
1571                                            && !getMapArea().equals(oldMapArea) && !paneResized) {
1572    
1573                                    mapAreaChanged = false;
1574    
1575                                    // if (getMapArea().covers(oldMapArea)) {
1576                                    // // quickPreviewHint = ZOOM_OUT;
1577                                    // paintedSomething = drawScaledPreviewImage_Zoom((Graphics2D)
1578                                    // g);
1579                                    // } else if (oldMapArea.covers(getMapArea())) {
1580                                    // quickPreviewHint = ZOOM_IN;
1581                                    paintedSomething = drawScaledPreviewImage_Zoom((Graphics2D) g);
1582                                    // }
1583                          }                          }
1584                    }
1585    
1586                          // draw new box                  if (!paintedSomething) {
                         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);  
 //                      }  
 //  
 //                      graphics.setXORMode(Color.green);  
 //  
 //                      /*  
 //                       * if ((lastX > 0) && (lastY > 0)) { drawRectangle(graphics); }  
 //                       */  
 //  
 //                      // draw new box  
 //                      lastX = x;  
 //                      lastY = y;  
 //                      drawRectangle(graphics);  
 //              }  
   
         }  
   
         // sk.cs  
         // private void processDrag(int x1, int y1, int x2, int y2) {  
         // sk.ce  
         protected void processDrag(final int x1, final int y1, final int x2,  
                         final int y2, final MouseEvent e) {  
1587    
1588                  /****                          g.drawImage(getFinalImage(), 0, 0, null);
                  * If no layer is availabe we dont want a NullPointerException  
                  */  
                 if (mapArea == null)  
                         return;  
1589    
1590                  // System.out.println("processing drag from " + x1 + "," + y1 + " -> "                          paintedSomething = true; // cand. for removal
1591                  // + x2 + "," + y2);                  }
                 if ((x1 == x2) && (y1 == y2)) {  
                         if (isClickable()) {  
                                 mouseClicked(new MouseEvent(this, 0, new Date().getTime(), 0,  
                                                 x1, y1, y2, false));  
                         }  
1592    
1593                          return;          }
1594    
1595            /**
1596             * Heavily works on releasing all resources related to the four
1597             * {@link Image}s used to cache the results of the different renderers.<br>
1598             * In November 2009 i had some memory leaking problems with {@link XMapPane}
1599             * . The resources of the buffered images were never released. It seem to be
1600             * important to call the GC right after flushing the images.<br>
1601             * Hence this method may take a while, because it calls the GC up to four
1602             * times.
1603             */
1604            private void disposeImages() {
1605    
1606                    // System.out.println("vorher = "
1607                    // + new MbDecimalFormatter().format(LangUtil.gcTotal()));
1608                    // bi.flush();
1609                    // return bi = null;
1610                    // System.out.println("nacher = "
1611                    // + new MbDecimalFormatter().format(LangUtil.gcTotal()));
1612                    //
1613                    // System.out.println("\n");
1614    
1615                    if (preFinalImage != null) {
1616                            preFinalImage.flush();
1617                            preFinalImage = null;
1618                            LangUtil.gc();
1619                    }
1620                    if (finalImage != null) {
1621                            finalImage.flush();
1622                            finalImage = null;
1623                            LangUtil.gc();
1624                    }
1625                    if (localImage != null) {
1626                            localImage.flush();
1627                            localImage = null;
1628                            LangUtil.gc();
1629                    }
1630                    if (bgImage != null) {
1631                            bgImage.flush();
1632                            bgImage = null;
1633                            LangUtil.gc();
1634                  }                  }
1635    
1636                  final Rectangle bounds = this.getBounds();          }
1637    
1638                  final double mapWidth = mapArea.getWidth();          //
1639                  final double mapHeight = mapArea.getHeight();          // /**
1640            // * Performs a {@value #PAN} action. During panning, the displacement is
1641            // * stored in {@link #imageOrigin} object. Calling {@link #performPan()}
1642            // will
1643            // * reset the offset and call {@link #setMapArea(Envelope)}.
1644            // */
1645            // public void performPan() {
1646            //
1647            // final Rectangle winBounds = getVisibleRect();
1648            //
1649            // winBounds.translate(-imageOrigin.x, -imageOrigin.y);
1650            // final Envelope newMapArea = tranformWindowToGeo(winBounds.x,
1651            // winBounds.y, winBounds.x + winBounds.width, winBounds.y
1652            // + winBounds.height);
1653            //
1654            // imageOrigin.x = 0;
1655            // imageOrigin.y = 0;
1656            //
1657            // if (!setMapArea(newMapArea)) {
1658            // /**
1659            // * If setMapArea returns true, the finalImage is updated anyways.
1660            // * This if-case exists to ensure that we repaint a correct image
1661            // * even if the new panning area has been denied.
1662            // */
1663            // updateFinalImage();
1664            // repaint();
1665            // }
1666            //
1667            // if (getCursor() == SwingUtil.PANNING_CURSOR)
1668            // setCursor(SwingUtil.PAN_CURSOR);
1669            // }
1670    
1671                  final double startX = ((x1 * mapWidth) / (double) bounds.width)          /**
1672                                  + mapArea.getMinX();           * Entfernt einen Listener von der Map.
1673                  final double startY = (((bounds.getHeight() - y1) * mapHeight) / (double) bounds.height)           *
1674                                  + mapArea.getMinY();           * @param l
1675                  final double endX = ((x2 * mapWidth) / (double) bounds.width)           *            zu entfernender Listener
1676                                  + mapArea.getMinX();           */
1677                  final double endY = (((bounds.getHeight() - y2) * mapHeight) / (double) bounds.height)          public void removeMapPaneListener(final JMapPaneListener l) {
1678                                  + mapArea.getMinY();                  mapPaneListeners.remove(l);
   
                 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  
   
                         drawRectangle(this.getGraphics());  
                         // make the dragged rectangle (in map coords) the new BBOX  
                         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 Coordinate ll = new Coordinate(left, bottom);  
                         final Coordinate ur = new Coordinate(right, top);  
                         // 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(); }  
 //                       */  
 //              }  
   
                 // xulu.so  
                 // setMapArea(mapArea);  
                 // xulu.eo  
                 repaint();  
1679          }          }
1680    
1681          private boolean isClickable() {          /**
1682                  return clickable;           * Cancels all running renderers and sets the flag to start new ones. <br>
1683             *
1684             * @see #startRenderThreadsTimer
1685             */
1686            private void requestStartRendering() {
1687                    if (bgExecuter != null)
1688                            bgExecuter.cancelTask();
1689    
1690                    localExecuter.cancelTask();
1691    
1692                    mapImageInvalid = true;
1693                    if (paneResized) {
1694                            paneResized = false;
1695                            disposeImages();
1696                    }
1697                    requestStartRendering = true;
1698    
1699          }          }
1700    
1701          private org.geotools.styling.Style setupStyle(final int type, final Color color) {          /**
1702                  final StyleFactory sf = org.geotools.factory.CommonFactoryFinder           * Calculate the affine transforms used to convert between world and pixel
1703                                  .getStyleFactory(null);           * coordinates. The calculations here are very basic and assume a cartesian
1704                  final StyleBuilder sb = new StyleBuilder();           * reference system.
1705             * <p>
1706             * Tne transform is calculated such that {@code envelope} will be centred in
1707             * the display
1708             *
1709             * @param envelope
1710             *            the current map extent (world coordinates)
1711             * @param paintArea
1712             *            the current map pane extent (screen units)
1713             */
1714            private void resetTransforms() {
1715                    // System.out
1716                    // .println("paintArea in resetTeansofrms = " + getVisibleRect());
1717                    if (!isWellDefined())
1718                            return;
1719    
1720                  org.geotools.styling.Style s = sf.createStyle();                  if (mapArea == null)
1721                  s.setTitle("selection");                          return;
1722    
1723                  // TODO parameterise the color                  final ReferencedEnvelope refMapEnv = new ReferencedEnvelope(mapArea,
1724                  final PolygonSymbolizer ps = sb.createPolygonSymbolizer(color);                                  getMapContext().getCoordinateReferenceSystem());
                 ps.setStroke(sb.createStroke(color));  
1725    
1726                  final LineSymbolizer ls = sb.createLineSymbolizer(color);                  worldToScreen = RendererUtilities.worldToScreenTransform(refMapEnv,
1727                  final Graphic h = sb.createGraphic();                                  getVisibleRect());
                 h.setMarks(new Mark[] { sb.createMark("square", color) });  
1728    
1729                  final PointSymbolizer pts = sb.createPointSymbolizer(h);                  try {
1730                            screenToWorld = worldToScreen.createInverse();
1731    
1732                  // Rule r = sb.createRule(new Symbolizer[]{ps,ls,pts});                  } catch (final NoninvertibleTransformException ex) {
1733                  switch (type) {                          LOGGER
1734                  case POLYGON:                                          .error("can't invert worldToScreen to get screenToWorld!",
1735                          s = sb.createStyle(ps);                                                          ex);
1736                    }
1737            }
1738    
1739            public void setBgContext(final MapContext context) {
1740    
1741                          break;                  // Remove the default listener from the old context
1742                    if (this.bgContext != null) {
1743                            this.bgContext.removeMapLayerListListener(bgContextListener);
1744    
1745                            // adding listener to all layers
1746                            for (final MapLayer mapLayer : bgContext.getLayers()) {
1747                                    mapLayer.removeMapLayerListener(bgMapLayerListener);
1748                            }
1749                    }
1750    
1751                  case POINT:                  this.bgContext = context;
                         s = sb.createStyle(pts);  
1752    
1753                          break;                  if (context != null) {
1754                            // setMapArea(bgContext.getAreaOfInterest());
1755    
1756                  case LINE:                          this.bgContext.addMapLayerListListener(bgContextListener);
1757                          s = sb.createStyle(ls);  
1758                            // adding listener to all layers
1759                            for (final MapLayer mapLayer : bgContext.getLayers()) {
1760                                    mapLayer.addMapLayerListener(bgMapLayerListener);
1761                            }
1762                  }                  }
1763    
1764                  return s;                  requestStartRendering();
1765          }          }
1766    
1767            public void setJava2dHints(final RenderingHints java2dHints) {
1768                    this.java2dHints = java2dHints;
1769            }
1770    
1771            public void setLocalContext(final MapContext context) {
1772                    // Remove the default listener from the old context
1773                    if (this.localContext != null) {
1774                            this.localContext.removeMapLayerListListener(localContextListener);
1775    
1776                            // adding listener to all layers
1777                            for (final MapLayer mapLayer : localContext.getLayers()) {
1778                                    mapLayer.removeMapLayerListener(localMapLayerListener);
1779                            }
1780                    }
1781    
1782                    this.localContext = context;
1783    
1784                    if (context != null) {
1785    
1786                            // setMapArea(localContext.getAreaOfInterest());
1787    
1788          public void propertyChange(final PropertyChangeEvent evt) {                          getLocalRenderer().setContext(localContext);
                 final String prop = evt.getPropertyName();  
1789    
1790                  if (prop.equalsIgnoreCase("crs")) {                          this.localContext.addMapLayerListListener(localContextListener);
1791                          context.setAreaOfInterest(context.getAreaOfInterest(),  
1792                                          (CoordinateReferenceSystem) evt.getNewValue());                          // adding listener to all layers
1793                            for (final MapLayer mapLayer : localContext.getLayers()) {
1794                                    mapLayer.addMapLayerListener(localMapLayerListener);
1795                            }
1796                  }                  }
1797    
1798                    requestStartRendering();
1799    
1800          }          }
1801    
1802          public boolean isReset() {          public void setBorder(final Border b) {
1803                  return reset;                  super.setBorder(b);
1804          }          }
1805    
1806          public void setReset(final boolean reset) {          /**
1807                  this.reset = reset;           * Triggers to repaint (fast) and re-render (slow) the JMapPane.
1808             */
1809            public void refresh() {
1810                    mapImageInvalid = true;
1811                    repaint();
1812          }          }
1813    
1814          public void layerAdded(final MapLayerListEvent event) {          // /**
1815                  changed = true;          // * Triggers to use new {@link GTRenderer} and refresh the map. Should be
1816            // * called after {@link Style}s have been changed because GTRenderer is
1817            // * otherwise not working well.
1818            // */
1819            // public void refreshRenderers() {
1820            // localRenderer = GTUtil.createGTRenderer();
1821            // setLocalContext(getMapContext());
1822            // mapImageInvalid = true;
1823            // repaint();
1824            // }
1825    
1826                  if (context.getLayers().length == 1) { // the first one          /**
1827             * Set the new map area.
1828             *
1829             * @param newMapArea
1830             * @return <code>true</code> if the mapArea has been changed and a repaint
1831             *         has been triggered.
1832             */
1833            public boolean setMapArea(final Envelope newMapArea) {
1834                    if (newMapArea == null)
1835                            return false;
1836                    if (getMapContext().getCoordinateReferenceSystem() == null)
1837                            return false;
1838                    return setMapArea(new ReferencedEnvelope(newMapArea, getMapContext()
1839                                    .getCoordinateReferenceSystem()));
1840            }
1841    
1842                          try {          /**
1843                                  // xulu.sc           * Set the new map area.
1844                                  // mapArea = context.getLayerBounds();           *
1845                                  mapArea = context.getAreaOfInterest();           * @param newMapArea
1846                                  if (mapArea == null)           * @return <code>true</code> if the mapArea has been changed and a repaint
1847                                          mapArea = context.getLayerBounds();           *         has been triggered.
1848                                  // xulu.ec           */
1849                          } catch (final IOException e) {          public boolean setMapArea(final ReferencedEnvelope newMapArea) {
1850                                  // TODO Auto-generated catch block  
1851                                  e.printStackTrace();                  if (newMapArea == null
1852                                    || bestAllowedMapArea(newMapArea).equals(mapArea)) {
1853                            // No change.. no need to repaint
1854                            return false;
1855                    }
1856    
1857                    // Testing, whether NaN or Infinity are used in the newMapArea
1858                    if (newMapArea.isNull() || Double.isInfinite(newMapArea.getMaxX())
1859                                    || Double.isInfinite(newMapArea.getMaxY())
1860                                    || Double.isInfinite(newMapArea.getMinX())
1861                                    || Double.isInfinite(newMapArea.getMinY())) {
1862                            // No change.. ugly new values
1863                            LOGGER.warn("setMapArea has been called with newArea = "
1864                                            + newMapArea);
1865                            return false;
1866                    }
1867    
1868                    final Envelope candNew = bestAllowedMapArea(newMapArea);
1869    
1870                    // Testing, whether the difference if just minimal
1871                    if (mapArea != null) {
1872                            final double tolX = mapArea.getWidth() / 1000.;
1873                            final double tolY = mapArea.getHeight() / 1000.;
1874                            if ((candNew.getMinX() - tolX < mapArea.getMinX())
1875                                            && (mapArea.getMinX() < candNew.getMinX() + tolX)
1876                                            && (candNew.getMaxX() - tolX < mapArea.getMaxX())
1877                                            && (mapArea.getMaxX() < candNew.getMaxX() + tolX)
1878    
1879                                            && (candNew.getMinY() - tolY < mapArea.getMinY())
1880                                            && (mapArea.getMinY() < candNew.getMinY() + tolY)
1881                                            && (candNew.getMaxY() - tolY < mapArea.getMaxY())
1882                                            && (mapArea.getMaxY() < candNew.getMaxY() + tolY)
1883    
1884                            ) {
1885                                    // The two mapAreas only differ my 1/1000th.. ignore
1886    
1887                                    return false;
1888                          }                          }
1889                    }
1890    
1891                    // New map are is accepted:
1892                    oldMapArea = mapArea;
1893                    mapArea = candNew;
1894                    resetTransforms();
1895    
1896                          reset = true;                  if (localContext != null) {
1897                            localContext.setAreaOfInterest(mapArea, localContext
1898                                            .getCoordinateReferenceSystem());
1899                    }
1900                    if (bgContext != null) {
1901                            bgContext.setAreaOfInterest(mapArea, localContext
1902                                            .getCoordinateReferenceSystem());
1903                  }                  }
1904    
1905                  repaint();                  mapAreaChanged = true;
         }  
1906    
1907          public void layerRemoved(final MapLayerListEvent event) {                  repaint(200); // Do not remove it!
1908                  changed = true;  
1909                  repaint();                  requestStartRendering();
1910    
1911                    return true;
1912          }          }
1913    
1914          public void layerChanged(final MapLayerListEvent event) {          /**
1915                  changed = true;           * Set the background color of the map.
1916                  // System.out.println("layer changed - repaint");           *
1917                  repaint();           * @param if <code>null</code>, white is used.
1918             */
1919            public void setMapBackgroundColor(final Color bgColor) {
1920                    this.mapBackgroundColor = bgColor;
1921          }          }
1922    
1923          public void layerMoved(final MapLayerListEvent event) {          /**
1924                  changed = true;           * Set the BufferedImage to use as a flaoting icon in the lower right corner
1925                  repaint();           *
1926             * @param mapImageIcon
1927             *            <code>null</code> is allowed and deactivates this icon.
1928             */
1929            public void setMapImage(final BufferedImage mapImage) {
1930                    this.mapImage = mapImage;
1931          }          }
1932    
1933          protected void drawRectangle(final Graphics graphics) {          /**
1934                  // undraw last box/draw new box           * Sets whether a layer is regarded or ignored on {@link #SELECT_TOP},
1935                  final int left = Math.min(startX, lastX);           * {@link #SELECT_ALL} and {@link #SELECT_ONE_FROM_TOP} actions.
1936                  final int right = Math.max(startX, lastX);           *
1937                  final int top = Math.max(startY, lastY);           * @param layer
1938                  final int bottom = Math.min(startY, lastY);           *            a layer
1939                  final int width = right - left;           * @param selectable
1940                  final int height = top - bottom;           *            if {@code false} the layer is ignored during the upper
1941                  // System.out.println("drawing rect("+left+","+bottom+","+ width+","+           *            mentioned actions. If <code>null</code>, the default (true)
1942                  // height+")");           *            will be used.
1943                  graphics.drawRect(left, bottom, width, height);           */
1944            public void setMapLayerSelectable(final MapLayer layer,
1945                            final Boolean selectable) {
1946                    if (selectable == null)
1947                            mapLayerSelectable.remove(layer);
1948                    else
1949                            mapLayerSelectable.put(layer, selectable);
1950          }          }
1951    
1952          /**          /**
1953           * 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
1954           * or pan the map.           * anything outside of this extend.
1955           *           *
1956           * @param clickable           * @param maxExtend
1957             *            <code>null</code> to not have this restriction.
1958           */           */
1959          public void setClickable(final boolean clickable) {          public void setMaxExtend(final Envelope maxExtend) {
1960                  this.clickable = clickable;                  this.maxExtend = maxExtend;
1961          }          }
1962    
1963          public void mouseMoved(final MouseEvent e) {          /**
1964             * Set the maximum allowed zoom scale. This is the smaller number value of
1965             * the two. If <code>null</code> is passed, Double.MINVALUE are used which
1966             * mean there is no restriction.
1967             *
1968             * @author <a href="mailto:[email protected]">Stefan Alfons
1969             *         Kr&uuml;ger</a>
1970             */
1971            public void setMaxZoomScale(final Double maxZoomScale) {
1972                    this.maxZoomScale = maxZoomScale == null ? Double.MIN_VALUE
1973                                    : maxZoomScale;
1974          }          }
1975    
1976            // /** Stored the time used for the last real rendering in ms. **/
1977            private long lastRenderingDuration = 1000;
1978            private XMapPaneTool tool = null;
1979    
1980            private Timer blinkTimer;
1981    
         // xulu.sn  
1982          /**          /**
1983           * Korrigiert den {@link Envelope} aka {@code mapArea} auf die beste           * Set the minimum (nearest) allowed zoom scale. This is the bigger number
1984           * erlaubte Flaeche damit die Massstabsbeschaenkungen noch eingehalten           * value of the two. If <code>null</code> is passed, Double.MAXVALUE are
1985           * werden, FALLS der uebergeben Envelope nicht schon gueltig sein sollte.<br/>           * used which mean there is no restriction.
1986           * Since 21. April 09: Before thecalculation starts, the aspect ratio is           *
          * corrected. This change implies, that setMapArea() will most of the time  
          * not allow setting to a wrong aspectRatio.  
1987           *           *
1988           * @author <a href="mailto:[email protected]">Stefan Alfons           * @author <a href="mailto:[email protected]">Stefan Alfons
1989           *         Kr&uuml;ger</a>           *         Kr&uuml;ger</a>
1990           */           */
1991          public Envelope bestAllowedMapArea(Envelope env) {          public void setMinZoomScale(final Double minZoomScale) {
1992                  if (getWidth() == 0)                  this.minZoomScale = minZoomScale == null ? Double.MAX_VALUE
1993                          return env;                                  : minZoomScale;
1994                  if (env == null)          }
1995                          return env;  
1996            /**
1997             * If <code>true</code>, allow the {@link XMapPane} to process #repaint()
1998             * requests. Otherwise the map will not paint anything and not start any
1999             * rendering {@link Thread}s.
2000             */
2001            public void setPainting(final boolean b) {
2002                    acceptsRepaintCalls = b;
2003                    if (acceptsRepaintCalls == true)
2004                            repaint();
2005            }
2006    
2007            private void setRendererHints(final Map<Object, Object> rendererHints) {
2008                    if (rendererHints != null)
2009                            this.rendererHints = rendererHints;
2010            }
2011    
2012            // @Deprecated
2013            // public void setState(final int state) {
2014            // this.state = state;
2015            //
2016            // // throw new RuntimeException("Old concept.. migrate to new concept!");
2017            //
2018            // // xMapPaneMouseListener.setEnabled((state == ZOOM_IN
2019            // // || state == ZOOM_OUT || state == PAN));
2020            //
2021            // // Je nach Aktion den Cursor umsetzen
2022            // updateCursor();
2023            // }
2024    
2025            public void configureMouse(MouseInputType type, XMapPaneAction action) {
2026                    xMapPaneMouseListener.actions.put(type, action);
2027            }
2028    
2029            /**
2030             * Configure the {@link XMapPaneTool} that active on the map. Passing
2031             * <code>null</code> will set the NO_ACTION tool.
2032             */
2033            public void setTool(XMapPaneTool tool) {
2034                    if (tool == null)
2035                            tool = XMapPaneTool.NO_ACTION;
2036                    this.tool = tool;
2037                    xMapPaneMouseListener.configure(tool);
2038                    setCursor(tool.getCursor());
2039            }
2040    
2041            // /**
2042            // * Standardmaessig wird der Cursor automatisch je nach MapPane-Aktion
2043            // (Zoom,
2044            // * Auswahl, ...) gesetzt. Mit dieser Methode kann ein statischer Cursor
2045            // * gesetzt werden, der unabhaengig von der aktuellen MapPanes-Aktion
2046            // * beibehalten wird. Um diesen statischen Cursor wieder zu entfernen, kann
2047            // * {@code null} als Parameter uebergeben werden
2048            // *
2049            // * @param cursor
2050            // * Cursor
2051            // */
2052            // public void setStaticCursor(final Cursor cursor) {
2053            // this.staticCursor = cursor;
2054            // if (cursor != null)
2055            // super.setCursor(cursor);
2056            // }
2057    
2058            /**
2059             * Starts rendering on one or two threads
2060             */
2061            private void startRendering() {
2062    
2063                    if (!isWellDefined() || !acceptsRepaintCalls) {
2064                            // if we are not ready to start rendering, try it again the next
2065                            // time the timer is chacking the flag.
2066                            requestStartRendering = true;
2067                            return;
2068                    }
2069    
2070                    if (bgExecuter != null) {
2071                            // Stop all renderers
2072                            bgExecuter.cancelTask();
2073                    }
2074    
2075                    localExecuter.cancelTask();
2076    
2077                    final Rectangle curPaintArea = getVisibleRect();
2078    
2079                  /**                  /**
2080                   * Correct the aspect Ratio before we check the rest. Otherwise we might                   * We have to set new renderer
                  * easily fail.  
2081                   */                   */
                 env = fixAspectRatio(this.getBounds(), env);  
2082    
2083                  final double scale = env.getWidth() / getWidth();                  if (getBgContext() != null) {
2084                  final double centerX = env.getMinX() + env.getWidth() / 2.;                          bgRenderer.setJava2DHints(getJava2dHints());
2085                  final double centerY = env.getMinY() + env.getHeight() / 2.;                          bgRenderer.setRendererHints(getRendererHints());
2086                  double newWidth2;  
2087                  double newHeight2;                          // bgExecuter = new RenderingExecutor();
2088                  if (scale < getMaxZoomScale()) {                          // LOGGER.debug("starting bg renderer:");
2089                          // ****************************************************************************                          // // /* System.out.println("rendering"); */
2090                          // Wir zoomen weiter rein als erlaubt => Anpassen des envelope                          // final GTRenderer createGTRenderer = GTUtil.createGTRenderer(
2091                          // ****************************************************************************                          // bgContext, getRendererHints());
2092                          newWidth2 = getMaxZoomScale() * getWidth() / 2.;                          // createGTRenderer.setJava2DHints(getJava2dHints());
2093                          newHeight2 = getMaxZoomScale() * getHeight() / 2.;                          // bgExecuter.submit(getBgContext().getAreaOfInterest(),
2094                  } else if (scale > getMinZoomScale()) {                          // curPaintArea,
2095                          // ****************************************************************************                          // (Graphics2D) getBgImage().getGraphics(), createGTRenderer);
2096                          // Wir zoomen weiter raus als erlaubt => Anpassen des envelope                  }
2097                          // ****************************************************************************  
2098                          newWidth2 = getMinZoomScale() * getWidth() / 2.;                  if (getMapContext() != null) {
2099                          newHeight2 = getMinZoomScale() * getHeight() / 2.;                          // localExecuter = new RenderingExecutor(this, 150l);
2100                            // LOGGER.debug("starting local renderer:");
2101    
2102                            getLocalRenderer().setJava2DHints(getJava2dHints());
2103                            getLocalRenderer().setRendererHints(getRendererHints());
2104    
2105                            final boolean submitted = localExecuter.submit(getMapArea(),
2106                                            curPaintArea, (Graphics2D) getLocalImage().getGraphics(),
2107                                            getLocalRenderer());
2108                            if (submitted)
2109                                    repaintTimer.restart();
2110                            else
2111                                    requestStartRendering = true; // Try to start rendering
2112                            // again in
2113                            // a moment
2114                    }
2115    
2116                    updateCursor();
2117            }
2118    
2119            private RenderingHints getJava2dHints() {
2120                    return java2dHints;
2121            }
2122    
2123            /**
2124             * Transformiert einen Geo-Koordinaten-Bereich in Fenster-Koordinaten.
2125             *
2126             * @param ox
2127             *            X-Koordinate der VON-Position
2128             * @param oy
2129             *            Y-Koordinate der VON-Position
2130             * @param px
2131             *            X-Koordinate der BIS-Position
2132             * @param py
2133             *            Y-Koordinate der BIS-Position
2134             */
2135            public Envelope tranformGeoToWindow(final double ox, final double oy,
2136                            final double px, final double py) {
2137                    final AffineTransform at = getWorldToScreenTransform();
2138                    Point2D geoO;
2139                    // try {
2140                    geoO = at.transform(new Point2D.Double(ox, oy), null);
2141                    final Point2D geoP = at.transform(new Point2D.Double(px, py), null);
2142                    return new Envelope(geoO.getX(), geoP.getX(), geoO.getY(), geoP.getY());
2143                    // } catch (final NoninvertibleTransformException e) {
2144                    // LOGGER.error(e);
2145                    // return new Envelope(ox, oy, px, py);
2146                    // }
2147            }
2148    
2149            /**
2150             * Transformiert einen Geo-Koordinate in eine Fenster-Koordinaten.
2151             *
2152             * @param x
2153             *            X-Koordinate der VON-Position
2154             * @param y
2155             *            Y-Koordinate der VON-Position
2156             */
2157            public Point2D tranformGeoToWindow(final double x, final double y) {
2158                    return getWorldToScreenTransform().transform(new Point2D.Double(x, y),
2159                                    null);
2160            }
2161    
2162            /**
2163             * Transformiert einen Fenster-Koordinaten-Bereich in Geo-Koordinaten.
2164             *
2165             * @param ox
2166             *            X-Koordinate der VON-Position
2167             * @param oy
2168             *            Y-Koordinate der VON-Position
2169             * @param px
2170             *            X-Koordinate der BIS-Position
2171             * @param py
2172             *            Y-Koordinate der BIS-Position
2173             */
2174            public Envelope tranformWindowToGeo(final int ox, final int oy,
2175                            final int px, final int py) {
2176                    final AffineTransform at = getScreenToWorld();
2177                    final Point2D geoO = at.transform(new Point2D.Double(ox, oy), null);
2178                    final Point2D geoP = at.transform(new Point2D.Double(px, py), null);
2179    
2180                    // Mmmmm... don't really understand why its x,x,y,y
2181                    // return new Envelope(geoO.getX(), geoP.getX(), geoO.getY(),
2182                    // geoP.getY());
2183                    return new Envelope(new Coordinate(geoO.getX(), geoO.getY()),
2184                                    new Coordinate(geoP.getX(), geoP.getY()));
2185            }
2186    
2187            /**
2188             * Will update the cursor. If all rendering is finished also stops the
2189             * {@link #repaintTimer}
2190             */
2191            public void updateCursor() {
2192    
2193                    // if the renderers have stopped, also stop the timer that is updating
2194                    // the final image
2195                    if (bgExecuter != null && bgExecuter.isRunning()
2196                                    || localExecuter.isRunning()) {
2197                            setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
2198                            return;
2199                  } else {                  } else {
2200                          // ****************************************************************************                          // Allow one last rendering
2201                          // Die mapArea / der Envelope ist ist gueltig! Keine Aenderungen                          if (repaintTimer.isRunning()) {
2202                          // ****************************************************************************                                  // System.out.println("one last rendering....");
2203                          return env;                                  repaintTimer.stop();
2204                                    updateFinalImage();
2205                                    repaint();
2206                            }
2207                    }
2208                    //              
2209                    // //
2210                    // // wenn manueller Cursor gesetzt ist, dann diesen verwenden
2211                    // (unabhaengig
2212                    // // von der aktuellen Aktion
2213                    // if (this.staticCursor != null) {
2214                    // setCursor(staticCursor);
2215                    // return;
2216                    // }
2217                    //              
2218                    if (getCursor() == SwingUtil.PANNING_CURSOR) {
2219                            // This cursor will reset itself
2220                            return;
2221                  }                  }
2222    
2223                  final Coordinate ll = new Coordinate(centerX - newWidth2, centerY                  setCursor(tool.getCursor());
                                 - newHeight2);  
                 final Coordinate ur = new Coordinate(centerX + newWidth2, centerY  
                                 + newHeight2);  
2224    
2225                  return new Envelope(ll, ur);                  //
2226                    // // Set the cursor depending on what tool is in use...
2227                    // switch (state) {
2228                    // case SELECT_TOP:
2229                    // case SELECT_ONE_FROM_TOP:
2230                    // case SELECT_ALL:
2231                    // setCursor(SwingUtil.CROSSHAIR_CURSOR);
2232                    // break;
2233                    // case ZOOM_IN:
2234                    // setCursor(SwingUtil.ZOOMIN_CURSOR);
2235                    // break;
2236                    // case ZOOM_OUT:
2237                    // setCursor(SwingUtil.ZOOMOUT_CURSOR);
2238                    // break;
2239                    // case PAN:
2240                    // setCursor(SwingUtil.PAN_CURSOR);
2241                    // break;
2242                    // default:
2243                    // setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
2244                    // break;
2245                    // }
2246          }          }
2247    
2248          /**          /**
2249           * Retuns the minimum allowed zoom scale. This is the bigger number value of           * The renderers are all rendering into their own {@link Image}s. This
2250           * the two. Defaults to {@link Double}.MAX_VALUE           * method combines all images to one {@link #finalImage}. The
2251             * {@link #repaintTimer} is calling this method regularely to update the
2252             * {@link #finalImage} even if the renderers are still working.
2253             */
2254            synchronized protected Image updateFinalImage() {
2255    
2256                    // Render the two map images first, into the preFinalImage
2257                    if (bgExecuter != null) {
2258                            final Graphics2D preFinalG = (Graphics2D) getPreFinalImage()
2259                                            .getGraphics();
2260                            preFinalG.setBackground(getMapBackgroundColor());
2261    
2262                            preFinalG.drawImage(getBgImage(), 0, 0, getMapBackgroundColor(),
2263                                            null);
2264    
2265                            // // Draw the local layers image
2266                            preFinalG.drawImage(getLocalImage(), 0, 0, null);
2267                            preFinalG.dispose();
2268    
2269                    } else {
2270                            preFinalImage = getLocalImage();
2271                    }
2272    
2273                    final Graphics2D finalG = getFinalImage().createGraphics();
2274                    finalG.setBackground(getMapBackgroundColor());
2275                    finalG.drawImage(getPreFinalImage(), getImageOrigin().x,
2276                                    getImageOrigin().y, getMapBackgroundColor(), null);
2277    
2278                    // When panning, we have to clear the area around the image
2279                    final Rectangle painedArea = new Rectangle(getImageOrigin().x,
2280                                    getImageOrigin().y, getFinalImage().getWidth(), getFinalImage()
2281                                                    .getHeight());
2282                    SwingUtil.clearAround(finalG, painedArea, getVisibleRect(),
2283                                    getMapBackgroundColor());
2284    
2285                    addGadgets(finalG, false);
2286    
2287                    finalG.dispose();
2288    
2289                    return finalImage;
2290            }
2291    
2292            /**
2293             * Paints some optional stuff into the given {@link Graphics2D}. Usually
2294             * called as the last layer when {@link #updateFinalImage()}
2295           *           *
2296           * @author <a href="mailto:[email protected]">Stefan Alfons           * @param forceWait
2297           *         Kr&uuml;ger</a>           *            if <code>true</code>, a Wait-message will be painted even
2298             *            though the rendering threads may not yet have started. If
2299             *            <code>false</code>, it will only depend on
2300             *            {@link #localExecuter.isRunning} and #bgExecuter.isRunning
2301           */           */
2302          public Double getMinZoomScale() {          private void addGadgets(final Graphics2D graphics, final boolean forceWait) {
2303                  return minZoomScale;  
2304                    // Paint a logo to the bottom right if available
2305                    if (mapImage != null) {
2306                            final Rectangle visibleRect = getVisibleRect();
2307                            graphics.drawImage(mapImage, visibleRect.width
2308                                            - mapImage.getWidth() - 10, getVisibleRect().height
2309                                            - mapImage.getHeight() - 10, null);
2310                    }
2311    
2312                    int y = 17;
2313    
2314                    // If the rendering process is still running, indicate this is the image
2315                    if (forceWait || bgExecuter != null && bgExecuter.isRunning()
2316                                    || localExecuter.isRunning()) {
2317    
2318                            y += 8;
2319    
2320                            final Color c = graphics.getColor();
2321                            graphics.setFont(waitFont);
2322    
2323                            graphics.setColor(getMapBackgroundColor());
2324                            graphics.drawString(waitMsg, 5, y);
2325                            graphics.setColor(getMapBackgroundColor());
2326                            graphics.drawString(waitMsg, 7, y + 2);
2327                            graphics.setColor(Color.BLACK);
2328                            graphics.drawString(waitMsg, 6, y + 1);
2329    
2330                            graphics.setColor(c);
2331    
2332                            y += 21;
2333                    }
2334    
2335                    if (!renderingErrors.isEmpty() && isShowExceptions()) {
2336    
2337                            final Color c = graphics.getColor();
2338                            graphics.setFont(errorFont);
2339    
2340                            for (final Exception ex : renderingErrors) {
2341    
2342                                    String errStr = ex.getLocalizedMessage();
2343    
2344                                    if (errStr == null)
2345                                            errStr = ex.getMessage();
2346                                    if (errStr == null)
2347                                            errStr = "unknown error: " + ex.getClass().getSimpleName();
2348    
2349                                    graphics.setColor(getMapBackgroundColor());
2350                                    graphics.drawString(errStr, 5, y);
2351                                    graphics.setColor(Color.RED);
2352                                    graphics.drawString(errStr, 6, y + 1);
2353    
2354                                    y += 19;
2355                            }
2356    
2357                            graphics.setColor(c);
2358                    }
2359    
2360          }          }
2361    
2362          /**          /**
2363           * Retuns the maximum allowed zoom scale. This is the smaller number value           * Sets the {@link #mapArea} to best possibly present the given features. If
2364           * of the two. Defaults to {@link Double}.MIN_VALUE           * only one single point is given, the window is moved over the point.
2365             *
2366             * @param features
2367             *            if <code>null</code> or size==0, the function doesn nothing.
2368             */
2369            public void zoomTo(
2370                            final FeatureCollection<SimpleFeatureType, SimpleFeature> features) {
2371    
2372                    // if (!isWellDefined()) return;
2373    
2374                    final CoordinateReferenceSystem mapCRS = getMapContext()
2375                                    .getCoordinateReferenceSystem();
2376                    final CoordinateReferenceSystem fCRS = features.getSchema()
2377                                    .getCoordinateReferenceSystem();
2378    
2379                    ReferencedEnvelope _mapArea;
2380                    if (mapArea == null)
2381                            _mapArea = features.getBounds();
2382                    else
2383                            _mapArea = getMapArea();
2384                    double width = _mapArea.getWidth();
2385                    double height = _mapArea.getHeight();
2386                    final double ratio = height / width;
2387    
2388                    if (features == null || features.size() == 0) {
2389                            // feature count == 0 Zoom to the full extend
2390                            return;
2391                    } else if (features.size() == 1) {
2392    
2393                            // feature count == 1 Just move the window to the point and zoom 'a
2394                            // bit'
2395                            final SimpleFeature singleFeature = features.iterator().next();
2396    
2397                            if (((Geometry) singleFeature.getDefaultGeometry())
2398                                            .getCoordinates().length > 1) {
2399                                    // System.out.println("Zoomed to only pne poylgon");
2400                                    // Poly
2401                                    // TODO max width vs. height
2402                                    width = features.getBounds().getWidth() * 3;
2403                                    height = ratio * width;
2404                            } else {
2405                                    // System.out.println("Zoomed in a bit becasue only one point");
2406                                    // width *= .9;
2407                                    // height *= .9;
2408                            }
2409    
2410                            Coordinate centre = features.getBounds().centre();
2411                            if (!mapCRS.equals(fCRS)) {
2412                                    // only to calculations if the CRS differ
2413                                    try {
2414                                            MathTransform fToMap;
2415                                            fToMap = CRS.findMathTransform(fCRS, mapCRS);
2416                                            // centre is transformed to the mapCRS
2417                                            centre = JTS.transform(centre, null, fToMap);
2418                                    } catch (final FactoryException e) {
2419                                            LOGGER.error("Looking for a Math transform", e);
2420                                    } catch (final TransformException e) {
2421                                            LOGGER.error("Looking for a Math transform", e);
2422                                    }
2423                            }
2424    
2425                            final Coordinate newLeftBottom = new Coordinate(centre.x - width
2426                                            / 2., centre.y - height / 2.);
2427                            final Coordinate newTopRight = new Coordinate(
2428                                            centre.x + width / 2., centre.y + height / 2.);
2429    
2430                            final Envelope newMapArea = new Envelope(newLeftBottom, newTopRight);
2431    
2432                            setMapArea(newMapArea);
2433    
2434                    } else {
2435                            final ReferencedEnvelope fBounds = features.getBounds();
2436    
2437                            ReferencedEnvelope bounds;
2438                            if (!mapCRS.equals(fCRS)) {
2439                                    bounds = JTSUtil.transformEnvelope(fBounds, mapCRS);
2440                            } else {
2441                                    bounds = fBounds;
2442                            }
2443                            // BB umrechnen von Layer-CRS in Map-CRS
2444    
2445                            // Expand a bit
2446                            addDefaultMargin(bounds);
2447    
2448                            setMapArea(bounds);
2449                    }
2450            }
2451    
2452            private ReferencedEnvelope addDefaultMargin(ReferencedEnvelope bounds) {
2453                    return JTSUtil.expandEnvelope(bounds, Math.max(0,
2454                                    defaultMaxMapExtendMode));
2455            }
2456    
2457            private Envelope addDefaultMargin(Envelope bounds) {
2458                    return JTSUtil.expandEnvelope(bounds, Math.max(0,
2459                                    defaultMaxMapExtendMode));
2460            }
2461    
2462            /**
2463             * Zooms towards a point.
2464             *
2465             * @param center
2466             *            position in window coordinates
2467             * @param zoomFactor
2468             *            > 1 for zoom in, < 1 for zoom out. Default is 1.33
2469             */
2470            public void zoomTo(final Point center) {
2471                    zoomTo(center, null);
2472            }
2473    
2474            /**
2475             * Zooms towards a point.
2476             *
2477             * @param center
2478             *            position in window coordinates
2479             * @param zoomFaktor
2480             *            > 1 for zoom out, < 1 for zoom in. Default is .5
2481             */
2482            public void zoomTo(Point center, Double zoomFaktor) {
2483                    if (zoomFaktor == null || zoomFaktor == 0.)
2484                            zoomFaktor = .5;
2485    
2486                    final Point2D gcenter = getScreenToWorld().transform(center, null);
2487                    center = null;
2488    
2489                    if (Double.isNaN(gcenter.getX()) || Double.isNaN(gcenter.getY())
2490                                    || Double.isInfinite(gcenter.getX())
2491                                    || Double.isInfinite(gcenter.getY())
2492    
2493                    ) {
2494                            // Not inside valid CRS area! cancel
2495                            return;
2496                    }
2497    
2498                    final Envelope mapArea = getMapArea();
2499    
2500                    final Envelope newMapArea = new Envelope(mapArea);
2501                    newMapArea.expandBy((mapArea.getWidth() * zoomFaktor - mapArea
2502                                    .getWidth()) / 2., (mapArea.getHeight() * zoomFaktor - mapArea
2503                                    .getHeight()) / 2.);
2504    
2505                    // // Move the newMapArea above the new center if we zoom in:
2506                    newMapArea.translate(gcenter.getX() - mapArea.centre().x, gcenter
2507                                    .getY()
2508                                    - mapArea.centre().y);
2509    
2510                    setMapArea(newMapArea);
2511            }
2512    
2513            /**
2514             * Shall non-fatal rendering exceptions be reported in the mappane or be
2515             * dropped quitely.
2516             */
2517            public void setShowExceptions(final boolean showExceptions) {
2518                    this.showExceptions = showExceptions;
2519            }
2520    
2521            /**
2522             * Shall exceptions be reported in the mappane?
2523             */
2524            public boolean isShowExceptions() {
2525                    return showExceptions;
2526            }
2527    
2528            public GTRenderer getLocalRenderer() {
2529                    return localRenderer;
2530            }
2531    
2532            /**
2533             * Setzt den Kartenausschnitt auf die Ausdehnung eines bestimmten Layers.
2534             * Macht nichts, wenn {@code null} uebergeben wird.
2535             *
2536             * <br>
2537             *
2538             * @param layer
2539             *            ein Layer
2540             */
2541            public void zoomToLayer(MapLayer layer) {
2542                    if (layer == null)
2543                            return;
2544                    try {
2545    
2546                            // BB umrechnen von Layer-CRS in Map-CRS
2547                            final CoordinateReferenceSystem targetCRS = getMapContext()
2548                                            .getCoordinateReferenceSystem();
2549                            final CoordinateReferenceSystem sourceCRS = layer
2550                                            .getFeatureSource().getSchema()
2551                                            .getCoordinateReferenceSystem();
2552    
2553                            Envelope mapAreaNew;
2554                            if (!CRS.equalsIgnoreMetadata(sourceCRS, targetCRS)) {
2555                                    mapAreaNew = JTSUtil.transformEnvelope(layer.getFeatureSource()
2556                                                    .getBounds(), sourceCRS, targetCRS);
2557                            } else {
2558                                    try {
2559                                            mapAreaNew = layer.getFeatureSource().getBounds();
2560                                    } catch (java.lang.IllegalArgumentException e) {
2561                                            LOGGER.error("Can't calc layers bounds...", e);
2562                                            mapAreaNew = null;
2563    
2564                                            /**
2565                                             *
2566                                             23.10.2009 11:20:50
2567                                             * org.geotools.data.shapefile.shp.PolygonHandler read
2568                                             * WARNUNG: only one hole in this polygon record ERROR
2569                                             * JMapPane zoomToLayer Zoom to layer did not terminate
2570                                             * correctly java.lang.IllegalArgumentException: Points of
2571                                             * LinearRing do not form a closed linestring at
2572                                             * com.vividsolutions
2573                                             * .jts.geom.LinearRing.validateConstruction
2574                                             * (LinearRing.java:105) at
2575                                             * com.vividsolutions.jts.geom.LinearRing
2576                                             * .<init>(LinearRing.java:100) at
2577                                             * com.vividsolutions.jts.geom
2578                                             * .GeometryFactory.createLinearRing
2579                                             * (GeometryFactory.java:339) at
2580                                             * org.geotools.data.shapefile.
2581                                             * shp.PolygonHandler.read(PolygonHandler.java:188) at
2582                                             * org.geotools
2583                                             * .data.shapefile.shp.ShapefileReader$Record.shape
2584                                             * (ShapefileReader.java:106) at
2585                                             * org.geotools.data.shapefile.
2586                                             * ShapefileAttributeReader.next(
2587                                             * ShapefileAttributeReader.java:157) at
2588                                             * org.geotools.data.shapefile
2589                                             * .indexed.IndexedShapefileAttributeReader
2590                                             * .next(IndexedShapefileAttributeReader.java:122) at
2591                                             * org.geotools
2592                                             * .data.FIDFeatureReader.next(FIDFeatureReader.java:96) at
2593                                             * org.geotools.data.FIDFeatureReader.next(FIDFeatureReader.
2594                                             * java:55) at org.geotools.data.MaxFeatureReader.next(
2595                                             * MaxFeatureReader.java:61) at
2596                                             * org.geotools.data.MaxFeatureReader
2597                                             * .next(MaxFeatureReader.java:61)
2598                                             **/
2599                                    }
2600                            }
2601    
2602                            // Kartenbereich um 10% vergroessern, damit z.B. auch ein
2603                            // Punkt-Layer,
2604                            // welches nur aus 2 Punnkten besteht, sichtbar ist (Punkte liegen
2605                            // sonst
2606                            // genau auf dem Rand der angezeigten Flaeche)
2607    
2608                            if (mapAreaNew != null) {
2609    
2610                                    mapAreaNew = addDefaultMargin(mapAreaNew);
2611                                    setMapArea(mapAreaNew);
2612                            } else {
2613                                    LOGGER
2614                                                    .warn("Couldn't transformEnvelope when zooming to the layer");
2615                            }
2616                    } catch (Exception err) {
2617                            LOGGER.error("Zoom to layer did not terminate correctly", err);
2618                    }
2619            }
2620    
2621            /**
2622             * Zooms the {@link SelectableXMapPane} to the {@link Envelope} of a layer.
2623             *
2624             * <br>
2625             * A refresh of the map is not done automatically
2626             *
2627             * @param index
2628             *            Index of the {@link MapLayer} in the {@link MapContext} (from
2629             *            back to top)
2630           *           *
2631           * @author <a href="mailto:[email protected]">Stefan Alfons           * @author <a href="mailto:[email protected]">Stefan Alfons
2632           *         Kr&uuml;ger</a>           *         Kr&uuml;ger</a>
2633           */           */
2634          public Double getMaxZoomScale() {          public void zoomToLayer(int index) {
2635                  return maxZoomScale;                  final MapContext context = getMapContext();
2636                    if (context != null)
2637                            zoomToLayer(context.getLayer(index));
2638          }          }
2639    
2640          /**          /**
2641           * Set the maximum allowed zoom scale. This is the smaller number value of           * Zooms the {@link SelectableXMapPane} to the {@link Envelope} of the
2642           * the two.           * selected layer. The layer is selected by the idx, counting from front to
2643             * back, like humans would expect in a {@link JList}
2644             *
2645             * <br>
2646             * A refresh of the map is not done automatically
2647             *
2648             *
2649             *
2650             * @param index
2651             *            Reverse index of the {@link MapLayer} in the
2652             *            {@link MapContext}
2653           *           *
2654           * @author <a href="mailto:[email protected]">Stefan Alfons           * @author <a href="mailto:[email protected]">Stefan Alfons
2655           *         Kr&uuml;ger</a>           *         Kr&uuml;ger</a>
2656           */           */
2657          public void setMaxZoomScale(final Double maxZoomScale) {          public void zoomToLayerIdxReverse(int index) {
2658                  // System.out.println("setting max scale to "+maxZoomScale);                  zoomToLayer(getMapContext().getLayerCount() - 1 - index);
                 this.maxZoomScale = maxZoomScale;  
2659          }          }
2660    
2661          /**          /**
2662           * Set the minimum (nearest) allowed zoom scale. This is the bigger number           * Aktiviert oder deaktiviert das AntiAliasing for diese
2663           * value of the two.           * {@link SelectableXMapPane}. AntiALiasing ist besonders fuer
2664             * Textbeschriftung sehr schoen, verbraucht aber auch mehr Performance.
2665           *           *
2666           * @author <a href="mailto:[email protected]">Stefan Alfons           * @author <a href="mailto:[email protected]">Stefan Alfons
2667           *         Kr&uuml;ger</a>           *         Kr&uuml;ger</a>
2668           */           */
2669          public void setMinZoomScale(final Double minZoomScale) {          public void setAntiAliasing(final boolean aa) {
2670                  this.minZoomScale = minZoomScale;                  // LOGGER.info("Setting AntiAliasing for this JMapPane to " + aa);
2671                    RenderingHints java2DHints = java2dHints;
2672                    if (java2DHints == null) {
2673                            java2DHints = GeoTools.getDefaultHints();
2674                    }
2675    
2676                    java2DHints.put(RenderingHints.KEY_ANTIALIASING,
2677                                    aa ? RenderingHints.VALUE_ANTIALIAS_ON
2678                                                    : RenderingHints.VALUE_ANTIALIAS_OFF);
2679                    java2DHints.put(RenderingHints.KEY_TEXT_ANTIALIASING,
2680                                    aa ? RenderingHints.VALUE_TEXT_ANTIALIAS_ON
2681                                                    : RenderingHints.VALUE_TEXT_ANTIALIAS_OFF);
2682                    java2DHints.put(RenderingHints.KEY_RENDERING,
2683                                    aa ? RenderingHints.VALUE_RENDER_QUALITY
2684                                                    : RenderingHints.VALUE_RENDER_SPEED);
2685    
2686            }
2687    
2688            public Point getImageOrigin() {
2689                    return imageOrigin;
2690            }
2691    
2692            /**
2693             * If {@link #maxExtend} is <code>null</code> the following rules are used
2694             * to create a default maximum.
2695             * <ul>
2696             * <li>Values &lt; 0 : don't grow to fit the monitors aspect ratio, no
2697             * margin</li>
2698             * <li>Values 0 : grow to fit the monitors aspect ratio, no margin</li>
2699             * <li>Values &gt; 0 : grow to fit the monitors aspect ratio, and add a
2700             * relative margin</li>
2701             * </ul>
2702             * **/
2703            public void setDefaultMaxMapExtendMode(double defaultMaxMapExtendMode) {
2704                    this.defaultMaxMapExtendMode = defaultMaxMapExtendMode;
2705            }
2706    
2707            /**
2708             * If {@link #maxExtend} is <code>null</code> the following rules are used
2709             * to create a default maximum.
2710             * <ul>
2711             * <li>Values &lt; 0 : don't grow to fit the monitors aspect ratio, no
2712             * margin</li>
2713             * <li>Values 0 : grow to fit the monitors aspect ratio, no margin</li>
2714             * <li>Values &gt; 0 : grow to fit the monitors aspect ratio, and add a
2715             * relative margin</li>
2716             * </ul>
2717             * **/
2718            public double getDefaultMaxMapExtendMode() {
2719                    return defaultMaxMapExtendMode;
2720            }
2721    
2722            final static int BLINK_TIMER_DEPLAY = 800;
2723    
2724            private Timer initBlinkTimer() {
2725                    Timer timer = new Timer(BLINK_TIMER_DEPLAY, new ActionListener() {
2726    
2727                            @Override
2728                            public void actionPerformed(ActionEvent e) {
2729                                    XMapPane.this.repaint(300);
2730                            }
2731                    });
2732                    timer.setDelay(BLINK_TIMER_DEPLAY);
2733                    timer.setRepeats(false);
2734                    return timer;
2735            }
2736    
2737            /**
2738             * Makes the given {@link FeatureCollection} bink in the map for a moment
2739             */
2740            public void blink(
2741                            FeatureCollection<SimpleFeatureType, SimpleFeature> features) {
2742                    {
2743                            blinkTimer.stop();
2744                            repaint();
2745                            blinkTimer = initBlinkTimer();
2746    
2747                            DefaultMapContext mc = new DefaultMapContext(getMapContext()
2748                                            .getCoordinateReferenceSystem());
2749    
2750                            Style style = StylingUtil.STYLE_FACTORY.createStyle();
2751                            style.featureTypeStyles().add(
2752                                            StylingUtil.createBlinkFeatureTypeStyle(features));
2753    
2754                            // style = StylingUtil.createStyleSimple(features, Color.pink,
2755                            // Color.WHITE);
2756    
2757                            DefaultMapLayer dml = new DefaultMapLayer(features, style);
2758                            mc.addLayer(dml);
2759    
2760                            GTRenderer renderer = new StreamingRenderer();
2761    
2762                            renderer.setJava2DHints(getJava2dHints());
2763    
2764                            renderer.setContext(mc);
2765    
2766                            Graphics2D g2d = (Graphics2D) getGraphics();
2767                            renderer.paint(g2d, getVisibleRect(), getMapArea());
2768    
2769                            blinkTimer.start();
2770    
2771                    }
2772    
2773          }          }
         // xulu.en  
2774    
2775  }  }

Legend:
Removed from v.341  
changed lines
  Added in v.695

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26