/[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 505 by alfonx, Sat Oct 31 10:53:43 2009 UTC branches/1.0-gt2-2.6/src/gtmig/org/geotools/swing/XMapPane.java revision 524 by alfonx, Wed Nov 18 09:56:47 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;  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;
 import java.awt.event.MouseMotionListener;  
40  import java.awt.geom.AffineTransform;  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.opengis.filter.FilterFactory2;  import org.geotools.swing.event.MapMouseEvent;
72    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;  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);  
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          public static final int Select = 4;          /**
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           * what renders the map           * 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          GTRenderer renderer;          public static final long INITIAL_REPAINT_DELAY = 1000;
196    
197            protected RenderingExecutor bgExecuter;
198    
199            /**
200             * the map context to render
201             */
202            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 114  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          boolean changed = true;                  // aktuelle Geo-Position ueber Transformation des JMapPane berechnen
266                    if (e != null && e.getSource() instanceof XMapPane) {
267    
268          LabelCache labelCache = new LabelCacheImpl();                          final XMapPane xMapPane = (XMapPane) e.getSource();
269    
270          protected boolean reset = false;                          if (!xMapPane.isWellDefined())
271                                    return null;
272    
273          int startX;                          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 startY;          /**
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            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    
         // /**  
         // * Is max. 1 or 0 of the 2 axised allowed to extend the maxExtend? If  
         // * <code>true</code> the extends has to be fully inside maxExtend  
         // **/  
         // boolean maxExtendForceMode = true;  
   
         private boolean clickable;  
   
         int lastX;  
   
         int lastY;  
   
296          private Double maxZoomScale = Double.MIN_VALUE;          private Double maxZoomScale = Double.MIN_VALUE;
297          private Double minZoomScale = Double.MAX_VALUE;          private Double minZoomScale = Double.MAX_VALUE;
298    
299          /**          /**
300           * Wenn true, dann wurde PANNING via mouseDraged-Events begonnen. Dieses           * This color is used as the default background color when painting a map.
          * Flag wird benutzt um nur einmal den passenden Cursor nur einmal zu  
          * setzen.  
301           */           */
302          private boolean panning_started = false;          private Color mapBackgroundColor = Color.WHITE;
303    
304          /**          /**
305           * This color is used as the default background color when painting a map.           * This {@link MouseListener} is managing all zoom related tasks
306           */           */
307          private Color mapBackgroundColor = Color.WHITE;          public final ZoomXMapPaneMouseListener zoomMapPaneMouseListener = new ZoomXMapPaneMouseListener(
308                            this);
309    
310            /**
311             * 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          public JMapPane() {          /**
317                  this(null, true, null, null);           * The flag {@link #requestStartRendering} can be set to true by events.
318             * This {@link Timer} checks the flag regularly and starts one renderer
319             * thread.
320             */
321            final private Timer startRenderThreadsTimer;
322    
323            private Map<Object, Object> rendererHints;
324    
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                    setOpaque(true);
370    
371                    setLocalContext(localContext);
372    
373                  ff = (FilterFactory2) org.geotools.factory.CommonFactoryFinder                  /**
374                                  .getFilterFactory(null);                   * Adding the #zoomMapPaneMouseListener
375                  setRenderer(render);                   */
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                  setContext(context);                          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(100, new ActionListener() {
431    
432                            @Override
433                            public void actionPerformed(ActionEvent e) {
434                                    synchronized (requestStartRendering) {
435                                            if (requestStartRendering && isWellDefined()) {
436                                                    
437                                                    if (localExecuter.isRunning()){
438                                                            localExecuter.cancelTask();
439                                                    } else {
440                                                            requestStartRendering = false;
441                                                            startRendering();
442                                                    }
443                                            }
444                                    }
445                            }
446                    });
447                    startRenderThreadsTimer.start();
448    
449                  this.addMouseListener(this);          }
450                  this.addMouseMotionListener(this);  
451                  setCursor(new Cursor(Cursor.CROSSHAIR_CURSOR));          // TODO doku
452            public XMapPane() {
453                    this(null, null);
454          }          }
455    
456          /**          /**
457           * get the renderer           * Sets the mapArea to best possibly present the given features. If only one
458             * single point is given, the window is moved over the point.
459             *
460             * Note: The method does not call {@link #repaint()} on the
461             * {@link SelectableXMapPane} .
462             *
463             * @param features
464             *            if <code>null</code> or size==0, the function doesn nothing.
465           */           */
466          public GTRenderer getRenderer() {          public void zoomTo(
467                  return renderer;                          FeatureCollection<SimpleFeatureType, SimpleFeature> features) {
468    
469                    CoordinateReferenceSystem mapCRS = getContext()
470                                    .getCoordinateReferenceSystem();
471                    CoordinateReferenceSystem fCRS = features.getSchema()
472                                    .getGeometryDescriptor().getCoordinateReferenceSystem();
473    
474                    double width = mapArea.getWidth();
475                    double height = mapArea.getHeight();
476                    double ratio = height / width;
477    
478                    if (features == null || features.size() == 0) {
479                            // feature count == 0 Zoom to the full extend
480                            return;
481                    } else if (features.size() == 1) {
482    
483                            // feature count == 1 Just move the window to the point and zoom 'a
484                            // bit'
485                            SimpleFeature singleFeature = (SimpleFeature) features.iterator()
486                                            .next();
487    
488                            if (((Geometry) singleFeature.getDefaultGeometry())
489                                            .getCoordinates().length > 1) {
490                                    // System.out.println("Zoomed to only pne poylgon");
491                                    // Poly
492                                    // TODO max width vs. height
493                                    width = features.getBounds().getWidth() * 3;
494                                    height = ratio * width;
495                            } else {
496                                    // System.out.println("Zoomed in a bit becasue only one point");
497                                    // width *= .9;
498                                    // height *= .9;
499                            }
500    
501                            Coordinate centre = features.getBounds().centre();
502                            if (!mapCRS.equals(fCRS)) {
503                                    // only to calculations if the CRS differ
504                                    try {
505                                            MathTransform fToMap;
506                                            fToMap = CRS.findMathTransform(fCRS, mapCRS);
507                                            // centre is transformed to the mapCRS
508                                            centre = JTS.transform(centre, null, fToMap);
509                                    } catch (FactoryException e) {
510                                            LOGGER.error("Looking for a Math transform", e);
511                                    } catch (TransformException e) {
512                                            LOGGER.error("Looking for a Math transform", e);
513                                    }
514                            }
515    
516                            Coordinate newLeftBottom = new Coordinate(centre.x - width / 2.,
517                                            centre.y - height / 2.);
518                            Coordinate newTopRight = new Coordinate(centre.x + width / 2.,
519                                            centre.y + height / 2.);
520    
521                            Envelope newMapArea = new Envelope(newLeftBottom, newTopRight);
522    
523                            setMapArea(newMapArea);
524    
525                    } else {
526                            ReferencedEnvelope fBounds = features.getBounds();
527    
528                            Envelope bounds;
529                            if (!mapCRS.equals(fCRS)) {
530                                    bounds = JTSUtil.transformEnvelope(fBounds, fCRS, mapCRS);
531                            } else {
532                                    bounds = fBounds;
533                            }
534                            // BB umrechnen von Layer-CRS in Map-CRS
535    
536                            // Expand a bit
537                            bounds.expandBy(bounds.getWidth() / 6., bounds.getHeight() / 6.);
538    
539                            setMapArea(bounds);
540                    }
541          }          }
542    
543          public void setRenderer(final GTRenderer renderer) {          private void setRendererHints(Map<Object, Object> rendererHints) {
544                  Map<Object, Object> hints = new HashMap<Object, Object>();                  this.rendererHints = rendererHints;
545            }
546    
547                  this.renderer = renderer;          /**
548                  // MS: Apply hint also for ShapeFileRenderer           * Return <code>true</code> if a CRS and a {@link #mapArea} are set and the
549                  // if (renderer instanceof StreamingRenderer) {           * {@link XMapPane} is visible and has bounds set.
550                  hints = renderer.getRendererHints();           */
551                  if (hints == null) {          public boolean isWellDefined() {
552                          hints = new HashMap<Object, Object>();  
553                    try {
554    
555                            if (getContext() == null)
556                                    return false;
557                            if (getContext().getLayerCount() <= 0)
558                                    return false;
559                            if (getMapArea() == null)
560                                    return false;
561                            if (getBounds().getWidth() == 0)
562                                    return false;
563                            if (getBounds().getHeight() == 0)
564                                    return false;
565                    } catch (Exception e) {
566                            return false;
567                  }                  }
568                  if (hints.containsKey(StreamingRenderer.LABEL_CACHE_KEY)) {                  return true;
569                          labelCache = (LabelCache) hints          }
570                                          .get(StreamingRenderer.LABEL_CACHE_KEY);  
571            /**
572             * Default delay (milliseconds) before the map will be redrawn when resizing
573             * the pane. This is to avoid flickering while drag-resizing.
574             */
575            public static final int DEFAULT_RESIZING_PAINT_DELAY = 500; // delay in
576            // milliseconds
577    
578            private Timer resizeTimer;
579            private int resizingPaintDelay;
580            /**
581             * We store the old transform for a moment to use it for the
582             * "quick scaled preview" in case of ZoomIn
583             **/
584            protected AffineTransform oldScreenToWorld = null;
585    
586            /**
587             * Manuell gesetzter statischer Cursor, unabhaengig von der aktuellen
588             * MapPane-Funktion
589             */
590            protected Cursor staticCursor = null;
591    
592            /**
593             * Standardmaessig wird der Cursor automatisch je nach MapPane-Aktion (Zoom,
594             * Auswahl, ...) gesetzt. Mit dieser Methode kann ein statischer Cursor
595             * gesetzt werden, der unabhaengig von der aktuellen MapPanes-Aktion
596             * beibehalten wird. Um diesen statischen Cursor wieder zu entfernen, kann
597             * {@code null} als Parameter uebergeben werden
598             *
599             * @param cursor
600             *            Cursor
601             */
602            public void setStaticCursor(Cursor cursor) {
603                    this.staticCursor = cursor;
604                    if (cursor != null)
605                            super.setCursor(cursor);
606            }
607    
608            /**
609             * Liefert den statisch eingestellten Cursor, der unabhaengig von der
610             * eingestellten MapPane-Aktion (Zoom, Auswahl, ...) verwendet wird.
611             *
612             * @return {@code null}, wenn kein statischer Cursor verwendet, sondern der
613             *         Cursor automatisch je nach MapPane-Aktion eingestellt wird.
614             */
615            public Cursor getStaticCursor() {
616                    return this.staticCursor;
617            }
618    
619            /**
620             * Abhaengig von selState wird der Cursor gesetzt
621             */
622            public void updateCursor() {
623    
624                    if (bgExecuter != null && bgExecuter.isRunning()
625                                    || localExecuter != null && localExecuter.isRunning()) {
626                            setCursor(WAIT_CURSOR);
627                            return;
628                  } else {                  } else {
629                          hints.put(StreamingRenderer.LABEL_CACHE_KEY, labelCache);                          // Allow one last rendering
630                            if (repainterTimer.isRunning()) {
631                                    repainterTimer.stop();
632                                    updateFinalImage();
633                                    repaint();
634                            }
635                  }                  }
636    
637                  hints.put("memoryPreloadingEnabled", Boolean.TRUE);                  // wenn manueller Cursor gesetzt ist, dann diesen verwenden (unabhaengig
638                    // von der aktuellen Aktion
639                    if (this.staticCursor != null) {
640                            setCursor(staticCursor);
641                            return;
642                    }
643                    if (getCursor() == SwingUtil.PANNING_CURSOR) {
644                            // This cursor will reset itself
645                            return;
646                    }
647    
648                  renderer.setRendererHints(hints);                  // Je nach Aktion den Cursor umsetzen
649                  // }                  switch (state) {
650                    case SELECT_TOP:
651                    case SELECT_ONE_FROM_TOP:
652                    case SELECT_ALL:
653                            setCursor(SwingUtil.CROSSHAIR_CURSOR);
654                            break;
655                    case ZOOM_IN:
656                            setCursor(SwingUtil.ZOOMIN_CURSOR);
657                            break;
658                    case ZOOM_OUT:
659                            setCursor(SwingUtil.ZOOMOUT_CURSOR);
660                            break;
661                    case PAN:
662                            setCursor(SwingUtil.PAN_CURSOR);
663                            break;
664                    default:
665                            setCursor(normalCursor);
666                            break;
667                    }
668            }
669    
670                  if (this.context != null) {          //
671                          this.renderer.setContext(this.context);          // /**
672            // * Gibt den "normalen" Cursor zurueck. Dieser kann neben dem "pointer"
673            // auch
674            // * ein Sanduhr-Wartecursor sein.
675            // *
676            // * @author <a href="mailto:[email protected]">Stefan Alfons
677            // * Kr&uuml;ger</a>
678            // */
679            // public Cursor getNormalCursor() {
680            // return normalCursor;
681            // }
682            //
683            // /**
684            // * Setzt den "normalen" Cursor. Dieser kann neben dem default "pointer"
685            // z.B.
686            // * auch ein Sanduhr-Wartecursor sein.
687            // *
688            // * @author <a href="mailto:[email protected]">Stefan Alfons
689            // * Kr&uuml;ger</a>
690            // */
691            // public void setNormalCursor(Cursor normalCursor) {
692            // this.normalCursor = normalCursor;
693            // }
694    
695            /**
696             * Berechnet die Transformation zwischen Fenster- und Karten-Koordinaten
697             * neu.
698             */
699            protected void resetTransforms() {
700                    if (getMapArea() == null || getWidth() == 0 || getHeight() == 0)
701                            return;
702    
703                    // We store the last Transform
704                    oldScreenToWorld = screenToWorld;
705    
706                    this.screenToWorld = new AffineTransform(
707                    // Genauso wie die Fenster-Koordinaten, werden die Longitude-Koordinaten
708                                    // nach rechts (Osten) hin groesser
709                                    // --> positive Verschiebung
710                                    getMapArea().getWidth() / getWidth(),
711                                    // keine Verzerrung
712                                    0.0, 0.0,
713                                    // Waehrend die Fenster-Koordinaten nach unten hin groesser
714                                    // werden,
715                                    // werden Latitude-Koordinaten nach Sueden hin keiner
716                                    // --> negative Verschiebung
717                                    -getMapArea().getHeight() / getHeight(),
718                                    // Die Longitude-Koordinaten werden nach Osten hin groesser
719                                    // --> obere linke Ecke des Fensters hat also den Minimalwert
720                                    getMapArea().getMinX(),
721                                    // Die Latitude-Koordinaten werden nach Norden hin groesser
722                                    // --> obere linke Ecke des Fensters hat also den Maximalwert
723                                    getMapArea().getMaxY());
724    
725                    try {
726                            this.worldToScreen = screenToWorld.createInverse();
727                    } catch (NoninvertibleTransformException e) {
728                            LOGGER.error(e);
729                  }                  }
730          }          }
731    
732            /**
733             * Transformation zwischen Fenster-Koordinaten und Karten-Koordinaten
734             * (lat/lon)
735             */
736            protected AffineTransform screenToWorld = null;
737    
738            private AffineTransform worldToScreen;
739    
740            /**
741             * Listens to changes of the "local" {@link MapContext} and triggers
742             * repaints where needed.
743             */
744            private MapLayerListListener localContextListener = new MapLayerListListener() {
745    
746                    @Override
747                    public void layerAdded(final MapLayerListEvent event) {
748                            event.getLayer().addMapLayerListener(localMapLayerListener);
749    
750                            if (localContext.getLayers().length == 1) { // the first one
751                                    // if the Area of Interest is unset, the LayerBounds are used
752                                    if (!setMapArea(localContext.getAreaOfInterest()))
753                                            repaint();
754    
755                                    return;
756                            }
757    
758                            // We need to redraw, even in case that the mapArea didn't change
759                            // mapImageInvalid = true;
760                            // repaint();
761                            requestStartRendering();
762    
763                    }
764    
765                    @Override
766                    public void layerRemoved(final MapLayerListEvent event) {
767                            if (event.getLayer() != null)
768                                    event.getLayer().removeMapLayerListener(localMapLayerListener);
769                            // mapImageInvalid = true;
770                            // repaint();
771                            requestStartRendering();
772                    }
773    
774                    @Override
775                    public void layerChanged(final MapLayerListEvent event) {
776                            // mapImageInvalid = true;
777                            // repaint();
778                            requestStartRendering();
779                    }
780    
781                    @Override
782                    public void layerMoved(final MapLayerListEvent event) {
783                            // mapImageInvalid = true;
784                            // repaint();
785                            requestStartRendering();
786                    }
787            };
788    
789            /**
790             * Listens to changes of the "background" {@link MapContext} and triggers
791             * repaints where needed.
792             */
793            private MapLayerListListener bgContextListener = new MapLayerListListener() {
794    
795                    @Override
796                    public void layerAdded(final MapLayerListEvent event) {
797                            event.getLayer().addMapLayerListener(bgMapLayerListener);
798    
799                            if (localContext.getLayers().length == 0
800                                            && bgContext.getLayers().length == 1) { // the first one and
801                                    // localContext is
802                                    // empty
803                                    if (!setMapArea(localContext.getAreaOfInterest()))
804                                            requestStartRendering();
805                                    return;
806                            }
807    
808                            // We need to redraw, even in case that the mapArea didn't change
809                            // mapImageInvalid = true;
810                            // repaint();
811                            requestStartRendering();
812    
813                    }
814    
815                    @Override
816                    public void layerRemoved(final MapLayerListEvent event) {
817                            if (event.getLayer() != null)
818                                    event.getLayer().removeMapLayerListener(bgMapLayerListener);
819                            // mapImageInvalid = true;
820                            // repaint();
821                            requestStartRendering();
822                    }
823    
824                    @Override
825                    public void layerChanged(final MapLayerListEvent event) {
826                            // mapImageInvalid = true;
827                            // repaint();
828                            requestStartRendering();
829                    }
830    
831                    @Override
832                    public void layerMoved(final MapLayerListEvent event) {
833                            // mapImageInvalid = true;
834                            // repaint();
835                            requestStartRendering();
836                    }
837            };
838    
839            /**
840             * Listens to each layer in the local {@link MapContext} for changes and
841             * triggers repaints.
842             */
843            protected MapLayerListener localMapLayerListener = new MapLayerAdapter() {
844    
845                    @Override
846                    public void layerShown(MapLayerEvent event) {
847                            // mapImageInvalid = true;
848                            // repaint();
849                            requestStartRendering();
850                    }
851    
852                    @Override
853                    public void layerHidden(MapLayerEvent event) {
854                            // mapImageInvalid = true;
855                            // repaint();
856                            requestStartRendering();
857                    }
858    
859                    @Override
860                    public void layerChanged(MapLayerEvent event) {
861                            // Change of SLD for example
862                            // mapImageInvalid = true;
863                            // repaint();
864                            requestStartRendering();
865                    }
866            };
867    
868            /**
869             * Listens to each layer in the local {@link MapContext} for changes and
870             * triggers repaints.
871             */
872            protected MapLayerListener bgMapLayerListener = new MapLayerAdapter() {
873    
874                    @Override
875                    public void layerShown(MapLayerEvent event) {
876                            // mapImageInvalid = true;
877                            // repaint();
878                            requestStartRendering();
879                    }
880    
881                    @Override
882                    public void layerHidden(MapLayerEvent event) {
883                            // mapImageInvalid = true;
884                            // repaint();
885                            requestStartRendering();
886                    }
887    
888                    @Override
889                    public void layerChanged(MapLayerEvent event) {
890                            // Change of SLD for example
891                            // mapImageInvalid = true;
892                            // repaint();
893                            requestStartRendering();
894                    }
895            };
896    
897            /**
898             * Liefert eine affine Transformation, um von den Fenster-Koordinaten in die
899             * Karten-Koordinaten (Lat/Lon) umzurechnen.
900             *
901             * @return eine Kopie der aktuellen Transformation; <code>null</code> wenn
902             *         noch keine Karte angezeigt wird
903             */
904            public AffineTransform getScreenToWorld() {
905                    if (screenToWorld == null)
906                            resetTransforms();
907                    // nur Kopie der Transformation zurueckgeben!
908                    if (screenToWorld == null)
909                            return null;
910                    return new AffineTransform(screenToWorld);
911            }
912    
913            public AffineTransform getWorldToScreenTransform() {
914                    if (worldToScreen == null) {
915                            resetTransforms();
916                    }
917                    // nur Kopie der Transformation zurueckgeben!
918                    return new AffineTransform(worldToScreen);
919            }
920    
921          public MapContext getContext() {          public MapContext getContext() {
922                  return context;                  if (localContext == null) {
923                            this.localContext = new DefaultMapContext();
924                            this.localContext.addMapLayerListListener(localContextListener);
925                    }
926                    return localContext;
927          }          }
928    
929          public void setContext(final MapContext context) {          public MapContext getBgContext() {
930                  if (this.context != null) {                  return bgContext;
931                          this.context.removeMapLayerListListener(this);          }
932    
933            /**
934             *
935             * @param context
936             */
937            public void setLocalContext(final MapContext context) {
938                    // Remove the default listener from the old context
939                    if (this.localContext != null) {
940                            this.localContext.removeMapLayerListListener(localContextListener);
941    
942                            // adding listener to all layers
943                            for (MapLayer mapLayer : localContext.getLayers()) {
944                                    mapLayer.removeMapLayerListener(localMapLayerListener);
945                            }
946                  }                  }
947    
948                  this.context = context;                  this.localContext = context;
949    
950                  if (context != null) {                  if (context != null) {
951                          this.context.addMapLayerListListener(this);                          setMapArea(localContext.getAreaOfInterest());
952    
953                            this.localContext.addMapLayerListListener(localContextListener);
954    
955                            // adding listener to all layers
956                            for (MapLayer mapLayer : localContext.getLayers()) {
957                                    mapLayer.addMapLayerListener(localMapLayerListener);
958                            }
959                    }
960    
961                    mapImageInvalid = true;
962                    repaint();
963            }
964    
965            public void setBgContext(final MapContext context) {
966    
967                    // Remove the default listener from the old context
968                    if (this.bgContext != null) {
969                            this.bgContext.removeMapLayerListListener(bgContextListener);
970    
971                            // adding listener to all layers
972                            for (MapLayer mapLayer : bgContext.getLayers()) {
973                                    mapLayer.removeMapLayerListener(bgMapLayerListener);
974                            }
975                  }                  }
976    
977                  if (renderer != null) {                  this.bgContext = context;
978                          renderer.setContext(this.context);  
979                    if (context != null) {
980                            setMapArea(bgContext.getAreaOfInterest());
981    
982                            this.bgContext.addMapLayerListListener(bgContextListener);
983    
984                            // adding listener to all layers
985                            for (MapLayer mapLayer : bgContext.getLayers()) {
986                                    mapLayer.addMapLayerListener(bgMapLayerListener);
987                            }
988                  }                  }
989                    mapImageInvalid = true;
990                    repaint();
991          }          }
992    
993            /**
994             * Returns a copy of the mapArea
995             *
996             * @return
997             */
998          public Envelope getMapArea() {          public Envelope getMapArea() {
999                  return mapArea;                  if (mapArea == null) {
1000                            final Rectangle paneBounds = getBounds();
1001    
1002                            try {
1003                                    mapArea = localContext.getLayerBounds();
1004                            } catch (final IOException e) {
1005                                    LOGGER.warn("context.getLayerBounds()", e);
1006                            }
1007    
1008                            if (mapArea != null) {
1009                                    /* either the viewer size has changed or we've done a reset */
1010                                    mapImageInvalid = true; /* note we need to redraw */
1011                                    oldRect = paneBounds; /* store what the current size is */
1012                                    mapArea = bestAllowedMapArea(mapArea);
1013                            }
1014                    }
1015    
1016                    if (mapArea == null)
1017                            return null;
1018    
1019                    return new Envelope(mapArea);
1020          }          }
1021    
1022          public void setMapArea(final Envelope mapArea) {          /**
1023                  this.mapArea = mapArea;           * @param newMapArea
1024             * @return <code>true</code> if the mapArea has been changed and a repaint
1025             *         has been triggered.
1026             */
1027            public boolean setMapArea(final Envelope newMapArea) {
1028    
1029                    if (newMapArea == null
1030                                    || bestAllowedMapArea(newMapArea).equals(mapArea)) {
1031                            // No change.. no need to repaint
1032                            return false;
1033                    }
1034    
1035                    // Testing, whether NaN or Infinity are used in the newMapArea
1036                    if (newMapArea.isNull() || Double.isInfinite(newMapArea.getMaxX())
1037                                    || Double.isInfinite(newMapArea.getMaxY())
1038                                    || Double.isInfinite(newMapArea.getMinX())
1039                                    || Double.isInfinite(newMapArea.getMinY())) {
1040                            // No change.. ugly new values
1041                            LOGGER.warn("setMapArea has been called with newArea = "
1042                                            + newMapArea);
1043                            return false;
1044                    }
1045    
1046                    // Testing, whether the difference if just minimal
1047                    if (mapArea != null) {
1048                            Envelope candNew = bestAllowedMapArea(newMapArea);
1049                            double tolX = mapArea.getWidth() / 1000.;
1050                            double tolY = mapArea.getHeight() / 1000.;
1051                            if ((candNew.getMinX() - tolX < mapArea.getMinX())
1052                                            && (mapArea.getMinX() < candNew.getMinX() + tolX)
1053                                            && (candNew.getMaxX() - tolX < mapArea.getMaxX())
1054                                            && (mapArea.getMaxX() < candNew.getMaxX() + tolX)
1055    
1056                                            && (candNew.getMinY() - tolY < mapArea.getMinY())
1057                                            && (mapArea.getMinY() < candNew.getMinY() + tolY)
1058                                            && (candNew.getMaxY() - tolY < mapArea.getMaxY())
1059                                            && (mapArea.getMaxY() < candNew.getMaxY() + tolY)
1060    
1061                            ) {
1062                                    // The two mapAreas only differ my 1/1000th.. ignore
1063    
1064                                    return false;
1065                            }
1066                    }
1067    
1068                    oldMapArea = mapArea;
1069    
1070                    this.mapArea = bestAllowedMapArea(newMapArea);
1071    
1072                    if (localContext != null) {
1073                            localContext.setAreaOfInterest(mapArea, localContext
1074                                            .getCoordinateReferenceSystem());
1075                    }
1076                    if (bgContext != null) {
1077                            bgContext.setAreaOfInterest(mapArea, localContext
1078                                            .getCoordinateReferenceSystem());
1079                    }
1080                    resetTransforms();
1081                    mapImageInvalid = true;
1082                    mapAreaChanged = true;
1083                    repaint();
1084    
1085    //              LOGGER.debug("New maparea = " + mapArea);
1086                    return true;
1087          }          }
1088    
1089          public int getState() {          public int getState() {
1090                  return state;                  return state;
1091          }          }
1092    
1093            /**
1094             * Enables/Disables the ZOOM Mouse Listener. Upates the Cursor and stops the
1095             * repaint Timer if
1096             *
1097             * @param state
1098             */
1099          public void setState(final int state) {          public void setState(final int state) {
1100                  this.state = state;                  this.state = state;
1101    
1102                  // System.out.println("State: " + state);                  zoomMapPaneMouseListener.setEnabled((state == ZOOM_IN
1103          }                                  || state == ZOOM_OUT || state == PAN));
1104    
1105          public double getZoomFactor() {                  // Je nach Aktion den Cursor umsetzen
1106                  return zoomFactor;                  updateCursor();
1107          }          }
1108    
1109          public void setZoomFactor(final double zoomFactor) {          /** Cursor wenn kein Mausbutton gedrueckt wird. default oder SwingUtil.PAN **/
1110                  this.zoomFactor = zoomFactor;          protected static Cursor normalCursor = Cursor
1111          }                          .getPredefinedCursor(Cursor.DEFAULT_CURSOR);
1112    
1113            public static final Cursor WAIT_CURSOR = Cursor
1114                            .getPredefinedCursor(Cursor.WAIT_CURSOR);
1115    
1116            public static final int NONE = -123;
1117    
1118            private RenderingExecutor localExecuter = new RenderingExecutor(this, 150l);
1119    
1120            private BufferedImage finalImage;
1121    
1122            /**
1123             * A flag set it {@link #setMapArea(Envelope)} to indicated the
1124             * {@link #paintComponent(Graphics)} method, that the image on-screen is
1125             * associated with {@link #oldMapArea} and may hence be scaled for a quick
1126             * preview.<br/>
1127             * The flag is reset
1128             **/
1129            private boolean mapAreaChanged = false;
1130    
1131            private JFrame finalImageFrame;
1132    
1133            private volatile Boolean requestStartRendering = false;
1134            private BufferedImage preFinalImage;
1135    
1136          protected void paintComponent(final Graphics g) {          protected void paintComponent(final Graphics g) {
1137                  super.paintComponent(g);                  // Maybe update the cursor
1138                    updateCursor();
1139    
1140                  if ((renderer == null) || (mapArea == null)) {                  if (!acceptsRepaintCalls)
1141                          return;                          return;
                 }  
1142    
1143                  final Rectangle r = getBounds();                  boolean paintedSomething = false;
                 final Rectangle dr = new Rectangle(r.width, r.height);  
1144    
1145                  if (!r.equals(oldRect) || reset) {                  if (mapImageInvalid) { /* if the map changed then redraw */
1146                          if (!r.equals(oldRect) && (mapArea == null)) {  
1147                                  try {                          mapImageInvalid = false; // Reset for next round
1148                                          mapArea = context.getLayerBounds();  
1149                                  } catch (final IOException e) {                          // If the new mapArea and the oldMapArea intersect, we can draw some
1150                                          LOGGER.warn("context.getLayerBounds()", e);                          // quick scaled preview to make the user feel that something is
1151                            // happening.
1152                            if (mapAreaChanged && oldMapArea != null
1153                                            && getMapArea().intersects(oldMapArea)
1154                                            & !getMapArea().equals(oldMapArea)) {
1155    
1156                                    mapAreaChanged = false;
1157    
1158                                    if (getMapArea().covers(oldMapArea)) {
1159                                            setQuickPreviewHint(ZOOM_OUT);
1160                                            paintedSomething = drawScaledPreviewImage_Zoom((Graphics2D) g);
1161                                    } else if (oldMapArea.covers(getMapArea())) {
1162                                            setQuickPreviewHint(ZOOM_IN);
1163                                            paintedSomething = drawScaledPreviewImage_Zoom((Graphics2D) g);
1164                                  }                                  }
                         }  
1165    
1166                          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 */  
1167    
1168                                  mapArea = JTSUtil.fixAspectRatio(r, mapArea, false);                          if (paneResized) {
1169                                    paneResized = false;
1170                                    preFinalImage = null;
1171                                    finalImage = null;
1172                                    localImage = null;
1173                                    bgImage = null;
1174                                    // gadgetsImage = null;
1175                          }                          }
                 }  
1176    
1177                  if (!mapArea.equals(oldMapArea)) { /* did the map extent change? */                          // Start the Threads and Timers to render the image
1178                          changed = true;                          requestStartRendering();
1179                          oldMapArea = mapArea;  
                         // when we tell the context that the bounds have changed WMSLayers  
                         // can refresh them selves  
                         context.setAreaOfInterest(mapArea, context  
                                         .getCoordinateReferenceSystem());  
1180                  }                  }
1181    
1182                  if (changed) { /* if the map changed then redraw */                  if (!paintedSomething) {
                         changed = false;  
                           
                         // The baseImage should not have alpha  
                         baseImage = new BufferedImage(dr.width, dr.height,  
                                         BufferedImage.TYPE_INT_RGB);  
   
                         final Graphics2D ig = baseImage.createGraphics();  
                         ig.setBackground(getMapBackgroundColor());  
                         ig.fillRect(0, 0, dr.width, dr.height);  
                           
 //                      /* System.out.println("rendering"); */  
                         if (renderer.getContext() != null)  
                                 renderer.setContext(context);  
1183    
1184                          // TODO is this clearing still needed? We already replace all that stuff whenever we change the style. Deactivated 31.10.09.. let's see                          // TODO Should just paint the getFinalImage(). Update should be
1185  //                      labelCache.clear(); // work around anoying labelcache bug                          // called by timer every 300ms, and the repaint() until all threads
1186                            // are done.
1187                            g.drawImage(getFinalImage(), 0, 0, this);
1188    
1189                          // draw the map                          paintedSomething = true;
1190                          renderer.paint(ig, dr, mapArea);                  }
1191    
1192                          // TODO nur machen, wenn panning beginnt          }
                         panningImage = new BufferedImage(dr.width, dr.height,  
                                         BufferedImage.TYPE_INT_RGB);  
1193    
1194                  }          /**
1195             * Cancels all running renderers and sets the flag to start new ones. <br/>
1196             *
1197             * @see #startRenderThreadsTimer
1198             */
1199            private void requestStartRendering() {
1200                    if (bgExecuter != null)
1201                            bgExecuter.cancelTask();
1202                    if (localExecuter != null)
1203                            localExecuter.cancelTask();
1204                    requestStartRendering = true;
1205                    
1206            }
1207    
1208            /**
1209             * Transformiert einen Fenster-Koordinaten-Bereich in Geo-Koordinaten.
1210             *
1211             * @param ox
1212             *            X-Koordinate der VON-Position
1213             * @param oy
1214             *            Y-Koordinate der VON-Position
1215             * @param px
1216             *            X-Koordinate der BIS-Position
1217             * @param py
1218             *            Y-Koordinate der BIS-Position
1219             */
1220            public Envelope tranformWindowToGeo(int ox, int oy, int px, int py) {
1221                    AffineTransform at = getScreenToWorld();
1222                    Point2D geoO = at.transform(new Point2D.Double(ox, oy), null);
1223                    Point2D geoP = at.transform(new Point2D.Double(px, py), null);
1224                    return new Envelope(geoO.getX(), geoP.getX(), geoO.getY(), geoP.getY());
1225            }
1226    
1227                  ((Graphics2D) g).drawImage(baseImage, 0, 0, this);          /**
1228             * Transformiert einen Geo-Koordinaten-Bereich in Fenster-Koordinaten.
1229             *
1230             * @param ox
1231             *            X-Koordinate der VON-Position
1232             * @param oy
1233             *            Y-Koordinate der VON-Position
1234             * @param px
1235             *            X-Koordinate der BIS-Position
1236             * @param py
1237             *            Y-Koordinate der BIS-Position
1238             * @param winToGeotransform
1239             *            Eine Window to Geo transform. If <code>null</code>,
1240             *            {@link #getScreenToWorld()} is used.
1241             */
1242            public Envelope tranformGeoToWindow(double ox, double oy, double px,
1243                            double py, AffineTransform winToGeotransform) {
1244                    AffineTransform at = winToGeotransform == null ? getScreenToWorld()
1245                                    : winToGeotransform;
1246                    Point2D geoO;
1247                    try {
1248                            geoO = at.inverseTransform(new Point2D.Double(ox, oy), null);
1249                            Point2D geoP = at
1250                                            .inverseTransform(new Point2D.Double(px, py), null);
1251                            return new Envelope(geoO.getX(), geoP.getX(), geoO.getY(), geoP
1252                                            .getY());
1253                    } catch (NoninvertibleTransformException e) {
1254                            LOGGER.error(e);
1255                            return new Envelope(ox, oy, px, py);
1256                    }
1257          }          }
1258    
1259          public void mouseClicked(final MouseEvent e) {          /**
1260                  if (mapArea == null)           * Diretly paints scaled preview into the {@link SelectableXMapPane}. Used
1261                          return;           * to give the user something to look at while we are rendering. Method
1262                  // System.out.println("before area "+mapArea+"\nw:"+mapArea.getWidth()+"           * should be called after {@link #setMapArea(Envelope)} has been set to the
1263                  // h:"+mapArea.getHeight());           * new mapArea and transform has been reset.<br/>
1264                  final Rectangle bounds = this.getBounds();           * This method does nothing if the {@link #lastRenderingDuration} is smaller
1265                  final double x = (double) (e.getX());           * then a trashhold.
1266                  final double y = (double) (e.getY());           *
1267                  final double width = mapArea.getWidth();           * @param g
1268                  final double height = mapArea.getHeight();           *            Graphics2D to paint the preview into
1269                  // xulu.sc           *
1270                  // double width2 = mapArea.getWidth() / 2.0;           * @param state
1271                  // double height2 = mapArea.getHeight() / 2.0;           *            Max be {@link #ZOOM_IN} or {@link #ZOOM_OUT}
1272                  final double width2 = width / 2.0;           */
1273                  final double height2 = height / 2.0;          protected boolean drawScaledPreviewImage_Zoom(Graphics2D graphics) {
                 // xulu.ec  
                 final double mapX = ((x * width) / (double) bounds.width)  
                                 + mapArea.getMinX();  
                 final double mapY = (((bounds.getHeight() - y) * height) / (double) bounds.height)  
                                 + mapArea.getMinY();  
1274    
1275                  /*                  if (quickPreviewHint == 0)
1276                   * System.out.println(""+x+"->"+mapX);                          return false;
                  * System.out.println(""+y+"->"+mapY);  
                  */  
1277    
1278                  /*                  graphics.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
1279                   * Coordinate ll = new Coordinate(mapArea.getMinX(), mapArea.getMinY());                                  RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR);
1280                   * Coordinate ur = new Coordinate(mapArea.getMaxX(), mapArea.getMaxY());                  graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
1281                   */                                  RenderingHints.VALUE_ANTIALIAS_OFF);
1282                  double zlevel = 1.0;                  graphics.setRenderingHint(RenderingHints.KEY_RENDERING,
1283                                    RenderingHints.VALUE_RENDER_SPEED);
1284    
1285                  switch (state) {                  if (oldMapArea == null)
1286                  case Pan:                          return false;
                         zlevel = 1.0;  
                         // xulu.sc SK: return here.. a mouselistener is managing the PANNING  
                         // break;  
                         return;  
                         // xulu.ec  
                 case ZoomIn:  
                         zlevel = zoomFactor;  
1287    
1288                          break;                  Rectangle visibleArea = getVisibleRect();
1289    
1290                  case ZoomOut:                  // Calculate the oldMapArea in the current WindowCoordinates:
1291                          zlevel = 1.0 / zoomFactor;                  Envelope oldMapWindow = tranformGeoToWindow(oldMapArea.getMinX(),
1292                                    oldMapArea.getMinY(), oldMapArea.getMaxX(), oldMapArea
1293                                                    .getMaxY(), null);
1294    
1295                          break;                  int xx1 = (int) Math.round(oldMapWindow.getMinX());
1296                  //                  int yy1 = (int) Math.round(oldMapWindow.getMinY());
1297                  // case Select:                  int xx2 = (int) Math.round(oldMapWindow.getMaxX());
1298                  // doSelection(mapX, mapY, selectionLayer);                  int yy2 = (int) Math.round(oldMapWindow.getMaxY());
                 //  
                 // return;  
1299    
1300                  default:                  graphics.drawImage(getPreFinalImage(), xx1, yy1, xx2, yy2,
1301                          return;                                  (int) visibleArea.getMinX(), (int) visibleArea.getMinY(),
1302                  }                                  (int) visibleArea.getMaxX(), (int) visibleArea.getMaxY(),
1303                                    getMapBackgroundColor(), null);
1304    
1305                  final Coordinate ll = new Coordinate(mapX - (width2 / zlevel), mapY                  Rectangle painedArea = new Rectangle(xx1, yy1, xx2 - xx1, yy2 - yy1);
                                 - (height2 / zlevel));  
                 final Coordinate ur = new Coordinate(mapX + (width2 / zlevel), mapY  
                                 + (height2 / zlevel));  
                 // xulu.sc SK: Check for min/max scale  
                 // mapArea = new Envelope(ll, ur);  
                 final Envelope newMapArea = new Envelope(ll, ur);  
                 setMapArea(bestAllowedMapArea(newMapArea));  
                 // xulu.ec  
1306    
1307                  // sk.ec                  SwingUtil.clearAround(graphics, painedArea, visibleArea);
1308    
1309                  // System.out.println("after area "+mapArea+"\nw:"+mapArea.getWidth()+"                  addGadgets(graphics);
                 // h:"+mapArea.getHeight());  
                 repaint();  
         }  
1310    
1311          public void mouseEntered(final MouseEvent e) {                  quickPreviewHint = 0;
1312    
1313                    graphics.dispose();
1314                    
1315                    // Something has been drawn
1316                    return true;
1317          }          }
1318    
1319          public void mouseExited(final MouseEvent e) {          final static Font waitFont = new Font("Arial", Font.BOLD, 30);
1320    
1321            /**
1322             * Paints some optinal stuff into the given {@link Graphics2D}. Usually
1323             * called as the last paint on the mapImage.
1324             */
1325            private void addGadgets(Graphics2D graphics) {
1326    
1327                    if (mapImage != null)
1328                            graphics.drawImage(mapImage, getBounds().width
1329                                            - mapImage.getWidth() - 10, getBounds().height
1330                                            - mapImage.getHeight() - 10, this);
1331    
1332                    // If still rendering, paint a gray shadow or so...
1333                    if (bgExecuter != null && bgExecuter.isRunning()
1334                                    || localExecuter != null && localExecuter.isRunning()) {
1335                            graphics.setColor(Color.BLACK);
1336    
1337                            graphics.setFont(waitFont);
1338                            graphics.drawString("Wait...", 40, 70); //i8n
1339                            
1340                            graphics.setColor(getMapBackgroundColor());
1341                    }
1342    
1343          }          }
1344    
1345          public void mousePressed(final MouseEvent e) {          /**
1346                  startX = e.getX();           * Accumulates all three images
1347                  startY = e.getY();           *
1348                  lastX = 0;           * @return
1349                  lastY = 0;           */
1350            synchronized protected BufferedImage updateFinalImage() {
1351    
1352                    final Graphics2D finalG = (Graphics2D) getFinalImage().getGraphics();
1353                    finalG.setBackground(getMapBackgroundColor());
1354    
1355                    // Render the two map images first, into the preFinalImage
1356                    if (bgExecuter != null)
1357                    {
1358                            final Graphics2D preFinalG = (Graphics2D) getPreFinalImage()
1359                                            .getGraphics();
1360                            preFinalG.setBackground(getMapBackgroundColor());
1361    
1362                            preFinalG.drawImage(getBgImage(), 0, 0, getMapBackgroundColor(),
1363                                            null);
1364                            
1365                            // // Draw the local layers image
1366                            preFinalG.drawImage(getLocalImage(), 0, 0, null);
1367                            preFinalG.dispose();
1368                    } else {
1369                            preFinalImage = getLocalImage();
1370                    }
1371    
1372                    finalG.drawImage(getPreFinalImage(), imageOrigin.x, imageOrigin.y,
1373                                    getMapBackgroundColor(), null);
1374    
1375                    final int finalImageHeight = getFinalImage().getHeight(null);
1376                    final int finalImageWidth = getFinalImage().getWidth(null);
1377    
1378                    Rectangle painedArea = new Rectangle(imageOrigin.x, imageOrigin.y,
1379                                    finalImageWidth, finalImageHeight);
1380                    SwingUtil.clearAround(finalG, painedArea, getVisibleRect());
1381    
1382                    addGadgets(finalG);
1383    
1384                    finalG.dispose();
1385    
1386                    return finalImage;
1387          }          }
1388    
1389          public void mouseReleased(final MouseEvent e) {          private Image getFinalImage() {
                 final int endX = e.getX();  
                 final int endY = e.getY();  
1390    
1391                  processDrag(startX, startY, endX, endY, e);                  if (finalImage == null) {
1392                  lastX = 0;                          finalImage = null;
1393                  lastY = 0;                          Rectangle curPaintArea = getVisibleRect();
1394                            finalImage = new BufferedImage(curPaintArea.width,
1395                                            curPaintArea.height, BufferedImage.TYPE_INT_RGB);
1396    
1397                  /**                          requestStartRendering();
1398                   * Es wird nicht (mehr) gepannt!                  }
1399                   */                  return finalImage;
                 panning_started = false;  
1400          }          }
1401    
1402          public void mouseDragged(final MouseEvent e) {          private Image getPreFinalImage() {
1403                  final Graphics graphics = this.getGraphics();                  if (preFinalImage == null) {
1404                  final int x = e.getX();                          preFinalImage = null;
1405                  final int y = e.getY();                          Rectangle curPaintArea = getVisibleRect();
   
                 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);  
                         }  
1406    
1407                          // move the image with the mouse                          preFinalImage = new BufferedImage(curPaintArea.width,
1408                          if ((lastX > 0) && (lastY > 0)) {                                          curPaintArea.height, BufferedImage.TYPE_INT_RGB);
                                 final int dx = lastX - startX;  
                                 final int dy = lastY - startY;  
                                 // System.out.println("translate "+dx+","+dy);  
                                 final Graphics2D g2 = panningImage.createGraphics();  
                                 g2.setBackground(getMapBackgroundColor());  
   
                                 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) {  
1409    
1410                  /****                          requestStartRendering();
                  * If no layers exist, we ignore the drag.  
                  */  
                 if (context.getLayerCount() <= 0) {  
                         return;  
1411                  }                  }
1412                    return preFinalImage;
1413            }
1414    
1415                  // System.out.println("processing drag from " + x1 + "," + y1 + " -> "          /**
1416                  // + x2 + "," + y2);           * While dragging, the {@link #updateFinalImage()} method is translating the
1417                  if ((x1 == x2) && (y1 == y2)) {           * cached images while setting it together.
1418                          if (isClickable()) {           **/
1419                                  mouseClicked(new MouseEvent(this, 0, new Date().getTime(), 0,          Point imageOrigin = new Point(0, 0);
                                                 x1, y1, y2, false));  
                         }  
1420    
1421            /**
1422             * Starts rendering on one or two threads
1423             */
1424            private void startRendering() {
1425    
1426                    if (!isWellDefined())
1427                          return;                          return;
1428    
1429                    if (bgExecuter != null){
1430                            // Stop all renderers
1431                            bgExecuter.cancelTask();
1432                  }                  }
1433    
1434                  final Rectangle bounds = this.getBounds();                  if (localExecuter != null){
1435                            localExecuter.cancelTask();
1436                    }
1437            
1438                    Rectangle curPaintArea = getVisibleRect();
1439    
1440                  final double mapWidth = mapArea.getWidth();                  labelCache.clear();
                 final double mapHeight = mapArea.getHeight();  
1441    
1442                  final double startX = ((x1 * mapWidth) / (double) bounds.width)                  /**
1443                                  + mapArea.getMinX();                   * We have to set new renderer
1444                  final double startY = (((bounds.getHeight() - y1) * mapHeight) / (double) bounds.height)                   */
                                 + mapArea.getMinY();  
                 final double endX = ((x2 * mapWidth) / (double) bounds.width)  
                                 + mapArea.getMinX();  
                 final double endY = (((bounds.getHeight() - y2) * mapHeight) / (double) bounds.height)  
                                 + mapArea.getMinY();  
   
                 if ((state == JMapPane.Pan) || (e.getButton() == MouseEvent.BUTTON3)) {  
                         // move the image with the mouse  
                         // calculate X offsets from start point to the end Point  
                         final double deltaX1 = endX - startX;  
   
                         // System.out.println("deltaX " + deltaX1);  
                         // new edges  
                         final double left = mapArea.getMinX() - deltaX1;  
                         final double right = mapArea.getMaxX() - deltaX1;  
   
                         // now for Y  
                         final double deltaY1 = endY - startY;  
   
                         // System.out.println("deltaY " + deltaY1);  
                         final double bottom = mapArea.getMinY() - deltaY1;  
                         final double top = mapArea.getMaxY() - deltaY1;  
                         final Coordinate ll = new Coordinate(left, bottom);  
                         final Coordinate ur = new Coordinate(right, top);  
                         // xulu.sc  
                         // mapArea = fixAspectRatio(this.getBounds(), new Envelope(ll, ur));  
   
                         setMapArea(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  
1445    
1446                          drawRectangle(this.getGraphics());                  if (getBgContext() != null) {
1447                          // make the dragged rectangle (in map coords) the new BBOX                          bgExecuter = new RenderingExecutor(this, 333l);
1448                          final double left = Math.min(startX, endX);                          LOGGER.debug("starting bg renderer:");
1449                          final double right = Math.max(startX, endX);                          // /* System.out.println("rendering"); */
1450                          final double bottom = Math.min(startY, endY);                          final GTRenderer createGTRenderer = GTUtil.createGTRenderer(
1451                          final double top = Math.max(startY, endY);                                          bgContext, getRendererHints());
1452                          final Coordinate ll = new Coordinate(left, bottom);                          createGTRenderer.setJava2DHints(getJava2dHints());
1453                          final Coordinate ur = new Coordinate(right, top);                          bgExecuter.submit(getBgContext().getAreaOfInterest(), curPaintArea,
1454                          // xulu.sc                                          (Graphics2D) getBgImage().getGraphics(), createGTRenderer);
1455                    }
1456                          // mapArea = fixAspectRatio(this.getBounds(), new Envelope(ll, ur));  
1457                          setMapArea(bestAllowedMapArea(new Envelope(ll, ur)));                  if (getContext() != null) {
1458    //                      localExecuter = new RenderingExecutor(this, 150l);
1459                          // sk.sc                          LOGGER.debug("starting local renderer:");
1460                           {                          final GTRenderer createGTRenderer = GTUtil.createGTRenderer(
1461                          // // SK tries to paint a preview of the zoom ;-9 aha.... well                                          localContext, getRendererHints());
1462  //                                                        createGTRenderer.setJava2DHints(getJava2dHints());
1463  //                               double reductionFactor = 1/8.;                          localExecuter.submit(getContext().getAreaOfInterest(),
1464  ////                                                                      curPaintArea, (Graphics2D) getLocalImage().getGraphics(),
1465  ////                     BufferedImage reducedBaseImage = new BufferedImage((int)(baseImage.getWidth()*reductionFactor), (int)(baseImage.getHeight()*reductionFactor), BufferedImage.TYPE_INT_RGB);                                          createGTRenderer);
1466  ////                     Graphics2D reducedG = (Graphics2D) reducedBaseImage.getGraphics();                  }
1467  //                       AffineTransform reductionTransform =new AffineTransform();  
1468  //                       reductionTransform.scale(reductionFactor, reductionFactor);                  updateCursor();
 ////                    reducedG.drawImage(baseImage, reductionTransform, null);  
 //                        
 //                       Graphics2D graphics = (Graphics2D) JMapPane.this.getGraphics();  
 ////                     graphics.getTransform().scale(reductionFactor, reductionFactor);  
 //                        
 //                       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();  
         }  
1469    
         private boolean isClickable() {  
                 return clickable;  
1470          }          }
1471    
1472          //          /**
1473          // private org.geotools.styling.Style setupStyle(final int type, final Color           * Lazyly initializes a {@link BufferedImage} for the background renderer.
1474          // color) {           */
1475          // 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;  
         // }  
1476    
1477          public void propertyChange(final PropertyChangeEvent evt) {                  if (bgImage == null) {
1478                  final String prop = evt.getPropertyName();                          Rectangle curPaintArea = getVisibleRect();
1479    
1480                  if (prop.equalsIgnoreCase("crs")) {                          bgImage = new BufferedImage(curPaintArea.width + 1,
1481                          context.setAreaOfInterest(context.getAreaOfInterest(),                                          curPaintArea.height + 1, BufferedImage.TYPE_INT_ARGB);
                                         (CoordinateReferenceSystem) evt.getNewValue());  
1482                  }                  }
1483    
1484                    return bgImage;
1485          }          }
1486    
1487          public boolean isReset() {          /** An (transparent) image to paint over the map in the lower right corner **/
1488                  return reset;          private BufferedImage mapImage = null;
1489    
1490            private boolean acceptsRepaintCalls = true;
1491    
1492            /**
1493             * Get the BufferedImage to use as a flaoting icon in the lower right
1494             * corner.
1495             *
1496             * @return <code>null</code> if the feature is deactivated.
1497             */
1498            public BufferedImage getMapImage() {
1499                    return mapImage;
1500          }          }
1501    
1502          public void setReset(final boolean reset) {          /**
1503                  this.reset = reset;           * Set the BufferedImage to use as a flaoting icon in the lower right corner
1504             *
1505             * @param mapImageIcon
1506             *            <code>null</code> is allowed and deactivates this icon.
1507             */
1508            public void setMapImage(BufferedImage mapImage) {
1509                    this.mapImage = mapImage;
1510          }          }
1511    
1512          public void layerAdded(final MapLayerListEvent event) {          /**
1513                  changed = true;           * Lazyly initializes a {@link BufferedImage} for the background renderer.
1514             */
1515            private BufferedImage getLocalImage() {
1516    
1517                  if (context.getLayers().length == 1) { // the first one                  if (localImage == null) {
1518    
1519                          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();  
                         }  
1520    
1521                          reset = true;                          localImage = new BufferedImage(curPaintArea.width + 1,
1522                                            curPaintArea.height + 1, BufferedImage.TYPE_INT_ARGB);
1523                  }                  }
1524    
1525                  repaint();                  return localImage;
         }  
   
         public void layerRemoved(final MapLayerListEvent event) {  
                 changed = true;  
                 repaint();  
1526          }          }
1527    
         public void layerChanged(final MapLayerListEvent event) {  
                 changed = true;  
                 // System.out.println("layer changed - repaint");  
                 repaint();  
         }  
1528    
1529          public void layerMoved(final MapLayerListEvent event) {          /**
1530                  changed = true;           * Called by the {@linkplain XMapPane.RenderingTask} when rendering has been
1531             * completed Publishes a {@linkplain MapPaneEvent} of type {@code
1532             * MapPaneEvent.Type.RENDERING_STOPPED} to listeners.
1533             *
1534             * @see MapPaneListener#onRenderingStopped(org.geotools.swing.event.MapPaneEvent)
1535             */
1536            public void onRenderingCompleted() {
1537                    repainterTimer.stop();
1538                    updateFinalImage();
1539                  repaint();                  repaint();
1540          }          }
1541    
1542          protected void drawRectangle(final Graphics graphics) {          /**
1543                  // undraw last box/draw new box           * Called by the {@linkplain XMapPane.RenderingTask} when rendering was
1544                  final int left = Math.min(startX, lastX);           * cancelled. Publishes a {@linkplain MapPaneEvent} of type {@code
1545                  final int right = Math.max(startX, lastX);           * MapPaneEvent.Type.RENDERING_STOPPED} to listeners.
1546                  final int top = Math.max(startY, lastY);           *
1547                  final int bottom = Math.min(startY, lastY);           * @see MapPaneListener#onRenderingStopped(org.geotools.swing.event.MapPaneEvent)
1548                  final int width = right - left;           */
1549                  final int height = top - bottom;          public void onRenderingCancelled() {
1550                  // System.out.println("drawing rect("+left+","+bottom+","+ width+","+                  repainterTimer.stop();
1551                  // height+")");                  LOGGER.debug("Rendering cancelled");
                 graphics.drawRect(left, bottom, width, height);  
1552          }          }
1553    
1554          /**          /**
1555           * if clickable is set to true then a single click on the map pane will zoom           * Called by the {@linkplain XMapPane.RenderingTask} when rendering failed.
1556           * or pan the map.           * Publishes a {@linkplain MapPaneEvent} of type {@code
1557             * MapPaneEvent.Type.RENDERING_STOPPED} to listeners.
1558             *
1559             * @param renderingError
1560             *            The error that occured during rendering
1561           *           *
1562           * @param clickable           * @see MapPaneListener#onRenderingStopped(org.geotools.swing.event.MapPaneEvent)
1563           */           */
1564          public void setClickable(final boolean clickable) {          public void onRenderingFailed(Exception renderingError) {
1565                  this.clickable = clickable;                  repainterTimer.stop();
1566                    LOGGER.warn("Rendering failed", renderingError);
1567                    updateFinalImage();
1568                    repaint();
1569    
1570          }          }
1571    
1572          public void mouseMoved(final MouseEvent e) {  
1573            @Override
1574            public void propertyChange(final PropertyChangeEvent evt) {
1575                    final String prop = evt.getPropertyName();
1576    
1577                    if (prop.equalsIgnoreCase("crs")) {
1578                            localContext.setAreaOfInterest(localContext.getAreaOfInterest(),
1579                                            (CoordinateReferenceSystem) evt.getNewValue());
1580                    }
1581          }          }
1582    
         // xulu.sn  
1583          /**          /**
1584           * Korrigiert den {@link Envelope} aka {@code mapArea} auf die beste           * Korrigiert den {@link Envelope} aka {@code mapArea} auf die beste
1585           * erlaubte Flaeche damit die Massstabsbeschaenkungen noch eingehalten           * erlaubte Flaeche damit die Massstabsbeschaenkungen noch eingehalten
# Line 879  public class JMapPane extends JPanel imp Line 1595  public class JMapPane extends JPanel imp
1595                  if (getWidth() == 0)                  if (getWidth() == 0)
1596                          return env;                          return env;
1597                  if (env == null)                  if (env == null)
1598                          return env;                          return null;
1599    
1600                  Envelope newArea = null;                  Envelope newArea = null;
1601    
# Line 888  public class JMapPane extends JPanel imp Line 1604  public class JMapPane extends JPanel imp
1604                   * easily fail. We allow to grow here, because we don't check against                   * easily fail. We allow to grow here, because we don't check against
1605                   * the maxExtend                   * the maxExtend
1606                   */                   */
1607                  env = JTSUtil.fixAspectRatio(this.getBounds(), env, true);                  Rectangle curPaintArea = getVisibleRect();
1608    
1609                    env = JTSUtil.fixAspectRatio(curPaintArea, env, true);
1610    
1611                  final double scale = env.getWidth() / getWidth();                  final double scale = env.getWidth() / getWidth();
1612                  final double centerX = env.getMinX() + env.getWidth() / 2.;                  final double centerX = env.getMinX() + env.getWidth() / 2.;
# Line 1030  public class JMapPane extends JPanel imp Line 1748  public class JMapPane extends JPanel imp
1748                                                          false);                                                          false);
1749                                  }                                  }
1750                          }                          }
   
1751                  }                  }
1752    
1753                  return newArea;                  return newArea;
# Line 1109  public class JMapPane extends JPanel imp Line 1826  public class JMapPane extends JPanel imp
1826    
1827          public Envelope getMaxExtend() {          public Envelope getMaxExtend() {
1828                  if (maxExtend == null) {                  if (maxExtend == null) {
1829                          try {                          final ReferencedEnvelope layerBounds = GTUtil
1830                                  return JTSUtil.fixAspectRatio(this.getBounds(),                                          .getVisibleLayoutBounds(localContext);
1831                                                  // Kartenbereich um 10% vergroessern                          if (layerBounds == null) {
1832                                                  JTSUtil.expandEnvelope(context.getLayerBounds(), 0.1),                                  // TODO Last fallback could be the CRS valid area
1833                                                  true);                                  return null;
                         } catch (IOException e) {  
                                 LOGGER  
                                                 .warn(  
                                                                 "maxExtend == null; failed to getLayerBounds of context",  
                                                                 e);  
1834                          }                          }
1835    
1836                            // Kartenbereich um 10% vergroessern
1837                            return JTSUtil.fixAspectRatio(this.getBounds(), JTSUtil
1838                                            .expandEnvelope(layerBounds, 0.1), true);
1839                  }                  }
1840                  return maxExtend;                  return maxExtend;
1841          }          }
1842    
1843          /**          /**
1844           * Set the background color of the map.           * Set the background color of the map.
1845             *
1846           * @param if <code>null</code>, white is used.           * @param if <code>null</code>, white is used.
1847           */           */
1848          public void setMapBackgroundColor(Color bgColor) {          public void setMapBackgroundColor(Color bgColor) {
1849                  if (bgColor == null) bgColor = Color.WHITE;                  if (bgColor == null)
1850                            bgColor = Color.WHITE;
1851                  this.mapBackgroundColor = bgColor;                  this.mapBackgroundColor = bgColor;
1852          }          }
1853    
1854          /**          /**
1855           * Returns the background {@link Color} of the map pane. Default is white.           * Returns the background {@link Color} of the map pane. Default is white.
1856          **/           **/
1857          public Color getMapBackgroundColor() {          public Color getMapBackgroundColor() {
1858                  return mapBackgroundColor;                  return mapBackgroundColor;
1859          }          }
1860    
1861            /**
1862             *
1863             * @param b
1864             */
1865            public void setPainting(boolean b) {
1866                    acceptsRepaintCalls = b;
1867            }
1868    
1869            /**
1870             * Fuegt der Map einen Listener hinzu.
1871             *
1872             * @param l
1873             *            neuer Listener
1874             */
1875            public void addMapPaneListener(JMapPaneListener l) {
1876                    mapPaneListeners.add(l);
1877            }
1878    
1879            /**
1880             * Liste der angeschlossenen Listener, die auf Aktionen des MapPanes
1881             * lauschen.
1882             */
1883            protected Vector<JMapPaneListener> mapPaneListeners = new Vector<JMapPaneListener>();
1884    
1885            /**
1886             * A flag indicating if dispose() was already called. If true, then further
1887             * use of this {@link SelectableXMapPane} is undefined.
1888             */
1889            private boolean disposed = false;
1890    
1891            /**
1892             * Entfernt einen Listener von der Map.
1893             *
1894             * @param l
1895             *            zu entfernender Listener
1896             */
1897            public void removeMapPaneListener(JMapPaneListener l) {
1898                    mapPaneListeners.remove(l);
1899            }
1900    
1901            /** Stored the time used for the last real rendering in ms. **/
1902            private long lastRenderingDuration = Long.MAX_VALUE;
1903    
1904            // if null, no quick preview will be shown
1905            private int quickPreviewHint = 0;
1906    
1907            /**
1908             * For every rendering thread started,
1909             * {@link GTUtil#createGTRenderer(MapContext)} is called to create a new
1910             * renderer. These Java2D rendering hints are passed to the
1911             * {@link GTRenderer}. The java2dHints are the same for all renderers (bg
1912             * and local).
1913             */
1914            private RenderingHints java2dHints;
1915    
1916            /**
1917             * Returns in milli seconds the time the last rending of the
1918             * {@link SelectableXMapPane} took. #Long.MAX_VALUE if the JMapPane has not
1919             * been rendered yet.
1920             */
1921            public long getLastRenderingDuration() {
1922                    return lastRenderingDuration;
1923            }
1924    
1925            /**
1926             * Should be called when the {@link JMapPane} is not needed no more to help
1927             * the GarbageCollector
1928             *
1929             * Removes all {@link JMapPaneListener}s that are registered
1930             *
1931             * @author <a href="mailto:[email protected]">Stefan Alfons
1932             *         Kr&uuml;ger</a>
1933             */
1934            public void dispose() {
1935                    if (isDisposed())
1936                            return;
1937                    
1938                    
1939                    setPainting(false);
1940    
1941                    disposed = true;
1942    
1943                    if (bgExecuter != null) {
1944                            bgExecuter.cancelTask();
1945                            bgExecuter.dispose();
1946                    }
1947    
1948                    if (localExecuter != null) {
1949                            localExecuter.cancelTask();
1950                            localExecuter.dispose();
1951                    }
1952    
1953                    startRenderThreadsTimer.stop();
1954    
1955                    if (bgImage != null)
1956                            bgImage.flush();
1957                    if (localImage != null)
1958                            localImage.flush();
1959                    if (finalImage != null)
1960                            finalImage.flush();
1961                    if (preFinalImage != null)
1962                            preFinalImage.flush();
1963    
1964                    // Alle mapPaneListener entfernen
1965                    mapPaneListeners.clear();
1966    
1967                    removeMouseMotionListener(zoomMapPaneMouseListener);
1968                    removeMouseListener(zoomMapPaneMouseListener);
1969    
1970                    if (localContext != null)
1971                            getContext().clearLayerList();
1972                    if (bgContext != null)
1973                            getBgContext().clearLayerList();
1974    
1975                    removeAll();
1976            }
1977    
1978            /**
1979             * A flag indicating if dispose() has already been called. If true, then
1980             * further use of this {@link SelectableXMapPane} is undefined.
1981             */
1982            private boolean isDisposed() {
1983                    return disposed;
1984            }
1985    
1986            public void setQuickPreviewHint(int quickPreviewHint) {
1987                    this.quickPreviewHint = quickPreviewHint;
1988    
1989            }
1990    
1991            public void setJava2dHints(RenderingHints java2dHints) {
1992                    this.java2dHints = java2dHints;
1993            }
1994    
1995            public RenderingHints getJava2dHints() {
1996                    return java2dHints;
1997            }
1998    
1999            /**
2000             * Zooms towards a point.
2001             *
2002             * @param center
2003             *            position in window coordinates
2004             * @param zoomFaktor
2005             *            > 1 for zoom in, < 1 for zoom out. Default is 1.33.
2006             */
2007            public void zoomTo(Point center, Double zoomFaktor) {
2008                    if (zoomFaktor == null || zoomFaktor == 0.)
2009                            zoomFaktor = 2.;
2010    
2011                    Point2D gcenter = getScreenToWorld().transform(center, null);
2012                    center = null;
2013    
2014                    if (Double.isNaN(gcenter.getX()) || Double.isNaN(gcenter.getY())
2015                                    || Double.isInfinite(gcenter.getX())
2016                                    || Double.isInfinite(gcenter.getY())
2017    
2018                    ) {
2019                            // Not inside valid CRS area! cancel
2020                            return;
2021                    }
2022    
2023                    final Envelope mapArea = getMapArea();
2024    
2025                    Envelope newMapArea = new Envelope(mapArea);
2026                    newMapArea.expandBy((mapArea.getWidth() * zoomFaktor - mapArea
2027                                    .getWidth()) / 2., (mapArea.getHeight() * zoomFaktor - mapArea
2028                                    .getHeight()) / 2.);
2029    
2030                    // Move the newMapArea above the new center
2031                    newMapArea.translate(gcenter.getX() - mapArea.centre().x, gcenter
2032                                    .getY()
2033                                    - mapArea.centre().y);
2034    
2035                    setMapArea(newMapArea);
2036            }
2037    
2038            /**
2039             * Zooms towards a point.
2040             *
2041             * @param center
2042             *            position in window coordinates
2043             * @param zoomFactor
2044             *            > 1 for zoom in, < 1 for zoom out. Default is 1.33
2045             */
2046            public void zoomTo(Point center) {
2047                    zoomTo(center, null);
2048            }
2049    
2050            public void mouseDragged(Point startPos, Point lastPos, MouseEvent event) {
2051    
2052                    if ((getState() == XMapPane.PAN)
2053                                    || ((event.getModifiersEx() & InputEvent.BUTTON3_DOWN_MASK) != 0)) {
2054    
2055                            if (getCursor() != SwingUtil.PANNING_CURSOR) {
2056                                    setCursor(SwingUtil.PANNING_CURSOR);
2057    
2058                                    // While panning, we deactivate the rendering. So the tasts are
2059                                    // ready to start when the panning os done.
2060                                    if (bgExecuter != null)
2061                                            bgExecuter.cancelTask();
2062                                    if (localExecuter != null)
2063                                            localExecuter.cancelTask();
2064                            }
2065    
2066                            if (lastPos.x > 0 && lastPos.y > 0) {
2067                                    final int dx = event.getX() - lastPos.x;
2068                                    final int dy = event.getY() - lastPos.y;
2069    
2070                                    // TODO Stop dragging when the drag would not be valid...
2071                                    // boolean dragValid = true;
2072                                    // // check if this panning results in a valid mapArea
2073                                    // {
2074                                    // Rectangle winBounds = xMapPane.getBounds();
2075                                    // winBounds.translate(xMapPane.imageOrigin.x,
2076                                    // -xMapPane.imageOrigin.y);
2077                                    // Envelope newMapAreaBefore = xMapPane.tranformWindowToGeo(
2078                                    // winBounds.x, winBounds.y, winBounds.x
2079                                    // + winBounds.width, winBounds.y
2080                                    // + winBounds.height);
2081                                    //                                      
2082                                    //
2083                                    // winBounds = xMapPane.getBounds();
2084                                    // Point testIng = new Point(xMapPane.imageOrigin);
2085                                    // testIng.translate(dx, dy);
2086                                    // winBounds.translate(testIng.x, -testIng.y);
2087                                    // Envelope newMapAreaAfter = xMapPane.tranformWindowToGeo(
2088                                    // winBounds.x, winBounds.y, winBounds.x
2089                                    // + winBounds.width, winBounds.y
2090                                    // + winBounds.height);
2091                                    //
2092                                    // // If the last drag doesn't change the MapArea anymore cancel
2093                                    // it.
2094                                    // if (xMapPane.bestAllowedMapArea(newMapAreaAfter).equals(
2095                                    // xMapPane.bestAllowedMapArea(newMapAreaBefore))){
2096                                    // dragValid = false;
2097                                    // return;
2098                                    // }
2099                                    // }
2100    
2101                                    imageOrigin.translate(dx, dy);
2102                                    updateFinalImage();
2103                                    repaint();
2104                            }
2105    
2106                    } else if ((getState() == XMapPane.ZOOM_IN)
2107                                    || (getState() == XMapPane.ZOOM_OUT)
2108                                    || (getState() == XMapPane.SELECT_ALL)
2109                                    || (getState() == XMapPane.SELECT_TOP)
2110                    // || (getState() == XMapPane.SELECT_ONE_FROM_TOP)
2111                    ) {
2112                            final Graphics graphics = getGraphics();
2113    
2114                            drawRectangle(graphics, startPos, event.getPoint());
2115    
2116                            if ((lastPos.x > 0) && (lastPos.y > 0)) {
2117                                    drawRectangle(graphics, startPos, lastPos);
2118                            }
2119    
2120                    }
2121    
2122            }
2123    
2124            /**
2125             * Draws a rectangle in XOR mode from the origin at {@link #startPos} to the
2126             * given point. All in screen coordinates.
2127             */
2128            protected void drawRectangle(final Graphics graphics, Point startPos,
2129                            Point e) {
2130                    
2131                    if (!isWellDefined()) return;
2132                    
2133                    // undraw last box/draw new box
2134                    final int left = Math.min(startPos.x, e.x);
2135                    final int right = Math.max(startPos.x, e.x);
2136                    final int top = Math.max(startPos.y, e.y);
2137                    final int bottom = Math.min(startPos.y, e.y);
2138                    final int width = right - left;
2139                    final int height = top - bottom;
2140    
2141                    if (width == 0 && height == 0)
2142                            return;
2143    
2144                    graphics.setXORMode(Color.WHITE);
2145                    graphics.drawRect(left, bottom, width, height);
2146            }
2147    
2148            /**
2149             * Finalizes a PAN action
2150             */
2151            public void performPan() {
2152                    Rectangle winBounds = getBounds();
2153                    winBounds.translate(-imageOrigin.x, -imageOrigin.y);
2154                    Envelope newMapArea = tranformWindowToGeo(winBounds.x, winBounds.y,
2155                                    winBounds.x + winBounds.width, winBounds.y + winBounds.height);
2156    
2157                    imageOrigin.x = 0;
2158                    imageOrigin.y = 0;
2159    
2160                    if (!setMapArea(newMapArea)) {
2161                            updateFinalImage();
2162                            repaint();
2163                    }
2164    
2165                    if (getCursor() == SwingUtil.PANNING_CURSOR)
2166                            setCursor(SwingUtil.PAN_CURSOR);
2167            }
2168    
2169            public void onRenderingPending() {
2170    //              LOGGER.debug("Pending rendering updates the preview...");
2171                    updateFinalImage();
2172                    repaint();
2173            }
2174    
2175  }  }

Legend:
Removed from v.505  
changed lines
  Added in v.524

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26