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

Legend:
Removed from v.511  
changed lines
  Added in v.612

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26