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

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

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26