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

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

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26