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

Legend:
Removed from v.529  
changed lines
  Added in v.540

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26