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

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

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

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

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

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26