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

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

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

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

Legend:
Removed from v.148  
changed lines
  Added in v.511

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26