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

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

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

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

Legend:
Removed from v.332  
changed lines
  Added in v.516

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26