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

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

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26