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

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

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

branches/1.0-gt2-2.6/src/gtmig/org/geotools/swing/JMapPane.java revision 418 by alfonx, Mon Sep 28 15:36:11 2009 UTC branches/1.0-gt2-2.6/src/gtmig/org/geotools/swing/XMapPane.java revision 521 by alfonx, Tue Nov 17 12:51:37 2009 UTC
# Line 16  Line 16 
16  package gtmig.org.geotools.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;
57    import org.geotools.geometry.jts.JTS;
58    import org.geotools.geometry.jts.ReferencedEnvelope;
59    import org.geotools.map.DefaultMapContext;
60  import org.geotools.map.MapContext;  import org.geotools.map.MapContext;
61    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.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;  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.StreamingRenderer;  import org.geotools.swing.JMapPane;
71  import org.geotools.renderer.shape.ShapefileRenderer;  import org.geotools.swing.event.MapMouseEvent;
72  import org.opengis.filter.FilterFactory2;  import org.geotools.swing.event.MapPaneEvent;
73    import org.geotools.swing.event.MapPaneListener;
74    import org.opengis.feature.simple.SimpleFeature;
75    import org.opengis.feature.simple.SimpleFeatureType;
76    import org.opengis.referencing.FactoryException;
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.GeometryFactory;  import com.vividsolutions.jts.geom.Geometry;
92    
93  public class JMapPane extends JPanel implements MouseListener,  public class XMapPane extends JPanel implements PropertyChangeListener {
94                  MouseMotionListener, PropertyChangeListener, MapLayerListListener {          private static Logger LOGGER = Logger.getLogger(XMapPane.class);
         private static Logger LOGGER = Logger.getLogger(JMapPane.class.getName());  
95    
96          private static final long serialVersionUID = -8647971481359690499L;          /**
97             * Sets whether a layer is regarded or ignored on {@link #SELECT_TOP},
98          public static final int Reset = 0;           * {@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            public void setMapLayerSelectable(MapLayer layer, Boolean selectable) {
108                    if (selectable == null)
109                            mapLayerSelectable.remove(layer);
110                    else
111                            mapLayerSelectable.put(layer, selectable);
112            }
113    
114          public static final int ZoomIn = 1;          /**
115             * 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            final protected HashMap<MapLayer, Boolean> mapLayerSelectable = new HashMap<MapLayer, Boolean>();
120    
121          public static final int ZoomOut = 2;          /**
122             * 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            public boolean isMapLayerSelectable(MapLayer layer) {
130                    Boolean selectable = mapLayerSelectable.get(layer);
131                    return selectable == null ? true : selectable;
132            }
133    
134          public static final int Pan = 3;          /**
135             * Flag fuer Modus "Kartenausschnitt bewegen". Nicht fuer Window-Auswahl
136             * moeglich!
137             *
138             * @see #setState(int)
139             */
140            public static final int PAN = 1;
141            /**
142             * Flag fuer Modus "Heran zoomen".
143             *
144             * @see #setState(int)
145             * @see #setState(int)
146             */
147            public static final int ZOOM_IN = 2;
148            /**
149             * Flag fuer Modus "Heraus zoomen". Nicht fuer Window-Auswahl moeglich!
150             *
151             * @see #setState(int)
152             */
153            public static final int ZOOM_OUT = 3;
154            /**
155             * Flag fuer Modus
156             * "SimpleFeature-Auswahl auf dem obersten (sichtbaren) Layer".
157             *
158             * @see #setState(int)
159             * @see #setState(int)
160             */
161            public static final int SELECT_TOP = 4;
162            /**
163             * Flag fuer Modus "SimpleFeature-Auswahl auf allen (sichtbaren) Layern".
164             *
165             * @see #setState(int)
166             * @see #setState(int)
167             */
168            public static final int SELECT_ALL = 103;
169            /**
170             * Flag fuer Modus
171             * "Auswahl nur eines Features, das erste sichtbare von Oben".
172             *
173             * @see #setState(int)
174             * @see #setState(int)
175             */
176            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          public static final int Select = 4;          protected RenderingExecutor bgExecuter;
198    
199          /**          /**
200           * what renders the map           * the map context to render
201           */           */
202          GTRenderer renderer;          MapContext localContext;
   
203          /**          /**
204           * the map context to render           * the map context to render
205           */           */
206          MapContext context;          MapContext bgContext;
207    
208          /**          /**
209           * the area of the map to draw           * the area of the map to draw
210           */           */
211          protected Envelope mapArea;          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           * the size of the pane last time we drew           * the size of the pane last time we drew
# Line 112  public class JMapPane extends JPanel imp Line 221  public class JMapPane extends JPanel imp
221          protected Rectangle oldRect = null;          protected Rectangle oldRect = null;
222    
223          /**          /**
224           * the last map area drawn.           * The Renderer for the Background uses this Image. When set to null, please
225             * dispose the {@link Graphics2D}
226           */           */
227          protected Envelope oldMapArea = null;          protected BufferedImage bgImage;
228    
229          /**          /**
230           * the base image of the map           * The Renderer for the LocalLayers uses this Image. When set to null,
231             * please dispose this {@link Graphics2D}
232           */           */
233          protected BufferedImage baseImage, panningImage;          volatile protected BufferedImage localImage;
234    
235          /**          /**
236           * a factory for filters           * compass and icon are rendered into this image
237           */           */
238          FilterFactory2 ff;          // protected BufferedImage gadgetsImage;
239    
240          /**          /**
241           * a factory for geometries           * The default state is ZOOM_IN, hence by default the
242           */           * {@link #zoomMapPaneMouseListener} is also enabled.
243          GeometryFactory gf = new GeometryFactory(); // FactoryFinder.getGeometryFactory(null);           **/
244            private int state = ZOOM_IN;
         private int state = ZoomIn;  
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                    if (e != null && e instanceof MapMouseEvent)
256                            try {
257                                    return ((MapMouseEvent) e).getMapPosition().toPoint2D();
258                            } catch (Exception err) {
259                                    LOGGER
260                                                    .error(
261                                                                    "return ((GeoMouseEvent) e).getMapCoordinate(null).toPoint2D();",
262                                                                    err);
263                            }
264    
265                    // aktuelle Geo-Position ueber Transformation des JMapPane berechnen
266                    if (e != null && e.getSource() instanceof XMapPane) {
267    
268          boolean changed = true;                          final XMapPane xMapPane = (XMapPane) e.getSource();
269    
270          LabelCache labelCache = new LabelCacheImpl();                          if (!xMapPane.isWellDefined())
271                                    return null;
272    
273          protected boolean reset = false;                          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          int startX;          /**
283             * A flag indicating that the shown image is invalid and needs to be
284             * re-rendered.
285             */
286            protected boolean mapImageInvalid = true;
287    
288          int startY;          protected LabelCache labelCache = new LabelCacheImpl();
289    
290          /**          /**
291           * If not <code>null</code>, the {@link JMapPane} will not allow to zoom/pan           * If not <code>null</code>, the {@link XMapPane} will not allow to zoom/pan
292           * out of that area           * out of that area
293           **/           **/
294          private Envelope maxExtend = null;          private Envelope maxExtend = null;
295    
296          // /**          private Double maxZoomScale = Double.MIN_VALUE;
297          // * Is max. 1 or 0 of the 2 axised allowed to extend the maxExtend? If          private Double minZoomScale = Double.MAX_VALUE;
         // * <code>true</code> the extends has to be fully inside maxExtend  
         // **/  
         // boolean maxExtendForceMode = true;  
   
         private boolean clickable;  
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 Double maxZoomScale = Double.MIN_VALUE;          /**
311          private Double minZoomScale = Double.MAX_VALUE;           * A flag indicating, that the image size has changed and the buffered
312             * images are not big enough any more
313             **/
314            protected boolean paneResized = false;
315    
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          public JMapPane() {          private Map<Object, Object> rendererHints;
324                  this(null, true, null, null);  
325            public Map<Object, Object> getRendererHints() {
326                    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                  ff = (FilterFactory2) org.geotools.factory.CommonFactoryFinder                  setOpaque(true);
                                 .getFilterFactory(null);  
                 setRenderer(render);  
370    
371                  setContext(context);                  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                            public void actionPerformed(ActionEvent e) {
391                                    paneResized = true;
392    
393                                    if (!isWellDefined())
394                                            return;
395    
396                                    Rectangle bounds = getVisibleRect();
397    
398                                    Envelope geoMapArea = tranformWindowToGeo(bounds.x, bounds.y,
399                                                    bounds.x + bounds.width, bounds.y + bounds.height);
400    
401                                    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                    });
417    
418    //              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                  this.addMouseListener(this);          }
444                  this.addMouseMotionListener(this);  
445                  setCursor(new Cursor(Cursor.CROSSHAIR_CURSOR));          // 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<Object, Object> hints = new HashMap<Object, Object>();                                  .getCoordinateReferenceSystem();
465                    CoordinateReferenceSystem fCRS = features.getSchema()
466                                    .getGeometryDescriptor().getCoordinateReferenceSystem();
467    
468                    double width = mapArea.getWidth();
469                    double height = mapArea.getHeight();
470                    double ratio = height / width;
471    
472                  this.renderer = renderer;                  if (features == null || features.size() == 0) {
473                            // feature count == 0 Zoom to the full extend
474                            return;
475                    } else if (features.size() == 1) {
476    
477                  if (renderer instanceof StreamingRenderer                          // feature count == 1 Just move the window to the point and zoom 'a
478                                  || renderer instanceof ShapefileRenderer) {                          // bit'
479                          hints = renderer.getRendererHints();                          SimpleFeature singleFeature = (SimpleFeature) features.iterator()
480                          if (hints == null) {                                          .next();
481                                  hints = new HashMap<Object, Object>();  
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 {
490                                    // System.out.println("Zoomed in a bit becasue only one point");
491                                    // width *= .9;
492                                    // height *= .9;
493                          }                          }
494                          if (hints.containsKey(StreamingRenderer.LABEL_CACHE_KEY)) {  
495                                  labelCache = (LabelCache) hints                          Coordinate centre = features.getBounds().centre();
496                                                  .get(StreamingRenderer.LABEL_CACHE_KEY);                          if (!mapCRS.equals(fCRS)) {
497                                    // only to calculations if the CRS differ
498                                    try {
499                                            MathTransform fToMap;
500                                            fToMap = CRS.findMathTransform(fCRS, mapCRS);
501                                            // 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                            Coordinate newLeftBottom = new Coordinate(centre.x - width / 2.,
511                                            centre.y - height / 2.);
512                            Coordinate newTopRight = new Coordinate(centre.x + width / 2.,
513                                            centre.y + height / 2.);
514    
515                            Envelope newMapArea = new Envelope(newLeftBottom, newTopRight);
516    
517                            setMapArea(newMapArea);
518    
519                    } else {
520                            ReferencedEnvelope fBounds = features.getBounds();
521    
522                            Envelope bounds;
523                            if (!mapCRS.equals(fCRS)) {
524                                    bounds = JTSUtil.transformEnvelope(fBounds, fCRS, mapCRS);
525                          } else {                          } else {
526                                  hints.put(StreamingRenderer.LABEL_CACHE_KEY, labelCache);                                  bounds = fBounds;
527                            }
528                            // BB umrechnen von Layer-CRS in Map-CRS
529    
530                            // Expand a bit
531                            bounds.expandBy(bounds.getWidth() / 6., bounds.getHeight() / 6.);
532    
533                            setMapArea(bounds);
534                    }
535            }
536    
537            private void setRendererHints(Map<Object, Object> rendererHints) {
538                    this.rendererHints = rendererHints;
539            }
540    
541            /**
542             * 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                    try {
548    
549                            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            /**
566             * 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            private Timer resizeTimer;
573            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            /**
581             * Manuell gesetzter statischer Cursor, unabhaengig von der aktuellen
582             * MapPane-Funktion
583             */
584            protected Cursor staticCursor = null;
585    
586            /**
587             * Standardmaessig wird der Cursor automatisch je nach MapPane-Aktion (Zoom,
588             * Auswahl, ...) gesetzt. Mit dieser Methode kann ein statischer Cursor
589             * 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            /**
603             * 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            /**
614             * Abhaengig von selState wird der Cursor gesetzt
615             */
616            public void updateCursor() {
617    
618                    if (bgExecuter != null && bgExecuter.isRunning()
619                                    || 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                    // wenn manueller Cursor gesetzt ist, dann diesen verwenden (unabhaengig
632                    // 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                    // Je nach Aktion den Cursor umsetzen
643                    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            //
665            // /**
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            /**
690             * Berechnet die Transformation zwischen Fenster- und Karten-Koordinaten
691             * neu.
692             */
693            protected void resetTransforms() {
694                    if (getMapArea() == null || getWidth() == 0 || getHeight() == 0)
695                            return;
696    
697                    // We store the last Transform
698                    oldScreenToWorld = screenToWorld;
699    
700                    this.screenToWorld = new AffineTransform(
701                    // 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                    try {
720                            this.worldToScreen = screenToWorld.createInverse();
721                    } catch (NoninvertibleTransformException e) {
722                            LOGGER.error(e);
723                    }
724            }
725    
726            /**
727             * Transformation zwischen Fenster-Koordinaten und Karten-Koordinaten
728             * (lat/lon)
729             */
730            protected AffineTransform screenToWorld = null;
731    
732            private AffineTransform worldToScreen;
733    
734            /**
735             * Listens to changes of the "local" {@link MapContext} and triggers
736             * repaints where needed.
737             */
738            private MapLayerListListener localContextListener = new MapLayerListListener() {
739    
740                    @Override
741                    public void layerAdded(final MapLayerListEvent event) {
742                            event.getLayer().addMapLayerListener(localMapLayerListener);
743    
744                            if (localContext.getLayers().length == 1) { // the first one
745                                    // if the Area of Interest is unset, the LayerBounds are used
746                                    if (!setMapArea(localContext.getAreaOfInterest()))
747                                            repaint();
748    
749                                    return;
750                            }
751    
752                            // We need to redraw, even in case that the mapArea didn't change
753                            // mapImageInvalid = true;
754                            // repaint();
755                            requestStartRendering();
756    
757                    }
758    
759                    @Override
760                    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                    @Override
769                    public void layerChanged(final MapLayerListEvent event) {
770                            // mapImageInvalid = true;
771                            // repaint();
772                            requestStartRendering();
773                    }
774    
775                    @Override
776                    public void layerMoved(final MapLayerListEvent event) {
777                            // mapImageInvalid = true;
778                            // repaint();
779                            requestStartRendering();
780                    }
781            };
782    
783            /**
784             * Listens to changes of the "background" {@link MapContext} and triggers
785             * repaints where needed.
786             */
787            private MapLayerListListener bgContextListener = new MapLayerListListener() {
788    
789                    @Override
790                    public void layerAdded(final MapLayerListEvent event) {
791                            event.getLayer().addMapLayerListener(bgMapLayerListener);
792    
793                            if (localContext.getLayers().length == 0
794                                            && bgContext.getLayers().length == 1) { // the first one and
795                                    // localContext is
796                                    // empty
797                                    if (!setMapArea(localContext.getAreaOfInterest()))
798                                            requestStartRendering();
799                                    return;
800                          }                          }
801    
802                          hints.put("memoryPreloadingEnabled", Boolean.TRUE);                          // We need to redraw, even in case that the mapArea didn't change
803                            // mapImageInvalid = true;
804                            // repaint();
805                            requestStartRendering();
806    
                         renderer.setRendererHints(hints);  
807                  }                  }
808    
809                  // this.highlightRenderer = new StreamingRenderer();                  @Override
810                  // this.selectionRenderer = new StreamingRenderer();                  public void layerRemoved(final MapLayerListEvent event) {
811                            if (event.getLayer() != null)
812                                    event.getLayer().removeMapLayerListener(bgMapLayerListener);
813                            // mapImageInvalid = true;
814                            // repaint();
815                            requestStartRendering();
816                    }
817    
818                    @Override
819                    public void layerChanged(final MapLayerListEvent event) {
820                            // mapImageInvalid = true;
821                            // repaint();
822                            requestStartRendering();
823                    }
824    
825                    @Override
826                    public void layerMoved(final MapLayerListEvent event) {
827                            // mapImageInvalid = true;
828                            // repaint();
829                            requestStartRendering();
830                    }
831            };
832    
833            /**
834             * Listens to each layer in the local {@link MapContext} for changes and
835             * triggers repaints.
836             */
837            protected MapLayerListener localMapLayerListener = new MapLayerAdapter() {
838    
839                    @Override
840                    public void layerShown(MapLayerEvent event) {
841                            // mapImageInvalid = true;
842                            // repaint();
843                            requestStartRendering();
844                    }
845    
846                  // highlightRenderer.setRendererHints(hints);                  @Override
847                  // selectionRenderer.setRendererHints(hints);                  public void layerHidden(MapLayerEvent event) {
848                            // mapImageInvalid = true;
849                            // repaint();
850                            requestStartRendering();
851                    }
852    
853                  // renderer.setRendererHints(hints);                  @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 (this.context != null) {          /**
863                          this.renderer.setContext(this.context);           * Listens to each layer in the local {@link MapContext} for changes and
864             * triggers repaints.
865             */
866            protected MapLayerListener bgMapLayerListener = new MapLayerAdapter() {
867    
868                    @Override
869                    public void layerShown(MapLayerEvent event) {
870                            // mapImageInvalid = true;
871                            // repaint();
872                            requestStartRendering();
873                    }
874    
875                    @Override
876                    public void layerHidden(MapLayerEvent event) {
877                            // mapImageInvalid = true;
878                            // repaint();
879                            requestStartRendering();
880                  }                  }
881    
882                    @Override
883                    public void layerChanged(MapLayerEvent event) {
884                            // Change of SLD for example
885                            // mapImageInvalid = true;
886                            // repaint();
887                            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          public MapContext getContext() {          public MapContext getContext() {
916                  return context;                  if (localContext == null) {
917                            this.localContext = new DefaultMapContext();
918                            this.localContext.addMapLayerListListener(localContextListener);
919                    }
920                    return localContext;
921          }          }
922    
923          public void setContext(final MapContext context) {          public MapContext getBgContext() {
924                  if (this.context != null) {                  return bgContext;
925                          this.context.removeMapLayerListListener(this);          }
926    
927            /**
928             *
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                  this.context = context;                  this.localContext = context;
943    
944                  if (context != null) {                  if (context != null) {
945                          this.context.addMapLayerListListener(this);                          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 (renderer != null) {                  mapImageInvalid = true;
956                          renderer.setContext(this.context);                  repaint();
957            }
958    
959            public void setBgContext(final MapContext context) {
960    
961                    // Remove the default listener from the old context
962                    if (this.bgContext != null) {
963                            this.bgContext.removeMapLayerListListener(bgContextListener);
964    
965                            // adding listener to all layers
966                            for (MapLayer mapLayer : bgContext.getLayers()) {
967                                    mapLayer.removeMapLayerListener(bgMapLayerListener);
968                            }
969                    }
970    
971                    this.bgContext = context;
972    
973                    if (context != null) {
974                            setMapArea(bgContext.getAreaOfInterest());
975    
976                            this.bgContext.addMapLayerListListener(bgContextListener);
977    
978                            // adding listener to all layers
979                            for (MapLayer mapLayer : bgContext.getLayers()) {
980                                    mapLayer.addMapLayerListener(bgMapLayerListener);
981                            }
982                  }                  }
983                    mapImageInvalid = true;
984                    repaint();
985          }          }
986    
987            /**
988             * Returns a copy of the mapArea
989             *
990             * @return
991             */
992          public Envelope getMapArea() {          public Envelope getMapArea() {
993                  return mapArea;                  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                    return new Envelope(mapArea);
1014          }          }
1015    
1016          public void setMapArea(final Envelope mapArea) {          /**
1017                  this.mapArea = mapArea;           * @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 (newMapArea == null
1024                                    || bestAllowedMapArea(newMapArea).equals(mapArea)) {
1025                            // No change.. no need to repaint
1026                            return false;
1027                    }
1028    
1029                    // Testing, whether NaN or Infinity are used in the newMapArea
1030                    if (newMapArea.isNull() || Double.isInfinite(newMapArea.getMaxX())
1031                                    || 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                    if (mapArea != null) {
1042                            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                                            && (candNew.getMinY() - tolY < mapArea.getMinY())
1051                                            && (mapArea.getMinY() < candNew.getMinY() + tolY)
1052                                            && (candNew.getMaxY() - tolY < mapArea.getMaxY())
1053                                            && (mapArea.getMaxY() < candNew.getMaxY() + tolY)
1054    
1055                            ) {
1056                                    // The two mapAreas only differ my 1/1000th.. ignore
1057    
1058                                    return false;
1059                            }
1060                    }
1061    
1062                    oldMapArea = mapArea;
1063    
1064                    this.mapArea = bestAllowedMapArea(newMapArea);
1065    
1066                    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() {          public int getState() {
1084                  return state;                  return state;
1085          }          }
1086    
1087            /**
1088             * Enables/Disables the ZOOM Mouse Listener. Upates the Cursor and stops the
1089             * repaint Timer if
1090             *
1091             * @param state
1092             */
1093          public void setState(final int state) {          public void setState(final int state) {
1094                  this.state = state;                  this.state = state;
1095    
1096                  // System.out.println("State: " + state);                  zoomMapPaneMouseListener.setEnabled((state == ZOOM_IN
1097          }                                  || state == ZOOM_OUT || state == PAN));
1098    
1099          public double getZoomFactor() {                  // Je nach Aktion den Cursor umsetzen
1100                  return zoomFactor;                  updateCursor();
1101          }          }
1102    
1103          public void setZoomFactor(final double zoomFactor) {          /** Cursor wenn kein Mausbutton gedrueckt wird. default oder SwingUtil.PAN **/
1104                  this.zoomFactor = zoomFactor;          protected static Cursor normalCursor = Cursor
1105          }                          .getPredefinedCursor(Cursor.DEFAULT_CURSOR);
1106    
1107            public static final Cursor WAIT_CURSOR = Cursor
1108                            .getPredefinedCursor(Cursor.WAIT_CURSOR);
1109    
1110            public static final int NONE = -123;
1111    
1112            private RenderingExecutor localExecuter;
1113    
1114            private BufferedImage finalImage;
1115    
1116            /**
1117             * A flag set it {@link #setMapArea(Envelope)} to indicated the
1118             * {@link #paintComponent(Graphics)} method, that the image on-screen is
1119             * associated with {@link #oldMapArea} and may hence be scaled for a quick
1120             * preview.<br/>
1121             * The flag is reset
1122             **/
1123            private boolean mapAreaChanged = false;
1124    
1125            private JFrame finalImageFrame;
1126    
1127            private volatile Boolean requestStartRendering = false;
1128            private BufferedImage preFinalImage;
1129    
1130          protected void paintComponent(final Graphics g) {          protected void paintComponent(final Graphics g) {
1131                  super.paintComponent(g);                  // Maybe update the cursor
1132                    updateCursor();
1133    
1134                  if ((renderer == null) || (mapArea == null)) {                  if (!acceptsRepaintCalls)
1135                          return;                          return;
                 }  
1136    
1137                  final Rectangle r = getBounds();                  boolean paintedSomething = false;
                 final Rectangle dr = new Rectangle(r.width, r.height);  
1138    
1139                  if (!r.equals(oldRect) || reset) {                  if (mapImageInvalid) { /* if the map changed then redraw */
1140                          if (!r.equals(oldRect) && (mapArea == null)) {  
1141                                  try {                          mapImageInvalid = false; // Reset for next round
1142                                          mapArea = context.getLayerBounds();  
1143                                  } catch (final IOException e) {                          // If the new mapArea and the oldMapArea intersect, we can draw some
1144                                          LOGGER.warn("context.getLayerBounds()", e);                          // 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                          if (mapArea != null) {                          }
                                 /* either the viewer size has changed or we've done a reset */  
                                 changed = true; /* note we need to redraw */  
                                 reset = false; /* forget about the reset */  
                                 oldRect = r; /* store what the current size is */  
1161    
1162                                  mapArea = fixAspectRatio(r, mapArea, false);                          if (paneResized) {
1163                                    paneResized = false;
1164                                    preFinalImage = null;
1165                                    finalImage = null;
1166                                    localImage = null;
1167                                    bgImage = null;
1168                                    // gadgetsImage = null;
1169                          }                          }
                 }  
1170    
1171                  if (!mapArea.equals(oldMapArea)) { /* did the map extent change? */                          // Start the Threads and Timers to render the image
1172                          changed = true;                          requestStartRendering();
1173                          oldMapArea = mapArea;  
                         // when we tell the context that the bounds have changed WMSLayers  
                         // can refresh them selves  
                         context.setAreaOfInterest(mapArea, context  
                                         .getCoordinateReferenceSystem());  
1174                  }                  }
1175    
1176                  if (changed) { /* if the map changed then redraw */                  if (!paintedSomething) {
                         changed = false;  
                         baseImage = new BufferedImage(dr.width, dr.height,  
                                         BufferedImage.TYPE_INT_ARGB);  
1177    
1178                          final Graphics2D ig = baseImage.createGraphics();                          // TODO Should just paint the getFinalImage(). Update should be
1179                          /* System.out.println("rendering"); */                          // called by timer every 300ms, and the repaint() until all threads
1180                          if (renderer.getContext() != null)                          // are done.
1181                                  renderer.setContext(context);                          g.drawImage(getFinalImage(), 0, 0, this);
                         labelCache.clear(); // work around anoying labelcache bug  
1182    
1183                          // draw the map                          paintedSomething = true;
1184                          renderer.paint((Graphics2D) ig, dr, mapArea);                  }
1185    
1186                          // TODO nur machen, wenn panning beginnt          }
                         panningImage = new BufferedImage(dr.width, dr.height,  
                                         BufferedImage.TYPE_INT_RGB);  
1187    
1188                  }          /**
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                  ((Graphics2D) g).drawImage(baseImage, 0, 0, this);          /**
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          /**          /**
1221           * Returns an {@link Envelope} that has the same aspect ratio as the given rectangle           * Transformiert einen Geo-Koordinaten-Bereich in Fenster-Koordinaten.
1222           * @param grow           *
1223           *            If <code>true</code>, than the area will be enlarged to match           * @param ox
1224           *            the aspect ratio. If <code>false</code>, it will only shrink.           *            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            /**
1253             * Diretly paints scaled preview into the {@link SelectableXMapPane}. Used
1254             * 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          private Envelope fixAspectRatio(final Rectangle r, final Envelope mapArea,          protected boolean drawScaledPreviewImage_Zoom(Graphics2D graphics) {
                         boolean grow) {  
1267    
1268                  final double mapWidth = mapArea.getWidth(); /* get the extent of the map */                  if (quickPreviewHint == 0)
1269                  final double mapHeight = mapArea.getHeight();                          return false;
                 final double scaleX = r.getWidth() / mapArea.getWidth(); /*  
                                                                                                                                  * calculate the  
                                                                                                                                  * new scale  
                                                                                                                                  */  
1270    
1271                  final double scaleY = r.getHeight() / mapArea.getHeight();                  graphics.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
1272                  double scale = 1.0; // stupid compiler!                                  RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR);
1273                    graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
1274                                    RenderingHints.VALUE_ANTIALIAS_OFF);
1275                    graphics.setRenderingHint(RenderingHints.KEY_RENDERING,
1276                                    RenderingHints.VALUE_RENDER_SPEED);
1277    
1278                  if ((grow && scaleX < scaleY) || (!grow && scaleX > scaleY)) {                  if (oldMapArea == null)
1279                          scale = scaleX;                          return false;
                 } else {  
                         scale = scaleY;  
                 }  
1280    
1281                  /* calculate the difference in width and height of the new extent */                  Rectangle visibleArea = getVisibleRect();
                 final double deltaX = /* Math.abs */((r.getWidth() / scale) - mapWidth);  
                 final double deltaY = /* Math.abs */((r.getHeight() / scale) - mapHeight);  
1282    
1283                  /*                  // Calculate the oldMapArea in the current WindowCoordinates:
1284                   * System.out.println("delta x " + deltaX);                  Envelope oldMapWindow = tranformGeoToWindow(oldMapArea.getMinX(),
1285                   * System.out.println("delta y " + deltaY);                                  oldMapArea.getMinY(), oldMapArea.getMaxX(), oldMapArea
1286                   */                                                  .getMaxY(), null);
1287    
1288                    int xx1 = (int) Math.round(oldMapWindow.getMinX());
1289                    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                    graphics.drawImage(getPreFinalImage(), xx1, yy1, xx2, yy2,
1294                                    (int) visibleArea.getMinX(), (int) visibleArea.getMinY(),
1295                                    (int) visibleArea.getMaxX(), (int) visibleArea.getMaxY(),
1296                                    getMapBackgroundColor(), null);
1297    
1298                    Rectangle painedArea = new Rectangle(xx1, yy1, xx2 - xx1, yy2 - yy1);
1299    
1300                    SwingUtil.clearAround(graphics, painedArea, visibleArea);
1301    
1302                  /* create the new extent */                  addGadgets(graphics);
                 final Coordinate ll = new Coordinate(  
                                 mapArea.getMinX() - (deltaX / 2.0), mapArea.getMinY()  
                                                 - (deltaY / 2.0));  
                 final Coordinate ur = new Coordinate(  
                                 mapArea.getMaxX() + (deltaX / 2.0), mapArea.getMaxY()  
                                                 + (deltaY / 2.0));  
1303    
1304                  return new Envelope(ll, ur);                  quickPreviewHint = 0;
1305    
1306                    graphics.dispose();
1307                    
1308                    // Something has been drawn
1309                    return true;
1310          }          }
1311    
1312          public void mouseClicked(final MouseEvent e) {          final static Font waitFont = new Font("Arial", Font.BOLD, 30);
                 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();  
1313    
1314                  /*          /**
1315                   * System.out.println(""+x+"->"+mapX);           * Paints some optinal stuff into the given {@link Graphics2D}. Usually
1316                   * System.out.println(""+y+"->"+mapY);           * called as the last paint on the mapImage.
1317                   */           */
1318            private void addGadgets(Graphics2D graphics) {
1319    
1320                  /*                  if (mapImage != null)
1321                   * Coordinate ll = new Coordinate(mapArea.getMinX(), mapArea.getMinY());                          graphics.drawImage(mapImage, getBounds().width
1322                   * Coordinate ur = new Coordinate(mapArea.getMaxX(), mapArea.getMaxY());                                          - mapImage.getWidth() - 10, getBounds().height
1323                   */                                          - mapImage.getHeight() - 10, this);
                 double zlevel = 1.0;  
1324    
1325                  switch (state) {                  // If still rendering, paint a gray shadow or so...
1326                  case Pan:                  if (bgExecuter != null && bgExecuter.isRunning()
1327                          zlevel = 1.0;                                  || localExecuter != null && localExecuter.isRunning()) {
1328                          // xulu.sc SK: return here.. a mouselistener is managing the PANNING                          graphics.setColor(Color.BLACK);
                         // break;  
                         return;  
                         // xulu.ec  
                 case ZoomIn:  
                         zlevel = zoomFactor;  
1329    
1330                          break;                          graphics.setFont(waitFont);
1331                            graphics.drawString("Wait...", 40, 70); //i8n
1332                            
1333                            graphics.setColor(getMapBackgroundColor());
1334                    }
1335    
1336                  case ZoomOut:          }
                         zlevel = 1.0 / zoomFactor;  
1337    
1338                          break;          /**
1339                  //           * Accumulates all three images
1340                  // case Select:           *
1341                  // doSelection(mapX, mapY, selectionLayer);           * @return
1342                  //           */
1343                  // return;          synchronized protected BufferedImage updateFinalImage() {
1344    
1345                  default:                  final Graphics2D finalG = (Graphics2D) getFinalImage().getGraphics();
1346                          return;                  finalG.setBackground(getMapBackgroundColor());
1347    
1348                    // Render the two map images first, into the preFinalImage
1349                    {
1350                            final Graphics2D preFinalG = (Graphics2D) getPreFinalImage()
1351                                            .getGraphics();
1352                            preFinalG.setBackground(getMapBackgroundColor());
1353    
1354                            preFinalG.drawImage(getBgImage(), 0, 0, getMapBackgroundColor(),
1355                                            null);
1356                            
1357                            // // Draw the local layers image
1358                            preFinalG.drawImage(getLocalImage(), 0, 0, null);
1359                            preFinalG.dispose();
1360                  }                  }
1361    
1362                  final Coordinate ll = new Coordinate(mapX - (width2 / zlevel), mapY                  finalG.drawImage(getPreFinalImage(), imageOrigin.x, imageOrigin.y,
1363                                  - (height2 / zlevel));                                  getMapBackgroundColor(), null);
                 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  
1364    
1365                  // sk.ec                  final int finalImageHeight = getFinalImage().getHeight(null);
1366                    final int finalImageWidth = getFinalImage().getWidth(null);
1367    
1368                  // System.out.println("after area "+mapArea+"\nw:"+mapArea.getWidth()+"                  Rectangle painedArea = new Rectangle(imageOrigin.x, imageOrigin.y,
1369                  // h:"+mapArea.getHeight());                                  finalImageWidth, finalImageHeight);
1370                  repaint();                  SwingUtil.clearAround(finalG, painedArea, getVisibleRect());
         }  
1371    
1372          public void mouseEntered(final MouseEvent e) {                  addGadgets(finalG);
1373          }  
1374                    finalG.dispose();
1375    
1376          public void mouseExited(final MouseEvent e) {                  return finalImage;
1377          }          }
1378    
1379          public void mousePressed(final MouseEvent e) {          private Image getFinalImage() {
1380                  startX = e.getX();  
1381                  startY = e.getY();                  if (finalImage == null) {
1382                  lastX = 0;                          finalImage = null;
1383                  lastY = 0;                          Rectangle curPaintArea = getVisibleRect();
1384                            finalImage = new BufferedImage(curPaintArea.width,
1385                                            curPaintArea.height, BufferedImage.TYPE_INT_RGB);
1386    
1387                            requestStartRendering();
1388                    }
1389                    return finalImage;
1390          }          }
1391    
1392          public void mouseReleased(final MouseEvent e) {          private Image getPreFinalImage() {
1393                  final int endX = e.getX();                  if (preFinalImage == null) {
1394                  final int endY = e.getY();                          preFinalImage = null;
1395                            Rectangle curPaintArea = getVisibleRect();
1396    
1397                  processDrag(startX, startY, endX, endY, e);                          preFinalImage = new BufferedImage(curPaintArea.width,
1398                  lastX = 0;                                          curPaintArea.height, BufferedImage.TYPE_INT_RGB);
                 lastY = 0;  
1399    
1400                  /**                          requestStartRendering();
1401                   * Es wird nicht (mehr) gepannt!                  }
1402                   */                  return preFinalImage;
                 panning_started = false;  
1403          }          }
1404    
1405          public void mouseDragged(final MouseEvent e) {          /**
1406                  final Graphics graphics = this.getGraphics();           * While dragging, the {@link #updateFinalImage()} method is translating the
1407                  final int x = e.getX();           * cached images while setting it together.
1408                  final int y = e.getY();           **/
1409            Point imageOrigin = new Point(0, 0);
                 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);  
                         }  
1410    
1411                          // move the image with the mouse          /**
1412                          if ((lastX > 0) && (lastY > 0)) {           * Starts rendering on one or two threads
1413                                  final int dx = lastX - startX;           */
1414                                  final int dy = lastY - startY;          private void startRendering() {
                                 // 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);  
                 // }  
                 //  
                 // graphics.setXORMode(Color.green);  
                 //  
                 // /*  
                 // * if ((lastX > 0) && (lastY > 0)) { drawRectangle(graphics); }  
                 // */  
                 //  
                 // // draw new box  
                 // lastX = x;  
                 // lastY = y;  
                 // drawRectangle(graphics);  
                 // }  
   
         }  
   
         // sk.cs  
         // 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) {  
1415    
1416                  /****                  if (!isWellDefined())
                  * If no layer is availabe we dont want a NullPointerException  
                  */  
                 if (mapArea == null)  
1417                          return;                          return;
1418    
1419                  // System.out.println("processing drag from " + x1 + "," + y1 + " -> "                  if (bgExecuter != null)
1420                  // + x2 + "," + y2);                          // Stop all renderers
1421                  if ((x1 == x2) && (y1 == y2)) {                          bgExecuter.cancelTask();
1422                          if (isClickable()) {  
1423                                  mouseClicked(new MouseEvent(this, 0, new Date().getTime(), 0,                  if (localExecuter != null)
1424                                                  x1, y1, y2, false));                          localExecuter.cancelTask();
1425                          }          
1426                    Rectangle curPaintArea = getVisibleRect();
1427    
1428                          return;                  labelCache.clear();
                 }  
1429    
1430                  final Rectangle bounds = this.getBounds();                  /**
1431                     * We have to set new renderer
1432                     */
1433    
1434                  final double mapWidth = mapArea.getWidth();                  if (getBgContext() != null) {
1435                  final double mapHeight = mapArea.getHeight();                          bgExecuter = new RenderingExecutor(this, 333l);
1436                            LOGGER.debug("starting bg renderer:");
1437                            // /* System.out.println("rendering"); */
1438                            final GTRenderer createGTRenderer = GTUtil.createGTRenderer(
1439                                            localContext, getRendererHints());
1440                            createGTRenderer.setJava2DHints(getJava2dHints());
1441                            bgExecuter.submit(getBgContext().getAreaOfInterest(), curPaintArea,
1442                                            (Graphics2D) getBgImage().getGraphics(), createGTRenderer);
1443                    }
1444    
1445                  final double startX = ((x1 * mapWidth) / (double) bounds.width)                  if (getContext() != null) {
1446                                  + mapArea.getMinX();                          localExecuter = new RenderingExecutor(this, 150l);
1447                  final double startY = (((bounds.getHeight() - y1) * mapHeight) / (double) bounds.height)                          LOGGER.debug("starting local renderer:");
1448                                  + mapArea.getMinY();                          final GTRenderer createGTRenderer = GTUtil.createGTRenderer(
1449                  final double endX = ((x2 * mapWidth) / (double) bounds.width)                                          localContext, getRendererHints());
1450                                  + mapArea.getMinX();                          createGTRenderer.setJava2DHints(getJava2dHints());
1451                  final double endY = (((bounds.getHeight() - y2) * mapHeight) / (double) bounds.height)                          localExecuter.submit(getContext().getAreaOfInterest(),
1452                                  + mapArea.getMinY();                                          curPaintArea, (Graphics2D) getLocalImage().getGraphics(),
1453                                            createGTRenderer);
1454                  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(bestAllowedMapArea(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  
1455    
1456                          drawRectangle(this.getGraphics());                  updateCursor();
                         // make the dragged rectangle (in map coords) the new BBOX  
                         final double left = Math.min(startX, endX);  
                         final double right = Math.max(startX, endX);  
                         final double bottom = Math.min(startY, endY);  
                         final double top = Math.max(startY, endY);  
                         final Coordinate ll = new Coordinate(left, bottom);  
                         final Coordinate ur = new Coordinate(right, top);  
                         // xulu.sc  
   
                         // mapArea = fixAspectRatio(this.getBounds(), new Envelope(ll, ur));  
                         setMapArea(bestAllowedMapArea(new Envelope(ll, ur)));  
   
                         // sk.sc  
                         // {  
                         // // SK tries to paint a preview of the zoom ;-9 aha.... well  
                         // Graphics2D graphics = (Graphics2D) JMapPane.this.getGraphics();  
                         // graphics.setRenderingHint(RenderingHints.KEY_INTERPOLATION,  
                         // RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR);  
                         // graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING,  
                         // RenderingHints.VALUE_ANTIALIAS_OFF);  
                         // graphics.setRenderingHint(RenderingHints.KEY_RENDERING,  
                         // RenderingHints.VALUE_RENDER_SPEED);  
                         // graphics.drawImage(baseImage, 0, 0, JMapPane.this.getWidth(),  
                         // JMapPane.this.getHeight(), x1, y1, x2, y2, null);  
                         // }  
                         // xulu.ec  
                 } else if (state == JMapPane.ZoomOut) {  
                         drawRectangle(this.getGraphics());  
   
                         // make the dragged rectangle in screen coords the new map size?  
                         final double left = Math.min(startX, endX);  
                         final double right = Math.max(startX, endX);  
                         final double bottom = Math.min(startY, endY);  
                         final double top = Math.max(startY, endY);  
                         final double nWidth = (mapWidth * mapWidth) / (right - left);  
                         final double nHeight = (mapHeight * mapHeight) / (top - bottom);  
                         final double deltaX1 = left - mapArea.getMinX();  
                         final double nDeltaX1 = (deltaX1 * nWidth) / mapWidth;  
                         final double deltaY1 = bottom - mapArea.getMinY();  
                         final double nDeltaY1 = (deltaY1 * nHeight) / mapHeight;  
                         final Coordinate ll = new Coordinate(mapArea.getMinX() - nDeltaX1,  
                                         mapArea.getMinY() - nDeltaY1);  
                         final double deltaX2 = mapArea.getMaxX() - right;  
                         final double nDeltaX2 = (deltaX2 * nWidth) / mapWidth;  
                         final double deltaY2 = mapArea.getMaxY() - top;  
                         final double nDeltaY2 = (deltaY2 * nHeight) / mapHeight;  
                         final Coordinate ur = new Coordinate(mapArea.getMaxX() + nDeltaX2,  
                                         mapArea.getMaxY() + nDeltaY2);  
                         // xulu.sc  
                         // mapArea = fixAspectRatio(this.getBounds(), new Envelope(ll, ur));  
                         setMapArea(bestAllowedMapArea(new Envelope(ll, ur)));  
   
                         // xulu.ec  
                 }  
                 // else if (state == JMapPane.Select && selectionLayer != null) {  
                 // final double left = Math.min(startX, endX);  
                 // final double right = Math.max(startX, endX);  
                 // final double bottom = Math.min(startY, endY);  
                 // final double top = Math.max(startY, endY);  
                 //  
                 // String name = selectionLayer.getFeatureSource().getSchema()  
                 // .getDefaultGeometry().getLocalName();  
                 //  
                 // if (name == "") {  
                 // name = "the_geom";  
                 // }  
                 // final Filter bb = ff.bbox(ff.property(name), left, bottom, right,  
                 // top,  
                 // getContext().getCoordinateReferenceSystem().toString());  
                 // // System.out.println(bb.toString());  
                 // if (selectionManager != null) {  
                 // selectionManager.selectionChanged(this, bb);  
                 // }  
                 // /*  
                 // * FeatureCollection fc; selection = null; try { fc =  
                 // * selectionLayer.getFeatureSource().getFeatures(bb); selection =  
                 // * fc; } catch (IOException e) { e.printStackTrace(); }  
                 // */  
                 // }  
   
                 // xulu.so  
                 // setMapArea(mapArea);  
                 // xulu.eo  
                 repaint();  
         }  
1457    
         private boolean isClickable() {  
                 return clickable;  
1458          }          }
1459    
1460          //          /**
1461          // private org.geotools.styling.Style setupStyle(final int type, final Color           * Lazyly initializes a {@link BufferedImage} for the background renderer.
1462          // color) {           */
1463          // final StyleFactory sf = org.geotools.factory.CommonFactoryFinder          private BufferedImage getBgImage() {
         // .getStyleFactory(null);  
         // final StyleBuilder sb = new StyleBuilder();  
         //  
         // org.geotools.styling.Style s = sf.createStyle();  
         // s.setTitle("selection");  
         //  
         // // TODO parameterise the color  
         // final PolygonSymbolizer ps = sb.createPolygonSymbolizer(color);  
         // ps.setStroke(sb.createStroke(color));  
         //  
         // final LineSymbolizer ls = sb.createLineSymbolizer(color);  
         // final Graphic h = sb.createGraphic();  
         // h.setMarks(new Mark[] { sb.createMark("square", color) });  
         //  
         // final PointSymbolizer pts = sb.createPointSymbolizer(h);  
         //  
         // // Rule r = sb.createRule(new Symbolizer[]{ps,ls,pts});  
         // switch (type) {  
         // case POLYGON:  
         // s = sb.createStyle(ps);  
         //  
         // break;  
         //  
         // case POINT:  
         // s = sb.createStyle(pts);  
         //  
         // break;  
         //  
         // case LINE:  
         // s = sb.createStyle(ls);  
         // }  
         //  
         // return s;  
         // }  
1464    
1465          public void propertyChange(final PropertyChangeEvent evt) {                  if (bgImage == null) {
1466                  final String prop = evt.getPropertyName();                          Rectangle curPaintArea = getVisibleRect();
1467    
1468                  if (prop.equalsIgnoreCase("crs")) {                          bgImage = new BufferedImage(curPaintArea.width + 1,
1469                          context.setAreaOfInterest(context.getAreaOfInterest(),                                          curPaintArea.height + 1, BufferedImage.TYPE_INT_ARGB);
                                         (CoordinateReferenceSystem) evt.getNewValue());  
1470                  }                  }
1471    
1472                    return bgImage;
1473          }          }
1474    
1475          public boolean isReset() {          /** An (transparent) image to paint over the map in the lower right corner **/
1476                  return reset;          private BufferedImage mapImage = null;
1477    
1478            private boolean acceptsRepaintCalls = true;
1479    
1480            /**
1481             * Get the BufferedImage to use as a flaoting icon in the lower right
1482             * corner.
1483             *
1484             * @return <code>null</code> if the feature is deactivated.
1485             */
1486            public BufferedImage getMapImage() {
1487                    return mapImage;
1488          }          }
1489    
1490          public void setReset(final boolean reset) {          /**
1491                  this.reset = reset;           * Set the BufferedImage to use as a flaoting icon in the lower right corner
1492             *
1493             * @param mapImageIcon
1494             *            <code>null</code> is allowed and deactivates this icon.
1495             */
1496            public void setMapImage(BufferedImage mapImage) {
1497                    this.mapImage = mapImage;
1498          }          }
1499    
1500          public void layerAdded(final MapLayerListEvent event) {          /**
1501                  changed = true;           * Lazyly initializes a {@link BufferedImage} for the background renderer.
1502             */
1503            private BufferedImage getLocalImage() {
1504    
1505                  if (context.getLayers().length == 1) { // the first one                  if (localImage == null) {
1506    
1507                          try {                          Rectangle curPaintArea = getVisibleRect();
                                 // xulu.sc  
                                 // mapArea = context.getLayerBounds();  
                                 mapArea = context.getAreaOfInterest();  
                                 if (mapArea == null)  
                                         mapArea = context.getLayerBounds();  
                                 // xulu.ec  
                         } catch (final IOException e) {  
                                 // TODO Auto-generated catch block  
                                 e.printStackTrace();  
                         }  
1508    
1509                          reset = true;                          localImage = new BufferedImage(curPaintArea.width + 1,
1510                                            curPaintArea.height + 1, BufferedImage.TYPE_INT_ARGB);
1511                  }                  }
1512    
1513                  repaint();                  return localImage;
1514          }          }
1515    
1516          public void layerRemoved(final MapLayerListEvent event) {  
1517                  changed = true;          /**
1518             * Called by the {@linkplain XMapPane.RenderingTask} when rendering has been
1519             * completed Publishes a {@linkplain MapPaneEvent} of type {@code
1520             * MapPaneEvent.Type.RENDERING_STOPPED} to listeners.
1521             *
1522             * @see MapPaneListener#onRenderingStopped(org.geotools.swing.event.MapPaneEvent)
1523             */
1524            public void onRenderingCompleted() {
1525                    updateFinalImage();
1526                  repaint();                  repaint();
1527          }          }
1528    
1529          public void layerChanged(final MapLayerListEvent event) {          /**
1530                  changed = true;           * Called by the {@linkplain XMapPane.RenderingTask} when rendering was
1531                  // System.out.println("layer changed - repaint");           * cancelled. Publishes a {@linkplain MapPaneEvent} of type {@code
1532                  repaint();           * MapPaneEvent.Type.RENDERING_STOPPED} to listeners.
1533             *
1534             * @see MapPaneListener#onRenderingStopped(org.geotools.swing.event.MapPaneEvent)
1535             */
1536            public void onRenderingCancelled() {
1537                    LOGGER.debug("Rendering cancelled");
1538          }          }
1539    
1540          public void layerMoved(final MapLayerListEvent event) {          /**
1541                  changed = true;           * Called by the {@linkplain XMapPane.RenderingTask} when rendering failed.
1542             * Publishes a {@linkplain MapPaneEvent} of type {@code
1543             * MapPaneEvent.Type.RENDERING_STOPPED} to listeners.
1544             *
1545             * @param renderingError
1546             *            The error that occured during rendering
1547             *
1548             * @see MapPaneListener#onRenderingStopped(org.geotools.swing.event.MapPaneEvent)
1549             */
1550            public void onRenderingFailed(Exception renderingError) {
1551                    LOGGER.warn("Rendering failed", renderingError);
1552                    updateFinalImage();
1553                  repaint();                  repaint();
         }  
1554    
         protected void drawRectangle(final Graphics graphics) {  
                 // undraw last box/draw new box  
                 final int left = Math.min(startX, lastX);  
                 final int right = Math.max(startX, lastX);  
                 final int top = Math.max(startY, lastY);  
                 final int bottom = Math.min(startY, lastY);  
                 final int width = right - left;  
                 final int height = top - bottom;  
                 // System.out.println("drawing rect("+left+","+bottom+","+ width+","+  
                 // height+")");  
                 graphics.drawRect(left, bottom, width, height);  
1555          }          }
1556    
1557          /**          /**
1558           * if clickable is set to true then a single click on the map pane will zoom           * Called when a rendering request has been rejected. This will be common,
1559           * or pan the map.           * such as when the user pauses during drag-resizing fo the map pane. The
1560           *           * base implementation does nothing. It is provided for sub-classes to
1561           * @param clickable           * override if required.
1562           */           */
1563          public void setClickable(final boolean clickable) {          public void onRenderingRejected() {
1564                  this.clickable = clickable;                  LOGGER.warn("Rendering rejected");
1565                    repaint();
1566          }          }
1567    
1568          public void mouseMoved(final MouseEvent e) {          @Override
1569            public void propertyChange(final PropertyChangeEvent evt) {
1570                    final String prop = evt.getPropertyName();
1571    
1572                    if (prop.equalsIgnoreCase("crs")) {
1573                            localContext.setAreaOfInterest(localContext.getAreaOfInterest(),
1574                                            (CoordinateReferenceSystem) evt.getNewValue());
1575                    }
1576          }          }
1577    
         // xulu.sn  
1578          /**          /**
1579           * Korrigiert den {@link Envelope} aka {@code mapArea} auf die beste           * Korrigiert den {@link Envelope} aka {@code mapArea} auf die beste
1580           * erlaubte Flaeche damit die Massstabsbeschaenkungen noch eingehalten           * erlaubte Flaeche damit die Massstabsbeschaenkungen noch eingehalten
# Line 910  public class JMapPane extends JPanel imp Line 1590  public class JMapPane extends JPanel imp
1590                  if (getWidth() == 0)                  if (getWidth() == 0)
1591                          return env;                          return env;
1592                  if (env == null)                  if (env == null)
1593                          return env;                          return null;
1594    
1595                  Envelope newArea = null;                  Envelope newArea = null;
1596    
1597                  /**                  /**
1598                   * Correct the aspect Ratio before we check the rest. Otherwise we might                   * Correct the aspect Ratio before we check the rest. Otherwise we might
1599                   * easily fail.                   * easily fail. We allow to grow here, because we don't check against
1600                     * the maxExtend
1601                   */                   */
1602                  env = fixAspectRatio(this.getBounds(), env, false);                  Rectangle curPaintArea = getVisibleRect();
1603    
1604                    env = JTSUtil.fixAspectRatio(curPaintArea, env, true);
1605    
1606                  final double scale = env.getWidth() / getWidth();                  final double scale = env.getWidth() / getWidth();
1607                  final double centerX = env.getMinX() + env.getWidth() / 2.;                  final double centerX = env.getMinX() + env.getWidth() / 2.;
# Line 955  public class JMapPane extends JPanel imp Line 1638  public class JMapPane extends JPanel imp
1638                  }                  }
1639    
1640                  Envelope maxAllowedExtend = getMaxExtend();                  Envelope maxAllowedExtend = getMaxExtend();
1641                  while (maxAllowedExtend != null && !maxAllowedExtend.contains(newArea)) {                  while (maxAllowedExtend != null && !maxAllowedExtend.contains(newArea)
1642                                    && newArea != null && !newArea.isNull()
1643                                    && !Double.isNaN(newArea.getMinX())
1644                                    && !Double.isNaN(newArea.getMaxX())
1645                                    && !Double.isNaN(newArea.getMinY())
1646                                    && !Double.isNaN(newArea.getMaxY())) {
1647                          /*                          /*
1648                           * If a maxExtend is set, we have to honour that...                           * If a maxExtend is set, we have to honour that...
1649                           */                           */
# Line 963  public class JMapPane extends JPanel imp Line 1651  public class JMapPane extends JPanel imp
1651                          // Exceeds top? Move down and maybe cut                          // Exceeds top? Move down and maybe cut
1652                          if (newArea.getMaxY() > maxAllowedExtend.getMaxY()) {                          if (newArea.getMaxY() > maxAllowedExtend.getMaxY()) {
1653                                  double divY = newArea.getMaxY() - maxAllowedExtend.getMaxY();                                  double divY = newArea.getMaxY() - maxAllowedExtend.getMaxY();
1654                                  LOGGER.debug("Moving area down by " + divY);                                  // LOGGER.debug("Moving area down by " + divY);
1655    
1656                                  newArea = new Envelope(new Coordinate(newArea.getMinX(),                                  newArea = new Envelope(new Coordinate(newArea.getMinX(),
1657                                                  newArea.getMinY() - divY), new Coordinate(newArea                                                  newArea.getMinY() - divY), new Coordinate(newArea
1658                                                  .getMaxX(), newArea.getMaxY() - divY));                                                  .getMaxX(), newArea.getMaxY() - divY));
1659    
1660                                  if (newArea.getMinY() < maxAllowedExtend.getMinY()) {                                  if (newArea.getMinY() < maxAllowedExtend.getMinY()) {
1661                                          LOGGER.debug("Now it exeeds the bottom border.. cut!");                                          // LOGGER.debug("Now it exeeds the bottom border.. cut!");
1662                                          // And cut the bottom if it moved out of the area                                          // And cut the bottom if it moved out of the area
1663                                          newArea = new Envelope(new Coordinate(newArea.getMinX(),                                          newArea = new Envelope(new Coordinate(newArea.getMinX(),
1664                                                          maxAllowedExtend.getMinY()), new Coordinate(newArea                                                          maxAllowedExtend.getMinY()), new Coordinate(newArea
1665                                                          .getMaxX(), newArea.getMaxY()));                                                          .getMaxX(), newArea.getMaxY()));
1666    
1667                                          LOGGER.debug("and fix aspect ratio");                                          // LOGGER.debug("and fix aspect ratio");
1668    
1669                                          newArea = fixAspectRatio(this.getBounds(), newArea, false);                                          newArea = JTSUtil.fixAspectRatio(this.getBounds(), newArea,
1670                                                            false);
1671                                  }                                  }
1672                          }                          }
1673    
1674                          // Exceeds bottom? Move up and maybe cut                          // Exceeds bottom? Move up and maybe cut
1675                          if (newArea.getMinY() < maxAllowedExtend.getMinY()) {                          if (newArea.getMinY() < maxAllowedExtend.getMinY()) {
1676                                  double divY = newArea.getMinY() - maxAllowedExtend.getMinY();                                  double divY = newArea.getMinY() - maxAllowedExtend.getMinY();
1677                                  LOGGER.debug("Moving area up by " + divY);                                  // LOGGER.debug("Moving area up by " + divY);
1678    
1679                                  newArea = new Envelope(new Coordinate(newArea.getMinX(),                                  newArea = new Envelope(new Coordinate(newArea.getMinX(),
1680                                                  newArea.getMinY() - divY), new Coordinate(newArea                                                  newArea.getMinY() - divY), new Coordinate(newArea
1681                                                  .getMaxX(), newArea.getMaxY() - divY));                                                  .getMaxX(), newArea.getMaxY() - divY));
1682    
1683                                  if (newArea.getMaxY() > maxAllowedExtend.getMaxY()) {                                  if (newArea.getMaxY() > maxAllowedExtend.getMaxY()) {
1684                                          LOGGER.debug("Now it exeeds the top border.. cut!");                                          // LOGGER.debug("Now it exeeds the top border.. cut!");
1685                                          // And cut the bottom if it moved out of the area                                          // And cut the bottom if it moved out of the area
1686                                          newArea = new Envelope(new Coordinate(newArea.getMinX(),                                          newArea = new Envelope(new Coordinate(newArea.getMinX(),
1687                                                          newArea.getMinY()), new Coordinate(newArea                                                          newArea.getMinY()), new Coordinate(newArea
1688                                                          .getMaxX(), maxAllowedExtend.getMaxY()));                                                          .getMaxX(), maxAllowedExtend.getMaxY()));
1689    
1690                                          LOGGER.debug("and fix aspect ratio");                                          // LOGGER.debug("and fix aspect ratio");
1691    
1692                                          newArea = fixAspectRatio(this.getBounds(), newArea, false);                                          newArea = JTSUtil.fixAspectRatio(this.getBounds(), newArea,
1693                                                            false);
1694                                  }                                  }
1695                          }                          }
1696    
# Line 1009  public class JMapPane extends JPanel imp Line 1699  public class JMapPane extends JPanel imp
1699    
1700                                  // Move left..                                  // Move left..
1701                                  double divX = newArea.getMaxX() - maxAllowedExtend.getMaxX();                                  double divX = newArea.getMaxX() - maxAllowedExtend.getMaxX();
1702                                  LOGGER.debug("Moving area left by " + divX);                                  // LOGGER.debug("Moving area left by " + divX);
1703    
1704                                  newArea = new Envelope(new Coordinate(newArea.getMinX() - divX,                                  newArea = new Envelope(new Coordinate(newArea.getMinX() - divX,
1705                                                  newArea.getMinY()), new Coordinate(newArea.getMaxX()                                                  newArea.getMinY()), new Coordinate(newArea.getMaxX()
1706                                                  - divX, newArea.getMaxY()));                                                  - divX, newArea.getMaxY()));
1707    
1708                                  if (newArea.getMinX() < maxAllowedExtend.getMinX()) {                                  if (newArea.getMinX() < maxAllowedExtend.getMinX()) {
1709                                          LOGGER.debug("Now it exeeds the left border.. cut!");                                          // LOGGER.debug("Now it exeeds the left border.. cut!");
1710                                          // And cut the left if it moved out of the area                                          // And cut the left if it moved out of the area
1711                                          newArea = new Envelope(new Coordinate(maxExtend.getMinX(),                                          newArea = new Envelope(new Coordinate(maxAllowedExtend
1712                                                          newArea.getMinY()), new Coordinate(newArea                                                          .getMinX(), newArea.getMinY()), new Coordinate(
1713                                                          .getMaxX(), newArea.getMaxY()));                                                          newArea.getMaxX(), newArea.getMaxY()));
1714    
1715                                          LOGGER.debug("and fix aspect ratio");                                          // LOGGER.debug("and fix aspect ratio");
1716    
1717                                          newArea = fixAspectRatio(this.getBounds(), newArea, false);                                          newArea = JTSUtil.fixAspectRatio(this.getBounds(), newArea,
1718                                                            false);
1719                                  }                                  }
1720                          }                          }
1721    
# Line 1033  public class JMapPane extends JPanel imp Line 1724  public class JMapPane extends JPanel imp
1724    
1725                                  // Move right..                                  // Move right..
1726                                  double divX = newArea.getMinX() - maxAllowedExtend.getMinX();                                  double divX = newArea.getMinX() - maxAllowedExtend.getMinX();
1727                                  LOGGER.debug("Moving area right by " + divX);                                  // LOGGER.debug("Moving area right by " + divX);
1728    
1729                                  newArea = new Envelope(new Coordinate(newArea.getMinX() - divX,                                  newArea = new Envelope(new Coordinate(newArea.getMinX() - divX,
1730                                                  newArea.getMinY()), new Coordinate(newArea.getMaxX()                                                  newArea.getMinY()), new Coordinate(newArea.getMaxX()
1731                                                  - divX, newArea.getMaxY()));                                                  - divX, newArea.getMaxY()));
1732    
1733                                  if (newArea.getMaxX() > maxAllowedExtend.getMaxX()) {                                  if (newArea.getMaxX() > maxAllowedExtend.getMaxX()) {
1734                                          LOGGER.debug("Now it exeeds the right border.. cut!");                                          // LOGGER.debug("Now it exeeds the right border.. cut!");
1735                                          // And cut the left if it moved out of the area                                          // And cut the left if it moved out of the area
1736                                          newArea = new Envelope(new Coordinate(newArea.getMinX(),                                          newArea = new Envelope(new Coordinate(newArea.getMinX(),
1737                                                          newArea.getMinY()), new Coordinate(maxAllowedExtend                                                          newArea.getMinY()), new Coordinate(maxAllowedExtend
1738                                                          .getMaxX(), newArea.getMaxY()));                                                          .getMaxX(), newArea.getMaxY()));
1739    
1740                                          LOGGER.debug("and fix aspect ratio");                                          // LOGGER.debug("and fix aspect ratio");
1741    
1742                                          newArea = fixAspectRatio(this.getBounds(), newArea, false);                                          newArea = JTSUtil.fixAspectRatio(this.getBounds(), newArea,
1743                                                            false);
1744                                  }                                  }
1745                          }                          }
   
1746                  }                  }
1747    
1748                  return newArea;                  return newArea;
# Line 1081  public class JMapPane extends JPanel imp Line 1772  public class JMapPane extends JPanel imp
1772    
1773          /**          /**
1774           * 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
1775           * the two.           * the two. If <code>null</code> is passed, Double.MINVALUE are used which
1776             * mean there is no restriction.
1777           *           *
1778           * @author <a href="mailto:[email protected]">Stefan Alfons           * @author <a href="mailto:[email protected]">Stefan Alfons
1779           *         Kr&uuml;ger</a>           *         Kr&uuml;ger</a>
1780           */           */
1781          public void setMaxZoomScale(final Double maxZoomScale) {          public void setMaxZoomScale(final Double maxZoomScale) {
1782                  this.maxZoomScale = maxZoomScale;                  this.maxZoomScale = maxZoomScale == null ? Double.MIN_VALUE
1783                                    : maxZoomScale;
1784          }          }
1785    
1786          /**          /**
1787           * Set the minimum (nearest) allowed zoom scale. This is the bigger number           * Set the minimum (nearest) allowed zoom scale. This is the bigger number
1788           * value of the two.           * value of the two. If <code>null</code> is passed, Double.MAXVALUE are
1789             * used which mean there is no restriction.
1790             *
1791           *           *
1792           * @author <a href="mailto:[email protected]">Stefan Alfons           * @author <a href="mailto:[email protected]">Stefan Alfons
1793           *         Kr&uuml;ger</a>           *         Kr&uuml;ger</a>
1794           */           */
1795          public void setMinZoomScale(final Double minZoomScale) {          public void setMinZoomScale(final Double minZoomScale) {
1796                  this.minZoomScale = minZoomScale;                  this.minZoomScale = minZoomScale == null ? Double.MAX_VALUE
1797                                    : minZoomScale;
1798          }          }
1799    
1800          /**          /**
# Line 1125  public class JMapPane extends JPanel imp Line 1821  public class JMapPane extends JPanel imp
1821    
1822          public Envelope getMaxExtend() {          public Envelope getMaxExtend() {
1823                  if (maxExtend == null) {                  if (maxExtend == null) {
1824                          try {                          final ReferencedEnvelope layerBounds = GTUtil
1825                                  return fixAspectRatio(this.getBounds(), context.getLayerBounds(), true);                                          .getVisibleLayoutBounds(localContext);
1826                          } catch (IOException e) {                          if (layerBounds == null) {
1827                                  LOGGER                                  // TODO Last fallback could be the CRS valid area
1828                                                  .warn(                                  return null;
                                                                 "maxExtend == null; faild to getLayerBounds of context",  
                                                                 e);  
1829                          }                          }
1830    
1831                            // Kartenbereich um 10% vergroessern
1832                            return JTSUtil.fixAspectRatio(this.getBounds(), JTSUtil
1833                                            .expandEnvelope(layerBounds, 0.1), true);
1834                  }                  }
1835                  return maxExtend;                  return maxExtend;
1836          }          }
1837    
1838            /**
1839             * Set the background color of the map.
1840             *
1841             * @param if <code>null</code>, white is used.
1842             */
1843            public void setMapBackgroundColor(Color bgColor) {
1844                    if (bgColor == null)
1845                            bgColor = Color.WHITE;
1846                    this.mapBackgroundColor = bgColor;
1847            }
1848    
1849            /**
1850             * Returns the background {@link Color} of the map pane. Default is white.
1851             **/
1852            public Color getMapBackgroundColor() {
1853                    return mapBackgroundColor;
1854            }
1855    
1856            /**
1857             *
1858             * @param b
1859             */
1860            public void setPainting(boolean b) {
1861                    acceptsRepaintCalls = b;
1862            }
1863    
1864            /**
1865             * Fuegt der Map einen Listener hinzu.
1866             *
1867             * @param l
1868             *            neuer Listener
1869             */
1870            public void addMapPaneListener(JMapPaneListener l) {
1871                    mapPaneListeners.add(l);
1872            }
1873    
1874            /**
1875             * Liste der angeschlossenen Listener, die auf Aktionen des MapPanes
1876             * lauschen.
1877             */
1878            protected Vector<JMapPaneListener> mapPaneListeners = new Vector<JMapPaneListener>();
1879    
1880            /**
1881             * A flag indicating if dispose() was already called. If true, then further
1882             * use of this {@link SelectableXMapPane} is undefined.
1883             */
1884            private boolean disposed = false;
1885    
1886            /**
1887             * Entfernt einen Listener von der Map.
1888             *
1889             * @param l
1890             *            zu entfernender Listener
1891             */
1892            public void removeMapPaneListener(JMapPaneListener l) {
1893                    mapPaneListeners.remove(l);
1894            }
1895    
1896            /** Stored the time used for the last real rendering in ms. **/
1897            private long lastRenderingDuration = Long.MAX_VALUE;
1898    
1899            // if null, no quick preview will be shown
1900            private int quickPreviewHint = 0;
1901    
1902            /**
1903             * For every rendering thread started,
1904             * {@link GTUtil#createGTRenderer(MapContext)} is called to create a new
1905             * renderer. These Java2D rendering hints are passed to the
1906             * {@link GTRenderer}. The java2dHints are the same for all renderers (bg
1907             * and local).
1908             */
1909            private RenderingHints java2dHints;
1910    
1911            /**
1912             * Returns in milli seconds the time the last rending of the
1913             * {@link SelectableXMapPane} took. #Long.MAX_VALUE if the JMapPane has not
1914             * been rendered yet.
1915             */
1916            public long getLastRenderingDuration() {
1917                    return lastRenderingDuration;
1918            }
1919    
1920            /**
1921             * Should be called when the {@link JMapPane} is not needed no more to help
1922             * the GarbageCollector
1923             *
1924             * Removes all {@link JMapPaneListener}s that are registered
1925             *
1926             * @author <a href="mailto:[email protected]">Stefan Alfons
1927             *         Kr&uuml;ger</a>
1928             */
1929            public void dispose() {
1930                    if (isDisposed())
1931                            return;
1932                    
1933                    setPainting(false);
1934    
1935                    disposed = true;
1936    
1937                    if (bgExecuter != null) {
1938                            bgExecuter.cancelTask();
1939                    }
1940    
1941                    if (localExecuter != null) {
1942                            localExecuter.cancelTask();
1943                    }
1944    
1945                    startRenderThreadsTimer.stop();
1946    
1947                    if (bgImage != null)
1948                            bgImage.flush();
1949                    if (localImage != null)
1950                            localImage.flush();
1951                    if (finalImage != null)
1952                            finalImage.flush();
1953                    if (preFinalImage != null)
1954                            preFinalImage.flush();
1955    
1956                    // Alle mapPaneListener entfernen
1957                    mapPaneListeners.clear();
1958    
1959                    removeMouseMotionListener(zoomMapPaneMouseListener);
1960                    removeMouseListener(zoomMapPaneMouseListener);
1961    
1962                    if (localContext != null)
1963                            getContext().clearLayerList();
1964                    if (bgContext != null)
1965                            getBgContext().clearLayerList();
1966    
1967                    removeAll();
1968            }
1969    
1970            /**
1971             * A flag indicating if dispose() has already been called. If true, then
1972             * further use of this {@link SelectableXMapPane} is undefined.
1973             */
1974            private boolean isDisposed() {
1975                    return disposed;
1976            }
1977    
1978            public void setQuickPreviewHint(int quickPreviewHint) {
1979                    this.quickPreviewHint = quickPreviewHint;
1980    
1981            }
1982    
1983            public void setJava2dHints(RenderingHints java2dHints) {
1984                    this.java2dHints = java2dHints;
1985            }
1986    
1987            public RenderingHints getJava2dHints() {
1988                    return java2dHints;
1989            }
1990    
1991            /**
1992             * Zooms towards a point.
1993             *
1994             * @param center
1995             *            position in window coordinates
1996             * @param zoomFaktor
1997             *            > 1 for zoom in, < 1 for zoom out. Default is 1.33.
1998             */
1999            public void zoomTo(Point center, Double zoomFaktor) {
2000                    if (zoomFaktor == null || zoomFaktor == 0.)
2001                            zoomFaktor = 2.;
2002    
2003                    Point2D gcenter = getScreenToWorld().transform(center, null);
2004                    center = null;
2005    
2006                    if (Double.isNaN(gcenter.getX()) || Double.isNaN(gcenter.getY())
2007                                    || Double.isInfinite(gcenter.getX())
2008                                    || Double.isInfinite(gcenter.getY())
2009    
2010                    ) {
2011                            // Not inside valid CRS area! cancel
2012                            return;
2013                    }
2014    
2015                    final Envelope mapArea = getMapArea();
2016    
2017                    Envelope newMapArea = new Envelope(mapArea);
2018                    newMapArea.expandBy((mapArea.getWidth() * zoomFaktor - mapArea
2019                                    .getWidth()) / 2., (mapArea.getHeight() * zoomFaktor - mapArea
2020                                    .getHeight()) / 2.);
2021    
2022                    // Move the newMapArea above the new center
2023                    newMapArea.translate(gcenter.getX() - mapArea.centre().x, gcenter
2024                                    .getY()
2025                                    - mapArea.centre().y);
2026    
2027                    setMapArea(newMapArea);
2028            }
2029    
2030            /**
2031             * Zooms towards a point.
2032             *
2033             * @param center
2034             *            position in window coordinates
2035             * @param zoomFactor
2036             *            > 1 for zoom in, < 1 for zoom out. Default is 1.33
2037             */
2038            public void zoomTo(Point center) {
2039                    zoomTo(center, null);
2040            }
2041    
2042            public void mouseDragged(Point startPos, Point lastPos, MouseEvent event) {
2043    
2044                    if ((getState() == XMapPane.PAN)
2045                                    || ((event.getModifiersEx() & InputEvent.BUTTON3_DOWN_MASK) != 0)) {
2046    
2047                            if (getCursor() != SwingUtil.PANNING_CURSOR) {
2048                                    setCursor(SwingUtil.PANNING_CURSOR);
2049    
2050                                    // While panning, we deactivate the rendering. So the tasts are
2051                                    // ready to start when the panning os done.
2052                                    if (bgExecuter != null)
2053                                            bgExecuter.cancelTask();
2054                                    if (localExecuter != null)
2055                                            localExecuter.cancelTask();
2056                            }
2057    
2058                            if (lastPos.x > 0 && lastPos.y > 0) {
2059                                    final int dx = event.getX() - lastPos.x;
2060                                    final int dy = event.getY() - lastPos.y;
2061    
2062                                    // TODO Stop dragging when the drag would not be valid...
2063                                    // boolean dragValid = true;
2064                                    // // check if this panning results in a valid mapArea
2065                                    // {
2066                                    // Rectangle winBounds = xMapPane.getBounds();
2067                                    // winBounds.translate(xMapPane.imageOrigin.x,
2068                                    // -xMapPane.imageOrigin.y);
2069                                    // Envelope newMapAreaBefore = xMapPane.tranformWindowToGeo(
2070                                    // winBounds.x, winBounds.y, winBounds.x
2071                                    // + winBounds.width, winBounds.y
2072                                    // + winBounds.height);
2073                                    //                                      
2074                                    //
2075                                    // winBounds = xMapPane.getBounds();
2076                                    // Point testIng = new Point(xMapPane.imageOrigin);
2077                                    // testIng.translate(dx, dy);
2078                                    // winBounds.translate(testIng.x, -testIng.y);
2079                                    // Envelope newMapAreaAfter = xMapPane.tranformWindowToGeo(
2080                                    // winBounds.x, winBounds.y, winBounds.x
2081                                    // + winBounds.width, winBounds.y
2082                                    // + winBounds.height);
2083                                    //
2084                                    // // If the last drag doesn't change the MapArea anymore cancel
2085                                    // it.
2086                                    // if (xMapPane.bestAllowedMapArea(newMapAreaAfter).equals(
2087                                    // xMapPane.bestAllowedMapArea(newMapAreaBefore))){
2088                                    // dragValid = false;
2089                                    // return;
2090                                    // }
2091                                    // }
2092    
2093                                    imageOrigin.translate(dx, dy);
2094                                    updateFinalImage();
2095                                    repaint();
2096                            }
2097    
2098                    } else if ((getState() == XMapPane.ZOOM_IN)
2099                                    || (getState() == XMapPane.ZOOM_OUT)
2100                                    || (getState() == XMapPane.SELECT_ALL)
2101                                    || (getState() == XMapPane.SELECT_TOP)
2102                    // || (getState() == XMapPane.SELECT_ONE_FROM_TOP)
2103                    ) {
2104                            final Graphics graphics = getGraphics();
2105    
2106                            drawRectangle(graphics, startPos, event.getPoint());
2107    
2108                            if ((lastPos.x > 0) && (lastPos.y > 0)) {
2109                                    drawRectangle(graphics, startPos, lastPos);
2110                            }
2111    
2112                    }
2113    
2114            }
2115    
2116            /**
2117             * Draws a rectangle in XOR mode from the origin at {@link #startPos} to the
2118             * given point. All in screen coordinates.
2119             */
2120            protected void drawRectangle(final Graphics graphics, Point startPos,
2121                            Point e) {
2122                    
2123                    if (!isWellDefined()) return;
2124                    
2125                    // undraw last box/draw new box
2126                    final int left = Math.min(startPos.x, e.x);
2127                    final int right = Math.max(startPos.x, e.x);
2128                    final int top = Math.max(startPos.y, e.y);
2129                    final int bottom = Math.min(startPos.y, e.y);
2130                    final int width = right - left;
2131                    final int height = top - bottom;
2132    
2133                    if (width == 0 && height == 0)
2134                            return;
2135    
2136                    graphics.setXORMode(Color.WHITE);
2137                    graphics.drawRect(left, bottom, width, height);
2138            }
2139    
2140            /**
2141             * Finalizes a PAN action
2142             */
2143            public void performPan() {
2144                    Rectangle winBounds = getBounds();
2145                    winBounds.translate(-imageOrigin.x, -imageOrigin.y);
2146                    Envelope newMapArea = tranformWindowToGeo(winBounds.x, winBounds.y,
2147                                    winBounds.x + winBounds.width, winBounds.y + winBounds.height);
2148    
2149                    imageOrigin.x = 0;
2150                    imageOrigin.y = 0;
2151    
2152                    if (!setMapArea(newMapArea)) {
2153                            updateFinalImage();
2154                            repaint();
2155                    }
2156    
2157                    if (getCursor() == SwingUtil.PANNING_CURSOR)
2158                            setCursor(SwingUtil.PAN_CURSOR);
2159            }
2160    
2161            public void onRenderingPending() {
2162    //              LOGGER.debug("Pending rendering updates the preview...");
2163                    updateFinalImage();
2164                    repaint();
2165            }
2166    
2167  }  }

Legend:
Removed from v.418  
changed lines
  Added in v.521

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26