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

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

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

branches/1.0-gt2-2.6/src/skrueger/geotools/XMapPane.java revision 536 by alfonx, Fri Nov 20 15:38:34 2009 UTC branches/2.0-RC2/src/skrueger/geotools/XMapPane.java revision 677 by alfonx, Fri Feb 5 15:03:17 2010 UTC
# Line 13  import java.awt.event.ActionEvent; Line 13  import java.awt.event.ActionEvent;
13  import java.awt.event.ActionListener;  import java.awt.event.ActionListener;
14  import java.awt.event.ComponentAdapter;  import java.awt.event.ComponentAdapter;
15  import java.awt.event.ComponentEvent;  import java.awt.event.ComponentEvent;
 import java.awt.event.InputEvent;  
16  import java.awt.event.MouseEvent;  import java.awt.event.MouseEvent;
17  import java.awt.event.MouseListener;  import java.awt.event.MouseListener;
18  import java.awt.geom.AffineTransform;  import java.awt.geom.AffineTransform;
# Line 26  import java.util.HashMap; Line 25  import java.util.HashMap;
25  import java.util.Map;  import java.util.Map;
26  import java.util.Vector;  import java.util.Vector;
27    
28    import javax.swing.JList;
29  import javax.swing.Timer;  import javax.swing.Timer;
30    import javax.swing.border.Border;
31    
32  import org.apache.log4j.Logger;  import org.apache.log4j.Logger;
33    import org.geotools.factory.GeoTools;
34  import org.geotools.feature.FeatureCollection;  import org.geotools.feature.FeatureCollection;
35  import org.geotools.geometry.Envelope2D;  import org.geotools.geometry.DirectPosition2D;
36  import org.geotools.geometry.jts.JTS;  import org.geotools.geometry.jts.JTS;
37  import org.geotools.geometry.jts.ReferencedEnvelope;  import org.geotools.geometry.jts.ReferencedEnvelope;
38  import org.geotools.map.DefaultMapContext;  import org.geotools.map.DefaultMapContext;
# Line 44  import org.geotools.referencing.CRS; Line 46  import org.geotools.referencing.CRS;
46  import org.geotools.renderer.GTRenderer;  import org.geotools.renderer.GTRenderer;
47  import org.geotools.renderer.label.LabelCacheImpl;  import org.geotools.renderer.label.LabelCacheImpl;
48  import org.geotools.renderer.lite.LabelCache;  import org.geotools.renderer.lite.LabelCache;
49    import org.geotools.renderer.lite.RendererUtilities;
50  import org.geotools.renderer.lite.StreamingRenderer;  import org.geotools.renderer.lite.StreamingRenderer;
51    import org.geotools.resources.image.ImageUtilities;
52  import org.geotools.swing.JMapPane;  import org.geotools.swing.JMapPane;
53  import org.geotools.swing.event.MapMouseEvent;  import org.geotools.swing.event.MapMouseEvent;
54  import org.geotools.swing.event.MapPaneEvent;  import org.geotools.swing.event.MapPaneEvent;
# Line 65  import schmitzm.geotools.map.event.MapLa Line 69  import schmitzm.geotools.map.event.MapLa
69  import schmitzm.lang.LangUtil;  import schmitzm.lang.LangUtil;
70  import schmitzm.swing.JPanel;  import schmitzm.swing.JPanel;
71  import schmitzm.swing.SwingUtil;  import schmitzm.swing.SwingUtil;
72    import schmitzm.swing.event.MouseInputType;
73    
74  import com.vividsolutions.jts.geom.Coordinate;  import com.vividsolutions.jts.geom.Coordinate;
75  import com.vividsolutions.jts.geom.Envelope;  import com.vividsolutions.jts.geom.Envelope;
# Line 95  import com.vividsolutions.jts.geom.Geome Line 100  import com.vividsolutions.jts.geom.Geome
100   */   */
101  public class XMapPane extends JPanel {  public class XMapPane extends JPanel {
102    
103          private static final int IMAGETYPE = BufferedImage.TYPE_INT_RGB;          /**
104          private static final int IMAGETYPE_withAlpha = BufferedImage.TYPE_INT_ARGB;           * If {@link #maxExtend} is <code>null</code> the following rules are used
105             * to create a default maximum.
106             * <ul>
107             * <li>Values &lt; 0 : don't grow to fit the monitors aspect ratio, no
108             * margin</li>
109             * <li>Values 0 : grow to fit the monitors aspect ratio, no margin</li>
110             * <li>Values &gt; 0 : grow to fit the monitors aspect ratio, and add a
111             * relative margin</li>
112             * </ul>
113             * **/
114            private double defaultMaxMapExtendMode = .05;
115    
116            // private static final int IMAGETYPE = BufferedImage.TYPE_INT_RGB;
117            // private static final int IMAGETYPE_withAlpha =
118            // BufferedImage.TYPE_INT_ARGB;
119            private static final int IMAGETYPE = BufferedImage.TYPE_3BYTE_BGR;
120    
121            public XMapPaneTool getTool() {
122                    return tool;
123            }
124    
125          private static Logger LOGGER = Logger.getLogger(XMapPane.class);          private static final int IMAGETYPE_withAlpha = BufferedImage.TYPE_4BYTE_ABGR;
126    
127            private final static Logger LOGGER = Logger.getLogger(XMapPane.class);
128    
129            /**
130             * A flag indicating whether the {@link XMapPane} is accepting repaints from
131             * the EDT. @see {@link XMapPane#setPainting(boolean))
132             **/
133          private boolean acceptsRepaintCalls = true;          private boolean acceptsRepaintCalls = true;
134    
135          /**          /**
# Line 124  public class XMapPane extends JPanel { Line 154  public class XMapPane extends JPanel {
154           * regularly and {@link #repaint()}. This {@link Timer} is stopped when all           * regularly and {@link #repaint()}. This {@link Timer} is stopped when all
155           * renderers have finished.           * renderers have finished.
156           *           *
157           * @see #INITIAL_REPAINT_DELAYAL           * @see INITIAL_REPAINT_DELAYAL
158           * @see #REPEATING_REPAINT_DELAY           * @see #REPEATING_REPAINT_DELAY
159           */           */
160          final private Timer repaintTimer;          final private Timer repaintTimer;
# Line 133  public class XMapPane extends JPanel { Line 163  public class XMapPane extends JPanel {
163           * The initial delay in milliseconds until the {@link #finalImage} is           * The initial delay in milliseconds until the {@link #finalImage} is
164           * updated the first time.           * updated the first time.
165           */           */
166          public static final int INITIAL_REPAINT_DELAY = 1000;          public static final int INITIAL_REPAINT_DELAY = 900;
167    
168          /**          /**
169           * While the {@link #bgExecuter} and {@link #localExecuter} are rendering,           * While the {@link #bgExecuter} and {@link #localExecuter} are rendering,
170           * the {@link #repaintTimer} is regularly updating the {@link #finalImage}           * the {@link #repaintTimer} is regularly updating the {@link #finalImage}
171           * with previews.           * with previews.
172           */           */
173          public static final long REPEATING_REPAINT_DELAY = 500;          public static final int REPEATING_REPAINT_DELAY = 500;
174    
175          /**          /**
176           * Default delay (milliseconds) before the map will be redrawn when resizing           * Default delay (milliseconds) before the map will be redrawn when resizing
177           * the pane. This is to avoid flickering while drag-resizing.           * the pane. This is to avoid flickering while drag-resizing.
178             *
179             * @see #resizeTimer
180           */           */
181          public static final int DEFAULT_RESIZING_PAINT_DELAY = 500;          public static final int DEFAULT_RESIZING_PAINT_DELAY = 600;
   
         public static final int NONE = -123;  
182    
183          /**          /**
184           * Flag fuer Modus "Kartenausschnitt bewegen". Nicht fuer Window-Auswahl           * This not-repeating {@link Timer} is re-started whenever the component is
185           * moeglich!           * resized. That means => only if the component is not resizing for
186           *           * {@link #DEFAULT_RESIZING_PAINT_DELAY} milliseconds, does the
187           * @see #setState(int)           * {@link XMapPane} react.
188           */           */
189          public static final int PAN = 1;          private final Timer resizeTimer;
190    
191          /**          /**
192           * Flag fuer Modus "SimpleFeature-Auswahl auf allen (sichtbaren) Layern".           * Flag for no-tool.
          *  
          * @see #setState(int)  
          * @see #setState(int)  
193           */           */
194          public static final int SELECT_ALL = 103;          public static final int NONE = -123;
195            //
196            // /**
197            // * Flag fuer Modus "Kartenausschnitt bewegen". Nicht fuer Window-Auswahl
198            // * moeglich!
199            // *
200            // * @see #setState(int)
201            // */
202            // public static final int PAN = 1;
203            //
204            // /**
205            // * Flag fuer Modus "Heran zoomen".
206            // *
207            // * @see #setState(int)
208            // * @see #setState(int)
209            // */
210            // public static final int ZOOM_IN = 2;
211            //
212            // /**
213            // * Flag fuer Modus "Heraus zoomen". Nicht fuer Window-Auswahl moeglich!
214            // *
215            // * @see #setState(int)
216            // */
217            // public static final int ZOOM_OUT = 3;
218    
219          /**          /**
220           * Flag fuer Modus           * {@link Font} used to paint the wait messages into the map
          * "Auswahl nur eines Features, das erste sichtbare von Oben".  
221           *           *
222           * @see #setState(int)           * @see #addGadgets(Graphics2D, boolean)
          * @see #setState(int)  
223           */           */
224          public static final int SELECT_ONE_FROM_TOP = 104;          final static Font waitFont = new Font("Arial", Font.BOLD, 28);
225    
226          /**          /**
227           * Flag fuer Modus           * {@link Font} used to paint error messages into the map
          * "SimpleFeature-Auswahl auf dem obersten (sichtbaren) Layer".  
228           *           *
229           * @see #setState(int)           * @see #addGadgets(Graphics2D, boolean)
          * @see #setState(int)  
230           */           */
         public static final int SELECT_TOP = 4;  
   
         public static final Cursor WAIT_CURSOR = Cursor  
                         .getPredefinedCursor(Cursor.WAIT_CURSOR);  
   
         final static Font waitFont = new Font("Arial", Font.BOLD, 30);  
         final String waitMsg = SwingUtil.R("WaitMess");  
231          final static Font errorFont = new Font("Arial", Font.BOLD, 13);          final static Font errorFont = new Font("Arial", Font.BOLD, 13);
232    
233          /**          /**
234           * Flag fuer Modus "Heran zoomen".           * If last average last two renderings took more than that many ms, show the
235           *           * user a scaled preview
236           * @see #setState(int)           **/
237           * @see #setState(int)          private static final long PRESCALE_MINTIME = 230;
          */  
         public static final int ZOOM_IN = 2;  
238    
239          /**          /**
240           * Flag fuer Modus "Heraus zoomen". Nicht fuer Window-Auswahl moeglich!           * The wait message painted into the map while rendering is going on on
241             * another thread.
242           *           *
243           * @see #setState(int)           * @see #addGadgets(Graphics2D, boolean)
244           */           */
245          public static final int ZOOM_OUT = 3;          final String waitMsg = SwingUtil.R("WaitMess");
246    
247          /**          /**
248           * Konvertiert die Maus-Koordinaten (relativ zum <code>JMapPane</code>) in           * Konvertiert die Maus-Koordinaten (relativ zum <code>JMapPane</code>) in
# Line 211  public class XMapPane extends JPanel { Line 251  public class XMapPane extends JPanel {
251           * @param e           * @param e
252           *            Maus-Ereignis           *            Maus-Ereignis
253           */           */
254          public static Point2D getMapCoordinatesFromEvent(final MouseEvent e) {          public static DirectPosition2D getMapCoordinatesFromEvent(final MouseEvent e) {
255                  // aktuelle Geo-Position aus GeoMouseEvent ermitteln                  // aktuelle Geo-Position aus GeoMouseEvent ermitteln
256                  if (e != null && e instanceof MapMouseEvent)                  if (e != null && e instanceof MapMouseEvent)
257                          try {                          try {
258                                  return ((MapMouseEvent) e).getMapPosition().toPoint2D();                                  return ((MapMouseEvent) e).getMapPosition();
259                          } catch (final Exception err) {                          } catch (final Exception err) {
260                                  LOGGER                                  LOGGER
261                                                  .error(                                                  .error(
# Line 232  public class XMapPane extends JPanel { Line 272  public class XMapPane extends JPanel {
272                                  return null;                                  return null;
273    
274                          final AffineTransform at = xMapPane.getScreenToWorld();                          final AffineTransform at = xMapPane.getScreenToWorld();
275                          if (at != null)                          if (at != null) {
276                                  return at.transform(e.getPoint(), null);                                  Point2D transformed = at.transform(e.getPoint(), null);
277                                    return new DirectPosition2D(xMapPane.getMapContext()
278                                                    .getCoordinateReferenceSystem(), transformed.getX(),
279                                                    transformed.getY());
280                            }
281                          return null;                          return null;
282                  }                  }
283                  throw new IllegalArgumentException(                  throw new IllegalArgumentException(
# Line 248  public class XMapPane extends JPanel { Line 292  public class XMapPane extends JPanel {
292    
293                  @Override                  @Override
294                  public void layerAdded(final MapLayerListEvent event) {                  public void layerAdded(final MapLayerListEvent event) {
295                            final MapLayer layer = event.getLayer();
                         MapLayer layer = event.getLayer();  
   
296                          layer.addMapLayerListener(bgMapLayerListener);                          layer.addMapLayerListener(bgMapLayerListener);
   
                         if (localContext.getLayers().length == 0  
                                         && bgContext.getLayers().length == 1) { // the first one and  
                                 // localContext is  
                                 // empty  
                                 if (!setMapArea(localContext.getAreaOfInterest()))  
                                         requestStartRendering();  
                                 return;  
                         }  
   
                         // We need to redraw, even in case that the mapArea didn't change  
                         // mapImageInvalid = true;  
                         // repaint();  
297                          requestStartRendering();                          requestStartRendering();
   
298                  }                  }
299    
300                  @Override                  @Override
301                  public void layerChanged(final MapLayerListEvent event) {                  public void layerChanged(final MapLayerListEvent event) {
                         // mapImageInvalid = true;  
                         // repaint();  
302                          requestStartRendering();                          requestStartRendering();
303                  }                  }
304    
305                  @Override                  @Override
306                  public void layerMoved(final MapLayerListEvent event) {                  public void layerMoved(final MapLayerListEvent event) {
                         // mapImageInvalid = true;  
                         // repaint();  
307                          requestStartRendering();                          requestStartRendering();
308                  }                  }
309    
# Line 287  public class XMapPane extends JPanel { Line 311  public class XMapPane extends JPanel {
311                  public void layerRemoved(final MapLayerListEvent event) {                  public void layerRemoved(final MapLayerListEvent event) {
312                          if (event.getLayer() != null)                          if (event.getLayer() != null)
313                                  event.getLayer().removeMapLayerListener(bgMapLayerListener);                                  event.getLayer().removeMapLayerListener(bgMapLayerListener);
                         // mapImageInvalid = true;  
                         // repaint();  
314                          requestStartRendering();                          requestStartRendering();
315                  }                  }
316          };          };
317    
318          /**          /**
319           * compass and icon are rendered into this image           * This {@link RenderingExecutor} manages the creation and cancellation of
320             * up to one {@link Thread} for rendering the {@link #localContext}.
321           */           */
322          // protected BufferedImage gadgetsImage;          private final RenderingExecutor localExecuter = new RenderingExecutor(this);
323    
324            /**
325             * This {@link RenderingExecutor} manages the creation and cancellation of
326             * up to one {@link Thread} for rendering the {@link #bgContext}.
327             */
328          protected RenderingExecutor bgExecuter;          protected RenderingExecutor bgExecuter;
329    
330          /**          /**
331           * The Renderer for the LocalLayers uses this Image. When set to null,           * The {@link #localRenderer} for the {@link #localContext} uses this
332           * please dispose this {@link Graphics2D}           * {@link Image}.
333           */           */
334          private BufferedImage localImage;          private BufferedImage localImage;
335    
         private BufferedImage finalImage;  
336          /**          /**
337           * If # {@link #bgExecuter} is using {@link #bgRenderer} for the Background           * The {@link #bgRenderer} for the {@link #bgContext} uses this
338           * uses this Image. When set to null, please dispose the {@link Graphics2D}           * {@link Image}.
339           */           */
340          private BufferedImage bgImage;          private BufferedImage bgImage;
341    
342          /**          /**
343             * This {@link Image} is a merge of the {@link #bgImage},
344             * {@link #localImage} and {@link #addGadgets(Graphics2D, boolean)}. It is
345             * updated with {@link #updateFinalImage()} and used for painting in
346             * {@link #paintComponent(Graphics)}
347             */
348            private BufferedImage finalImage;
349    
350            /**
351           * Optionally a transparent image to paint over the map in the lower right           * Optionally a transparent image to paint over the map in the lower right
352           * corner.           * corner.
353           *           *
# Line 330  public class XMapPane extends JPanel { Line 364  public class XMapPane extends JPanel {
364    
365                  @Override                  @Override
366                  public void layerChanged(final MapLayerEvent event) {                  public void layerChanged(final MapLayerEvent event) {
                         // Change of SLD for example  
                         // mapImageInvalid = true;  
                         // repaint();  
367                          requestStartRendering();                          requestStartRendering();
368                  }                  }
369    
370                  @Override                  @Override
371                  public void layerHidden(final MapLayerEvent event) {                  public void layerHidden(final MapLayerEvent event) {
                         // mapImageInvalid = true;  
                         // repaint();  
372                          requestStartRendering();                          requestStartRendering();
373                  }                  }
374    
375                  @Override                  @Override
376                  public void layerShown(final MapLayerEvent event) {                  public void layerShown(final MapLayerEvent event) {
                         // mapImageInvalid = true;  
                         // repaint();  
377                          requestStartRendering();                          requestStartRendering();
378                  }                  }
379          };          };
# Line 361  public class XMapPane extends JPanel { Line 388  public class XMapPane extends JPanel {
388           * While dragging, the {@link #updateFinalImage()} method is translating the           * While dragging, the {@link #updateFinalImage()} method is translating the
389           * cached images while setting it together.           * cached images while setting it together.
390           **/           **/
391          Point imageOrigin = new Point(0, 0);          private final Point imageOrigin = new Point(0, 0);
392          /**          /**
393           * For every rendering thread started,           * For every rendering thread started,
394           * {@link GTUtil#createGTRenderer(MapContext)} is called to create a new           * {@link GTUtil#createGTRenderer(MapContext)} is called to create a new
# Line 383  public class XMapPane extends JPanel { Line 410  public class XMapPane extends JPanel {
410                  public void layerAdded(final MapLayerListEvent event) {                  public void layerAdded(final MapLayerListEvent event) {
411                          event.getLayer().addMapLayerListener(localMapLayerListener);                          event.getLayer().addMapLayerListener(localMapLayerListener);
412    
413                          localRenderer.setContext(getContext());                          getLocalRenderer().setContext(getMapContext());
   
                         if (localContext.getLayers().length == 1) { // the first one  
                                 // if the Area of Interest is unset, the LayerBounds are used  
                                 if (!setMapArea(localContext.getAreaOfInterest()))  
                                         repaint();  
   
                                 return;  
                         }  
   
                         // We need to redraw, even in case that the mapArea didn't change  
                         // mapImageInvalid = true;  
                         // repaint();  
414                          requestStartRendering();                          requestStartRendering();
415    
416                  }                  }
417    
418                  @Override                  @Override
419                  public void layerChanged(final MapLayerListEvent event) {                  public void layerChanged(final MapLayerListEvent event) {
420                          // mapImageInvalid = true;                          // getLocalRenderer().setContext(getMapContext()); geht doch auch
421                          // repaint();                          // ohne?!?!? wow...
                         localRenderer.setContext(getContext());  
422                          requestStartRendering();                          requestStartRendering();
423                  }                  }
424    
425                  @Override                  @Override
426                  public void layerMoved(final MapLayerListEvent event) {                  public void layerMoved(final MapLayerListEvent event) {
427                          // mapImageInvalid = true;                          getLocalRenderer().setContext(getMapContext());
                         // repaint();  
                         localRenderer.setContext(getContext());  
428                          requestStartRendering();                          requestStartRendering();
429                  }                  }
430    
# Line 420  public class XMapPane extends JPanel { Line 432  public class XMapPane extends JPanel {
432                  public void layerRemoved(final MapLayerListEvent event) {                  public void layerRemoved(final MapLayerListEvent event) {
433                          if (event.getLayer() != null)                          if (event.getLayer() != null)
434                                  event.getLayer().removeMapLayerListener(localMapLayerListener);                                  event.getLayer().removeMapLayerListener(localMapLayerListener);
435                          // mapImageInvalid = true;                          getLocalRenderer().setContext(getMapContext());
                         // repaint();  
                         localRenderer.setContext(getContext());  
436                          requestStartRendering();                          requestStartRendering();
437                  }                  }
438          };          };
439    
         private final RenderingExecutor localExecuter = new RenderingExecutor(this);  
   
440          /**          /**
441           * Listens to each layer in the local {@link MapContext} for changes and           * Listens to each layer in the local {@link MapContext} for changes and
442           * triggers repaints.           * triggers repaints. We don't have to listen layerChanged, because that is
443             * already done in {@link #localContextListener}
444           */           */
445          protected MapLayerListener localMapLayerListener = new MapLayerAdapter() {          protected MapLayerListener localMapLayerListener = new MapLayerAdapter() {
446    
447                  @Override                  // @Override
448                  public void layerChanged(final MapLayerEvent event) {                  // public void layerChanged(final MapLayerEvent event) {
449                          localRenderer.setContext(getContext()); // betters for SLD changes?!                  // // getLocalRenderer().setContext(getMapContext()); // betters for SLD
450                          // Change of SLD for example                  // // // changes?!
451                          // mapImageInvalid = true;                  // // requestStartRendering();
452                          // repaint();                  // }
                         requestStartRendering();  
                 }  
453    
454                  @Override                  @Override
455                  public void layerHidden(final MapLayerEvent event) {                  public void layerHidden(final MapLayerEvent event) {
                         // mapImageInvalid = true;  
                         // repaint();  
456                          requestStartRendering();                          requestStartRendering();
457                  }                  }
458    
459                  @Override                  @Override
460                  public void layerShown(final MapLayerEvent event) {                  public void layerShown(final MapLayerEvent event) {
                         // mapImageInvalid = true;  
                         // repaint();  
461                          requestStartRendering();                          requestStartRendering();
462                  }                  }
463          };          };
464    
465          private final GTRenderer localRenderer = GTUtil.createGTRenderer();          final private GTRenderer localRenderer = GTUtil.createGTRenderer();
466    
467          private final GTRenderer bgRenderer = GTUtil.createGTRenderer();          private final GTRenderer bgRenderer = GTUtil.createGTRenderer();
468    
# Line 480  public class XMapPane extends JPanel { Line 483  public class XMapPane extends JPanel {
483          /**          /**
484           * This color is used as the default background color when painting a map.           * This color is used as the default background color when painting a map.
485           */           */
486          private Color mapBackgroundColor = Color.WHITE;          private Color mapBackgroundColor = null;
487    
488          /**          /**
489           * A flag indicating that the shown image is invalid and needs to be           * A flag indicating that the shown image is invalid and needs to be
# Line 524  public class XMapPane extends JPanel { Line 527  public class XMapPane extends JPanel {
527           * A flag indicating, that the image size has changed and the buffered           * A flag indicating, that the image size has changed and the buffered
528           * images are not big enough any more           * images are not big enough any more
529           **/           **/
530          protected boolean paneResized = false;          protected boolean paneResized = true;
531    
532          private BufferedImage preFinalImage;          private BufferedImage preFinalImage;
533    
534          // if null, no quick preview will be shown          // ** if 0, no quick preview will be shown **/
535          private int quickPreviewHint = 0;          // private int quickPreviewHint = 0;
536    
537          private Map<Object, Object> rendererHints = GTUtil          private Map<Object, Object> rendererHints = GTUtil
538                          .getDefaultGTRendererHints(localRenderer);                          .getDefaultGTRendererHints(getLocalRenderer());
539    
540            /**
541             * If set to <code>true</code>, the {@link #startRenderThreadsTimer} will
542             * start rendering {@link Thread}s
543             **/
544          private volatile Boolean requestStartRendering = false;          private volatile Boolean requestStartRendering = false;
545    
         private final Timer resizeTimer;  
   
         private final int resizingPaintDelay;  
   
546          /**          /**
547           * Transformation zwischen Fenster-Koordinaten und Karten-Koordinaten           * Transformation zwischen Fenster-Koordinaten und Karten-Koordinaten
548           * (lat/lon)           * (lat/lon)
# Line 552  public class XMapPane extends JPanel { Line 555  public class XMapPane extends JPanel {
555           * thread.           * thread.
556           */           */
557          final private Timer startRenderThreadsTimer;          final private Timer startRenderThreadsTimer;
558            //
559          /**          // /**
560           * The default state is ZOOM_IN, hence by default the          // * The default state is ZOOM_IN, hence by default the
561           * {@link #zoomMapPaneMouseListener} is also enabled.          // * {@link #xMapPaneMouseListener} is also enabled.
562           **/          // **/
563          private int state = ZOOM_IN;          // private int state = ZOOM_IN;
564            //
565          /**          // /**
566           * Manuell gesetzter statischer Cursor, unabhaengig von der aktuellen          // * Manuell gesetzter statischer Cursor, unabhaengig von der aktuellen
567           * MapPane-Funktion          // * MapPane-Funktion
568           */          // */
569          protected Cursor staticCursor = null;          // protected Cursor staticCursor = null;
570    
571          private AffineTransform worldToScreen;          private AffineTransform worldToScreen;
572    
573            // /**
574            // * This {@link MouseListener} is managing all zoom related tasks
575            // */
576            // private final ZoomXMapPaneMouseListener zoomMapPaneMouseListener = new
577            // ZoomXMapPaneMouseListener(
578            // this);
579    
580          /**          /**
581           * This {@link MouseListener} is managing all zoom related tasks           * This {@link MouseListener} is managing all zoom related tasks
582           */           */
583          public final ZoomXMapPaneMouseListener zoomMapPaneMouseListener = new ZoomXMapPaneMouseListener(          private final XMapPaneMouseListener xMapPaneMouseListener = new XMapPaneMouseListener(
584                          this);                          this);
585    
586          /** Is set if a renderer has an error **/          /** Is set if a renderer has an error **/
587          protected ArrayList<Exception> renderingErrors = new ArrayList<Exception>();          protected ArrayList<Exception> renderingErrors = new ArrayList<Exception>();
588    
589          // TODO doku          /**
590             * If <code>true</code>, then rendering exceptions are rendererd into the
591             * map pane
592             **/
593            private boolean showExceptions = false;
594    
595          public XMapPane() {          public XMapPane() {
596                  this(null, null);                  this(null, null);
597          }          }
# Line 585  public class XMapPane extends JPanel { Line 600  public class XMapPane extends JPanel {
600           * full constructor extending JPanel           * full constructor extending JPanel
601           *           *
602           * @param rendererHints           * @param rendererHints
603             *            may be <code>null</code>. Otherwise a {@link Map<Object,
604             *            Object>} of {@link RenderingHints} to override the default
605             *            from {@link GTUtil#getDefaultGTRendererHints(GTRenderer)}
606           *           *
          * @param layout  
          *            - layout (probably shouldn't be set)  
          * @param isDoubleBuffered  
          *            - a Swing thing I don't really understand  
          * @param render  
          *            - what to draw the map with  
607           * @param localContext           * @param localContext
608           *            - {@link MapContext} of layer to render.           *            The main {@link MapContext} to use. If <code>null</code>, an
609             *            empty {@link DefaultMapContext} will be created.
610           */           */
611          public XMapPane(final MapContext localContext_,          public XMapPane(final MapContext localContext_,
612                          final Map<Object, Object> rendererHints) {                          final Map<Object, Object> rendererHints) {
613                  super(true);                  super(true);
614    
615                    // A default setting
616                    RenderingHints hintsJava2d = ImageUtilities.NN_INTERPOLATION_HINT;
617                    setJava2dHints(hintsJava2d);
618    
619                  setRendererHints(rendererHints);                  setRendererHints(rendererHints);
620    
621                  setOpaque(true);                  setOpaque(true);
# Line 609  public class XMapPane extends JPanel { Line 626  public class XMapPane extends JPanel {
626                  /**                  /**
627                   * Adding the #zoomMapPaneMouseListener                   * Adding the #zoomMapPaneMouseListener
628                   */                   */
629                  this.addMouseListener(zoomMapPaneMouseListener);                  this.addMouseListener(xMapPaneMouseListener);
630                  this.addMouseMotionListener(zoomMapPaneMouseListener);                  this.addMouseMotionListener(xMapPaneMouseListener);
631                  this.addMouseWheelListener(zoomMapPaneMouseListener);                  this.addMouseWheelListener(xMapPaneMouseListener);
632    
633                    // By default the XMapPAne uses the ZOOM_IN tool.
634                    setTool(XMapPaneTool.ZOOM_IN);
635    
636                  /*                  /*
637                   * We use a Timer object to avoid rendering delays and flickering when                   * We use a Timer object to avoid rendering delays and flickering when
# Line 620  public class XMapPane extends JPanel { Line 640  public class XMapPane extends JPanel {
640                   * Using a ComponentListener doesn't work because, unlike a JFrame, the                   * Using a ComponentListener doesn't work because, unlike a JFrame, the
641                   * pane receives a stream of events during drag-resizing.                   * pane receives a stream of events during drag-resizing.
642                   */                   */
643                  resizingPaintDelay = DEFAULT_RESIZING_PAINT_DELAY;                  resizeTimer = new Timer(DEFAULT_RESIZING_PAINT_DELAY,
644                  resizeTimer = new Timer(resizingPaintDelay, new ActionListener() {                                  new ActionListener() {
   
                         public void actionPerformed(final ActionEvent e) {  
                                 paneResized = true;  
645    
646                                  if (!isWellDefined())                                          public void actionPerformed(final ActionEvent e) {
647                                          return;                                                  if (!isWellDefined())
648                                                            return;
649    
650                                  final Rectangle bounds = getVisibleRect();                                                  // LOGGER.debug("resizeTimer performed");
651    
652                                  final Envelope geoMapArea = tranformWindowToGeo(bounds.x,                                                  // final Rectangle bounds = getVisibleRect();
653                                                  bounds.y, bounds.x + bounds.width, bounds.y                                                  //
654                                                                  + bounds.height);                                                  // System.out.println("\n\ntimer performs with bounds = "
655                                                    // + bounds);
656    
657                                                    // final Envelope geoMapArea = tranformWindowToGeo(
658                                                    // bounds.x, bounds.y, bounds.x + bounds.width,
659                                                    // bounds.y + bounds.height);
660    
661                                                    paneResized = true;
662                                                    if (!setMapArea(getMapArea())) {
663                                                            // It's important to request new rendering here.
664                                                            // setMapArea only returns true and only calls
665                                                            // requestStartRendering if the maparea has changed.
666                                                            // But if the component is resized, the maparea
667                                                            // doesn't have to change.
668                                                            requestStartRendering();
669                                                    }
670    
671                                  setMapArea(bestAllowedMapArea(geoMapArea));                                          }
672                          }                                  });
                 });  
673                  resizeTimer.setRepeats(false);                  resizeTimer.setRepeats(false);
674    
675                  this.addComponentListener(new ComponentAdapter() {                  this.addComponentListener(new ComponentAdapter() {
676    
677                            private Rectangle oldVisibleRect;
678    
679                          @Override                          @Override
680                          public void componentResized(final ComponentEvent e) {                          public void componentResized(final ComponentEvent e) {
681                                  if (bgExecuter != null)  
682                                          bgExecuter.cancelTask();                                  // Seems to be called twice with the same size..
683                                  if (localExecuter != null)                                  if (oldVisibleRect != null
684                                          localExecuter.cancelTask();                                                  && oldVisibleRect.equals(getVisibleRect())) {
685                                            // LOGGER.debug("skipping resize.");
686                                            return;
687                                    }
688    
689                                    // LOGGER.debug("resized: " + getVisibleRect());
690                                  resizeTimer.restart();                                  resizeTimer.restart();
691                                    oldVisibleRect = getVisibleRect();
692                          }                          }
693    
694                  });                  });
# Line 655  public class XMapPane extends JPanel { Line 696  public class XMapPane extends JPanel {
696                  /*                  /*
697                   * Setting up the repaintTimer. Not started automatically.                   * Setting up the repaintTimer. Not started automatically.
698                   */                   */
699                  repaintTimer = new Timer((int) REPEATING_REPAINT_DELAY,                  repaintTimer = new Timer(REPEATING_REPAINT_DELAY, new ActionListener() {
700                                  new ActionListener() {  
701                            @Override
702                            public void actionPerformed(final ActionEvent e) {
703                                    if ((!localExecuter.isRunning())
704                                                    && (bgExecuter != null && !bgExecuter.isRunning())) {
705                                            repaintTimer.stop();
706                                    } else {
707                                            updateFinalImage();
708                                            XMapPane.this.repaint(100);
709    
710                                    }
711                            }
712                    });
713    
                                         @Override  
                                         public void actionPerformed(final ActionEvent e) {  
                                                 updateFinalImage();  
                                                 XMapPane.this.repaint();  
                                         }  
                                 });  
714                  repaintTimer.setInitialDelay(INITIAL_REPAINT_DELAY);                  repaintTimer.setInitialDelay(INITIAL_REPAINT_DELAY);
715                  repaintTimer.setRepeats(true);                  repaintTimer.setRepeats(true);
716    
# Line 681  public class XMapPane extends JPanel { Line 728  public class XMapPane extends JPanel {
728                                                  if (localExecuter.isRunning()) {                                                  if (localExecuter.isRunning()) {
729                                                          localExecuter.cancelTask();                                                          localExecuter.cancelTask();
730                                                  } else {                                                  } else {
731                                                            // Stupidly, but we have to recheck the
732                                                            setMapArea(getMapArea());
733                                                          requestStartRendering = false;                                                          requestStartRendering = false;
734                                                          startRendering();                                                          startRendering();
735                                                  }                                                  }
# Line 713  public class XMapPane extends JPanel { Line 762  public class XMapPane extends JPanel {
762           * @author <a href="mailto:[email protected]">Stefan Alfons           * @author <a href="mailto:[email protected]">Stefan Alfons
763           *         Kr&uuml;ger</a>           *         Kr&uuml;ger</a>
764           */           */
765          public Envelope bestAllowedMapArea(Envelope env) {          public ReferencedEnvelope bestAllowedMapArea(ReferencedEnvelope env) {
766    
767                  if (getWidth() == 0)                  if (getWidth() == 0)
768                          return env;                          return env;
769    
770                  if (env == null)                  if (env == null)
771                          return null;                          return null;
772    
# Line 765  public class XMapPane extends JPanel { Line 816  public class XMapPane extends JPanel {
816                  }                  }
817    
818                  final Envelope maxAllowedExtend = getMaxExtend();                  final Envelope maxAllowedExtend = getMaxExtend();
819    
820                    /*
821                     * If a maxAllowedExtend is set, we have to honour that...
822                     */
823                    Envelope lastCalculatedArea = null;
824                  while (maxAllowedExtend != null && !maxAllowedExtend.contains(newArea)                  while (maxAllowedExtend != null && !maxAllowedExtend.contains(newArea)
825                                  && newArea != null && !newArea.isNull()                                  && newArea != null && !newArea.isNull()
826                                  && !Double.isNaN(newArea.getMinX())                                  && !Double.isNaN(newArea.getMinX())
827                                  && !Double.isNaN(newArea.getMaxX())                                  && !Double.isNaN(newArea.getMaxX())
828                                  && !Double.isNaN(newArea.getMinY())                                  && !Double.isNaN(newArea.getMinY())
829                                  && !Double.isNaN(newArea.getMaxY())) {                                  && !Double.isNaN(newArea.getMaxY())
830                          /*                                   ) // Due to Double precision problems, this may iterate for ever
831                           * If a maxExtend is set, we have to honour that...                  {
832                           */                          
833                            if (newArea.equals(lastCalculatedArea))
834                                    break;
835                            // Check that we are not iterating for ever due to double precision rounding errors
836                            lastCalculatedArea = newArea;
837                            
838                          // Exceeds top? Move down and maybe cut                          // Exceeds top? Move down and maybe cut
839                          if (newArea.getMaxY() > maxAllowedExtend.getMaxY()) {                          if (newArea.getMaxY() > maxAllowedExtend.getMaxY()) {
840                                  final double divY = newArea.getMaxY()                                  final double divY = newArea.getMaxY()
# Line 794  public class XMapPane extends JPanel { Line 854  public class XMapPane extends JPanel {
854    
855                                          // LOGGER.debug("and fix aspect ratio");                                          // LOGGER.debug("and fix aspect ratio");
856    
857                                          newArea = JTSUtil.fixAspectRatio(this.getBounds(), newArea,                                          newArea = JTSUtil.fixAspectRatio(getVisibleRect(),
858                                                          false);                                                          new ReferencedEnvelope(newArea, env
859                                                                            .getCoordinateReferenceSystem()), false);
860                                  }                                  }
861                          }                          }
862    
# Line 818  public class XMapPane extends JPanel { Line 879  public class XMapPane extends JPanel {
879    
880                                          // LOGGER.debug("and fix aspect ratio");                                          // LOGGER.debug("and fix aspect ratio");
881    
882                                          newArea = JTSUtil.fixAspectRatio(this.getBounds(), newArea,                                          newArea = JTSUtil.fixAspectRatio(getVisibleRect(),
883                                                          false);                                                          new ReferencedEnvelope(newArea, env
884                                                                            .getCoordinateReferenceSystem()), false);
885                                  }                                  }
886                          }                          }
887    
# Line 844  public class XMapPane extends JPanel { Line 906  public class XMapPane extends JPanel {
906    
907                                          // LOGGER.debug("and fix aspect ratio");                                          // LOGGER.debug("and fix aspect ratio");
908    
909                                          newArea = JTSUtil.fixAspectRatio(this.getBounds(), newArea,                                          newArea = JTSUtil.fixAspectRatio(getVisibleRect(),
910                                                          false);                                                          new ReferencedEnvelope(newArea, env
911                                                                            .getCoordinateReferenceSystem()), false);
912                                  }                                  }
913                          }                          }
914    
# Line 870  public class XMapPane extends JPanel { Line 933  public class XMapPane extends JPanel {
933    
934                                          // LOGGER.debug("and fix aspect ratio");                                          // LOGGER.debug("and fix aspect ratio");
935    
936                                          newArea = JTSUtil.fixAspectRatio(this.getBounds(), newArea,                                          newArea = JTSUtil.fixAspectRatio(getVisibleRect(),
937                                                          false);                                                          new ReferencedEnvelope(newArea, env
938                                                                            .getCoordinateReferenceSystem()), false);
939                                  }                                  }
940                          }                          }
941                            
942                            
943                  }                  }
944    
945                  return newArea;                  return new ReferencedEnvelope(newArea, env
946                                    .getCoordinateReferenceSystem());
947          }          }
948    
949          /**          /**
# Line 904  public class XMapPane extends JPanel { Line 971  public class XMapPane extends JPanel {
971                          bgExecuter.dispose();                          bgExecuter.dispose();
972                  }                  }
973    
974                  if (localExecuter != null) {                  if (localExecuter.isRunning()) {
975                          int i = 0;                          int i = 0;
976                          localExecuter.cancelTask();                          localExecuter.cancelTask();
977                          while (i++ < 10 && localExecuter.isRunning()) {                          while (i++ < 10 && localExecuter.isRunning()) {
978                                  try {                                  try {
979                                          Thread.sleep(100);                                          Thread.sleep(200);
980                                  } catch (final InterruptedException e) {                                  } catch (final InterruptedException e) {
981                                          // TODO Auto-generated catch block                                          LOGGER
982                                          e.printStackTrace();                                                          .warn(
983                                                                            "while XMapPane we are waiting for the localExcutor to stop",
984                                                                            e);
985                                  }                                  }
986                          }                          }
987                          if (localExecuter.isRunning()) {                          if (localExecuter.isRunning()) {
988                                  System.out                                  LOGGER
989                                                  .println("BAD BAD BAD... still running the thread....");                                                  .warn("localExecutor Thread still running after 2s! Continuing anyways...");
990                          }                          }
991                          localExecuter.dispose();                          localExecuter.dispose();
992                  }                  }
                 //  
                 // if (bgImage != null) {  
                 // bgImage = dispose(bgImage);  
                 // bgImage = null;  
                 // // LangUtil.gcTotal();  
                 // }  
                 //  
                 // if (localImage != null) {  
                 // localImage = dispose(localImage);  
                 // localImage = null;  
                 // // LangUtil.gcTotal();  
                 // }  
                 //  
                 // if (finalImage != null) {  
                 // finalImage = dispose(finalImage);  
                 // finalImage = null;  
                 // // LangUtil.gcTotal();  
                 // }  
                 //  
                 // if (preFinalImage != null) {  
                 // preFinalImage = dispose(preFinalImage);  
                 // preFinalImage = null;  
                 // }  
                 disposeImages();  
993    
994                  // LangUtil.gcTotal();                  disposeImages();
995    
996                  // Alle mapPaneListener entfernen                  // Remove all mapPaneListeners that have registered with us
997                  mapPaneListeners.clear();                  mapPaneListeners.clear();
998    
999                  removeMouseMotionListener(zoomMapPaneMouseListener);                  removeMouseMotionListener(xMapPaneMouseListener);
1000                  removeMouseListener(zoomMapPaneMouseListener);                  removeMouseListener(xMapPaneMouseListener);
1001    
1002                  if (localContext != null)                  if (localContext != null)
1003                          getContext().clearLayerList();                          getMapContext().clearLayerList();
1004                  if (bgContext != null)                  if (bgContext != null)
1005                          getBgContext().clearLayerList();                          getBgContext().clearLayerList();
1006    
# Line 968  public class XMapPane extends JPanel { Line 1013  public class XMapPane extends JPanel {
1013           */           */
1014          protected void drawRectangle(final Graphics graphics, final Point startPos,          protected void drawRectangle(final Graphics graphics, final Point startPos,
1015                          final Point e) {                          final Point e) {
1016                    drawRectangle(graphics, startPos, e, Color.WHITE, false);
1017            }
1018    
1019            /**
1020             * Draws a rectangle in XOR mode from the origin at {@link #startPos} to the
1021             * given point. All in screen coordinates.
1022             */
1023            protected void drawRectangle(final Graphics graphics, final Point startPos,
1024                            final Point e, Color color, boolean fill) {
1025    
1026                  if (!isWellDefined())                  if (!isWellDefined())
1027                          return;                          return;
# Line 983  public class XMapPane extends JPanel { Line 1037  public class XMapPane extends JPanel {
1037                  if (width == 0 && height == 0)                  if (width == 0 && height == 0)
1038                          return;                          return;
1039    
1040                  graphics.setXORMode(Color.WHITE);                  graphics.setXORMode(color);
1041    
1042                    if (fill) {
1043                            graphics.fillRect(left, bottom, width, height);
1044                            graphics.setXORMode(Color.WHITE);
1045                    }
1046    
1047                  graphics.drawRect(left, bottom, width, height);                  graphics.drawRect(left, bottom, width, height);
1048          }          }
1049    
# Line 995  public class XMapPane extends JPanel { Line 1055  public class XMapPane extends JPanel {
1055           *           *
1056           * @param g           * @param g
1057           *            Graphics2D to paint the preview into           *            Graphics2D to paint the preview into
          *  
          * @param state  
          *            Max be {@link #ZOOM_IN} or {@link #ZOOM_OUT}  
1058           */           */
1059          protected boolean drawScaledPreviewImage_Zoom(final Graphics2D graphics) {          protected boolean drawScaledPreviewImage_Zoom(final Graphics2D graphics) {
1060    
1061                  if (quickPreviewHint == 0)                  // if (1 == 1)return false;
1062                          return false;                  // if (quickPreviewHint == 0)
1063                    // return false;
                 graphics.setRenderingHint(RenderingHints.KEY_INTERPOLATION,  
                                 RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR);  
                 graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING,  
                                 RenderingHints.VALUE_ANTIALIAS_OFF);  
                 graphics.setRenderingHint(RenderingHints.KEY_RENDERING,  
                                 RenderingHints.VALUE_RENDER_SPEED);  
1064    
1065                  if (oldMapArea == null)                  if (oldMapArea == null)
1066                          return false;                          return false;
1067    
1068                    if (getPreFinalImage() == null)
1069                            return false;
1070    
1071                  final Rectangle visibleArea = getVisibleRect();                  final Rectangle visibleArea = getVisibleRect();
1072    
1073                  // Calculate the oldMapArea in the current WindowCoordinates:                  // Calculate the oldMapArea in the current WindowCoordinates:
1074                  final Envelope oldMapWindow = tranformGeoToWindow(oldMapArea.getMinX(),                  final Envelope oldMapWindow = tranformGeoToWindow(oldMapArea.getMinX(),
1075                                  oldMapArea.getMinY(), oldMapArea.getMaxX(), oldMapArea                                  oldMapArea.getMinY(), oldMapArea.getMaxX(), oldMapArea
1076                                                  .getMaxY(), null);                                                  .getMaxY());
1077    
1078                  final int xx1 = (int) Math.round(oldMapWindow.getMinX());                  final int xx1 = (int) Math.round(oldMapWindow.getMinX());
1079                  final int yy1 = (int) Math.round(oldMapWindow.getMinY());                  final int yy1 = (int) Math.round(oldMapWindow.getMinY());
1080                  final int xx2 = (int) Math.round(oldMapWindow.getMaxX());                  final int xx2 = (int) Math.round(oldMapWindow.getMaxX());
1081                  final int yy2 = (int) Math.round(oldMapWindow.getMaxY());                  final int yy2 = (int) Math.round(oldMapWindow.getMaxY());
1082    
1083                    graphics.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
1084                                    RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR);
1085                    graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
1086                                    RenderingHints.VALUE_ANTIALIAS_OFF);
1087                    graphics.setRenderingHint(RenderingHints.KEY_RENDERING,
1088                                    RenderingHints.VALUE_RENDER_SPEED);
1089    
1090                  graphics.drawImage(getPreFinalImage(), xx1, yy1, xx2, yy2,                  graphics.drawImage(getPreFinalImage(), xx1, yy1, xx2, yy2,
1091                                  (int) visibleArea.getMinX(), (int) visibleArea.getMinY(),                                  (int) visibleArea.getMinX(), (int) visibleArea.getMinY(),
1092                                  (int) visibleArea.getMaxX(), (int) visibleArea.getMaxY(),                                  (int) visibleArea.getMaxX(), (int) visibleArea.getMaxY(),
# Line 1034  public class XMapPane extends JPanel { Line 1095  public class XMapPane extends JPanel {
1095                  final Rectangle painedArea = new Rectangle(xx1, yy1, xx2 - xx1, yy2                  final Rectangle painedArea = new Rectangle(xx1, yy1, xx2 - xx1, yy2
1096                                  - yy1);                                  - yy1);
1097    
1098                  SwingUtil.clearAround(graphics, painedArea, visibleArea);                  SwingUtil.clearAround(graphics, painedArea, visibleArea,
1099                                    getMapBackgroundColor());
1100    
1101                  addGadgets(graphics, true);                  addGadgets(graphics, true);
1102    
1103                  quickPreviewHint = 0;                  // quickPreviewHint = 0;
1104    
1105                  repaintTimer.restart();                  repaintTimer.restart();
1106    
                 graphics.dispose();  
   
1107                  // Something has been drawn                  // Something has been drawn
1108                  return true;                  return true;
1109          }          }
# Line 1056  public class XMapPane extends JPanel { Line 1116  public class XMapPane extends JPanel {
1116           * Lazyly initializes a {@link BufferedImage} for the background renderer.           * Lazyly initializes a {@link BufferedImage} for the background renderer.
1117           */           */
1118          private Image getBgImage() {          private Image getBgImage() {
1119                  //                  if (bgImage == null) {
1120                  // if (bgImage == null) {                          bgImage = new BufferedImage(getVisibleRect().width,
1121                  // bgImage = createImage(getBounds().width, getBounds().height);                                          getVisibleRect().height, IMAGETYPE);
1122                  // }                          SwingUtil.clearImage(finalImage, getMapBackgroundColor());
1123                    }
1124    
1125                  return bgImage;                  return bgImage;
1126          }          }
1127    
1128          public MapContext getContext() {          public MapContext getMapContext() {
1129                  if (localContext == null) {                  if (localContext == null) {
1130                          setLocalContext(new DefaultMapContext());                          setLocalContext(new DefaultMapContext());
1131                  }                  }
# Line 1075  public class XMapPane extends JPanel { Line 1136  public class XMapPane extends JPanel {
1136                  //                  //
1137                  if (finalImage == null) {                  if (finalImage == null) {
1138                          // Rectangle curPaintArea = getVisibleRect();                          // Rectangle curPaintArea = getVisibleRect();
1139                          finalImage = new BufferedImage(getBounds().width,                          finalImage = new BufferedImage(getVisibleRect().width,
1140                                          getBounds().height, IMAGETYPE);                                          getVisibleRect().height, IMAGETYPE);
1141                            SwingUtil.clearImage(finalImage, getMapBackgroundColor());
1142    
1143                          requestStartRendering();                          // requestStartRendering();
1144                  }                  }
1145                  return finalImage;                  return finalImage;
1146          }          }
1147    
         public RenderingHints getJava2dHints() {  
                 return java2dHints;  
         }  
   
1148          /**          /**
1149           * Lazyly initializes a {@link BufferedImage} for the background renderer.           * Lazyly initializes a {@link BufferedImage} for the background renderer.
1150           */           */
1151          private BufferedImage getLocalImage() {          private BufferedImage getLocalImage() {
1152    
1153                  if (localImage == null) {                  if (localImage == null) {
1154                          localImage = new BufferedImage(getBounds().width,                          localImage = new BufferedImage(getVisibleRect().width,
1155                                          getBounds().height, IMAGETYPE_withAlpha);                                          getVisibleRect().height, IMAGETYPE_withAlpha);
1156                            SwingUtil.clearImage(localImage, getMapBackgroundColor());
1157                  }                  }
1158    
1159                  return localImage;                  return localImage;
# Line 1110  public class XMapPane extends JPanel { Line 1169  public class XMapPane extends JPanel {
1169                          ReferencedEnvelope mapArea_ = null;                          ReferencedEnvelope mapArea_ = null;
1170                          try {                          try {
1171                                  mapArea_ = localContext.getLayerBounds();                                  mapArea_ = localContext.getLayerBounds();
1172                          } catch (final IOException e) {                          } catch (final Exception e) {
1173                                  LOGGER.warn("context.getLayerBounds()", e);                                  LOGGER.warn("localContext.getLayerBounds()", e);
1174                            }
1175    
1176                            if (mapArea_ == null && bgContext != null) {
1177                                    try {
1178                                            mapArea_ = bgContext.getLayerBounds();
1179                                    } catch (final IOException e) {
1180                                            LOGGER.warn("bgContext.getLayerBounds()", e);
1181                                    }
1182                          }                          }
1183    
1184                          if (mapArea_ != null) {                          if (mapArea_ != null) {
                                 mapImageInvalid = true; /* note we need to redraw */  
                                 // setMapArea(mapArea_); // results in a loop  
1185                                  mapArea = bestAllowedMapArea(mapArea_);                                  mapArea = bestAllowedMapArea(mapArea_);
1186                                    requestStartRendering();
1187                          }                          }
1188                  }                  }
1189    
1190                  if (mapArea == null)                  if (mapArea == null)
1191                          return null;                          return null;
1192    
1193                    // TODO is needed at all, this should go to setMapArea maybe
1194                  if (localContext.getCoordinateReferenceSystem() == null)                  if (localContext.getCoordinateReferenceSystem() == null)
1195                          try {                          try {
1196                                  localContext.setCoordinateReferenceSystem(GeoImportUtil                                  localContext.setCoordinateReferenceSystem(GeoImportUtil
1197                                                  .getDefaultCRS());                                                  .getDefaultCRS());
1198                          } catch (TransformException e) {                          } catch (final Exception e) {
1199                                  // TODO Auto-generated catch block                                  throw new RuntimeException("setting context CRS:", e);
                                 e.printStackTrace();  
                         } catch (FactoryException e) {  
                                 // TODO Auto-generated catch block  
                                 e.printStackTrace();  
1200                          }                          }
1201    
1202                  return new ReferencedEnvelope(mapArea, localContext                  return new ReferencedEnvelope(mapArea, localContext
# Line 1141  public class XMapPane extends JPanel { Line 1204  public class XMapPane extends JPanel {
1204          }          }
1205    
1206          /**          /**
1207           * Returns the background {@link Color} of the map pane. Default is white.           * Returns the background {@link Color} of the map pane. If not set, the
1208             * methods looks for a parent component and will use its background color.
1209             * If no parent component is available, WHITE is returned.
1210           **/           **/
1211          public Color getMapBackgroundColor() {          public Color getMapBackgroundColor() {
1212                    if (mapBackgroundColor == null) {
1213                            if (getParent() != null)
1214                                    return getParent().getBackground();
1215                            else
1216                                    return Color.WHITE;
1217                    }
1218                  return mapBackgroundColor;                  return mapBackgroundColor;
1219          }          }
1220    
# Line 1170  public class XMapPane extends JPanel { Line 1241  public class XMapPane extends JPanel {
1241    
1242          public Envelope getMaxExtend() {          public Envelope getMaxExtend() {
1243                  if (maxExtend == null) {                  if (maxExtend == null) {
1244    
1245                            // The next command may take long time!
1246                            // long start = System.currentTimeMillis();
1247                          final ReferencedEnvelope layerBounds = GTUtil                          final ReferencedEnvelope layerBounds = GTUtil
1248                                          .getVisibleLayoutBounds(localContext);                                          .getVisibleLayoutBounds(localContext);
1249                            //                      
1250                            // LOGGER.info(
1251                            // (System.currentTimeMillis()-start)+"m to get maxExtend");
1252                            //                      
1253                          if (layerBounds == null) {                          if (layerBounds == null) {
1254                                  // TODO Last fallback could be the CRS valid area                                  // // TODO Last fallback could be the CRS valid area
1255                                  return null;                                  return null;
1256                          }                          }
1257    
1258                          // Kartenbereich um 10% vergroessern                          return JTSUtil
1259                          return JTSUtil.fixAspectRatio(this.getBounds(), JTSUtil                                          .fixAspectRatio(getVisibleRect(), addDefaultMargin(layerBounds), true);
1260                                          .expandEnvelope(layerBounds, 0.1), true);  
1261                  }                  }
1262                  return maxExtend;                  return maxExtend;
1263          }          }
# Line 1207  public class XMapPane extends JPanel { Line 1285  public class XMapPane extends JPanel {
1285          }          }
1286    
1287          private Image getPreFinalImage() {          private Image getPreFinalImage() {
                 // if (preFinalImage == null) {  
                 //                        
                 // // Rectangle curPaintArea = getVisibleRect();  
                 // // preFinalImage = new BufferedImage(curPaintArea.width,  
                 // // curPaintArea.height, BufferedImage.TYPE_INT_RGB);  
                 //                        
                 // preFinalImage = createImage(getBounds().width, getBounds().height);  
                 //  
                 // requestStartRendering();  
                 // }  
1288                  return preFinalImage;                  return preFinalImage;
1289          }          }
1290    
# Line 1244  public class XMapPane extends JPanel { Line 1312  public class XMapPane extends JPanel {
1312                  return new AffineTransform(screenToWorld);                  return new AffineTransform(screenToWorld);
1313          }          }
1314    
1315          public int getState() {          // public int getState() {
1316                  return state;          // return state;
1317          }          // }
1318            //
1319          /**          // /**
1320           * Liefert den statisch eingestellten Cursor, der unabhaengig von der          // * Liefert den statisch eingestellten Cursor, der unabhaengig von der
1321           * eingestellten MapPane-Aktion (Zoom, Auswahl, ...) verwendet wird.          // * eingestellten MapPane-Aktion (Zoom, Auswahl, ...) verwendet wird.
1322           *          // *
1323           * @return {@code null}, wenn kein statischer Cursor verwendet, sondern der          // * @return {@code null}, wenn kein statischer Cursor verwendet, sondern
1324           *         Cursor automatisch je nach MapPane-Aktion eingestellt wird.          // der
1325           */          // * Cursor automatisch je nach MapPane-Aktion eingestellt wird.
1326          public Cursor getStaticCursor() {          // */
1327                  return this.staticCursor;          // public Cursor getStaticCursor() {
1328          }          // return this.staticCursor;
1329            // }
1330    
1331          public AffineTransform getWorldToScreenTransform() {          public AffineTransform getWorldToScreenTransform() {
1332                  if (worldToScreen == null) {                  if (worldToScreen == null) {
# Line 1293  public class XMapPane extends JPanel { Line 1362  public class XMapPane extends JPanel {
1362           * {@link XMapPane} is visible and has bounds set.           * {@link XMapPane} is visible and has bounds set.
1363           */           */
1364          public boolean isWellDefined() {          public boolean isWellDefined() {
   
1365                  try {                  try {
1366                            if (getMapContext() == null)
                         if (getContext() == null)  
                                 return false;  
                         if (getContext().getLayerCount() <= 0)  
1367                                  return false;                                  return false;
1368                          if (getMapArea() == null)                          if (getMapContext().getLayerCount() <= 0)
1369                                  return false;                                  return false;
1370                          if (getBounds().getWidth() == 0)                          if (getVisibleRect().getWidth() == 0)
1371                                  return false;                                  return false;
1372                          if (getBounds().getHeight() == 0)                          if (getVisibleRect().getHeight() == 0)
1373                                  return false;                                  return false;
1374                            // if (getMapArea() == null)
1375                            // return false;
1376                  } catch (final Exception e) {                  } catch (final Exception e) {
1377                          return false;                          return false;
1378                  }                  }
1379                  return true;                  return true;
1380          }          }
1381    
1382          public void mouseDragged(final Point startPos, final Point lastPos,          /**
1383                          final MouseEvent event) {           * Usually called from {@link XMapPaneAction_Pan} to pan the image.
1384             *
1385                  if ((getState() == XMapPane.PAN)           * @param startPos
1386                                  || ((event.getModifiersEx() & InputEvent.BUTTON3_DOWN_MASK) != 0)) {           *            in screen coordinates
1387             * @param lastPos
1388                          if (getCursor() != SwingUtil.PANNING_CURSOR) {           *            in screen coordinates
1389                                  setCursor(SwingUtil.PANNING_CURSOR);           */
1390            public void pan(final int dX, final int dY) {
1391                                  // While panning, we deactivate the rendering. So the tasts are  
1392                                  // ready to start when the panning os done.                  // Panning needs a panning coursor
1393                                  if (bgExecuter != null)                  if (getCursor() != SwingUtil.PANNING_CURSOR) {
1394                                          bgExecuter.cancelTask();                          setCursor(SwingUtil.PANNING_CURSOR);
1395                                  if (localExecuter != null)  
1396                                          localExecuter.cancelTask();                          // While panning, we deactivate the rendering. So the tasks are
1397                          }                          // ready to start when the panning is finished.
1398                            if (bgExecuter != null && bgExecuter.isRunning())
1399                          if (lastPos.x > 0 && lastPos.y > 0) {                                  bgExecuter.cancelTask();
1400                                  final int dx = event.getX() - lastPos.x;                          if (localExecuter.isRunning())
1401                                  final int dy = event.getY() - lastPos.y;                                  localExecuter.cancelTask();
   
                                 // TODO Stop dragging when the drag would not be valid...  
                                 // boolean dragValid = true;  
                                 // // check if this panning results in a valid mapArea  
                                 // {  
                                 // Rectangle winBounds = xMapPane.getBounds();  
                                 // winBounds.translate(xMapPane.imageOrigin.x,  
                                 // -xMapPane.imageOrigin.y);  
                                 // Envelope newMapAreaBefore = xMapPane.tranformWindowToGeo(  
                                 // winBounds.x, winBounds.y, winBounds.x  
                                 // + winBounds.width, winBounds.y  
                                 // + winBounds.height);  
                                 //                                        
                                 //  
                                 // winBounds = xMapPane.getBounds();  
                                 // Point testIng = new Point(xMapPane.imageOrigin);  
                                 // testIng.translate(dx, dy);  
                                 // winBounds.translate(testIng.x, -testIng.y);  
                                 // Envelope newMapAreaAfter = xMapPane.tranformWindowToGeo(  
                                 // winBounds.x, winBounds.y, winBounds.x  
                                 // + winBounds.width, winBounds.y  
                                 // + winBounds.height);  
                                 //  
                                 // // If the last drag doesn't change the MapArea anymore cancel  
                                 // it.  
                                 // if (xMapPane.bestAllowedMapArea(newMapAreaAfter).equals(  
                                 // xMapPane.bestAllowedMapArea(newMapAreaBefore))){  
                                 // dragValid = false;  
                                 // return;  
                                 // }  
                                 // }  
   
                                 imageOrigin.translate(dx, dy);  
                                 updateFinalImage();  
                                 repaint();  
                         }  
   
                 } else if ((getState() == XMapPane.ZOOM_IN)  
                                 || (getState() == XMapPane.ZOOM_OUT)  
                                 || (getState() == XMapPane.SELECT_ALL)  
                                 || (getState() == XMapPane.SELECT_TOP)  
                 // || (getState() == XMapPane.SELECT_ONE_FROM_TOP)  
                 ) {  
                         final Graphics graphics = getGraphics();  
   
                         drawRectangle(graphics, startPos, event.getPoint());  
   
                         if ((lastPos.x > 0) && (lastPos.y > 0)) {  
                                 drawRectangle(graphics, startPos, lastPos);  
                         }  
   
                         graphics.dispose();  
   
1402                  }                  }
1403                    //
1404                    // if (lastPos.x > 0 && lastPos.y > 0) {
1405                    // final int dx = event.getX() - lastPos.x;
1406                    // final int dy = event.getY() - lastPos.y;
1407    
1408                    // TODO Stop dragging when the drag would not be valid...
1409                    // boolean dragValid = true;
1410                    // // check if this panning results in a valid mapArea
1411                    // {
1412                    // Rectangle winBounds = xMapPane.getBounds();
1413                    // winBounds.translate(xMapPane.imageOrigin.x,
1414                    // -xMapPane.imageOrigin.y);
1415                    // Envelope newMapAreaBefore = xMapPane.tranformWindowToGeo(
1416                    // winBounds.x, winBounds.y, winBounds.x
1417                    // + winBounds.width, winBounds.y
1418                    // + winBounds.height);
1419                    //                                      
1420                    //
1421                    // winBounds = xMapPane.getBounds();
1422                    // Point testIng = new Point(xMapPane.imageOrigin);
1423                    // testIng.translate(dx, dy);
1424                    // winBounds.translate(testIng.x, -testIng.y);
1425                    // Envelope newMapAreaAfter = xMapPane.tranformWindowToGeo(
1426                    // winBounds.x, winBounds.y, winBounds.x
1427                    // + winBounds.width, winBounds.y
1428                    // + winBounds.height);
1429                    //
1430                    // // If the last drag doesn't change the MapArea anymore cancel
1431                    // it.
1432                    // if (xMapPane.bestAllowedMapArea(newMapAreaAfter).equals(
1433                    // xMapPane.bestAllowedMapArea(newMapAreaBefore))){
1434                    // dragValid = false;
1435                    // return;
1436                    // }
1437                    // }
1438    
1439                    getImageOrigin().translate(dX, dY);
1440                    updateFinalImage();
1441                    repaint();
1442                    // }
1443    
1444                    // } else if ((getState() == XMapPane.ZOOM_IN)
1445                    // || (getState() == XMapPane.ZOOM_OUT)
1446                    // || (getState() == XMapPane.SELECT_ALL)
1447                    // || (getState() == XMapPane.SELECT_TOP)) {
1448                    //
1449                    // // Draws a rectangle
1450                    // final Graphics2D graphics = (Graphics2D) getGraphics();
1451                    // drawRectangle(graphics, startPos, event.getPoint());
1452                    // if ((lastPos.x > 0) && (lastPos.y > 0))
1453                    // drawRectangle(graphics, startPos, lastPos);
1454                    // graphics.dispose();
1455                    // }
1456          }          }
1457    
1458          /**          /**
1459           * Called by the {@link RenderingExecutor} when rendering was cancelled.           * Called by the {@link RenderingExecutor} when rendering was cancelled.
1460           */           */
1461          public void onRenderingCancelled() {          public void onRenderingCancelled() {
1462                    // LOGGER.debug("Rendering cancelled");
1463                  repaintTimer.stop();                  repaintTimer.stop();
                 LOGGER.debug("Rendering cancelled");  
1464          }          }
1465    
1466          /**          /**
1467           * Called by the {@link RenderingExecutor} when rendering has been           * Called by the {@link RenderingExecutor} when rendering has been
1468           * completed.           * completed.
1469             *
1470             * @param l
1471             *            long ms the rendering took
1472           */           */
1473          public void onRenderingCompleted() {          public void onRenderingCompleted(final long l) {
1474                    lastRenderingDuration = (lastRenderingDuration + l) / 2;
1475                    // LOGGER
1476                    // .debug("complete rendering after " + lastRenderingDuration
1477                    // + "ms");
1478    
1479                  repaintTimer.stop();                  repaintTimer.stop();
1480                  updateFinalImage();  
1481                  repaint();                  // We "forget" about an exception every time we complete a rendering
1482                    // thread successfully
1483                  if (renderingErrors.size() > 0)                  if (renderingErrors.size() > 0)
1484                          renderingErrors.remove(0);                          renderingErrors.remove(0);
1485    
1486                    updateFinalImage();
1487                    repaint();
1488          }          }
1489    
1490          /**          /**
# Line 1420  public class XMapPane extends JPanel { Line 1498  public class XMapPane extends JPanel {
1498           * @see MapPaneListener#onRenderingStopped(org.geotools.swing.event.MapPaneEvent)           * @see MapPaneListener#onRenderingStopped(org.geotools.swing.event.MapPaneEvent)
1499           */           */
1500          public void onRenderingFailed(final Exception renderingError) {          public void onRenderingFailed(final Exception renderingError) {
1501                  this.renderingErrors.add(renderingError);  
1502                    // Store the exceptions so we can show it to the user:
1503                    if (!(renderingError instanceof java.lang.IllegalArgumentException && renderingError
1504                                    .getMessage().equals(
1505                                                    "Argument \"sourceCRS\" should not be null.")))
1506                            this.renderingErrors.add(renderingError);
1507                  if (renderingErrors.size() > 3)                  if (renderingErrors.size() > 3)
1508                          renderingErrors.remove(0);                          renderingErrors.remove(0);
1509    
1510                  repaintTimer.stop();                  repaintTimer.stop();
1511    
1512                  LOGGER.warn("Rendering failed", renderingError);                  LOGGER.warn("Rendering failed", renderingError);
1513                  updateFinalImage();                  updateFinalImage();
1514                  repaint();                  repaint();
1515    
1516          }          }
1517    
         public void onRenderingPending() {  
                 // LOGGER.debug("Pending rendering updates the preview...");  
                 updateFinalImage();  
                 repaint();  
         }  
   
1518          @Override          @Override
1519          protected void paintComponent(final Graphics g) {          protected void paintComponent(final Graphics g) {
                 if (!acceptsRepaintCalls)  
                         return;  
1520    
1521                  // Maybe update the cursor and maybe stop the repainting timer                  // Maybe update the cursor and maybe stop the repainting timer
1522                  updateCursor();                  updateCursor();
1523    
1524                    if (!acceptsRepaintCalls)
1525                            return;
1526    
1527                    if (!isWellDefined())
1528                            return;
1529                    //
1530                    // if (paneResized) {
1531                    // // ((Graphics2D) g).setBackground(getMapBackgroundColor());
1532                    // // g.clearRect(0, 0, getVisibleRect().width,
1533                    // getVisibleRect().height);
1534                    // return;
1535                    // }
1536    
1537                  // super.paintComponent(g); // candidate for removal                  // super.paintComponent(g); // candidate for removal
1538    
1539                  boolean paintedSomething = false;                  boolean paintedSomething = false;
# Line 1455  public class XMapPane extends JPanel { Line 1545  public class XMapPane extends JPanel {
1545                          // If the new mapArea and the oldMapArea intersect, we can draw some                          // If the new mapArea and the oldMapArea intersect, we can draw some
1546                          // quick scaled preview to make the user feel that something is                          // quick scaled preview to make the user feel that something is
1547                          // happening.                          // happening.
1548                          if (mapAreaChanged && oldMapArea != null                          if (lastRenderingDuration > PRESCALE_MINTIME && mapAreaChanged
1549                                            && oldMapArea != null
1550                                          && getMapArea().intersects(oldMapArea)                                          && getMapArea().intersects(oldMapArea)
1551                                          & !getMapArea().equals(oldMapArea)) {                                          && !getMapArea().equals(oldMapArea) && !paneResized) {
1552    
1553                                  mapAreaChanged = false;                                  mapAreaChanged = false;
1554    
1555                                  if (getMapArea().covers(oldMapArea)) {                                  // if (getMapArea().covers(oldMapArea)) {
1556                                          setQuickPreviewHint(ZOOM_OUT);                                  // // quickPreviewHint = ZOOM_OUT;
1557                                          paintedSomething = drawScaledPreviewImage_Zoom((Graphics2D) g);                                  // paintedSomething = drawScaledPreviewImage_Zoom((Graphics2D)
1558                                  } else if (oldMapArea.covers(getMapArea())) {                                  // g);
1559                                          setQuickPreviewHint(ZOOM_IN);                                  // } else if (oldMapArea.covers(getMapArea())) {
1560                                          paintedSomething = drawScaledPreviewImage_Zoom((Graphics2D) g);                                  // quickPreviewHint = ZOOM_IN;
1561                                  }                                  paintedSomething = drawScaledPreviewImage_Zoom((Graphics2D) g);
1562                                    // }
                         }  
   
                         if (paneResized) {  
                                 paneResized = false;  
                                 disposeImages();  
1563                          }                          }
   
                         // Start the Threads and Timers to render the image  
                         requestStartRendering();  
   
1564                  }                  }
1565    
1566                  if (!paintedSomething) {                  if (!paintedSomething) {
1567    
1568                          g.drawImage(getFinalImage(), 0, 0, null);                          g.drawImage(getFinalImage(), 0, 0, null);
1569    
                         g.dispose(); // cand. for removal  
   
1570                          paintedSomething = true; // cand. for removal                          paintedSomething = true; // cand. for removal
1571                  }                  }
1572    
# Line 1535  public class XMapPane extends JPanel { Line 1615  public class XMapPane extends JPanel {
1615    
1616          }          }
1617    
         /**  
          * Performs a {@value #PAN} action. During panning, the displacement is  
          * stored in {@link #imageOrigin} object. Calling {@link #performPan()} will  
          * reset the offset and call {@link #setMapArea(Envelope)}.  
          */  
         public void performPan() {  
   
                 final Rectangle winBounds = getBounds();  
                 winBounds.translate(-imageOrigin.x, -imageOrigin.y);  
                 final Envelope newMapArea = tranformWindowToGeo(winBounds.x,  
                                 winBounds.y, winBounds.x + winBounds.width, winBounds.y  
                                                 + winBounds.height);  
   
                 imageOrigin.x = 0;  
                 imageOrigin.y = 0;  
   
                 if (!setMapArea(newMapArea)) {  
                         /**  
                          * If setMapArea returns true, the finalImage is updated anyways.  
                          * This if-case exists to ensure that we repaint a correct image  
                          * even if the new panning area has been denied.  
                          */  
                         updateFinalImage();  
                         repaint();  
                 }  
   
                 if (getCursor() == SwingUtil.PANNING_CURSOR)  
                         setCursor(SwingUtil.PAN_CURSOR);  
         }  
   
1618          //          //
1619          // /**          // /**
1620          // * Nuetzlich wenn die Componente gedruckt (z.B. wenn ein Screenshot          // * Performs a {@value #PAN} action. During panning, the displacement is
1621          // gemacht          // * stored in {@link #imageOrigin} object. Calling {@link #performPan()}
1622          // * wird) wird. Dann werden wird der Hintergrund auf WEISS gesetzt.          // will
1623          // *          // * reset the offset and call {@link #setMapArea(Envelope)}.
         // * @author <a href="mailto:[email protected]">Stefan Alfons  
         // * Kr&uuml;ger</a>  
1624          // */          // */
1625          // @Override          // public void performPan() {
1626          // public void print(final Graphics g) {          //
1627          // final Color orig = getBackground();          // final Rectangle winBounds = getVisibleRect();
         // setBackground(Color.WHITE);  
1628          //          //
1629          // // wrap in try/finally so that we always restore the state          // winBounds.translate(-imageOrigin.x, -imageOrigin.y);
1630          // try {          // final Envelope newMapArea = tranformWindowToGeo(winBounds.x,
1631          // super.print(g);          // winBounds.y, winBounds.x + winBounds.width, winBounds.y
1632          // } finally {          // + winBounds.height);
1633          // setBackground(orig);          //
1634            // imageOrigin.x = 0;
1635            // imageOrigin.y = 0;
1636            //
1637            // if (!setMapArea(newMapArea)) {
1638            // /**
1639            // * If setMapArea returns true, the finalImage is updated anyways.
1640            // * This if-case exists to ensure that we repaint a correct image
1641            // * even if the new panning area has been denied.
1642            // */
1643            // updateFinalImage();
1644            // repaint();
1645          // }          // }
1646            //
1647            // if (getCursor() == SwingUtil.PANNING_CURSOR)
1648            // setCursor(SwingUtil.PAN_CURSOR);
1649          // }          // }
1650    
1651          /**          /**
# Line 1605  public class XMapPane extends JPanel { Line 1666  public class XMapPane extends JPanel {
1666          private void requestStartRendering() {          private void requestStartRendering() {
1667                  if (bgExecuter != null)                  if (bgExecuter != null)
1668                          bgExecuter.cancelTask();                          bgExecuter.cancelTask();
1669                  if (localExecuter != null)  
1670                          localExecuter.cancelTask();                  localExecuter.cancelTask();
1671    
1672                    mapImageInvalid = true;
1673                    if (paneResized) {
1674                            paneResized = false;
1675                            disposeImages();
1676                    }
1677                  requestStartRendering = true;                  requestStartRendering = true;
1678    
1679          }          }
1680  //  
1681  //      /**          /**
1682  //       * Berechnet die Transformation zwischen Fenster- und Karten-Koordinaten           * Calculate the affine transforms used to convert between world and pixel
1683  //       * neu.           * coordinates. The calculations here are very basic and assume a cartesian
1684  //       */           * reference system.
1685  //      protected void resetTransforms() {           * <p>
1686  //              if (getMapArea() == null || getWidth() == 0 || getHeight() == 0)           * Tne transform is calculated such that {@code envelope} will be centred in
1687  //                      return;           * the display
1688  //           *
1689  //              // We store the last Transform           * @param envelope
1690  //              oldScreenToWorld = screenToWorld;           *            the current map extent (world coordinates)
1691  //           * @param paintArea
1692  //              this.screenToWorld = new AffineTransform(           *            the current map pane extent (screen units)
1693  //              // Genauso wie die Fenster-Koordinaten, werden die Longitude-Koordinaten           */
1694  //                              // nach rechts (Osten) hin groesser          private void resetTransforms() {
1695  //                              // --> positive Verschiebung                  // System.out
1696  //                              getMapArea().getWidth() / getWidth(),                  // .println("paintArea in resetTeansofrms = " + getVisibleRect());
1697  //                              // keine Verzerrung                  if (!isWellDefined())
1698  //                              0.0, 0.0,                          return;
1699  //                              // Waehrend die Fenster-Koordinaten nach unten hin groesser  
1700  //                              // werden,                  if (mapArea == null)
1701  //                              // werden Latitude-Koordinaten nach Sueden hin keiner                          return;
1702  //                              // --> negative Verschiebung  
1703  //                              -getMapArea().getHeight() / getHeight(),                  final ReferencedEnvelope refMapEnv = new ReferencedEnvelope(mapArea,
1704  //                              // Die Longitude-Koordinaten werden nach Osten hin groesser                                  getMapContext().getCoordinateReferenceSystem());
1705  //                              // --> obere linke Ecke des Fensters hat also den Minimalwert  
1706  //                              getMapArea().getMinX(),                  worldToScreen = RendererUtilities.worldToScreenTransform(refMapEnv,
1707  //                              // Die Latitude-Koordinaten werden nach Norden hin groesser                                  getVisibleRect());
1708  //                              // --> obere linke Ecke des Fensters hat also den Maximalwert  
1709  //                              getMapArea().getMaxY());                  try {
1710  //                          screenToWorld = worldToScreen.createInverse();
1711  //              try {  
1712  //                      this.worldToScreen = screenToWorld.createInverse();                  } catch (final NoninvertibleTransformException ex) {
1713  //              } catch (final NoninvertibleTransformException e) {                          LOGGER
1714  //                      LOGGER.error(e);                                          .error("can't invert worldToScreen to get screenToWorld!",
1715  //              }                                                          ex);
1716  //      }                  }
1717                    }
           
   
     /**  
      * Calculate the affine transforms used to convert between  
      * world and pixel coordinates. The calculations here are very  
      * basic and assume a cartesian reference system.  
      * <p>  
      * Tne transform is calculated such that {@code envelope} will  
      * be centred in the display  
      *  
      * @param envelope the current map extent (world coordinates)  
      * @param paintArea the current map pane extent (screen units)  
      */  
     private void resetTransforms() {  
         ReferencedEnvelope refEnv = new ReferencedEnvelope(mapArea, getContext().getCoordinateReferenceSystem());  
   
         Rectangle paintArea = getBounds();  
           
         double xscale = paintArea.getWidth() / refEnv.getWidth();  
         double yscale = paintArea.getHeight() / refEnv.getHeight();  
   
         double scale = Math.min(xscale, yscale);  
   
         double xoff = refEnv.getMedian(0) * scale - paintArea.getCenterX();  
         double yoff = refEnv.getMedian(1) * scale + paintArea.getCenterY();  
   
         worldToScreen = new AffineTransform(scale, 0, 0, -scale, -xoff, yoff);  
         try {  
             screenToWorld = worldToScreen.createInverse();  
   
         } catch (NoninvertibleTransformException ex) {  
             ex.printStackTrace();  
         }  
     }  
           
           
1718    
1719          public void setBgContext(final MapContext context) {          public void setBgContext(final MapContext context) {
1720    
# Line 1700  public class XMapPane extends JPanel { Line 1731  public class XMapPane extends JPanel {
1731                  this.bgContext = context;                  this.bgContext = context;
1732    
1733                  if (context != null) {                  if (context != null) {
1734                          setMapArea(bgContext.getAreaOfInterest());                          // setMapArea(bgContext.getAreaOfInterest());
1735    
1736                          this.bgContext.addMapLayerListListener(bgContextListener);                          this.bgContext.addMapLayerListListener(bgContextListener);
1737    
# Line 1709  public class XMapPane extends JPanel { Line 1740  public class XMapPane extends JPanel {
1740                                  mapLayer.addMapLayerListener(bgMapLayerListener);                                  mapLayer.addMapLayerListener(bgMapLayerListener);
1741                          }                          }
1742                  }                  }
1743                  mapImageInvalid = true;  
1744                  repaint();                  requestStartRendering();
1745          }          }
1746    
1747          public void setJava2dHints(final RenderingHints java2dHints) {          public void setJava2dHints(final RenderingHints java2dHints) {
1748                  this.java2dHints = java2dHints;                  this.java2dHints = java2dHints;
1749          }          }
1750    
         /**  
          *  
          * @param context  
          */  
1751          public void setLocalContext(final MapContext context) {          public void setLocalContext(final MapContext context) {
1752                  // Remove the default listener from the old context                  // Remove the default listener from the old context
1753                  if (this.localContext != null) {                  if (this.localContext != null) {
# Line 1736  public class XMapPane extends JPanel { Line 1763  public class XMapPane extends JPanel {
1763    
1764                  if (context != null) {                  if (context != null) {
1765    
1766                          setMapArea(localContext.getAreaOfInterest());                          // setMapArea(localContext.getAreaOfInterest());
1767    
1768                          localRenderer.setContext(localContext);                          getLocalRenderer().setContext(localContext);
1769    
1770                          this.localContext.addMapLayerListListener(localContextListener);                          this.localContext.addMapLayerListListener(localContextListener);
1771    
# Line 1748  public class XMapPane extends JPanel { Line 1775  public class XMapPane extends JPanel {
1775                          }                          }
1776                  }                  }
1777    
1778                    requestStartRendering();
1779    
1780            }
1781    
1782            public void setBorder(final Border b) {
1783                    super.setBorder(b);
1784            }
1785    
1786            /**
1787             * Triggers to repaint (fast) and re-render (slow) the JMapPane.
1788             */
1789            public void refresh() {
1790                  mapImageInvalid = true;                  mapImageInvalid = true;
1791                  repaint();                  repaint();
1792          }          }
1793    
1794            // /**
1795            // * Triggers to use new {@link GTRenderer} and refresh the map. Should be
1796            // * called after {@link Style}s have been changed because GTRenderer is
1797            // * otherwise not working well.
1798            // */
1799            // public void refreshRenderers() {
1800            // localRenderer = GTUtil.createGTRenderer();
1801            // setLocalContext(getMapContext());
1802            // mapImageInvalid = true;
1803            // repaint();
1804            // }
1805    
1806          /**          /**
1807             * Set the new map area.
1808             *
1809           * @param newMapArea           * @param newMapArea
1810           * @return <code>true</code> if the mapArea has been changed and a repaint           * @return <code>true</code> if the mapArea has been changed and a repaint
1811           *         has been triggered.           *         has been triggered.
1812           */           */
1813          public boolean setMapArea(final Envelope newMapArea) {          public boolean setMapArea(final Envelope newMapArea) {
1814                    if (newMapArea == null)
1815                            return false;
1816                    if (getMapContext().getCoordinateReferenceSystem() == null)
1817                            return false;
1818                    return setMapArea(new ReferencedEnvelope(newMapArea, getMapContext()
1819                                    .getCoordinateReferenceSystem()));
1820            }
1821    
1822            /**
1823             * Set the new map area.
1824             *
1825             * @param newMapArea
1826             * @return <code>true</code> if the mapArea has been changed and a repaint
1827             *         has been triggered.
1828             */
1829            public boolean setMapArea(final ReferencedEnvelope newMapArea) {
1830    
1831                  if (newMapArea == null                  if (newMapArea == null
1832                                  || bestAllowedMapArea(newMapArea).equals(mapArea)) {                                  || bestAllowedMapArea(newMapArea).equals(mapArea)) {
# Line 1776  public class XMapPane extends JPanel { Line 1845  public class XMapPane extends JPanel {
1845                          return false;                          return false;
1846                  }                  }
1847    
1848                    final Envelope candNew = bestAllowedMapArea(newMapArea);
1849    
1850                  // Testing, whether the difference if just minimal                  // Testing, whether the difference if just minimal
1851                  if (mapArea != null) {                  if (mapArea != null) {
                         final Envelope candNew = bestAllowedMapArea(newMapArea);  
1852                          final double tolX = mapArea.getWidth() / 1000.;                          final double tolX = mapArea.getWidth() / 1000.;
1853                          final double tolY = mapArea.getHeight() / 1000.;                          final double tolY = mapArea.getHeight() / 1000.;
1854                          if ((candNew.getMinX() - tolX < mapArea.getMinX())                          if ((candNew.getMinX() - tolX < mapArea.getMinX())
# Line 1798  public class XMapPane extends JPanel { Line 1868  public class XMapPane extends JPanel {
1868                          }                          }
1869                  }                  }
1870    
1871                    // New map are is accepted:
1872                  oldMapArea = mapArea;                  oldMapArea = mapArea;
1873                    mapArea = candNew;
1874                  this.mapArea = bestAllowedMapArea(newMapArea);                  resetTransforms();
1875    
1876                  if (localContext != null) {                  if (localContext != null) {
1877                          localContext.setAreaOfInterest(mapArea, localContext                          localContext.setAreaOfInterest(mapArea, localContext
# Line 1810  public class XMapPane extends JPanel { Line 1881  public class XMapPane extends JPanel {
1881                          bgContext.setAreaOfInterest(mapArea, localContext                          bgContext.setAreaOfInterest(mapArea, localContext
1882                                          .getCoordinateReferenceSystem());                                          .getCoordinateReferenceSystem());
1883                  }                  }
1884                  resetTransforms();  
                 mapImageInvalid = true;  
1885                  mapAreaChanged = true;                  mapAreaChanged = true;
                 repaint();  
1886    
1887                  // LOGGER.debug("New maparea = " + mapArea);                  repaint(200); // Do not remove it!
1888    
1889                    requestStartRendering();
1890    
1891                  return true;                  return true;
1892          }          }
1893    
# Line 1824  public class XMapPane extends JPanel { Line 1896  public class XMapPane extends JPanel {
1896           *           *
1897           * @param if <code>null</code>, white is used.           * @param if <code>null</code>, white is used.
1898           */           */
1899          public void setMapBackgroundColor(Color bgColor) {          public void setMapBackgroundColor(final Color bgColor) {
                 if (bgColor == null)  
                         bgColor = Color.WHITE;  
1900                  this.mapBackgroundColor = bgColor;                  this.mapBackgroundColor = bgColor;
1901          }          }
1902    
# Line 1884  public class XMapPane extends JPanel { Line 1954  public class XMapPane extends JPanel {
1954          }          }
1955    
1956          // /** Stored the time used for the last real rendering in ms. **/          // /** Stored the time used for the last real rendering in ms. **/
1957          // private long lastRenderingDuration = Long.MAX_VALUE;          private long lastRenderingDuration = 1000;
1958            private XMapPaneTool tool = null;
1959    
1960          /**          /**
1961           * Set the minimum (nearest) allowed zoom scale. This is the bigger number           * Set the minimum (nearest) allowed zoom scale. This is the bigger number
# Line 1901  public class XMapPane extends JPanel { Line 1972  public class XMapPane extends JPanel {
1972          }          }
1973    
1974          /**          /**
1975           *           * If <code>true</code>, allow the {@link XMapPane} to process #repaint()
1976           * @param b           * requests. Otherwise the map will not paint anything and not start any
1977             * rendering {@link Thread}s.
1978           */           */
1979          public void setPainting(final boolean b) {          public void setPainting(final boolean b) {
1980                  acceptsRepaintCalls = b;                  acceptsRepaintCalls = b;
1981          }                  if (acceptsRepaintCalls == true)
1982                            repaint();
         // /**  
         // * Returns in milli seconds the time the last rending of the  
         // * {@link SelectableXMapPane} took. #Long.MAX_VALUE if the JMapPane has  
         // not  
         // * been rendered yet.  
         // */  
         // public long getLastRenderingDuration() {  
         // return lastRenderingDuration;  
         // }  
   
         public void setQuickPreviewHint(final int quickPreviewHint) {  
                 this.quickPreviewHint = quickPreviewHint;  
   
1983          }          }
1984    
1985          private void setRendererHints(final Map<Object, Object> rendererHints) {          private void setRendererHints(final Map<Object, Object> rendererHints) {
# Line 1928  public class XMapPane extends JPanel { Line 1987  public class XMapPane extends JPanel {
1987                          this.rendererHints = rendererHints;                          this.rendererHints = rendererHints;
1988          }          }
1989    
1990          /**          // @Deprecated
1991           * Enables/Disables the ZOOM Mouse Listener. Upates the Cursor and stops the          // public void setState(final int state) {
1992           * repaint Timer if          // this.state = state;
1993           *          //
1994           * @param state          // // throw new RuntimeException("Old concept.. migrate to new concept!");
1995           */          //
1996          public void setState(final int state) {          // // xMapPaneMouseListener.setEnabled((state == ZOOM_IN
1997                  this.state = state;          // // || state == ZOOM_OUT || state == PAN));
1998            //
1999                  zoomMapPaneMouseListener.setEnabled((state == ZOOM_IN          // // Je nach Aktion den Cursor umsetzen
2000                                  || state == ZOOM_OUT || state == PAN));          // updateCursor();
2001            // }
2002    
2003                  // Je nach Aktion den Cursor umsetzen          public void configureMouse(MouseInputType type, XMapPaneAction action) {
2004                  updateCursor();                  xMapPaneMouseListener.actions.put(type, action);
2005          }          }
2006    
2007          /**          /**
2008           * Standardmaessig wird der Cursor automatisch je nach MapPane-Aktion (Zoom,           * Configure the {@link XMapPaneTool} that active on the map. Passing
2009           * Auswahl, ...) gesetzt. Mit dieser Methode kann ein statischer Cursor           * <code>null</code> will set the NO_ACTION tool.
2010           * gesetzt werden, der unabhaengig von der aktuellen MapPanes-Aktion           */
2011           * beibehalten wird. Um diesen statischen Cursor wieder zu entfernen, kann          public void setTool(XMapPaneTool tool) {
2012           * {@code null} als Parameter uebergeben werden                  if (tool == null)
2013           *                          tool = XMapPaneTool.NO_ACTION;
2014           * @param cursor                  this.tool = tool;
2015           *            Cursor                  xMapPaneMouseListener.configure(tool);
2016           */                  setCursor(tool.getCursor());
         public void setStaticCursor(final Cursor cursor) {  
                 this.staticCursor = cursor;  
                 if (cursor != null)  
                         super.setCursor(cursor);  
2017          }          }
2018    
2019            // /**
2020            // * Standardmaessig wird der Cursor automatisch je nach MapPane-Aktion
2021            // (Zoom,
2022            // * Auswahl, ...) gesetzt. Mit dieser Methode kann ein statischer Cursor
2023            // * gesetzt werden, der unabhaengig von der aktuellen MapPanes-Aktion
2024            // * beibehalten wird. Um diesen statischen Cursor wieder zu entfernen, kann
2025            // * {@code null} als Parameter uebergeben werden
2026            // *
2027            // * @param cursor
2028            // * Cursor
2029            // */
2030            // public void setStaticCursor(final Cursor cursor) {
2031            // this.staticCursor = cursor;
2032            // if (cursor != null)
2033            // super.setCursor(cursor);
2034            // }
2035    
2036          /**          /**
2037           * Starts rendering on one or two threads           * Starts rendering on one or two threads
2038           */           */
2039          private void startRendering() {          private void startRendering() {
2040    
2041                  if (!isWellDefined())                  if (!isWellDefined() || !acceptsRepaintCalls) {
2042                            // if we are not ready to start rendering, try it again the next
2043                            // time the timer is chacking the flag.
2044                            requestStartRendering = true;
2045                          return;                          return;
2046                    }
2047    
2048                  if (bgExecuter != null) {                  if (bgExecuter != null) {
2049                          // Stop all renderers                          // Stop all renderers
2050                          bgExecuter.cancelTask();                          bgExecuter.cancelTask();
2051                  }                  }
2052    
2053                  if (localExecuter != null) {                  localExecuter.cancelTask();
                         localExecuter.cancelTask();  
                 }  
2054    
2055                  final Rectangle curPaintArea = getVisibleRect();                  final Rectangle curPaintArea = getVisibleRect();
2056    
# Line 1998  public class XMapPane extends JPanel { Line 2073  public class XMapPane extends JPanel {
2073                          // (Graphics2D) getBgImage().getGraphics(), createGTRenderer);                          // (Graphics2D) getBgImage().getGraphics(), createGTRenderer);
2074                  }                  }
2075    
2076                  if (getContext() != null) {                  if (getMapContext() != null) {
2077                          // localExecuter = new RenderingExecutor(this, 150l);                          // localExecuter = new RenderingExecutor(this, 150l);
2078                          // LOGGER.debug("starting local renderer:");                          // LOGGER.debug("starting local renderer:");
2079    
2080                          localRenderer.setJava2DHints(getJava2dHints());                          getLocalRenderer().setJava2DHints(getJava2dHints());
2081                          localRenderer.setRendererHints(getRendererHints());                          getLocalRenderer().setRendererHints(getRendererHints());
2082    
2083                          ReferencedEnvelope areaOfInterest = getMapArea();                          final boolean submitted = localExecuter.submit(getMapArea(),
                         final boolean submitted = localExecuter.submit(areaOfInterest,  
2084                                          curPaintArea, (Graphics2D) getLocalImage().getGraphics(),                                          curPaintArea, (Graphics2D) getLocalImage().getGraphics(),
2085                                          localRenderer, getWorldToScreenTransform());                                          getLocalRenderer());
2086                          if (submitted)                          if (submitted)
2087                                  repaintTimer.restart();                                  repaintTimer.restart();
2088                          else                          else
2089                                  requestStartRendering = true; // Try to start rendering again in                                  requestStartRendering = true; // Try to start rendering
2090                            // again in
2091                          // a moment                          // a moment
2092                  }                  }
2093    
2094                  updateCursor();                  updateCursor();
2095          }          }
2096    
2097            private RenderingHints getJava2dHints() {
2098                    return java2dHints;
2099            }
2100    
2101          /**          /**
2102           * Transformiert einen Geo-Koordinaten-Bereich in Fenster-Koordinaten.           * Transformiert einen Geo-Koordinaten-Bereich in Fenster-Koordinaten.
2103           *           *
# Line 2035  public class XMapPane extends JPanel { Line 2114  public class XMapPane extends JPanel {
2114           *            {@link #getScreenToWorld()} is used.           *            {@link #getScreenToWorld()} is used.
2115           */           */
2116          public Envelope tranformGeoToWindow(final double ox, final double oy,          public Envelope tranformGeoToWindow(final double ox, final double oy,
2117                          final double px, final double py,                          final double px, final double py) {
2118                          final AffineTransform winToGeotransform) {                  final AffineTransform at = getWorldToScreenTransform();
                 final AffineTransform at = winToGeotransform == null ? getScreenToWorld()  
                                 : winToGeotransform;  
2119                  Point2D geoO;                  Point2D geoO;
2120                  try {                  // try {
2121                          geoO = at.inverseTransform(new Point2D.Double(ox, oy), null);                  geoO = at.transform(new Point2D.Double(ox, oy), null);
2122                          final Point2D geoP = at.inverseTransform(                  final Point2D geoP = at.transform(new Point2D.Double(px, py), null);
2123                                          new Point2D.Double(px, py), null);                  return new Envelope(geoO.getX(), geoP.getX(), geoO.getY(), geoP.getY());
2124                          return new Envelope(geoO.getX(), geoP.getX(), geoO.getY(), geoP                  // } catch (final NoninvertibleTransformException e) {
2125                                          .getY());                  // LOGGER.error(e);
2126                  } catch (final NoninvertibleTransformException e) {                  // return new Envelope(ox, oy, px, py);
2127                          LOGGER.error(e);                  // }
                         return new Envelope(ox, oy, px, py);  
                 }  
2128          }          }
2129    
2130          /**          /**
# Line 2069  public class XMapPane extends JPanel { Line 2144  public class XMapPane extends JPanel {
2144                  final AffineTransform at = getScreenToWorld();                  final AffineTransform at = getScreenToWorld();
2145                  final Point2D geoO = at.transform(new Point2D.Double(ox, oy), null);                  final Point2D geoO = at.transform(new Point2D.Double(ox, oy), null);
2146                  final Point2D geoP = at.transform(new Point2D.Double(px, py), null);                  final Point2D geoP = at.transform(new Point2D.Double(px, py), null);
2147                  return new Envelope(geoO.getX(), geoP.getX(), geoO.getY(), geoP.getY());  
2148                    // Mmmmm... don't really understand why its x,x,y,y
2149                    // return new Envelope(geoO.getX(), geoP.getX(), geoO.getY(),
2150                    // geoP.getY());
2151                    return new Envelope(new Coordinate(geoO.getX(), geoO.getY()),
2152                                    new Coordinate(geoP.getX(), geoP.getY()));
2153          }          }
2154    
2155          /**          /**
# Line 2081  public class XMapPane extends JPanel { Line 2161  public class XMapPane extends JPanel {
2161                  // if the renderers have stopped, also stop the timer that is updating                  // if the renderers have stopped, also stop the timer that is updating
2162                  // the final image                  // the final image
2163                  if (bgExecuter != null && bgExecuter.isRunning()                  if (bgExecuter != null && bgExecuter.isRunning()
2164                                  || localExecuter != null && localExecuter.isRunning()) {                                  || localExecuter.isRunning()) {
2165                          setCursor(WAIT_CURSOR);                          setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
2166                          return;                          return;
2167                  } else {                  } else {
2168                          // Allow one last rendering                          // Allow one last rendering
2169                          if (repaintTimer.isRunning()) {                          if (repaintTimer.isRunning()) {
2170                                  System.out.println("one last rendering....");                                  // System.out.println("one last rendering....");
2171                                  repaintTimer.stop();                                  repaintTimer.stop();
2172                                  updateFinalImage();                                  updateFinalImage();
2173                                  repaint();                                  repaint();
2174                          }                          }
2175                  }                  }
2176                    //              
2177                  // wenn manueller Cursor gesetzt ist, dann diesen verwenden (unabhaengig                  // //
2178                  // von der aktuellen Aktion                  // // wenn manueller Cursor gesetzt ist, dann diesen verwenden
2179                  if (this.staticCursor != null) {                  // (unabhaengig
2180                          setCursor(staticCursor);                  // // von der aktuellen Aktion
2181                          return;                  // if (this.staticCursor != null) {
2182                  }                  // setCursor(staticCursor);
2183                    // return;
2184                    // }
2185                    //              
2186                  if (getCursor() == SwingUtil.PANNING_CURSOR) {                  if (getCursor() == SwingUtil.PANNING_CURSOR) {
2187                          // This cursor will reset itself                          // This cursor will reset itself
2188                          return;                          return;
2189                  }                  }
2190    
2191                  // Set the cursor depending on what tool is in use...                  setCursor(tool.getCursor());
2192                  switch (state) {  
2193                  case SELECT_TOP:                  //
2194                  case SELECT_ONE_FROM_TOP:                  // // Set the cursor depending on what tool is in use...
2195                  case SELECT_ALL:                  // switch (state) {
2196                          setCursor(SwingUtil.CROSSHAIR_CURSOR);                  // case SELECT_TOP:
2197                          break;                  // case SELECT_ONE_FROM_TOP:
2198                  case ZOOM_IN:                  // case SELECT_ALL:
2199                          setCursor(SwingUtil.ZOOMIN_CURSOR);                  // setCursor(SwingUtil.CROSSHAIR_CURSOR);
2200                          break;                  // break;
2201                  case ZOOM_OUT:                  // case ZOOM_IN:
2202                          setCursor(SwingUtil.ZOOMOUT_CURSOR);                  // setCursor(SwingUtil.ZOOMIN_CURSOR);
2203                          break;                  // break;
2204                  case PAN:                  // case ZOOM_OUT:
2205                          setCursor(SwingUtil.PAN_CURSOR);                  // setCursor(SwingUtil.ZOOMOUT_CURSOR);
2206                          break;                  // break;
2207                  default:                  // case PAN:
2208                          setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));                  // setCursor(SwingUtil.PAN_CURSOR);
2209                          break;                  // break;
2210                  }                  // default:
2211                    // setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
2212                    // break;
2213                    // }
2214          }          }
2215    
2216          /**          /**
# Line 2154  public class XMapPane extends JPanel { Line 2240  public class XMapPane extends JPanel {
2240    
2241                  final Graphics2D finalG = getFinalImage().createGraphics();                  final Graphics2D finalG = getFinalImage().createGraphics();
2242                  finalG.setBackground(getMapBackgroundColor());                  finalG.setBackground(getMapBackgroundColor());
2243                  finalG.drawImage(getPreFinalImage(), imageOrigin.x, imageOrigin.y,                  finalG.drawImage(getPreFinalImage(), getImageOrigin().x,
2244                                  getMapBackgroundColor(), null);                                  getImageOrigin().y, getMapBackgroundColor(), null);
   
                 final int finalImageHeight = getFinalImage().getHeight(null);  
                 final int finalImageWidth = getFinalImage().getWidth(null);  
2245    
2246                  final Rectangle painedArea = new Rectangle(imageOrigin.x,                  // When panning, we have to clear the area around the image
2247                                  imageOrigin.y, finalImageWidth, finalImageHeight);                  final Rectangle painedArea = new Rectangle(getImageOrigin().x,
2248                  SwingUtil.clearAround(finalG, painedArea, getVisibleRect());                                  getImageOrigin().y, getFinalImage().getWidth(), getFinalImage()
2249                                                    .getHeight());
2250                    SwingUtil.clearAround(finalG, painedArea, getVisibleRect(),
2251                                    getMapBackgroundColor());
2252    
2253                  addGadgets(finalG, false);                   addGadgets(finalG, false);
2254    
2255                  finalG.dispose();                  finalG.dispose();
2256    
# Line 2181  public class XMapPane extends JPanel { Line 2267  public class XMapPane extends JPanel {
2267           *            <code>false</code>, it will only depend on           *            <code>false</code>, it will only depend on
2268           *            {@link #localExecuter.isRunning} and #bgExecuter.isRunning           *            {@link #localExecuter.isRunning} and #bgExecuter.isRunning
2269           */           */
2270          private void addGadgets(final Graphics2D graphics, boolean forceWait) {          private void addGadgets(final Graphics2D graphics, final boolean forceWait) {
2271    
2272                  // Paint a logo to the bottom right if available                  // Paint a logo to the bottom right if available
2273                  if (mapImage != null) {                  if (mapImage != null) {
2274                          graphics.drawImage(mapImage, getBounds().width                          final Rectangle visibleRect = getVisibleRect();
2275                                          - mapImage.getWidth() - 10, getBounds().height                          graphics.drawImage(mapImage, visibleRect.width
2276                                            - mapImage.getWidth() - 10, getVisibleRect().height
2277                                          - mapImage.getHeight() - 10, null);                                          - mapImage.getHeight() - 10, null);
2278                  }                  }
2279                    
                   
2280                  int y = 17;                  int y = 17;
2281    
2282                  // If the rendering process is still running, indicate this is the image                  // If the rendering process is still running, indicate this is the image
2283                  if (forceWait || bgExecuter != null && bgExecuter.isRunning()                  if (forceWait || bgExecuter != null && bgExecuter.isRunning()
2284                                  || localExecuter != null && localExecuter.isRunning()) {                                  || localExecuter.isRunning()) {
2285                            
2286                          y+=8;                          y += 8;
2287    
2288                          final Color c = graphics.getColor();                          final Color c = graphics.getColor();
2289                          graphics.setFont(waitFont);                          graphics.setFont(waitFont);
 //                      String waitStr = "Wait..."; // i8n  
2290    
2291                          graphics.setColor(getMapBackgroundColor());                          graphics.setColor(getMapBackgroundColor());
2292                          graphics.drawString(waitMsg, 5, y);                          graphics.drawString(waitMsg, 5, y);
2293                          graphics.setColor(getMapBackgroundColor());                          graphics.setColor(getMapBackgroundColor());
2294                          graphics.drawString(waitMsg, 7, y+2);                          graphics.drawString(waitMsg, 7, y + 2);
2295                          graphics.setColor(Color.BLACK);                          graphics.setColor(Color.BLACK);
2296                          graphics.drawString(waitMsg, 6, y+1);                          graphics.drawString(waitMsg, 6, y + 1);
2297    
2298                          graphics.setColor(c);                          graphics.setColor(c);
2299                            
2300                          y += 24;                          y += 21;
2301                  }                  }
2302    
2303                  if (renderingErrors != null) {                  if (!renderingErrors.isEmpty() && isShowExceptions()) {
2304    
2305                          final Color c = graphics.getColor();                          final Color c = graphics.getColor();
2306                          graphics.setFont(errorFont);                          graphics.setFont(errorFont);
2307    
2308                          for (Exception ex : renderingErrors) {                          for (final Exception ex : renderingErrors) {
   
                                 if (ex instanceof java.lang.IllegalArgumentException  
                                                 && ex.getMessage().equals(  
                                                                 "Argument \"sourceCRS\" should not be null."))  
                                         continue;  
2309    
2310                                  String errStr = ex.getLocalizedMessage();                                  String errStr = ex.getLocalizedMessage();
2311    
2312                                  graphics.setColor(Color.WHITE);                                  if (errStr == null)
2313                                            errStr = ex.getMessage();
2314                                    if (errStr == null)
2315                                            errStr = "unknown error: " + ex.getClass().getSimpleName();
2316    
2317                                    graphics.setColor(getMapBackgroundColor());
2318                                  graphics.drawString(errStr, 5, y);                                  graphics.drawString(errStr, 5, y);
2319                                  graphics.setColor(Color.RED);                                  graphics.setColor(Color.RED);
2320                                  graphics.drawString(errStr, 6, y + 1);                                  graphics.drawString(errStr, 6, y + 1);
# Line 2252  public class XMapPane extends JPanel { Line 2337  public class XMapPane extends JPanel {
2337          public void zoomTo(          public void zoomTo(
2338                          final FeatureCollection<SimpleFeatureType, SimpleFeature> features) {                          final FeatureCollection<SimpleFeatureType, SimpleFeature> features) {
2339    
2340                  final CoordinateReferenceSystem mapCRS = getContext()                  // if (!isWellDefined()) return;
2341    
2342                    final CoordinateReferenceSystem mapCRS = getMapContext()
2343                                  .getCoordinateReferenceSystem();                                  .getCoordinateReferenceSystem();
2344                  final CoordinateReferenceSystem fCRS = features.getSchema()                  final CoordinateReferenceSystem fCRS = features.getSchema()
2345                                  .getGeometryDescriptor().getCoordinateReferenceSystem();                                  .getCoordinateReferenceSystem();
2346    
2347                  double width = mapArea.getWidth();                  ReferencedEnvelope _mapArea;
2348                  double height = mapArea.getHeight();                  if (mapArea == null)
2349                            _mapArea = features.getBounds();
2350                    else
2351                            _mapArea = getMapArea();
2352                    double width = _mapArea.getWidth();
2353                    double height = _mapArea.getHeight();
2354                  final double ratio = height / width;                  final double ratio = height / width;
2355    
2356                  if (features == null || features.size() == 0) {                  if (features == null || features.size() == 0) {
# Line 2310  public class XMapPane extends JPanel { Line 2402  public class XMapPane extends JPanel {
2402                  } else {                  } else {
2403                          final ReferencedEnvelope fBounds = features.getBounds();                          final ReferencedEnvelope fBounds = features.getBounds();
2404    
2405                          Envelope bounds;                          ReferencedEnvelope bounds;
2406                          if (!mapCRS.equals(fCRS)) {                          if (!mapCRS.equals(fCRS)) {
2407                                  bounds = JTSUtil.transformEnvelope(fBounds, fCRS, mapCRS);                                  bounds = JTSUtil.transformEnvelope(fBounds, mapCRS);
2408                          } else {                          } else {
2409                                  bounds = fBounds;                                  bounds = fBounds;
2410                          }                          }
2411                          // BB umrechnen von Layer-CRS in Map-CRS                          // BB umrechnen von Layer-CRS in Map-CRS
2412    
2413                          // Expand a bit                          // Expand a bit
2414                          bounds.expandBy(bounds.getWidth() / 6., bounds.getHeight() / 6.);                          addDefaultMargin(bounds);
2415    
2416                          setMapArea(bounds);                          setMapArea(bounds);
2417                  }                  }
2418          }          }
2419    
2420            private ReferencedEnvelope addDefaultMargin(ReferencedEnvelope bounds) {
2421                    return JTSUtil.expandEnvelope(bounds, Math.max(0,
2422                                    defaultMaxMapExtendMode));
2423            }
2424    
2425            private Envelope addDefaultMargin(Envelope bounds) {
2426                    return JTSUtil.expandEnvelope(bounds, Math.max(0,
2427                                    defaultMaxMapExtendMode));
2428            }
2429    
2430          /**          /**
2431           * Zooms towards a point.           * Zooms towards a point.
2432           *           *
# Line 2343  public class XMapPane extends JPanel { Line 2445  public class XMapPane extends JPanel {
2445           * @param center           * @param center
2446           *            position in window coordinates           *            position in window coordinates
2447           * @param zoomFaktor           * @param zoomFaktor
2448           *            > 1 for zoom in, < 1 for zoom out. Default is 1.33.           *            > 1 for zoom out, < 1 for zoom in. Default is .5
2449           */           */
2450          public void zoomTo(Point center, Double zoomFaktor) {          public void zoomTo(Point center, Double zoomFaktor) {
2451                  if (zoomFaktor == null || zoomFaktor == 0.)                  if (zoomFaktor == null || zoomFaktor == 0.)
2452                          zoomFaktor = 2.;                          zoomFaktor = .5;
2453    
2454                  final Point2D gcenter = getScreenToWorld().transform(center, null);                  final Point2D gcenter = getScreenToWorld().transform(center, null);
2455                  center = null;                  center = null;
# Line 2368  public class XMapPane extends JPanel { Line 2470  public class XMapPane extends JPanel {
2470                                  .getWidth()) / 2., (mapArea.getHeight() * zoomFaktor - mapArea                                  .getWidth()) / 2., (mapArea.getHeight() * zoomFaktor - mapArea
2471                                  .getHeight()) / 2.);                                  .getHeight()) / 2.);
2472    
2473                  // Move the newMapArea above the new center                  // // Move the newMapArea above the new center if we zoom in:
2474                  newMapArea.translate(gcenter.getX() - mapArea.centre().x, gcenter                  newMapArea.translate(gcenter.getX() - mapArea.centre().x, gcenter
2475                                  .getY()                                  .getY()
2476                                  - mapArea.centre().y);                                  - mapArea.centre().y);
# Line 2376  public class XMapPane extends JPanel { Line 2478  public class XMapPane extends JPanel {
2478                  setMapArea(newMapArea);                  setMapArea(newMapArea);
2479          }          }
2480    
2481            /**
2482             * Shall non-fatal rendering exceptions be reported in the mappane or be
2483             * dropped quitely.
2484             */
2485            public void setShowExceptions(final boolean showExceptions) {
2486                    this.showExceptions = showExceptions;
2487            }
2488    
2489            /**
2490             * Shall exceptions be reported in the mappane?
2491             */
2492            public boolean isShowExceptions() {
2493                    return showExceptions;
2494            }
2495    
2496            public GTRenderer getLocalRenderer() {
2497                    return localRenderer;
2498            }
2499    
2500            /**
2501             * Setzt den Kartenausschnitt auf die Ausdehnung eines bestimmten Layers.
2502             * Macht nichts, wenn {@code null} uebergeben wird.
2503             *
2504             * <br>
2505             *
2506             * @param layer
2507             *            ein Layer
2508             */
2509            public void zoomToLayer(MapLayer layer) {
2510                    if (layer == null)
2511                            return;
2512                    try {
2513    
2514                            // BB umrechnen von Layer-CRS in Map-CRS
2515                            final CoordinateReferenceSystem targetCRS = getMapContext()
2516                                            .getCoordinateReferenceSystem();
2517                            final CoordinateReferenceSystem sourceCRS = layer
2518                                            .getFeatureSource().getSchema()
2519                                            .getCoordinateReferenceSystem();
2520    
2521                            Envelope mapAreaNew;
2522                            if (!CRS.equalsIgnoreMetadata(sourceCRS, targetCRS)) {
2523                                    mapAreaNew = JTSUtil.transformEnvelope(layer.getFeatureSource()
2524                                                    .getBounds(), sourceCRS, targetCRS);
2525                            } else {
2526                                    try {
2527                                            mapAreaNew = layer.getFeatureSource().getBounds();
2528                                    } catch (java.lang.IllegalArgumentException e) {
2529                                            LOGGER.error("Can't calc layers bounds...", e);
2530                                            mapAreaNew = null;
2531    
2532                                            /**
2533                                             *
2534                                             23.10.2009 11:20:50
2535                                             * org.geotools.data.shapefile.shp.PolygonHandler read
2536                                             * WARNUNG: only one hole in this polygon record ERROR
2537                                             * JMapPane zoomToLayer Zoom to layer did not terminate
2538                                             * correctly java.lang.IllegalArgumentException: Points of
2539                                             * LinearRing do not form a closed linestring at
2540                                             * com.vividsolutions
2541                                             * .jts.geom.LinearRing.validateConstruction
2542                                             * (LinearRing.java:105) at
2543                                             * com.vividsolutions.jts.geom.LinearRing
2544                                             * .<init>(LinearRing.java:100) at
2545                                             * com.vividsolutions.jts.geom
2546                                             * .GeometryFactory.createLinearRing
2547                                             * (GeometryFactory.java:339) at
2548                                             * org.geotools.data.shapefile.
2549                                             * shp.PolygonHandler.read(PolygonHandler.java:188) at
2550                                             * org.geotools
2551                                             * .data.shapefile.shp.ShapefileReader$Record.shape
2552                                             * (ShapefileReader.java:106) at
2553                                             * org.geotools.data.shapefile.
2554                                             * ShapefileAttributeReader.next(
2555                                             * ShapefileAttributeReader.java:157) at
2556                                             * org.geotools.data.shapefile
2557                                             * .indexed.IndexedShapefileAttributeReader
2558                                             * .next(IndexedShapefileAttributeReader.java:122) at
2559                                             * org.geotools
2560                                             * .data.FIDFeatureReader.next(FIDFeatureReader.java:96) at
2561                                             * org.geotools.data.FIDFeatureReader.next(FIDFeatureReader.
2562                                             * java:55) at org.geotools.data.MaxFeatureReader.next(
2563                                             * MaxFeatureReader.java:61) at
2564                                             * org.geotools.data.MaxFeatureReader
2565                                             * .next(MaxFeatureReader.java:61)
2566                                             **/
2567                                    }
2568                            }
2569    
2570                            // Kartenbereich um 10% vergroessern, damit z.B. auch ein
2571                            // Punkt-Layer,
2572                            // welches nur aus 2 Punnkten besteht, sichtbar ist (Punkte liegen
2573                            // sonst
2574                            // genau auf dem Rand der angezeigten Flaeche)
2575    
2576                            if (mapAreaNew != null) {
2577    
2578                                    mapAreaNew = addDefaultMargin(mapAreaNew);
2579                                    setMapArea(mapAreaNew);
2580                            } else {
2581                                    LOGGER
2582                                                    .warn("Couldn't transformEnvelope when zooming to the layer");
2583                            }
2584                    } catch (Exception err) {
2585                            LOGGER.error("Zoom to layer did not terminate correctly", err);
2586                    }
2587            }
2588    
2589            /**
2590             * Zooms the {@link SelectableXMapPane} to the {@link Envelope} of a layer.
2591             *
2592             * <br>
2593             * A refresh of the map is not done automatically
2594             *
2595             * @param index
2596             *            Index of the {@link MapLayer} in the {@link MapContext} (from
2597             *            back to top)
2598             *
2599             * @author <a href="mailto:[email protected]">Stefan Alfons
2600             *         Kr&uuml;ger</a>
2601             */
2602            public void zoomToLayer(int index) {
2603                    final MapContext context = getMapContext();
2604                    if (context != null)
2605                            zoomToLayer(context.getLayer(index));
2606            }
2607    
2608            /**
2609             * Zooms the {@link SelectableXMapPane} to the {@link Envelope} of the
2610             * selected layer. The layer is selected by the idx, counting from front to
2611             * back, like humans would expect in a {@link JList}
2612             *
2613             * <br>
2614             * A refresh of the map is not done automatically
2615             *
2616             *
2617             *
2618             * @param index
2619             *            Reverse index of the {@link MapLayer} in the
2620             *            {@link MapContext}
2621             *
2622             * @author <a href="mailto:[email protected]">Stefan Alfons
2623             *         Kr&uuml;ger</a>
2624             */
2625            public void zoomToLayerIdxReverse(int index) {
2626                    zoomToLayer(getMapContext().getLayerCount() - 1 - index);
2627            }
2628    
2629            /**
2630             * Aktiviert oder deaktiviert das AntiAliasing for diese
2631             * {@link SelectableXMapPane}. AntiALiasing ist besonders fuer
2632             * Textbeschriftung sehr schoen, verbraucht aber auch mehr Performance.
2633             *
2634             * @author <a href="mailto:[email protected]">Stefan Alfons
2635             *         Kr&uuml;ger</a>
2636             */
2637            public void setAntiAliasing(final boolean aa) {
2638                    // LOGGER.info("Setting AntiAliasing for this JMapPane to " + aa);
2639                    RenderingHints java2DHints = java2dHints;
2640                    if (java2DHints == null) {
2641                            java2DHints = GeoTools.getDefaultHints();
2642                    }
2643    
2644                    java2DHints.put(RenderingHints.KEY_ANTIALIASING,
2645                                    aa ? RenderingHints.VALUE_ANTIALIAS_ON
2646                                                    : RenderingHints.VALUE_ANTIALIAS_OFF);
2647                    java2DHints.put(RenderingHints.KEY_TEXT_ANTIALIASING,
2648                                    aa ? RenderingHints.VALUE_TEXT_ANTIALIAS_ON
2649                                                    : RenderingHints.VALUE_TEXT_ANTIALIAS_OFF);
2650                    java2DHints.put(RenderingHints.KEY_RENDERING,
2651                                    aa ? RenderingHints.VALUE_RENDER_QUALITY
2652                                                    : RenderingHints.VALUE_RENDER_SPEED);
2653    
2654            }
2655    
2656            public Point getImageOrigin() {
2657                    return imageOrigin;
2658            }
2659    
2660            /**
2661             * If {@link #maxExtend} is <code>null</code> the following rules are used
2662             * to create a default maximum.
2663             * <ul>
2664             * <li>Values &lt; 0 : don't grow to fit the monitors aspect ratio, no
2665             * margin</li>
2666             * <li>Values 0 : grow to fit the monitors aspect ratio, no margin</li>
2667             * <li>Values &gt; 0 : grow to fit the monitors aspect ratio, and add a
2668             * relative margin</li>
2669             * </ul>
2670             * **/
2671            public void setDefaultMaxMapExtendMode(double defaultMaxMapExtendMode) {
2672                    this.defaultMaxMapExtendMode = defaultMaxMapExtendMode;
2673            }
2674    
2675            /**
2676             * If {@link #maxExtend} is <code>null</code> the following rules are used
2677             * to create a default maximum.
2678             * <ul>
2679             * <li>Values &lt; 0 : don't grow to fit the monitors aspect ratio, no
2680             * margin</li>
2681             * <li>Values 0 : grow to fit the monitors aspect ratio, no margin</li>
2682             * <li>Values &gt; 0 : grow to fit the monitors aspect ratio, and add a
2683             * relative margin</li>
2684             * </ul>
2685             * **/
2686            public double getDefaultMaxMapExtendMode() {
2687                    return defaultMaxMapExtendMode;
2688            }
2689    
2690  }  }

Legend:
Removed from v.536  
changed lines
  Added in v.677

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26