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

Legend:
Removed from v.207  
changed lines
  Added in v.514

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26