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

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

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26