/[schmitzm]/trunk/src/skrueger/geotools/XMapPane.java
ViewVC logotype

Diff of /trunk/src/skrueger/geotools/XMapPane.java

Parent Directory Parent Directory | Revision Log Revision Log | View Patch Patch

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

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

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26