/[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

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

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

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26