/[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 540 by alfonx, Fri Nov 20 19:34:50 2009 UTC branches/2.0-RC2/src/skrueger/geotools/XMapPane.java revision 680 by alfonx, Fri Feb 5 19:46:10 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;
39    import org.geotools.map.DefaultMapLayer;
40  import org.geotools.map.MapContext;  import org.geotools.map.MapContext;
41  import org.geotools.map.MapLayer;  import org.geotools.map.MapLayer;
42  import org.geotools.map.event.MapLayerEvent;  import org.geotools.map.event.MapLayerEvent;
# Line 46  import org.geotools.renderer.label.Label Line 49  import org.geotools.renderer.label.Label
49  import org.geotools.renderer.lite.LabelCache;  import org.geotools.renderer.lite.LabelCache;
50  import org.geotools.renderer.lite.RendererUtilities;  import org.geotools.renderer.lite.RendererUtilities;
51  import org.geotools.renderer.lite.StreamingRenderer;  import org.geotools.renderer.lite.StreamingRenderer;
52    import org.geotools.resources.image.ImageUtilities;
53    import org.geotools.styling.Style;
54  import org.geotools.swing.JMapPane;  import org.geotools.swing.JMapPane;
55  import org.geotools.swing.event.MapMouseEvent;  import org.geotools.swing.event.MapMouseEvent;
56  import org.geotools.swing.event.MapPaneEvent;  import org.geotools.swing.event.MapPaneEvent;
# Line 63  import schmitzm.geotools.gui.SelectableX Line 68  import schmitzm.geotools.gui.SelectableX
68  import schmitzm.geotools.io.GeoImportUtil;  import schmitzm.geotools.io.GeoImportUtil;
69  import schmitzm.geotools.map.event.JMapPaneListener;  import schmitzm.geotools.map.event.JMapPaneListener;
70  import schmitzm.geotools.map.event.MapLayerAdapter;  import schmitzm.geotools.map.event.MapLayerAdapter;
71    import schmitzm.geotools.styling.StylingUtil;
72  import schmitzm.lang.LangUtil;  import schmitzm.lang.LangUtil;
73  import schmitzm.swing.JPanel;  import schmitzm.swing.JPanel;
74  import schmitzm.swing.SwingUtil;  import schmitzm.swing.SwingUtil;
75    import schmitzm.swing.event.MouseInputType;
76    
77  import com.vividsolutions.jts.geom.Coordinate;  import com.vividsolutions.jts.geom.Coordinate;
78  import com.vividsolutions.jts.geom.Envelope;  import com.vividsolutions.jts.geom.Envelope;
# Line 96  import com.vividsolutions.jts.geom.Geome Line 103  import com.vividsolutions.jts.geom.Geome
103   */   */
104  public class XMapPane extends JPanel {  public class XMapPane extends JPanel {
105    
106          private static final int IMAGETYPE = BufferedImage.TYPE_INT_RGB;          /**
107          private static final int IMAGETYPE_withAlpha = BufferedImage.TYPE_INT_ARGB;           * If {@link #maxExtend} is <code>null</code> the following rules are used
108             * to create a default maximum.
109             * <ul>
110             * <li>Values &lt; 0 : don't grow to fit the monitors aspect ratio, no
111             * margin</li>
112             * <li>Values 0 : grow to fit the monitors aspect ratio, no margin</li>
113             * <li>Values &gt; 0 : grow to fit the monitors aspect ratio, and add a
114             * relative margin</li>
115             * </ul>
116             * **/
117            private double defaultMaxMapExtendMode = .05;
118    
119            // private static final int IMAGETYPE = BufferedImage.TYPE_INT_RGB;
120            // private static final int IMAGETYPE_withAlpha =
121            // BufferedImage.TYPE_INT_ARGB;
122            private static final int IMAGETYPE = BufferedImage.TYPE_3BYTE_BGR;
123    
124            public XMapPaneTool getTool() {
125                    return tool;
126            }
127    
128          private static Logger LOGGER = Logger.getLogger(XMapPane.class);          private static final int IMAGETYPE_withAlpha = BufferedImage.TYPE_4BYTE_ABGR;
129    
130            private final static Logger LOGGER = Logger.getLogger(XMapPane.class);
131    
132            /**
133             * A flag indicating whether the {@link XMapPane} is accepting repaints from
134             * the EDT. @see {@link XMapPane#setPainting(boolean))
135             **/
136          private boolean acceptsRepaintCalls = true;          private boolean acceptsRepaintCalls = true;
137    
138          /**          /**
# Line 125  public class XMapPane extends JPanel { Line 157  public class XMapPane extends JPanel {
157           * regularly and {@link #repaint()}. This {@link Timer} is stopped when all           * regularly and {@link #repaint()}. This {@link Timer} is stopped when all
158           * renderers have finished.           * renderers have finished.
159           *           *
160           * @see #INITIAL_REPAINT_DELAYAL           * @see INITIAL_REPAINT_DELAYAL
161           * @see #REPEATING_REPAINT_DELAY           * @see #REPEATING_REPAINT_DELAY
162           */           */
163          final private Timer repaintTimer;          final private Timer repaintTimer;
# Line 134  public class XMapPane extends JPanel { Line 166  public class XMapPane extends JPanel {
166           * The initial delay in milliseconds until the {@link #finalImage} is           * The initial delay in milliseconds until the {@link #finalImage} is
167           * updated the first time.           * updated the first time.
168           */           */
169          public static final int INITIAL_REPAINT_DELAY = 1000;          public static final int INITIAL_REPAINT_DELAY = 900;
170    
171          /**          /**
172           * While the {@link #bgExecuter} and {@link #localExecuter} are rendering,           * While the {@link #bgExecuter} and {@link #localExecuter} are rendering,
173           * the {@link #repaintTimer} is regularly updating the {@link #finalImage}           * the {@link #repaintTimer} is regularly updating the {@link #finalImage}
174           * with previews.           * with previews.
175           */           */
176          public static final long REPEATING_REPAINT_DELAY = 500;          public static final int REPEATING_REPAINT_DELAY = 500;
177    
178          /**          /**
179           * Default delay (milliseconds) before the map will be redrawn when resizing           * Default delay (milliseconds) before the map will be redrawn when resizing
180           * the pane. This is to avoid flickering while drag-resizing.           * the pane. This is to avoid flickering while drag-resizing.
181             *
182             * @see #resizeTimer
183           */           */
184          public static final int DEFAULT_RESIZING_PAINT_DELAY = 600;          public static final int DEFAULT_RESIZING_PAINT_DELAY = 600;
185    
         public static final int NONE = -123;  
   
186          /**          /**
187           * Flag fuer Modus "Kartenausschnitt bewegen". Nicht fuer Window-Auswahl           * This not-repeating {@link Timer} is re-started whenever the component is
188           * moeglich!           * resized. That means => only if the component is not resizing for
189           *           * {@link #DEFAULT_RESIZING_PAINT_DELAY} milliseconds, does the
190           * @see #setState(int)           * {@link XMapPane} react.
191           */           */
192          public static final int PAN = 1;          private final Timer resizeTimer;
193    
194          /**          /**
195           * Flag fuer Modus "SimpleFeature-Auswahl auf allen (sichtbaren) Layern".           * Flag for no-tool.
          *  
          * @see #setState(int)  
          * @see #setState(int)  
196           */           */
197          public static final int SELECT_ALL = 103;          public static final int NONE = -123;
198            //
199            // /**
200            // * Flag fuer Modus "Kartenausschnitt bewegen". Nicht fuer Window-Auswahl
201            // * moeglich!
202            // *
203            // * @see #setState(int)
204            // */
205            // public static final int PAN = 1;
206            //
207            // /**
208            // * Flag fuer Modus "Heran zoomen".
209            // *
210            // * @see #setState(int)
211            // * @see #setState(int)
212            // */
213            // public static final int ZOOM_IN = 2;
214            //
215            // /**
216            // * Flag fuer Modus "Heraus zoomen". Nicht fuer Window-Auswahl moeglich!
217            // *
218            // * @see #setState(int)
219            // */
220            // public static final int ZOOM_OUT = 3;
221    
222          /**          /**
223           * Flag fuer Modus           * {@link Font} used to paint the wait messages into the map
          * "Auswahl nur eines Features, das erste sichtbare von Oben".  
224           *           *
225           * @see #setState(int)           * @see #addGadgets(Graphics2D, boolean)
          * @see #setState(int)  
226           */           */
227          public static final int SELECT_ONE_FROM_TOP = 104;          final static Font waitFont = new Font("Arial", Font.BOLD, 28);
228    
229          /**          /**
230           * Flag fuer Modus           * {@link Font} used to paint error messages into the map
          * "SimpleFeature-Auswahl auf dem obersten (sichtbaren) Layer".  
231           *           *
232           * @see #setState(int)           * @see #addGadgets(Graphics2D, boolean)
          * @see #setState(int)  
233           */           */
         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");  
234          final static Font errorFont = new Font("Arial", Font.BOLD, 13);          final static Font errorFont = new Font("Arial", Font.BOLD, 13);
235    
236          /**          /**
237           * Flag fuer Modus "Heran zoomen".           * If last average last two renderings took more than that many ms, show the
238           *           * user a scaled preview
239           * @see #setState(int)           **/
240           * @see #setState(int)          private static final long PRESCALE_MINTIME = 230;
          */  
         public static final int ZOOM_IN = 2;  
241    
242          /**          /**
243           * Flag fuer Modus "Heraus zoomen". Nicht fuer Window-Auswahl moeglich!           * The wait message painted into the map while rendering is going on on
244             * another thread.
245           *           *
246           * @see #setState(int)           * @see #addGadgets(Graphics2D, boolean)
247           */           */
248          public static final int ZOOM_OUT = 3;          final String waitMsg = SwingUtil.R("WaitMess");
249    
250          /**          /**
251           * Konvertiert die Maus-Koordinaten (relativ zum <code>JMapPane</code>) in           * Konvertiert die Maus-Koordinaten (relativ zum <code>JMapPane</code>) in
# Line 212  public class XMapPane extends JPanel { Line 254  public class XMapPane extends JPanel {
254           * @param e           * @param e
255           *            Maus-Ereignis           *            Maus-Ereignis
256           */           */
257          public static Point2D getMapCoordinatesFromEvent(final MouseEvent e) {          public static DirectPosition2D getMapCoordinatesFromEvent(final MouseEvent e) {
258                  // aktuelle Geo-Position aus GeoMouseEvent ermitteln                  // aktuelle Geo-Position aus GeoMouseEvent ermitteln
259                  if (e != null && e instanceof MapMouseEvent)                  if (e != null && e instanceof MapMouseEvent)
260                          try {                          try {
261                                  return ((MapMouseEvent) e).getMapPosition().toPoint2D();                                  return ((MapMouseEvent) e).getMapPosition();
262                          } catch (final Exception err) {                          } catch (final Exception err) {
263                                  LOGGER                                  LOGGER
264                                                  .error(                                                  .error(
# Line 233  public class XMapPane extends JPanel { Line 275  public class XMapPane extends JPanel {
275                                  return null;                                  return null;
276    
277                          final AffineTransform at = xMapPane.getScreenToWorld();                          final AffineTransform at = xMapPane.getScreenToWorld();
278                          if (at != null)                          if (at != null) {
279                                  return at.transform(e.getPoint(), null);                                  Point2D transformed = at.transform(e.getPoint(), null);
280                                    return new DirectPosition2D(xMapPane.getMapContext()
281                                                    .getCoordinateReferenceSystem(), transformed.getX(),
282                                                    transformed.getY());
283                            }
284                          return null;                          return null;
285                  }                  }
286                  throw new IllegalArgumentException(                  throw new IllegalArgumentException(
# Line 249  public class XMapPane extends JPanel { Line 295  public class XMapPane extends JPanel {
295    
296                  @Override                  @Override
297                  public void layerAdded(final MapLayerListEvent event) {                  public void layerAdded(final MapLayerListEvent event) {
298                            final MapLayer layer = event.getLayer();
                         MapLayer layer = event.getLayer();  
   
299                          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();  
300                          requestStartRendering();                          requestStartRendering();
   
301                  }                  }
302    
303                  @Override                  @Override
304                  public void layerChanged(final MapLayerListEvent event) {                  public void layerChanged(final MapLayerListEvent event) {
                         // mapImageInvalid = true;  
                         // repaint();  
305                          requestStartRendering();                          requestStartRendering();
306                  }                  }
307    
308                  @Override                  @Override
309                  public void layerMoved(final MapLayerListEvent event) {                  public void layerMoved(final MapLayerListEvent event) {
                         // mapImageInvalid = true;  
                         // repaint();  
310                          requestStartRendering();                          requestStartRendering();
311                  }                  }
312    
# Line 288  public class XMapPane extends JPanel { Line 314  public class XMapPane extends JPanel {
314                  public void layerRemoved(final MapLayerListEvent event) {                  public void layerRemoved(final MapLayerListEvent event) {
315                          if (event.getLayer() != null)                          if (event.getLayer() != null)
316                                  event.getLayer().removeMapLayerListener(bgMapLayerListener);                                  event.getLayer().removeMapLayerListener(bgMapLayerListener);
                         // mapImageInvalid = true;  
                         // repaint();  
317                          requestStartRendering();                          requestStartRendering();
318                  }                  }
319          };          };
320    
321          /**          /**
322           * compass and icon are rendered into this image           * This {@link RenderingExecutor} manages the creation and cancellation of
323             * up to one {@link Thread} for rendering the {@link #localContext}.
324           */           */
325          // protected BufferedImage gadgetsImage;          private final RenderingExecutor localExecuter = new RenderingExecutor(this);
326    
327            /**
328             * This {@link RenderingExecutor} manages the creation and cancellation of
329             * up to one {@link Thread} for rendering the {@link #bgContext}.
330             */
331          protected RenderingExecutor bgExecuter;          protected RenderingExecutor bgExecuter;
332    
333          /**          /**
334           * The Renderer for the LocalLayers uses this Image. When set to null,           * The {@link #localRenderer} for the {@link #localContext} uses this
335           * please dispose this {@link Graphics2D}           * {@link Image}.
336           */           */
337          private BufferedImage localImage;          private BufferedImage localImage;
338    
         private BufferedImage finalImage;  
339          /**          /**
340           * If # {@link #bgExecuter} is using {@link #bgRenderer} for the Background           * The {@link #bgRenderer} for the {@link #bgContext} uses this
341           * uses this Image. When set to null, please dispose the {@link Graphics2D}           * {@link Image}.
342           */           */
343          private BufferedImage bgImage;          private BufferedImage bgImage;
344    
345          /**          /**
346             * This {@link Image} is a merge of the {@link #bgImage},
347             * {@link #localImage} and {@link #addGadgets(Graphics2D, boolean)}. It is
348             * updated with {@link #updateFinalImage()} and used for painting in
349             * {@link #paintComponent(Graphics)}
350             */
351            private BufferedImage finalImage;
352    
353            /**
354           * 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
355           * corner.           * corner.
356           *           *
# Line 331  public class XMapPane extends JPanel { Line 367  public class XMapPane extends JPanel {
367    
368                  @Override                  @Override
369                  public void layerChanged(final MapLayerEvent event) {                  public void layerChanged(final MapLayerEvent event) {
                         // Change of SLD for example  
                         // mapImageInvalid = true;  
                         // repaint();  
370                          requestStartRendering();                          requestStartRendering();
371                  }                  }
372    
373                  @Override                  @Override
374                  public void layerHidden(final MapLayerEvent event) {                  public void layerHidden(final MapLayerEvent event) {
                         // mapImageInvalid = true;  
                         // repaint();  
375                          requestStartRendering();                          requestStartRendering();
376                  }                  }
377    
378                  @Override                  @Override
379                  public void layerShown(final MapLayerEvent event) {                  public void layerShown(final MapLayerEvent event) {
                         // mapImageInvalid = true;  
                         // repaint();  
380                          requestStartRendering();                          requestStartRendering();
381                  }                  }
382          };          };
# Line 362  public class XMapPane extends JPanel { Line 391  public class XMapPane extends JPanel {
391           * While dragging, the {@link #updateFinalImage()} method is translating the           * While dragging, the {@link #updateFinalImage()} method is translating the
392           * cached images while setting it together.           * cached images while setting it together.
393           **/           **/
394          Point imageOrigin = new Point(0, 0);          private final Point imageOrigin = new Point(0, 0);
395          /**          /**
396           * For every rendering thread started,           * For every rendering thread started,
397           * {@link GTUtil#createGTRenderer(MapContext)} is called to create a new           * {@link GTUtil#createGTRenderer(MapContext)} is called to create a new
# Line 384  public class XMapPane extends JPanel { Line 413  public class XMapPane extends JPanel {
413                  public void layerAdded(final MapLayerListEvent event) {                  public void layerAdded(final MapLayerListEvent event) {
414                          event.getLayer().addMapLayerListener(localMapLayerListener);                          event.getLayer().addMapLayerListener(localMapLayerListener);
415    
416                          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();  
417                          requestStartRendering();                          requestStartRendering();
418    
419                  }                  }
420    
421                  @Override                  @Override
422                  public void layerChanged(final MapLayerListEvent event) {                  public void layerChanged(final MapLayerListEvent event) {
423                          // mapImageInvalid = true;                          // getLocalRenderer().setContext(getMapContext()); geht doch auch
424                          // repaint();                          // ohne?!?!? wow...
                         localRenderer.setContext(getContext());  
425                          requestStartRendering();                          requestStartRendering();
426                  }                  }
427    
428                  @Override                  @Override
429                  public void layerMoved(final MapLayerListEvent event) {                  public void layerMoved(final MapLayerListEvent event) {
430                          // mapImageInvalid = true;                          getLocalRenderer().setContext(getMapContext());
                         // repaint();  
                         localRenderer.setContext(getContext());  
431                          requestStartRendering();                          requestStartRendering();
432                  }                  }
433    
# Line 422  public class XMapPane extends JPanel { Line 435  public class XMapPane extends JPanel {
435                  public void layerRemoved(final MapLayerListEvent event) {                  public void layerRemoved(final MapLayerListEvent event) {
436                          if (event.getLayer() != null)                          if (event.getLayer() != null)
437                                  event.getLayer().removeMapLayerListener(localMapLayerListener);                                  event.getLayer().removeMapLayerListener(localMapLayerListener);
438                          // mapImageInvalid = true;                          getLocalRenderer().setContext(getMapContext());
                         // repaint();  
                         localRenderer.setContext(getContext());  
439                          requestStartRendering();                          requestStartRendering();
440                  }                  }
441          };          };
442    
         private final RenderingExecutor localExecuter = new RenderingExecutor(this);  
   
443          /**          /**
444           * Listens to each layer in the local {@link MapContext} for changes and           * Listens to each layer in the local {@link MapContext} for changes and
445           * triggers repaints.           * triggers repaints. We don't have to listen layerChanged, because that is
446             * already done in {@link #localContextListener}
447           */           */
448          protected MapLayerListener localMapLayerListener = new MapLayerAdapter() {          protected MapLayerListener localMapLayerListener = new MapLayerAdapter() {
449    
450                  @Override                  // @Override
451                  public void layerChanged(final MapLayerEvent event) {                  // public void layerChanged(final MapLayerEvent event) {
452                          localRenderer.setContext(getContext()); // betters for SLD changes?!                  // // getLocalRenderer().setContext(getMapContext()); // betters for SLD
453                          // Change of SLD for example                  // // // changes?!
454                          // mapImageInvalid = true;                  // // requestStartRendering();
455                          // repaint();                  // }
                         requestStartRendering();  
                 }  
456    
457                  @Override                  @Override
458                  public void layerHidden(final MapLayerEvent event) {                  public void layerHidden(final MapLayerEvent event) {
                         // mapImageInvalid = true;  
                         // repaint();  
459                          requestStartRendering();                          requestStartRendering();
460                  }                  }
461    
462                  @Override                  @Override
463                  public void layerShown(final MapLayerEvent event) {                  public void layerShown(final MapLayerEvent event) {
                         // mapImageInvalid = true;  
                         // repaint();  
464                          requestStartRendering();                          requestStartRendering();
465                  }                  }
466          };          };
467    
468          private final GTRenderer localRenderer = GTUtil.createGTRenderer();          final private GTRenderer localRenderer = GTUtil.createGTRenderer();
469    
470          private final GTRenderer bgRenderer = GTUtil.createGTRenderer();          private final GTRenderer bgRenderer = GTUtil.createGTRenderer();
471    
# Line 482  public class XMapPane extends JPanel { Line 486  public class XMapPane extends JPanel {
486          /**          /**
487           * 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.
488           */           */
489          private Color mapBackgroundColor = Color.WHITE;          private Color mapBackgroundColor = null;
490    
491          /**          /**
492           * 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 526  public class XMapPane extends JPanel { Line 530  public class XMapPane extends JPanel {
530           * A flag indicating, that the image size has changed and the buffered           * A flag indicating, that the image size has changed and the buffered
531           * images are not big enough any more           * images are not big enough any more
532           **/           **/
533          protected boolean paneResized = false;          protected boolean paneResized = true;
534    
535          private BufferedImage preFinalImage;          private BufferedImage preFinalImage;
536    
537          // if null, no quick preview will be shown          // ** if 0, no quick preview will be shown **/
538          private int quickPreviewHint = 0;          // private int quickPreviewHint = 0;
539    
540          private Map<Object, Object> rendererHints = GTUtil          private Map<Object, Object> rendererHints = GTUtil
541                          .getDefaultGTRendererHints(localRenderer);                          .getDefaultGTRendererHints(getLocalRenderer());
542    
543            /**
544             * If set to <code>true</code>, the {@link #startRenderThreadsTimer} will
545             * start rendering {@link Thread}s
546             **/
547          private volatile Boolean requestStartRendering = false;          private volatile Boolean requestStartRendering = false;
548    
         private final Timer resizeTimer;  
   
549          /**          /**
550           * Transformation zwischen Fenster-Koordinaten und Karten-Koordinaten           * Transformation zwischen Fenster-Koordinaten und Karten-Koordinaten
551           * (lat/lon)           * (lat/lon)
# Line 552  public class XMapPane extends JPanel { Line 558  public class XMapPane extends JPanel {
558           * thread.           * thread.
559           */           */
560          final private Timer startRenderThreadsTimer;          final private Timer startRenderThreadsTimer;
561            //
562          /**          // /**
563           * The default state is ZOOM_IN, hence by default the          // * The default state is ZOOM_IN, hence by default the
564           * {@link #zoomMapPaneMouseListener} is also enabled.          // * {@link #xMapPaneMouseListener} is also enabled.
565           **/          // **/
566          private int state = ZOOM_IN;          // private int state = ZOOM_IN;
567            //
568          /**          // /**
569           * Manuell gesetzter statischer Cursor, unabhaengig von der aktuellen          // * Manuell gesetzter statischer Cursor, unabhaengig von der aktuellen
570           * MapPane-Funktion          // * MapPane-Funktion
571           */          // */
572          protected Cursor staticCursor = null;          // protected Cursor staticCursor = null;
573    
574          private AffineTransform worldToScreen;          private AffineTransform worldToScreen;
575    
576            // /**
577            // * This {@link MouseListener} is managing all zoom related tasks
578            // */
579            // private final ZoomXMapPaneMouseListener zoomMapPaneMouseListener = new
580            // ZoomXMapPaneMouseListener(
581            // this);
582    
583          /**          /**
584           * This {@link MouseListener} is managing all zoom related tasks           * This {@link MouseListener} is managing all zoom related tasks
585           */           */
586          public final ZoomXMapPaneMouseListener zoomMapPaneMouseListener = new ZoomXMapPaneMouseListener(          private final XMapPaneMouseListener xMapPaneMouseListener = new XMapPaneMouseListener(
587                          this);                          this);
588    
589          /** Is set if a renderer has an error **/          /** Is set if a renderer has an error **/
590          protected ArrayList<Exception> renderingErrors = new ArrayList<Exception>();          protected ArrayList<Exception> renderingErrors = new ArrayList<Exception>();
591    
592          // TODO doku          /**
593             * If <code>true</code>, then rendering exceptions are rendererd into the
594             * map pane
595             **/
596            private boolean showExceptions = false;
597    
598          public XMapPane() {          public XMapPane() {
599                  this(null, null);                  this(null, null);
600          }          }
# Line 585  public class XMapPane extends JPanel { Line 603  public class XMapPane extends JPanel {
603           * full constructor extending JPanel           * full constructor extending JPanel
604           *           *
605           * @param rendererHints           * @param rendererHints
606             *            may be <code>null</code>. Otherwise a {@link Map<Object,
607             *            Object>} of {@link RenderingHints} to override the default
608             *            from {@link GTUtil#getDefaultGTRendererHints(GTRenderer)}
609           *           *
          * @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  
610           * @param localContext           * @param localContext
611           *            - {@link MapContext} of layer to render.           *            The main {@link MapContext} to use. If <code>null</code>, an
612             *            empty {@link DefaultMapContext} will be created.
613           */           */
614          public XMapPane(final MapContext localContext_,          public XMapPane(final MapContext localContext_,
615                          final Map<Object, Object> rendererHints) {                          final Map<Object, Object> rendererHints) {
616                    
617                  super(true);                  super(true);
618                    
619                    blinkTimer = initBlinkTimer();
620    
621                    // A default setting
622                    RenderingHints hintsJava2d = ImageUtilities.NN_INTERPOLATION_HINT;
623                    setJava2dHints(hintsJava2d);
624    
625                  setRendererHints(rendererHints);                  setRendererHints(rendererHints);
626    
# Line 609  public class XMapPane extends JPanel { Line 632  public class XMapPane extends JPanel {
632                  /**                  /**
633                   * Adding the #zoomMapPaneMouseListener                   * Adding the #zoomMapPaneMouseListener
634                   */                   */
635                  this.addMouseListener(zoomMapPaneMouseListener);                  this.addMouseListener(xMapPaneMouseListener);
636                  this.addMouseMotionListener(zoomMapPaneMouseListener);                  this.addMouseMotionListener(xMapPaneMouseListener);
637                  this.addMouseWheelListener(zoomMapPaneMouseListener);                  this.addMouseWheelListener(xMapPaneMouseListener);
638    
639                    // By default the XMapPAne uses the ZOOM_IN tool.
640                    setTool(XMapPaneTool.ZOOM_IN);
641    
642                  /*                  /*
643                   * 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 646  public class XMapPane extends JPanel {
646                   * Using a ComponentListener doesn't work because, unlike a JFrame, the                   * Using a ComponentListener doesn't work because, unlike a JFrame, the
647                   * pane receives a stream of events during drag-resizing.                   * pane receives a stream of events during drag-resizing.
648                   */                   */
649                  resizeTimer = new Timer(DEFAULT_RESIZING_PAINT_DELAY, new ActionListener() {                  resizeTimer = new Timer(DEFAULT_RESIZING_PAINT_DELAY,
650                                    new ActionListener() {
                         public void actionPerformed(final ActionEvent e) {  
                                 paneResized = true;  
651    
652                                  if (!isWellDefined())                                          public void actionPerformed(final ActionEvent e) {
653                                          return;                                                  if (!isWellDefined())
654                                                            return;
655    
656                                  final Rectangle bounds = getVisibleRect();                                                  // LOGGER.debug("resizeTimer performed");
657    
658                                  final Envelope geoMapArea = tranformWindowToGeo(bounds.x,                                                  // final Rectangle bounds = getVisibleRect();
659                                                  bounds.y, bounds.x + bounds.width, bounds.y                                                  //
660                                                                  + bounds.height);                                                  // System.out.println("\n\ntimer performs with bounds = "
661                                                    // + bounds);
662    
663                                                    // final Envelope geoMapArea = tranformWindowToGeo(
664                                                    // bounds.x, bounds.y, bounds.x + bounds.width,
665                                                    // bounds.y + bounds.height);
666    
667                                                    paneResized = true;
668                                                    if (!setMapArea(getMapArea())) {
669                                                            // It's important to request new rendering here.
670                                                            // setMapArea only returns true and only calls
671                                                            // requestStartRendering if the maparea has changed.
672                                                            // But if the component is resized, the maparea
673                                                            // doesn't have to change.
674                                                            requestStartRendering();
675                                                    }
676    
677                                  setMapArea(bestAllowedMapArea(geoMapArea));                                          }
678                          }                                  });
                 });  
679                  resizeTimer.setRepeats(false);                  resizeTimer.setRepeats(false);
680    
681                  this.addComponentListener(new ComponentAdapter() {                  this.addComponentListener(new ComponentAdapter() {
682    
683                            private Rectangle oldVisibleRect;
684    
685                          @Override                          @Override
686                          public void componentResized(final ComponentEvent e) {                          public void componentResized(final ComponentEvent e) {
687                                  if (bgExecuter != null)  
688                                          bgExecuter.cancelTask();                                  // Seems to be called twice with the same size..
689                                  if (localExecuter != null)                                  if (oldVisibleRect != null
690                                          localExecuter.cancelTask();                                                  && oldVisibleRect.equals(getVisibleRect())) {
691                                            // LOGGER.debug("skipping resize.");
692                                            return;
693                                    }
694    
695                                    // LOGGER.debug("resized: " + getVisibleRect());
696                                  resizeTimer.restart();                                  resizeTimer.restart();
697                                    oldVisibleRect = getVisibleRect();
698                          }                          }
699    
700                  });                  });
# Line 654  public class XMapPane extends JPanel { Line 702  public class XMapPane extends JPanel {
702                  /*                  /*
703                   * Setting up the repaintTimer. Not started automatically.                   * Setting up the repaintTimer. Not started automatically.
704                   */                   */
705                  repaintTimer = new Timer((int) REPEATING_REPAINT_DELAY,                  repaintTimer = new Timer(REPEATING_REPAINT_DELAY, new ActionListener() {
706                                  new ActionListener() {  
707                            @Override
708                            public void actionPerformed(final ActionEvent e) {
709                                    if ((!localExecuter.isRunning())
710                                                    && (bgExecuter != null && !bgExecuter.isRunning())) {
711                                            repaintTimer.stop();
712                                    } else {
713                                            updateFinalImage();
714                                            XMapPane.this.repaint(100);
715    
716                                    }
717                            }
718                    });
719    
                                         @Override  
                                         public void actionPerformed(final ActionEvent e) {  
                                                 updateFinalImage();  
                                                 XMapPane.this.repaint();  
                                         }  
                                 });  
720                  repaintTimer.setInitialDelay(INITIAL_REPAINT_DELAY);                  repaintTimer.setInitialDelay(INITIAL_REPAINT_DELAY);
721                  repaintTimer.setRepeats(true);                  repaintTimer.setRepeats(true);
722    
# Line 680  public class XMapPane extends JPanel { Line 734  public class XMapPane extends JPanel {
734                                                  if (localExecuter.isRunning()) {                                                  if (localExecuter.isRunning()) {
735                                                          localExecuter.cancelTask();                                                          localExecuter.cancelTask();
736                                                  } else {                                                  } else {
737                                                            // Stupidly, but we have to recheck the
738                                                            setMapArea(getMapArea());
739                                                          requestStartRendering = false;                                                          requestStartRendering = false;
740                                                          startRendering();                                                          startRendering();
741                                                  }                                                  }
# Line 691  public class XMapPane extends JPanel { Line 747  public class XMapPane extends JPanel {
747    
748          }          }
749    
750    
751          /**          /**
752           * Fuegt der Map einen Listener hinzu.           * Fuegt der Map einen Listener hinzu.
753           *           *
# Line 712  public class XMapPane extends JPanel { Line 769  public class XMapPane extends JPanel {
769           * @author <a href="mailto:[email protected]">Stefan Alfons           * @author <a href="mailto:[email protected]">Stefan Alfons
770           *         Kr&uuml;ger</a>           *         Kr&uuml;ger</a>
771           */           */
772          public Envelope bestAllowedMapArea(Envelope env) {          public ReferencedEnvelope bestAllowedMapArea(ReferencedEnvelope env) {
773                  // return env;  
774                  if (getWidth() == 0)                  if (getWidth() == 0)
775                          return env;                          return env;
776    
777                  if (env == null)                  if (env == null)
778                          return null;                          return null;
779    
# Line 765  public class XMapPane extends JPanel { Line 823  public class XMapPane extends JPanel {
823                  }                  }
824    
825                  final Envelope maxAllowedExtend = getMaxExtend();                  final Envelope maxAllowedExtend = getMaxExtend();
826    
827                    // This variable is used to break the loop if it runs forever...
828                    Envelope lastCalculatedArea = null;
829                    /*
830                     * If a maxAllowedExtend is set, we have to honour that...
831                     */
832                  while (maxAllowedExtend != null && !maxAllowedExtend.contains(newArea)                  while (maxAllowedExtend != null && !maxAllowedExtend.contains(newArea)
833                                  && newArea != null && !newArea.isNull()                                  && newArea != null && !newArea.isNull()
834                                  && !Double.isNaN(newArea.getMinX())                                  && !Double.isNaN(newArea.getMinX())
835                                  && !Double.isNaN(newArea.getMaxX())                                  && !Double.isNaN(newArea.getMaxX())
836                                  && !Double.isNaN(newArea.getMinY())                                  && !Double.isNaN(newArea.getMinY())
837                                  && !Double.isNaN(newArea.getMaxY())) {                                  && !Double.isNaN(newArea.getMaxY())) // Due to Double precision
838                          /*                  // problems, this may
839                           * If a maxExtend is set, we have to honour that...                  // iterate for ever
840                           */                  {
841    
842                            if (newArea.equals(lastCalculatedArea))
843                                    break;
844                            // Check that we are not iterating for ever due to double precision
845                            // rounding errors
846                            lastCalculatedArea = newArea;
847    
848                          // Exceeds top? Move down and maybe cut                          // Exceeds top? Move down and maybe cut
849                          if (newArea.getMaxY() > maxAllowedExtend.getMaxY()) {                          if (newArea.getMaxY() > maxAllowedExtend.getMaxY()) {
# Line 794  public class XMapPane extends JPanel { Line 864  public class XMapPane extends JPanel {
864    
865                                          // LOGGER.debug("and fix aspect ratio");                                          // LOGGER.debug("and fix aspect ratio");
866    
867                                          newArea = JTSUtil.fixAspectRatio(getVisibleRect(), newArea,                                          newArea = JTSUtil.fixAspectRatio(getVisibleRect(),
868                                                          false);                                                          new ReferencedEnvelope(newArea, env
869                                                                            .getCoordinateReferenceSystem()), false);
870                                  }                                  }
871                          }                          }
872    
# Line 818  public class XMapPane extends JPanel { Line 889  public class XMapPane extends JPanel {
889    
890                                          // LOGGER.debug("and fix aspect ratio");                                          // LOGGER.debug("and fix aspect ratio");
891    
892                                          newArea = JTSUtil.fixAspectRatio(getVisibleRect(), newArea,                                          newArea = JTSUtil.fixAspectRatio(getVisibleRect(),
893                                                          false);                                                          new ReferencedEnvelope(newArea, env
894                                                                            .getCoordinateReferenceSystem()), false);
895                                  }                                  }
896                          }                          }
897    
# Line 844  public class XMapPane extends JPanel { Line 916  public class XMapPane extends JPanel {
916    
917                                          // LOGGER.debug("and fix aspect ratio");                                          // LOGGER.debug("and fix aspect ratio");
918    
919                                          newArea = JTSUtil.fixAspectRatio(getVisibleRect(), newArea,                                          newArea = JTSUtil.fixAspectRatio(getVisibleRect(),
920                                                          false);                                                          new ReferencedEnvelope(newArea, env
921                                                                            .getCoordinateReferenceSystem()), false);
922                                  }                                  }
923                          }                          }
924    
# Line 870  public class XMapPane extends JPanel { Line 943  public class XMapPane extends JPanel {
943    
944                                          // LOGGER.debug("and fix aspect ratio");                                          // LOGGER.debug("and fix aspect ratio");
945    
946                                          newArea = JTSUtil.fixAspectRatio(getVisibleRect(), newArea,                                          newArea = JTSUtil.fixAspectRatio(getVisibleRect(),
947                                                          false);                                                          new ReferencedEnvelope(newArea, env
948                                                                            .getCoordinateReferenceSystem()), false);
949                                  }                                  }
950                          }                          }
951    
952                  }                  }
953    
954                  return newArea;                  return new ReferencedEnvelope(newArea, env
955                                    .getCoordinateReferenceSystem());
956          }          }
957    
958          /**          /**
# Line 904  public class XMapPane extends JPanel { Line 980  public class XMapPane extends JPanel {
980                          bgExecuter.dispose();                          bgExecuter.dispose();
981                  }                  }
982    
983                  if (localExecuter != null) {                  if (localExecuter.isRunning()) {
984                          int i = 0;                          int i = 0;
985                          localExecuter.cancelTask();                          localExecuter.cancelTask();
986                          while (i++ < 10 && localExecuter.isRunning()) {                          while (i++ < 10 && localExecuter.isRunning()) {
987                                  try {                                  try {
988                                          Thread.sleep(100);                                          Thread.sleep(200);
989                                  } catch (final InterruptedException e) {                                  } catch (final InterruptedException e) {
990                                          // TODO Auto-generated catch block                                          LOGGER
991                                          e.printStackTrace();                                                          .warn(
992                                                                            "while XMapPane we are waiting for the localExcutor to stop",
993                                                                            e);
994                                  }                                  }
995                          }                          }
996                          if (localExecuter.isRunning()) {                          if (localExecuter.isRunning()) {
997                                  System.out                                  LOGGER
998                                                  .println("BAD BAD BAD... still running the thread....");                                                  .warn("localExecutor Thread still running after 2s! Continuing anyways...");
999                          }                          }
1000                          localExecuter.dispose();                          localExecuter.dispose();
1001                  }                  }
1002    
1003                  disposeImages();                  disposeImages();
1004    
1005                  // LangUtil.gcTotal();                  // Remove all mapPaneListeners that have registered with us
   
                 // Alle mapPaneListener entfernen  
1006                  mapPaneListeners.clear();                  mapPaneListeners.clear();
1007    
1008                  removeMouseMotionListener(zoomMapPaneMouseListener);                  removeMouseMotionListener(xMapPaneMouseListener);
1009                  removeMouseListener(zoomMapPaneMouseListener);                  removeMouseListener(xMapPaneMouseListener);
1010    
1011                  if (localContext != null)                  if (localContext != null)
1012                          getContext().clearLayerList();                          getMapContext().clearLayerList();
1013                  if (bgContext != null)                  if (bgContext != null)
1014                          getBgContext().clearLayerList();                          getBgContext().clearLayerList();
1015    
# Line 946  public class XMapPane extends JPanel { Line 1022  public class XMapPane extends JPanel {
1022           */           */
1023          protected void drawRectangle(final Graphics graphics, final Point startPos,          protected void drawRectangle(final Graphics graphics, final Point startPos,
1024                          final Point e) {                          final Point e) {
1025                    drawRectangle(graphics, startPos, e, Color.WHITE, false);
1026            }
1027    
1028            /**
1029             * Draws a rectangle in XOR mode from the origin at {@link #startPos} to the
1030             * given point. All in screen coordinates.
1031             */
1032            protected void drawRectangle(final Graphics graphics, final Point startPos,
1033                            final Point e, Color color, boolean fill) {
1034    
1035                  if (!isWellDefined())                  if (!isWellDefined())
1036                          return;                          return;
# Line 961  public class XMapPane extends JPanel { Line 1046  public class XMapPane extends JPanel {
1046                  if (width == 0 && height == 0)                  if (width == 0 && height == 0)
1047                          return;                          return;
1048    
1049                  graphics.setXORMode(Color.WHITE);                  graphics.setXORMode(color);
1050    
1051                    if (fill) {
1052                            graphics.fillRect(left, bottom, width, height);
1053                            graphics.setXORMode(Color.WHITE);
1054                    }
1055    
1056                  graphics.drawRect(left, bottom, width, height);                  graphics.drawRect(left, bottom, width, height);
1057          }          }
1058    
# Line 973  public class XMapPane extends JPanel { Line 1064  public class XMapPane extends JPanel {
1064           *           *
1065           * @param g           * @param g
1066           *            Graphics2D to paint the preview into           *            Graphics2D to paint the preview into
          *  
          * @param state  
          *            Max be {@link #ZOOM_IN} or {@link #ZOOM_OUT}  
1067           */           */
1068          protected boolean drawScaledPreviewImage_Zoom(final Graphics2D graphics) {          protected boolean drawScaledPreviewImage_Zoom(final Graphics2D graphics) {
1069    
1070  //              if (1 == 1)return false;                  // if (1 == 1)return false;
1071                                    // if (quickPreviewHint == 0)
1072                  if (quickPreviewHint == 0)                  // return false;
                         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);  
1073    
1074                  if (oldMapArea == null)                  if (oldMapArea == null)
1075                          return false;                          return false;
1076    
1077                    if (getPreFinalImage() == null)
1078                            return false;
1079    
1080                  final Rectangle visibleArea = getVisibleRect();                  final Rectangle visibleArea = getVisibleRect();
1081    
1082                  // Calculate the oldMapArea in the current WindowCoordinates:                  // Calculate the oldMapArea in the current WindowCoordinates:
# Line 1006  public class XMapPane extends JPanel { Line 1089  public class XMapPane extends JPanel {
1089                  final int xx2 = (int) Math.round(oldMapWindow.getMaxX());                  final int xx2 = (int) Math.round(oldMapWindow.getMaxX());
1090                  final int yy2 = (int) Math.round(oldMapWindow.getMaxY());                  final int yy2 = (int) Math.round(oldMapWindow.getMaxY());
1091    
1092                    graphics.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
1093                                    RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR);
1094                    graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
1095                                    RenderingHints.VALUE_ANTIALIAS_OFF);
1096                    graphics.setRenderingHint(RenderingHints.KEY_RENDERING,
1097                                    RenderingHints.VALUE_RENDER_SPEED);
1098    
1099                  graphics.drawImage(getPreFinalImage(), xx1, yy1, xx2, yy2,                  graphics.drawImage(getPreFinalImage(), xx1, yy1, xx2, yy2,
1100                                  (int) visibleArea.getMinX(), (int) visibleArea.getMinY(),                                  (int) visibleArea.getMinX(), (int) visibleArea.getMinY(),
1101                                  (int) visibleArea.getMaxX(), (int) visibleArea.getMaxY(),                                  (int) visibleArea.getMaxX(), (int) visibleArea.getMaxY(),
# Line 1014  public class XMapPane extends JPanel { Line 1104  public class XMapPane extends JPanel {
1104                  final Rectangle painedArea = new Rectangle(xx1, yy1, xx2 - xx1, yy2                  final Rectangle painedArea = new Rectangle(xx1, yy1, xx2 - xx1, yy2
1105                                  - yy1);                                  - yy1);
1106    
1107                  SwingUtil.clearAround(graphics, painedArea, visibleArea);                  SwingUtil.clearAround(graphics, painedArea, visibleArea,
1108                                    getMapBackgroundColor());
1109    
1110                  addGadgets(graphics, true);                  addGadgets(graphics, true);
1111    
1112                  quickPreviewHint = 0;                  // quickPreviewHint = 0;
1113    
1114                  repaintTimer.restart();                  repaintTimer.restart();
1115    
                 graphics.dispose();  
   
1116                  // Something has been drawn                  // Something has been drawn
1117                  return true;                  return true;
1118          }          }
# Line 1036  public class XMapPane extends JPanel { Line 1125  public class XMapPane extends JPanel {
1125           * Lazyly initializes a {@link BufferedImage} for the background renderer.           * Lazyly initializes a {@link BufferedImage} for the background renderer.
1126           */           */
1127          private Image getBgImage() {          private Image getBgImage() {
1128                  //                  if (bgImage == null) {
1129                  // if (bgImage == null) {                          bgImage = new BufferedImage(getVisibleRect().width,
1130                  // bgImage = createImage(getBounds().width, getBounds().height);                                          getVisibleRect().height, IMAGETYPE);
1131                  // }                          SwingUtil.clearImage(finalImage, getMapBackgroundColor());
1132                    }
1133    
1134                  return bgImage;                  return bgImage;
1135          }          }
1136    
1137          public MapContext getContext() {          public MapContext getMapContext() {
1138                  if (localContext == null) {                  if (localContext == null) {
1139                          setLocalContext(new DefaultMapContext());                          setLocalContext(new DefaultMapContext());
1140                  }                  }
# Line 1057  public class XMapPane extends JPanel { Line 1147  public class XMapPane extends JPanel {
1147                          // Rectangle curPaintArea = getVisibleRect();                          // Rectangle curPaintArea = getVisibleRect();
1148                          finalImage = new BufferedImage(getVisibleRect().width,                          finalImage = new BufferedImage(getVisibleRect().width,
1149                                          getVisibleRect().height, IMAGETYPE);                                          getVisibleRect().height, IMAGETYPE);
1150                            SwingUtil.clearImage(finalImage, getMapBackgroundColor());
1151    
1152                          requestStartRendering();                          // requestStartRendering();
1153                  }                  }
1154                  return finalImage;                  return finalImage;
1155          }          }
1156    
         public RenderingHints getJava2dHints() {  
                 return java2dHints;  
         }  
   
1157          /**          /**
1158           * Lazyly initializes a {@link BufferedImage} for the background renderer.           * Lazyly initializes a {@link BufferedImage} for the background renderer.
1159           */           */
# Line 1075  public class XMapPane extends JPanel { Line 1162  public class XMapPane extends JPanel {
1162                  if (localImage == null) {                  if (localImage == null) {
1163                          localImage = new BufferedImage(getVisibleRect().width,                          localImage = new BufferedImage(getVisibleRect().width,
1164                                          getVisibleRect().height, IMAGETYPE_withAlpha);                                          getVisibleRect().height, IMAGETYPE_withAlpha);
1165                            SwingUtil.clearImage(localImage, getMapBackgroundColor());
1166                  }                  }
1167    
1168                  return localImage;                  return localImage;
# Line 1090  public class XMapPane extends JPanel { Line 1178  public class XMapPane extends JPanel {
1178                          ReferencedEnvelope mapArea_ = null;                          ReferencedEnvelope mapArea_ = null;
1179                          try {                          try {
1180                                  mapArea_ = localContext.getLayerBounds();                                  mapArea_ = localContext.getLayerBounds();
1181                          } catch (final IOException e) {                          } catch (final Exception e) {
1182                                  LOGGER.warn("context.getLayerBounds()", e);                                  LOGGER.warn("localContext.getLayerBounds()", e);
1183                            }
1184    
1185                            if (mapArea_ == null && bgContext != null) {
1186                                    try {
1187                                            mapArea_ = bgContext.getLayerBounds();
1188                                    } catch (final IOException e) {
1189                                            LOGGER.warn("bgContext.getLayerBounds()", e);
1190                                    }
1191                          }                          }
1192    
1193                          if (mapArea_ != null) {                          if (mapArea_ != null) {
                                 mapImageInvalid = true; /* note we need to redraw */  
                                 // setMapArea(mapArea_); // results in a loop  
1194                                  mapArea = bestAllowedMapArea(mapArea_);                                  mapArea = bestAllowedMapArea(mapArea_);
1195                                    requestStartRendering();
1196                          }                          }
1197                  }                  }
1198    
# Line 1109  public class XMapPane extends JPanel { Line 1204  public class XMapPane extends JPanel {
1204                          try {                          try {
1205                                  localContext.setCoordinateReferenceSystem(GeoImportUtil                                  localContext.setCoordinateReferenceSystem(GeoImportUtil
1206                                                  .getDefaultCRS());                                                  .getDefaultCRS());
1207                          } catch (Exception e) {                          } catch (final Exception e) {
1208                                  throw new RuntimeException("setting context CRS:", e);                                  throw new RuntimeException("setting context CRS:", e);
1209                          }                          }
1210    
# Line 1118  public class XMapPane extends JPanel { Line 1213  public class XMapPane extends JPanel {
1213          }          }
1214    
1215          /**          /**
1216           * 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
1217             * methods looks for a parent component and will use its background color.
1218             * If no parent component is available, WHITE is returned.
1219           **/           **/
1220          public Color getMapBackgroundColor() {          public Color getMapBackgroundColor() {
1221                    if (mapBackgroundColor == null) {
1222                            if (getParent() != null)
1223                                    return getParent().getBackground();
1224                            else
1225                                    return Color.WHITE;
1226                    }
1227                  return mapBackgroundColor;                  return mapBackgroundColor;
1228          }          }
1229    
# Line 1147  public class XMapPane extends JPanel { Line 1250  public class XMapPane extends JPanel {
1250    
1251          public Envelope getMaxExtend() {          public Envelope getMaxExtend() {
1252                  if (maxExtend == null) {                  if (maxExtend == null) {
1253    
1254                            // The next command may take long time!
1255                            // long start = System.currentTimeMillis();
1256                          final ReferencedEnvelope layerBounds = GTUtil                          final ReferencedEnvelope layerBounds = GTUtil
1257                                          .getVisibleLayoutBounds(localContext);                                          .getVisibleLayoutBounds(localContext);
1258                            //                      
1259                            // LOGGER.info(
1260                            // (System.currentTimeMillis()-start)+"m to get maxExtend");
1261                            //                      
1262                          if (layerBounds == null) {                          if (layerBounds == null) {
1263                                  // TODO Last fallback could be the CRS valid area                                  // // TODO Last fallback could be the CRS valid area
1264                                  return null;                                  return null;
1265                          }                          }
1266    
1267                          // Kartenbereich um 10% vergroessern                          return JTSUtil.fixAspectRatio(getVisibleRect(),
1268                          return JTSUtil.fixAspectRatio(getVisibleRect(), JTSUtil                                          addDefaultMargin(layerBounds), true);
1269                                          .expandEnvelope(layerBounds, 0.1), true);  
1270                  }                  }
1271                  return maxExtend;                  return maxExtend;
1272          }          }
# Line 1184  public class XMapPane extends JPanel { Line 1294  public class XMapPane extends JPanel {
1294          }          }
1295    
1296          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();  
                 // }  
1297                  return preFinalImage;                  return preFinalImage;
1298          }          }
1299    
# Line 1221  public class XMapPane extends JPanel { Line 1321  public class XMapPane extends JPanel {
1321                  return new AffineTransform(screenToWorld);                  return new AffineTransform(screenToWorld);
1322          }          }
1323    
1324          public int getState() {          // public int getState() {
1325                  return state;          // return state;
1326          }          // }
1327            //
1328          /**          // /**
1329           * Liefert den statisch eingestellten Cursor, der unabhaengig von der          // * Liefert den statisch eingestellten Cursor, der unabhaengig von der
1330           * eingestellten MapPane-Aktion (Zoom, Auswahl, ...) verwendet wird.          // * eingestellten MapPane-Aktion (Zoom, Auswahl, ...) verwendet wird.
1331           *          // *
1332           * @return {@code null}, wenn kein statischer Cursor verwendet, sondern der          // * @return {@code null}, wenn kein statischer Cursor verwendet, sondern
1333           *         Cursor automatisch je nach MapPane-Aktion eingestellt wird.          // der
1334           */          // * Cursor automatisch je nach MapPane-Aktion eingestellt wird.
1335          public Cursor getStaticCursor() {          // */
1336                  return this.staticCursor;          // public Cursor getStaticCursor() {
1337          }          // return this.staticCursor;
1338            // }
1339    
1340          public AffineTransform getWorldToScreenTransform() {          public AffineTransform getWorldToScreenTransform() {
1341                  if (worldToScreen == null) {                  if (worldToScreen == null) {
# Line 1270  public class XMapPane extends JPanel { Line 1371  public class XMapPane extends JPanel {
1371           * {@link XMapPane} is visible and has bounds set.           * {@link XMapPane} is visible and has bounds set.
1372           */           */
1373          public boolean isWellDefined() {          public boolean isWellDefined() {
   
1374                  try {                  try {
1375                            if (getMapContext() == null)
                         if (getContext() == null)  
                                 return false;  
                         if (getContext().getLayerCount() <= 0)  
1376                                  return false;                                  return false;
1377                          if (getMapArea() == null)                          if (getMapContext().getLayerCount() <= 0)
1378                                  return false;                                  return false;
1379                          if (getBounds().getWidth() == 0)                          if (getVisibleRect().getWidth() == 0)
1380                                  return false;                                  return false;
1381                          if (getBounds().getHeight() == 0)                          if (getVisibleRect().getHeight() == 0)
1382                                  return false;                                  return false;
1383                            // if (getMapArea() == null)
1384                            // return false;
1385                  } catch (final Exception e) {                  } catch (final Exception e) {
1386                          return false;                          return false;
1387                  }                  }
1388                  return true;                  return true;
1389          }          }
1390    
1391          public void mouseDragged(final Point startPos, final Point lastPos,          /**
1392                          final MouseEvent event) {           * Usually called from {@link XMapPaneAction_Pan} to pan the image.
1393             *
1394                  if ((getState() == XMapPane.PAN)           * @param startPos
1395                                  || ((event.getModifiersEx() & InputEvent.BUTTON3_DOWN_MASK) != 0)) {           *            in screen coordinates
1396             * @param lastPos
1397                          if (getCursor() != SwingUtil.PANNING_CURSOR) {           *            in screen coordinates
1398                                  setCursor(SwingUtil.PANNING_CURSOR);           */
1399            public void pan(final int dX, final int dY) {
1400                                  // While panning, we deactivate the rendering. So the tasts are  
1401                                  // ready to start when the panning os done.                  // Panning needs a panning coursor
1402                                  if (bgExecuter != null)                  if (getCursor() != SwingUtil.PANNING_CURSOR) {
1403                                          bgExecuter.cancelTask();                          setCursor(SwingUtil.PANNING_CURSOR);
1404                                  if (localExecuter != null)  
1405                                          localExecuter.cancelTask();                          // While panning, we deactivate the rendering. So the tasks are
1406                          }                          // ready to start when the panning is finished.
1407                            if (bgExecuter != null && bgExecuter.isRunning())
1408                          if (lastPos.x > 0 && lastPos.y > 0) {                                  bgExecuter.cancelTask();
1409                                  final int dx = event.getX() - lastPos.x;                          if (localExecuter.isRunning())
1410                                  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();  
   
1411                  }                  }
1412                    //
1413                    // if (lastPos.x > 0 && lastPos.y > 0) {
1414                    // final int dx = event.getX() - lastPos.x;
1415                    // final int dy = event.getY() - lastPos.y;
1416    
1417                    // TODO Stop dragging when the drag would not be valid...
1418                    // boolean dragValid = true;
1419                    // // check if this panning results in a valid mapArea
1420                    // {
1421                    // Rectangle winBounds = xMapPane.getBounds();
1422                    // winBounds.translate(xMapPane.imageOrigin.x,
1423                    // -xMapPane.imageOrigin.y);
1424                    // Envelope newMapAreaBefore = xMapPane.tranformWindowToGeo(
1425                    // winBounds.x, winBounds.y, winBounds.x
1426                    // + winBounds.width, winBounds.y
1427                    // + winBounds.height);
1428                    //                                      
1429                    //
1430                    // winBounds = xMapPane.getBounds();
1431                    // Point testIng = new Point(xMapPane.imageOrigin);
1432                    // testIng.translate(dx, dy);
1433                    // winBounds.translate(testIng.x, -testIng.y);
1434                    // Envelope newMapAreaAfter = xMapPane.tranformWindowToGeo(
1435                    // winBounds.x, winBounds.y, winBounds.x
1436                    // + winBounds.width, winBounds.y
1437                    // + winBounds.height);
1438                    //
1439                    // // If the last drag doesn't change the MapArea anymore cancel
1440                    // it.
1441                    // if (xMapPane.bestAllowedMapArea(newMapAreaAfter).equals(
1442                    // xMapPane.bestAllowedMapArea(newMapAreaBefore))){
1443                    // dragValid = false;
1444                    // return;
1445                    // }
1446                    // }
1447    
1448                    getImageOrigin().translate(dX, dY);
1449                    updateFinalImage();
1450                    repaint();
1451                    // }
1452    
1453                    // } else if ((getState() == XMapPane.ZOOM_IN)
1454                    // || (getState() == XMapPane.ZOOM_OUT)
1455                    // || (getState() == XMapPane.SELECT_ALL)
1456                    // || (getState() == XMapPane.SELECT_TOP)) {
1457                    //
1458                    // // Draws a rectangle
1459                    // final Graphics2D graphics = (Graphics2D) getGraphics();
1460                    // drawRectangle(graphics, startPos, event.getPoint());
1461                    // if ((lastPos.x > 0) && (lastPos.y > 0))
1462                    // drawRectangle(graphics, startPos, lastPos);
1463                    // graphics.dispose();
1464                    // }
1465          }          }
1466    
1467          /**          /**
1468           * Called by the {@link RenderingExecutor} when rendering was cancelled.           * Called by the {@link RenderingExecutor} when rendering was cancelled.
1469           */           */
1470          public void onRenderingCancelled() {          public void onRenderingCancelled() {
1471                    // LOGGER.debug("Rendering cancelled");
1472                  repaintTimer.stop();                  repaintTimer.stop();
                 LOGGER.debug("Rendering cancelled");  
1473          }          }
1474    
1475          /**          /**
1476           * Called by the {@link RenderingExecutor} when rendering has been           * Called by the {@link RenderingExecutor} when rendering has been
1477           * completed.           * completed.
1478             *
1479             * @param l
1480             *            long ms the rendering took
1481           */           */
1482          public void onRenderingCompleted() {          public void onRenderingCompleted(final long l) {
1483                    lastRenderingDuration = (lastRenderingDuration + l) / 2;
1484                    // LOGGER
1485                    // .debug("complete rendering after " + lastRenderingDuration
1486                    // + "ms");
1487    
1488                  repaintTimer.stop();                  repaintTimer.stop();
1489                  updateFinalImage();  
1490                  repaint();                  // We "forget" about an exception every time we complete a rendering
1491                    // thread successfully
1492                  if (renderingErrors.size() > 0)                  if (renderingErrors.size() > 0)
1493                          renderingErrors.remove(0);                          renderingErrors.remove(0);
1494    
1495                    updateFinalImage();
1496                    repaint();
1497          }          }
1498    
1499          /**          /**
# Line 1397  public class XMapPane extends JPanel { Line 1507  public class XMapPane extends JPanel {
1507           * @see MapPaneListener#onRenderingStopped(org.geotools.swing.event.MapPaneEvent)           * @see MapPaneListener#onRenderingStopped(org.geotools.swing.event.MapPaneEvent)
1508           */           */
1509          public void onRenderingFailed(final Exception renderingError) {          public void onRenderingFailed(final Exception renderingError) {
1510                  this.renderingErrors.add(renderingError);  
1511                    // Store the exceptions so we can show it to the user:
1512                    if (!(renderingError instanceof java.lang.IllegalArgumentException && renderingError
1513                                    .getMessage().equals(
1514                                                    "Argument \"sourceCRS\" should not be null.")))
1515                            this.renderingErrors.add(renderingError);
1516                  if (renderingErrors.size() > 3)                  if (renderingErrors.size() > 3)
1517                          renderingErrors.remove(0);                          renderingErrors.remove(0);
1518    
1519                  repaintTimer.stop();                  repaintTimer.stop();
1520    
1521                  LOGGER.warn("Rendering failed", renderingError);                  LOGGER.warn("Rendering failed", renderingError);
1522                  updateFinalImage();                  updateFinalImage();
1523                  repaint();                  repaint();
1524    
1525          }          }
1526    
         public void onRenderingPending() {  
                 // LOGGER.debug("Pending rendering updates the preview...");  
                 updateFinalImage();  
                 repaint();  
         }  
   
1527          @Override          @Override
1528          protected void paintComponent(final Graphics g) {          protected void paintComponent(final Graphics g) {
                 if (!acceptsRepaintCalls)  
                         return;  
1529    
1530                  // Maybe update the cursor and maybe stop the repainting timer                  // Maybe update the cursor and maybe stop the repainting timer
1531                  updateCursor();                  updateCursor();
1532    
1533                    if (!acceptsRepaintCalls)
1534                            return;
1535    
1536                    if (!isWellDefined())
1537                            return;
1538                    //
1539                    // if (paneResized) {
1540                    // // ((Graphics2D) g).setBackground(getMapBackgroundColor());
1541                    // // g.clearRect(0, 0, getVisibleRect().width,
1542                    // getVisibleRect().height);
1543                    // return;
1544                    // }
1545    
1546                  // super.paintComponent(g); // candidate for removal                  // super.paintComponent(g); // candidate for removal
1547    
1548                  boolean paintedSomething = false;                  boolean paintedSomething = false;
# Line 1432  public class XMapPane extends JPanel { Line 1554  public class XMapPane extends JPanel {
1554                          // If the new mapArea and the oldMapArea intersect, we can draw some                          // If the new mapArea and the oldMapArea intersect, we can draw some
1555                          // quick scaled preview to make the user feel that something is                          // quick scaled preview to make the user feel that something is
1556                          // happening.                          // happening.
1557                          if (mapAreaChanged && oldMapArea != null                          if (lastRenderingDuration > PRESCALE_MINTIME && mapAreaChanged
1558                                            && oldMapArea != null
1559                                          && getMapArea().intersects(oldMapArea)                                          && getMapArea().intersects(oldMapArea)
1560                                          & !getMapArea().equals(oldMapArea)) {                                          && !getMapArea().equals(oldMapArea) && !paneResized) {
1561    
1562                                  mapAreaChanged = false;                                  mapAreaChanged = false;
1563    
1564                                  if (getMapArea().covers(oldMapArea)) {                                  // if (getMapArea().covers(oldMapArea)) {
1565                                          setQuickPreviewHint(ZOOM_OUT);                                  // // quickPreviewHint = ZOOM_OUT;
1566                                          paintedSomething = drawScaledPreviewImage_Zoom((Graphics2D) g);                                  // paintedSomething = drawScaledPreviewImage_Zoom((Graphics2D)
1567                                  } else if (oldMapArea.covers(getMapArea())) {                                  // g);
1568                                          setQuickPreviewHint(ZOOM_IN);                                  // } else if (oldMapArea.covers(getMapArea())) {
1569                                          paintedSomething = drawScaledPreviewImage_Zoom((Graphics2D) g);                                  // quickPreviewHint = ZOOM_IN;
1570                                  }                                  paintedSomething = drawScaledPreviewImage_Zoom((Graphics2D) g);
1571                                    // }
                         }  
   
                         if (paneResized) {  
                                 paneResized = false;  
                                 disposeImages();  
1572                          }                          }
   
                         // Start the Threads and Timers to render the image  
                         requestStartRendering();  
   
1573                  }                  }
1574    
1575                  if (!paintedSomething) {                  if (!paintedSomething) {
1576    
1577                          g.drawImage(getFinalImage(), 0, 0, null);                          g.drawImage(getFinalImage(), 0, 0, null);
1578    
                         g.dispose(); // cand. for removal  
   
1579                          paintedSomething = true; // cand. for removal                          paintedSomething = true; // cand. for removal
1580                  }                  }
1581    
# Line 1512  public class XMapPane extends JPanel { Line 1624  public class XMapPane extends JPanel {
1624    
1625          }          }
1626    
         /**  
          * 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() {  
   
                 Rectangle winBounds = getVisibleRect();  
                   
                 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);  
         }  
   
1627          //          //
1628          // /**          // /**
1629          // * Nuetzlich wenn die Componente gedruckt (z.B. wenn ein Screenshot          // * Performs a {@value #PAN} action. During panning, the displacement is
1630          // gemacht          // * stored in {@link #imageOrigin} object. Calling {@link #performPan()}
1631          // * wird) wird. Dann werden wird der Hintergrund auf WEISS gesetzt.          // will
1632          // *          // * reset the offset and call {@link #setMapArea(Envelope)}.
         // * @author <a href="mailto:[email protected]">Stefan Alfons  
         // * Kr&uuml;ger</a>  
1633          // */          // */
1634          // @Override          // public void performPan() {
         // public void print(final Graphics g) {  
         // final Color orig = getBackground();  
         // setBackground(Color.WHITE);  
1635          //          //
1636          // // wrap in try/finally so that we always restore the state          // final Rectangle winBounds = getVisibleRect();
1637          // try {          //
1638          // super.print(g);          // winBounds.translate(-imageOrigin.x, -imageOrigin.y);
1639          // } finally {          // final Envelope newMapArea = tranformWindowToGeo(winBounds.x,
1640          // setBackground(orig);          // winBounds.y, winBounds.x + winBounds.width, winBounds.y
1641            // + winBounds.height);
1642            //
1643            // imageOrigin.x = 0;
1644            // imageOrigin.y = 0;
1645            //
1646            // if (!setMapArea(newMapArea)) {
1647            // /**
1648            // * If setMapArea returns true, the finalImage is updated anyways.
1649            // * This if-case exists to ensure that we repaint a correct image
1650            // * even if the new panning area has been denied.
1651            // */
1652            // updateFinalImage();
1653            // repaint();
1654          // }          // }
1655            //
1656            // if (getCursor() == SwingUtil.PANNING_CURSOR)
1657            // setCursor(SwingUtil.PAN_CURSOR);
1658          // }          // }
1659    
1660          /**          /**
# Line 1583  public class XMapPane extends JPanel { Line 1675  public class XMapPane extends JPanel {
1675          private void requestStartRendering() {          private void requestStartRendering() {
1676                  if (bgExecuter != null)                  if (bgExecuter != null)
1677                          bgExecuter.cancelTask();                          bgExecuter.cancelTask();
1678                  if (localExecuter != null)  
1679                          localExecuter.cancelTask();                  localExecuter.cancelTask();
1680    
1681                    mapImageInvalid = true;
1682                    if (paneResized) {
1683                            paneResized = false;
1684                            disposeImages();
1685                    }
1686                  requestStartRendering = true;                  requestStartRendering = true;
1687    
1688          }          }
1689    
         //  
         // /**  
         // * Berechnet die Transformation zwischen Fenster- und Karten-Koordinaten  
         // * neu.  
         // */  
         // protected void resetTransforms() {  
         // if (getMapArea() == null || getWidth() == 0 || getHeight() == 0)  
         // return;  
         //  
         // // We store the last Transform  
         // oldScreenToWorld = screenToWorld;  
         //  
         // this.screenToWorld = new AffineTransform(  
         // // Genauso wie die Fenster-Koordinaten, werden die Longitude-Koordinaten  
         // // nach rechts (Osten) hin groesser  
         // // --> positive Verschiebung  
         // getMapArea().getWidth() / getWidth(),  
         // // keine Verzerrung  
         // 0.0, 0.0,  
         // // Waehrend die Fenster-Koordinaten nach unten hin groesser  
         // // werden,  
         // // werden Latitude-Koordinaten nach Sueden hin keiner  
         // // --> negative Verschiebung  
         // -getMapArea().getHeight() / getHeight(),  
         // // Die Longitude-Koordinaten werden nach Osten hin groesser  
         // // --> obere linke Ecke des Fensters hat also den Minimalwert  
         // getMapArea().getMinX(),  
         // // Die Latitude-Koordinaten werden nach Norden hin groesser  
         // // --> obere linke Ecke des Fensters hat also den Maximalwert  
         // getMapArea().getMaxY());  
         //  
         // try {  
         // this.worldToScreen = screenToWorld.createInverse();  
         // } catch (final NoninvertibleTransformException e) {  
         // LOGGER.error(e);  
         // }  
         // }  
   
1690          /**          /**
1691           * Calculate the affine transforms used to convert between world and pixel           * Calculate the affine transforms used to convert between world and pixel
1692           * coordinates. The calculations here are very basic and assume a cartesian           * coordinates. The calculations here are very basic and assume a cartesian
# Line 1641  public class XMapPane extends JPanel { Line 1701  public class XMapPane extends JPanel {
1701           *            the current map pane extent (screen units)           *            the current map pane extent (screen units)
1702           */           */
1703          private void resetTransforms() {          private void resetTransforms() {
1704                  ReferencedEnvelope refMapEnv = new ReferencedEnvelope(mapArea,                  // System.out
1705                                  getContext().getCoordinateReferenceSystem());                  // .println("paintArea in resetTeansofrms = " + getVisibleRect());
1706                    if (!isWellDefined())
1707                            return;
1708    
1709                  Rectangle paintArea = getVisibleRect(); // NOT USE GET BOUNDS!                  if (mapArea == null)
1710                                            return;
1711                  //          
1712                  // double xscale = paintArea.getWidth() / refEnv.getWidth();                  final ReferencedEnvelope refMapEnv = new ReferencedEnvelope(mapArea,
1713                  // double yscale = paintArea.getHeight() / refEnv.getHeight();                                  getMapContext().getCoordinateReferenceSystem());
                 //  
                 // double scale = Math.min(xscale, yscale);  
                 //  
                 // double xoff = refEnv.getMedian(0) * scale - paintArea.getCenterX();  
                 // double yoff = refEnv.getMedian(1) * scale + paintArea.getCenterY();  
1714    
1715                  worldToScreen = RendererUtilities.worldToScreenTransform(refMapEnv,                  worldToScreen = RendererUtilities.worldToScreenTransform(refMapEnv,
1716                                  paintArea);                                  getVisibleRect());
1717    
                 // worldToScreen = new AffineTransform(scale, 0, 0, -scale, -xoff,  
                 // yoff);  
1718                  try {                  try {
1719                          screenToWorld = worldToScreen.createInverse();                          screenToWorld = worldToScreen.createInverse();
1720    
1721                  } catch (NoninvertibleTransformException ex) {                  } catch (final NoninvertibleTransformException ex) {
1722                          ex.printStackTrace();                          LOGGER
1723                                            .error("can't invert worldToScreen to get screenToWorld!",
1724                                                            ex);
1725                  }                  }
1726          }          }
1727    
# Line 1683  public class XMapPane extends JPanel { Line 1740  public class XMapPane extends JPanel {
1740                  this.bgContext = context;                  this.bgContext = context;
1741    
1742                  if (context != null) {                  if (context != null) {
1743                          setMapArea(bgContext.getAreaOfInterest());                          // setMapArea(bgContext.getAreaOfInterest());
1744    
1745                          this.bgContext.addMapLayerListListener(bgContextListener);                          this.bgContext.addMapLayerListListener(bgContextListener);
1746    
# Line 1692  public class XMapPane extends JPanel { Line 1749  public class XMapPane extends JPanel {
1749                                  mapLayer.addMapLayerListener(bgMapLayerListener);                                  mapLayer.addMapLayerListener(bgMapLayerListener);
1750                          }                          }
1751                  }                  }
1752                  mapImageInvalid = true;  
1753                  repaint();                  requestStartRendering();
1754          }          }
1755    
1756          public void setJava2dHints(final RenderingHints java2dHints) {          public void setJava2dHints(final RenderingHints java2dHints) {
1757                  this.java2dHints = java2dHints;                  this.java2dHints = java2dHints;
1758          }          }
1759    
         /**  
          *  
          * @param context  
          */  
1760          public void setLocalContext(final MapContext context) {          public void setLocalContext(final MapContext context) {
1761                  // Remove the default listener from the old context                  // Remove the default listener from the old context
1762                  if (this.localContext != null) {                  if (this.localContext != null) {
# Line 1719  public class XMapPane extends JPanel { Line 1772  public class XMapPane extends JPanel {
1772    
1773                  if (context != null) {                  if (context != null) {
1774    
1775                          setMapArea(localContext.getAreaOfInterest());                          // setMapArea(localContext.getAreaOfInterest());
1776    
1777                          localRenderer.setContext(localContext);                          getLocalRenderer().setContext(localContext);
1778    
1779                          this.localContext.addMapLayerListListener(localContextListener);                          this.localContext.addMapLayerListListener(localContextListener);
1780    
# Line 1731  public class XMapPane extends JPanel { Line 1784  public class XMapPane extends JPanel {
1784                          }                          }
1785                  }                  }
1786    
1787                    requestStartRendering();
1788    
1789            }
1790    
1791            public void setBorder(final Border b) {
1792                    super.setBorder(b);
1793            }
1794    
1795            /**
1796             * Triggers to repaint (fast) and re-render (slow) the JMapPane.
1797             */
1798            public void refresh() {
1799                  mapImageInvalid = true;                  mapImageInvalid = true;
1800                  repaint();                  repaint();
1801          }          }
1802    
1803            // /**
1804            // * Triggers to use new {@link GTRenderer} and refresh the map. Should be
1805            // * called after {@link Style}s have been changed because GTRenderer is
1806            // * otherwise not working well.
1807            // */
1808            // public void refreshRenderers() {
1809            // localRenderer = GTUtil.createGTRenderer();
1810            // setLocalContext(getMapContext());
1811            // mapImageInvalid = true;
1812            // repaint();
1813            // }
1814    
1815          /**          /**
1816             * Set the new map area.
1817             *
1818           * @param newMapArea           * @param newMapArea
1819           * @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
1820           *         has been triggered.           *         has been triggered.
1821           */           */
1822          public boolean setMapArea(final Envelope newMapArea) {          public boolean setMapArea(final Envelope newMapArea) {
1823                    if (newMapArea == null)
1824                            return false;
1825                    if (getMapContext().getCoordinateReferenceSystem() == null)
1826                            return false;
1827                    return setMapArea(new ReferencedEnvelope(newMapArea, getMapContext()
1828                                    .getCoordinateReferenceSystem()));
1829            }
1830    
1831            /**
1832             * Set the new map area.
1833             *
1834             * @param newMapArea
1835             * @return <code>true</code> if the mapArea has been changed and a repaint
1836             *         has been triggered.
1837             */
1838            public boolean setMapArea(final ReferencedEnvelope newMapArea) {
1839    
1840                  if (newMapArea == null                  if (newMapArea == null
1841                                  || bestAllowedMapArea(newMapArea).equals(mapArea)) {                                  || bestAllowedMapArea(newMapArea).equals(mapArea)) {
# Line 1795  public class XMapPane extends JPanel { Line 1890  public class XMapPane extends JPanel {
1890                          bgContext.setAreaOfInterest(mapArea, localContext                          bgContext.setAreaOfInterest(mapArea, localContext
1891                                          .getCoordinateReferenceSystem());                                          .getCoordinateReferenceSystem());
1892                  }                  }
1893                  mapImageInvalid = true;  
1894                  mapAreaChanged = true;                  mapAreaChanged = true;
                 repaint();  
1895    
1896                  LOGGER.debug("New maparea = " + mapArea);                  repaint(200); // Do not remove it!
1897    
1898                    requestStartRendering();
1899    
1900                  return true;                  return true;
1901          }          }
1902    
# Line 1808  public class XMapPane extends JPanel { Line 1905  public class XMapPane extends JPanel {
1905           *           *
1906           * @param if <code>null</code>, white is used.           * @param if <code>null</code>, white is used.
1907           */           */
1908          public void setMapBackgroundColor(Color bgColor) {          public void setMapBackgroundColor(final Color bgColor) {
                 if (bgColor == null)  
                         bgColor = Color.WHITE;  
1909                  this.mapBackgroundColor = bgColor;                  this.mapBackgroundColor = bgColor;
1910          }          }
1911    
# Line 1868  public class XMapPane extends JPanel { Line 1963  public class XMapPane extends JPanel {
1963          }          }
1964    
1965          // /** Stored the time used for the last real rendering in ms. **/          // /** Stored the time used for the last real rendering in ms. **/
1966          // private long lastRenderingDuration = Long.MAX_VALUE;          private long lastRenderingDuration = 1000;
1967            private XMapPaneTool tool = null;
1968    
1969            private Timer blinkTimer ;
1970    
1971          /**          /**
1972           * 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 1885  public class XMapPane extends JPanel { Line 1983  public class XMapPane extends JPanel {
1983          }          }
1984    
1985          /**          /**
1986           *           * If <code>true</code>, allow the {@link XMapPane} to process #repaint()
1987           * @param b           * requests. Otherwise the map will not paint anything and not start any
1988             * rendering {@link Thread}s.
1989           */           */
1990          public void setPainting(final boolean b) {          public void setPainting(final boolean b) {
1991                  acceptsRepaintCalls = b;                  acceptsRepaintCalls = b;
1992          }                  if (acceptsRepaintCalls == true)
1993                            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;  
   
1994          }          }
1995    
1996          private void setRendererHints(final Map<Object, Object> rendererHints) {          private void setRendererHints(final Map<Object, Object> rendererHints) {
# Line 1912  public class XMapPane extends JPanel { Line 1998  public class XMapPane extends JPanel {
1998                          this.rendererHints = rendererHints;                          this.rendererHints = rendererHints;
1999          }          }
2000    
2001          /**          // @Deprecated
2002           * Enables/Disables the ZOOM Mouse Listener. Upates the Cursor and stops the          // public void setState(final int state) {
2003           * repaint Timer if          // this.state = state;
2004           *          //
2005           * @param state          // // throw new RuntimeException("Old concept.. migrate to new concept!");
2006           */          //
2007          public void setState(final int state) {          // // xMapPaneMouseListener.setEnabled((state == ZOOM_IN
2008                  this.state = state;          // // || state == ZOOM_OUT || state == PAN));
2009            //
2010                  zoomMapPaneMouseListener.setEnabled((state == ZOOM_IN          // // Je nach Aktion den Cursor umsetzen
2011                                  || state == ZOOM_OUT || state == PAN));          // updateCursor();
2012            // }
2013    
2014                  // Je nach Aktion den Cursor umsetzen          public void configureMouse(MouseInputType type, XMapPaneAction action) {
2015                  updateCursor();                  xMapPaneMouseListener.actions.put(type, action);
2016          }          }
2017    
2018          /**          /**
2019           * Standardmaessig wird der Cursor automatisch je nach MapPane-Aktion (Zoom,           * Configure the {@link XMapPaneTool} that active on the map. Passing
2020           * Auswahl, ...) gesetzt. Mit dieser Methode kann ein statischer Cursor           * <code>null</code> will set the NO_ACTION tool.
2021           * gesetzt werden, der unabhaengig von der aktuellen MapPanes-Aktion           */
2022           * beibehalten wird. Um diesen statischen Cursor wieder zu entfernen, kann          public void setTool(XMapPaneTool tool) {
2023           * {@code null} als Parameter uebergeben werden                  if (tool == null)
2024           *                          tool = XMapPaneTool.NO_ACTION;
2025           * @param cursor                  this.tool = tool;
2026           *            Cursor                  xMapPaneMouseListener.configure(tool);
2027           */                  setCursor(tool.getCursor());
         public void setStaticCursor(final Cursor cursor) {  
                 this.staticCursor = cursor;  
                 if (cursor != null)  
                         super.setCursor(cursor);  
2028          }          }
2029    
2030            // /**
2031            // * Standardmaessig wird der Cursor automatisch je nach MapPane-Aktion
2032            // (Zoom,
2033            // * Auswahl, ...) gesetzt. Mit dieser Methode kann ein statischer Cursor
2034            // * gesetzt werden, der unabhaengig von der aktuellen MapPanes-Aktion
2035            // * beibehalten wird. Um diesen statischen Cursor wieder zu entfernen, kann
2036            // * {@code null} als Parameter uebergeben werden
2037            // *
2038            // * @param cursor
2039            // * Cursor
2040            // */
2041            // public void setStaticCursor(final Cursor cursor) {
2042            // this.staticCursor = cursor;
2043            // if (cursor != null)
2044            // super.setCursor(cursor);
2045            // }
2046    
2047          /**          /**
2048           * Starts rendering on one or two threads           * Starts rendering on one or two threads
2049           */           */
2050          private void startRendering() {          private void startRendering() {
2051    
2052                  if (!isWellDefined())                  if (!isWellDefined() || !acceptsRepaintCalls) {
2053                            // if we are not ready to start rendering, try it again the next
2054                            // time the timer is chacking the flag.
2055                            requestStartRendering = true;
2056                          return;                          return;
2057                    }
2058    
2059                  if (bgExecuter != null) {                  if (bgExecuter != null) {
2060                          // Stop all renderers                          // Stop all renderers
2061                          bgExecuter.cancelTask();                          bgExecuter.cancelTask();
2062                  }                  }
2063    
2064                  if (localExecuter != null) {                  localExecuter.cancelTask();
                         localExecuter.cancelTask();  
                 }  
2065    
2066                  final Rectangle curPaintArea = getVisibleRect();                  final Rectangle curPaintArea = getVisibleRect();
2067    
# Line 1982  public class XMapPane extends JPanel { Line 2084  public class XMapPane extends JPanel {
2084                          // (Graphics2D) getBgImage().getGraphics(), createGTRenderer);                          // (Graphics2D) getBgImage().getGraphics(), createGTRenderer);
2085                  }                  }
2086    
2087                  if (getContext() != null) {                  if (getMapContext() != null) {
2088                          // localExecuter = new RenderingExecutor(this, 150l);                          // localExecuter = new RenderingExecutor(this, 150l);
2089                          // LOGGER.debug("starting local renderer:");                          // LOGGER.debug("starting local renderer:");
2090    
2091                          localRenderer.setJava2DHints(getJava2dHints());                          getLocalRenderer().setJava2DHints(getJava2dHints());
2092                          localRenderer.setRendererHints(getRendererHints());                          getLocalRenderer().setRendererHints(getRendererHints());
2093    
2094                          ReferencedEnvelope areaOfInterest = getMapArea();                          final boolean submitted = localExecuter.submit(getMapArea(),
                         final boolean submitted = localExecuter.submit(areaOfInterest,  
2095                                          curPaintArea, (Graphics2D) getLocalImage().getGraphics(),                                          curPaintArea, (Graphics2D) getLocalImage().getGraphics(),
2096                                          localRenderer, getWorldToScreenTransform());                                          getLocalRenderer());
2097                          if (submitted)                          if (submitted)
2098                                  repaintTimer.restart();                                  repaintTimer.restart();
2099                          else                          else
2100                                  requestStartRendering = true; // Try to start rendering again in                                  requestStartRendering = true; // Try to start rendering
2101                            // again in
2102                          // a moment                          // a moment
2103                  }                  }
2104    
2105                  updateCursor();                  updateCursor();
2106          }          }
2107    
2108            private RenderingHints getJava2dHints() {
2109                    return java2dHints;
2110            }
2111    
2112          /**          /**
2113           * Transformiert einen Geo-Koordinaten-Bereich in Fenster-Koordinaten.           * Transformiert einen Geo-Koordinaten-Bereich in Fenster-Koordinaten.
2114           *           *
# Line 2014  public class XMapPane extends JPanel { Line 2120  public class XMapPane extends JPanel {
2120           *            X-Koordinate der BIS-Position           *            X-Koordinate der BIS-Position
2121           * @param py           * @param py
2122           *            Y-Koordinate der BIS-Position           *            Y-Koordinate der BIS-Position
          * @param winToGeotransform  
          *            Eine Window to Geo transform. If <code>null</code>,  
          *            {@link #getScreenToWorld()} is used.  
2123           */           */
2124          public Envelope tranformGeoToWindow(final double ox, final double oy,          public Envelope tranformGeoToWindow(final double ox, final double oy,
2125                          final double px, final double py) {                          final double px, final double py) {
# Line 2033  public class XMapPane extends JPanel { Line 2136  public class XMapPane extends JPanel {
2136          }          }
2137    
2138          /**          /**
2139             * Transformiert einen Geo-Koordinate in eine Fenster-Koordinaten.
2140             *
2141             * @param x
2142             *            X-Koordinate der VON-Position
2143             * @param y
2144             *            Y-Koordinate der VON-Position
2145             */
2146            public Point2D tranformGeoToWindow(final double x, final double y) {
2147                    return getWorldToScreenTransform().transform(new Point2D.Double(x, y),
2148                                    null);
2149            }
2150    
2151            /**
2152           * Transformiert einen Fenster-Koordinaten-Bereich in Geo-Koordinaten.           * Transformiert einen Fenster-Koordinaten-Bereich in Geo-Koordinaten.
2153           *           *
2154           * @param ox           * @param ox
# Line 2049  public class XMapPane extends JPanel { Line 2165  public class XMapPane extends JPanel {
2165                  final AffineTransform at = getScreenToWorld();                  final AffineTransform at = getScreenToWorld();
2166                  final Point2D geoO = at.transform(new Point2D.Double(ox, oy), null);                  final Point2D geoO = at.transform(new Point2D.Double(ox, oy), null);
2167                  final Point2D geoP = at.transform(new Point2D.Double(px, py), null);                  final Point2D geoP = at.transform(new Point2D.Double(px, py), null);
2168                    
2169                  // Mmmmm... don't really understand why its x,x,y,y                  // Mmmmm... don't really understand why its x,x,y,y
2170  //              return new Envelope(geoO.getX(), geoP.getX(), geoO.getY(), geoP.getY());                  // return new Envelope(geoO.getX(), geoP.getX(), geoO.getY(),
2171                  return new Envelope( new Coordinate(geoO.getX(), geoO.getY()), new Coordinate(geoP.getX(), geoP.getY()));                  // geoP.getY());
2172                    return new Envelope(new Coordinate(geoO.getX(), geoO.getY()),
2173                                    new Coordinate(geoP.getX(), geoP.getY()));
2174          }          }
2175    
2176          /**          /**
# Line 2064  public class XMapPane extends JPanel { Line 2182  public class XMapPane extends JPanel {
2182                  // if the renderers have stopped, also stop the timer that is updating                  // if the renderers have stopped, also stop the timer that is updating
2183                  // the final image                  // the final image
2184                  if (bgExecuter != null && bgExecuter.isRunning()                  if (bgExecuter != null && bgExecuter.isRunning()
2185                                  || localExecuter != null && localExecuter.isRunning()) {                                  || localExecuter.isRunning()) {
2186                          setCursor(WAIT_CURSOR);                          setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
2187                          return;                          return;
2188                  } else {                  } else {
2189                          // Allow one last rendering                          // Allow one last rendering
2190                          if (repaintTimer.isRunning()) {                          if (repaintTimer.isRunning()) {
2191                                  System.out.println("one last rendering....");                                  // System.out.println("one last rendering....");
2192                                  repaintTimer.stop();                                  repaintTimer.stop();
2193                                  updateFinalImage();                                  updateFinalImage();
2194                                  repaint();                                  repaint();
2195                          }                          }
2196                  }                  }
2197                    //              
2198                  // wenn manueller Cursor gesetzt ist, dann diesen verwenden (unabhaengig                  // //
2199                  // von der aktuellen Aktion                  // // wenn manueller Cursor gesetzt ist, dann diesen verwenden
2200                  if (this.staticCursor != null) {                  // (unabhaengig
2201                          setCursor(staticCursor);                  // // von der aktuellen Aktion
2202                          return;                  // if (this.staticCursor != null) {
2203                  }                  // setCursor(staticCursor);
2204                    // return;
2205                    // }
2206                    //              
2207                  if (getCursor() == SwingUtil.PANNING_CURSOR) {                  if (getCursor() == SwingUtil.PANNING_CURSOR) {
2208                          // This cursor will reset itself                          // This cursor will reset itself
2209                          return;                          return;
2210                  }                  }
2211    
2212                  // Set the cursor depending on what tool is in use...                  setCursor(tool.getCursor());
2213                  switch (state) {  
2214                  case SELECT_TOP:                  //
2215                  case SELECT_ONE_FROM_TOP:                  // // Set the cursor depending on what tool is in use...
2216                  case SELECT_ALL:                  // switch (state) {
2217                          setCursor(SwingUtil.CROSSHAIR_CURSOR);                  // case SELECT_TOP:
2218                          break;                  // case SELECT_ONE_FROM_TOP:
2219                  case ZOOM_IN:                  // case SELECT_ALL:
2220                          setCursor(SwingUtil.ZOOMIN_CURSOR);                  // setCursor(SwingUtil.CROSSHAIR_CURSOR);
2221                          break;                  // break;
2222                  case ZOOM_OUT:                  // case ZOOM_IN:
2223                          setCursor(SwingUtil.ZOOMOUT_CURSOR);                  // setCursor(SwingUtil.ZOOMIN_CURSOR);
2224                          break;                  // break;
2225                  case PAN:                  // case ZOOM_OUT:
2226                          setCursor(SwingUtil.PAN_CURSOR);                  // setCursor(SwingUtil.ZOOMOUT_CURSOR);
2227                          break;                  // break;
2228                  default:                  // case PAN:
2229                          setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));                  // setCursor(SwingUtil.PAN_CURSOR);
2230                          break;                  // break;
2231                  }                  // default:
2232                    // setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
2233                    // break;
2234                    // }
2235          }          }
2236    
2237          /**          /**
# Line 2137  public class XMapPane extends JPanel { Line 2261  public class XMapPane extends JPanel {
2261    
2262                  final Graphics2D finalG = getFinalImage().createGraphics();                  final Graphics2D finalG = getFinalImage().createGraphics();
2263                  finalG.setBackground(getMapBackgroundColor());                  finalG.setBackground(getMapBackgroundColor());
2264                  finalG.drawImage(getPreFinalImage(), imageOrigin.x, imageOrigin.y,                  finalG.drawImage(getPreFinalImage(), getImageOrigin().x,
2265                                  getMapBackgroundColor(), null);                                  getImageOrigin().y, getMapBackgroundColor(), null);
2266    
2267                  final int finalImageHeight = getFinalImage().getHeight(null);                  // When panning, we have to clear the area around the image
2268                  final int finalImageWidth = getFinalImage().getWidth(null);                  final Rectangle painedArea = new Rectangle(getImageOrigin().x,
2269                                    getImageOrigin().y, getFinalImage().getWidth(), getFinalImage()
2270                  final Rectangle painedArea = new Rectangle(imageOrigin.x,                                                  .getHeight());
2271                                  imageOrigin.y, finalImageWidth, finalImageHeight);                  SwingUtil.clearAround(finalG, painedArea, getVisibleRect(),
2272                  SwingUtil.clearAround(finalG, painedArea, getVisibleRect());                                  getMapBackgroundColor());
2273    
2274                  addGadgets(finalG, false);                  addGadgets(finalG, false);
2275    
# Line 2164  public class XMapPane extends JPanel { Line 2288  public class XMapPane extends JPanel {
2288           *            <code>false</code>, it will only depend on           *            <code>false</code>, it will only depend on
2289           *            {@link #localExecuter.isRunning} and #bgExecuter.isRunning           *            {@link #localExecuter.isRunning} and #bgExecuter.isRunning
2290           */           */
2291          private void addGadgets(final Graphics2D graphics, boolean forceWait) {          private void addGadgets(final Graphics2D graphics, final boolean forceWait) {
2292    
2293                  // Paint a logo to the bottom right if available                  // Paint a logo to the bottom right if available
2294                  if (mapImage != null) {                  if (mapImage != null) {
2295                          Rectangle visibleRect = getVisibleRect();                          final Rectangle visibleRect = getVisibleRect();
2296                          graphics.drawImage(mapImage, visibleRect.width                          graphics.drawImage(mapImage, visibleRect.width
2297                                          - mapImage.getWidth() - 10, getVisibleRect().height                                          - mapImage.getWidth() - 10, getVisibleRect().height
2298                                          - mapImage.getHeight() - 10, null);                                          - mapImage.getHeight() - 10, null);
# Line 2178  public class XMapPane extends JPanel { Line 2302  public class XMapPane extends JPanel {
2302    
2303                  // If the rendering process is still running, indicate this is the image                  // If the rendering process is still running, indicate this is the image
2304                  if (forceWait || bgExecuter != null && bgExecuter.isRunning()                  if (forceWait || bgExecuter != null && bgExecuter.isRunning()
2305                                  || localExecuter != null && localExecuter.isRunning()) {                                  || localExecuter.isRunning()) {
2306    
2307                          y += 8;                          y += 8;
2308    
# Line 2194  public class XMapPane extends JPanel { Line 2318  public class XMapPane extends JPanel {
2318    
2319                          graphics.setColor(c);                          graphics.setColor(c);
2320    
2321                          y += 24;                          y += 21;
2322                  }                  }
2323    
2324                  if (renderingErrors != null) {                  if (!renderingErrors.isEmpty() && isShowExceptions()) {
2325    
2326                          final Color c = graphics.getColor();                          final Color c = graphics.getColor();
2327                          graphics.setFont(errorFont);                          graphics.setFont(errorFont);
2328    
2329                          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;  
2330    
2331                                  String errStr = ex.getLocalizedMessage();                                  String errStr = ex.getLocalizedMessage();
2332    
2333                                  graphics.setColor(Color.WHITE);                                  if (errStr == null)
2334                                            errStr = ex.getMessage();
2335                                    if (errStr == null)
2336                                            errStr = "unknown error: " + ex.getClass().getSimpleName();
2337    
2338                                    graphics.setColor(getMapBackgroundColor());
2339                                  graphics.drawString(errStr, 5, y);                                  graphics.drawString(errStr, 5, y);
2340                                  graphics.setColor(Color.RED);                                  graphics.setColor(Color.RED);
2341                                  graphics.drawString(errStr, 6, y + 1);                                  graphics.drawString(errStr, 6, y + 1);
# Line 2234  public class XMapPane extends JPanel { Line 2358  public class XMapPane extends JPanel {
2358          public void zoomTo(          public void zoomTo(
2359                          final FeatureCollection<SimpleFeatureType, SimpleFeature> features) {                          final FeatureCollection<SimpleFeatureType, SimpleFeature> features) {
2360    
2361                  final CoordinateReferenceSystem mapCRS = getContext()                  // if (!isWellDefined()) return;
2362    
2363                    final CoordinateReferenceSystem mapCRS = getMapContext()
2364                                  .getCoordinateReferenceSystem();                                  .getCoordinateReferenceSystem();
2365                  final CoordinateReferenceSystem fCRS = features.getSchema()                  final CoordinateReferenceSystem fCRS = features.getSchema()
2366                                  .getGeometryDescriptor().getCoordinateReferenceSystem();                                  .getCoordinateReferenceSystem();
2367    
2368                  double width = mapArea.getWidth();                  ReferencedEnvelope _mapArea;
2369                  double height = mapArea.getHeight();                  if (mapArea == null)
2370                            _mapArea = features.getBounds();
2371                    else
2372                            _mapArea = getMapArea();
2373                    double width = _mapArea.getWidth();
2374                    double height = _mapArea.getHeight();
2375                  final double ratio = height / width;                  final double ratio = height / width;
2376    
2377                  if (features == null || features.size() == 0) {                  if (features == null || features.size() == 0) {
# Line 2292  public class XMapPane extends JPanel { Line 2423  public class XMapPane extends JPanel {
2423                  } else {                  } else {
2424                          final ReferencedEnvelope fBounds = features.getBounds();                          final ReferencedEnvelope fBounds = features.getBounds();
2425    
2426                          Envelope bounds;                          ReferencedEnvelope bounds;
2427                          if (!mapCRS.equals(fCRS)) {                          if (!mapCRS.equals(fCRS)) {
2428                                  bounds = JTSUtil.transformEnvelope(fBounds, fCRS, mapCRS);                                  bounds = JTSUtil.transformEnvelope(fBounds, mapCRS);
2429                          } else {                          } else {
2430                                  bounds = fBounds;                                  bounds = fBounds;
2431                          }                          }
2432                          // BB umrechnen von Layer-CRS in Map-CRS                          // BB umrechnen von Layer-CRS in Map-CRS
2433    
2434                          // Expand a bit                          // Expand a bit
2435                          bounds.expandBy(bounds.getWidth() / 6., bounds.getHeight() / 6.);                          addDefaultMargin(bounds);
2436    
2437                          setMapArea(bounds);                          setMapArea(bounds);
2438                  }                  }
2439          }          }
2440    
2441            private ReferencedEnvelope addDefaultMargin(ReferencedEnvelope bounds) {
2442                    return JTSUtil.expandEnvelope(bounds, Math.max(0,
2443                                    defaultMaxMapExtendMode));
2444            }
2445    
2446            private Envelope addDefaultMargin(Envelope bounds) {
2447                    return JTSUtil.expandEnvelope(bounds, Math.max(0,
2448                                    defaultMaxMapExtendMode));
2449            }
2450    
2451          /**          /**
2452           * Zooms towards a point.           * Zooms towards a point.
2453           *           *
# Line 2325  public class XMapPane extends JPanel { Line 2466  public class XMapPane extends JPanel {
2466           * @param center           * @param center
2467           *            position in window coordinates           *            position in window coordinates
2468           * @param zoomFaktor           * @param zoomFaktor
2469           *            > 1 for zoom in, < 1 for zoom out. Default is 1.33.           *            > 1 for zoom out, < 1 for zoom in. Default is .5
2470           */           */
2471          public void zoomTo(Point center, Double zoomFaktor) {          public void zoomTo(Point center, Double zoomFaktor) {
2472                  if (zoomFaktor == null || zoomFaktor == 0.)                  if (zoomFaktor == null || zoomFaktor == 0.)
2473                          zoomFaktor = 2.;                          zoomFaktor = .5;
2474    
2475                  final Point2D gcenter = getScreenToWorld().transform(center, null);                  final Point2D gcenter = getScreenToWorld().transform(center, null);
2476                  center = null;                  center = null;
# Line 2349  public class XMapPane extends JPanel { Line 2490  public class XMapPane extends JPanel {
2490                  newMapArea.expandBy((mapArea.getWidth() * zoomFaktor - mapArea                  newMapArea.expandBy((mapArea.getWidth() * zoomFaktor - mapArea
2491                                  .getWidth()) / 2., (mapArea.getHeight() * zoomFaktor - mapArea                                  .getWidth()) / 2., (mapArea.getHeight() * zoomFaktor - mapArea
2492                                  .getHeight()) / 2.);                                  .getHeight()) / 2.);
2493                    
2494  // TODO we actually want that                  // // Move the newMapArea above the new center if we zoom in:
2495  //              // Move the newMapArea above the new center                  newMapArea.translate(gcenter.getX() - mapArea.centre().x, gcenter
2496  //              newMapArea.translate(gcenter.getX() - mapArea.centre().x, gcenter                                  .getY()
2497  //                              .getY()                                  - mapArea.centre().y);
 //                              - mapArea.centre().y);  
2498    
2499                  setMapArea(newMapArea);                  setMapArea(newMapArea);
2500          }          }
2501    
2502            /**
2503             * Shall non-fatal rendering exceptions be reported in the mappane or be
2504             * dropped quitely.
2505             */
2506            public void setShowExceptions(final boolean showExceptions) {
2507                    this.showExceptions = showExceptions;
2508            }
2509    
2510            /**
2511             * Shall exceptions be reported in the mappane?
2512             */
2513            public boolean isShowExceptions() {
2514                    return showExceptions;
2515            }
2516    
2517            public GTRenderer getLocalRenderer() {
2518                    return localRenderer;
2519            }
2520    
2521            /**
2522             * Setzt den Kartenausschnitt auf die Ausdehnung eines bestimmten Layers.
2523             * Macht nichts, wenn {@code null} uebergeben wird.
2524             *
2525             * <br>
2526             *
2527             * @param layer
2528             *            ein Layer
2529             */
2530            public void zoomToLayer(MapLayer layer) {
2531                    if (layer == null)
2532                            return;
2533                    try {
2534    
2535                            // BB umrechnen von Layer-CRS in Map-CRS
2536                            final CoordinateReferenceSystem targetCRS = getMapContext()
2537                                            .getCoordinateReferenceSystem();
2538                            final CoordinateReferenceSystem sourceCRS = layer
2539                                            .getFeatureSource().getSchema()
2540                                            .getCoordinateReferenceSystem();
2541    
2542                            Envelope mapAreaNew;
2543                            if (!CRS.equalsIgnoreMetadata(sourceCRS, targetCRS)) {
2544                                    mapAreaNew = JTSUtil.transformEnvelope(layer.getFeatureSource()
2545                                                    .getBounds(), sourceCRS, targetCRS);
2546                            } else {
2547                                    try {
2548                                            mapAreaNew = layer.getFeatureSource().getBounds();
2549                                    } catch (java.lang.IllegalArgumentException e) {
2550                                            LOGGER.error("Can't calc layers bounds...", e);
2551                                            mapAreaNew = null;
2552    
2553                                            /**
2554                                             *
2555                                             23.10.2009 11:20:50
2556                                             * org.geotools.data.shapefile.shp.PolygonHandler read
2557                                             * WARNUNG: only one hole in this polygon record ERROR
2558                                             * JMapPane zoomToLayer Zoom to layer did not terminate
2559                                             * correctly java.lang.IllegalArgumentException: Points of
2560                                             * LinearRing do not form a closed linestring at
2561                                             * com.vividsolutions
2562                                             * .jts.geom.LinearRing.validateConstruction
2563                                             * (LinearRing.java:105) at
2564                                             * com.vividsolutions.jts.geom.LinearRing
2565                                             * .<init>(LinearRing.java:100) at
2566                                             * com.vividsolutions.jts.geom
2567                                             * .GeometryFactory.createLinearRing
2568                                             * (GeometryFactory.java:339) at
2569                                             * org.geotools.data.shapefile.
2570                                             * shp.PolygonHandler.read(PolygonHandler.java:188) at
2571                                             * org.geotools
2572                                             * .data.shapefile.shp.ShapefileReader$Record.shape
2573                                             * (ShapefileReader.java:106) at
2574                                             * org.geotools.data.shapefile.
2575                                             * ShapefileAttributeReader.next(
2576                                             * ShapefileAttributeReader.java:157) at
2577                                             * org.geotools.data.shapefile
2578                                             * .indexed.IndexedShapefileAttributeReader
2579                                             * .next(IndexedShapefileAttributeReader.java:122) at
2580                                             * org.geotools
2581                                             * .data.FIDFeatureReader.next(FIDFeatureReader.java:96) at
2582                                             * org.geotools.data.FIDFeatureReader.next(FIDFeatureReader.
2583                                             * java:55) at org.geotools.data.MaxFeatureReader.next(
2584                                             * MaxFeatureReader.java:61) at
2585                                             * org.geotools.data.MaxFeatureReader
2586                                             * .next(MaxFeatureReader.java:61)
2587                                             **/
2588                                    }
2589                            }
2590    
2591                            // Kartenbereich um 10% vergroessern, damit z.B. auch ein
2592                            // Punkt-Layer,
2593                            // welches nur aus 2 Punnkten besteht, sichtbar ist (Punkte liegen
2594                            // sonst
2595                            // genau auf dem Rand der angezeigten Flaeche)
2596    
2597                            if (mapAreaNew != null) {
2598    
2599                                    mapAreaNew = addDefaultMargin(mapAreaNew);
2600                                    setMapArea(mapAreaNew);
2601                            } else {
2602                                    LOGGER
2603                                                    .warn("Couldn't transformEnvelope when zooming to the layer");
2604                            }
2605                    } catch (Exception err) {
2606                            LOGGER.error("Zoom to layer did not terminate correctly", err);
2607                    }
2608            }
2609    
2610            /**
2611             * Zooms the {@link SelectableXMapPane} to the {@link Envelope} of a layer.
2612             *
2613             * <br>
2614             * A refresh of the map is not done automatically
2615             *
2616             * @param index
2617             *            Index of the {@link MapLayer} in the {@link MapContext} (from
2618             *            back to top)
2619             *
2620             * @author <a href="mailto:[email protected]">Stefan Alfons
2621             *         Kr&uuml;ger</a>
2622             */
2623            public void zoomToLayer(int index) {
2624                    final MapContext context = getMapContext();
2625                    if (context != null)
2626                            zoomToLayer(context.getLayer(index));
2627            }
2628    
2629            /**
2630             * Zooms the {@link SelectableXMapPane} to the {@link Envelope} of the
2631             * selected layer. The layer is selected by the idx, counting from front to
2632             * back, like humans would expect in a {@link JList}
2633             *
2634             * <br>
2635             * A refresh of the map is not done automatically
2636             *
2637             *
2638             *
2639             * @param index
2640             *            Reverse index of the {@link MapLayer} in the
2641             *            {@link MapContext}
2642             *
2643             * @author <a href="mailto:[email protected]">Stefan Alfons
2644             *         Kr&uuml;ger</a>
2645             */
2646            public void zoomToLayerIdxReverse(int index) {
2647                    zoomToLayer(getMapContext().getLayerCount() - 1 - index);
2648            }
2649    
2650            /**
2651             * Aktiviert oder deaktiviert das AntiAliasing for diese
2652             * {@link SelectableXMapPane}. AntiALiasing ist besonders fuer
2653             * Textbeschriftung sehr schoen, verbraucht aber auch mehr Performance.
2654             *
2655             * @author <a href="mailto:[email protected]">Stefan Alfons
2656             *         Kr&uuml;ger</a>
2657             */
2658            public void setAntiAliasing(final boolean aa) {
2659                    // LOGGER.info("Setting AntiAliasing for this JMapPane to " + aa);
2660                    RenderingHints java2DHints = java2dHints;
2661                    if (java2DHints == null) {
2662                            java2DHints = GeoTools.getDefaultHints();
2663                    }
2664    
2665                    java2DHints.put(RenderingHints.KEY_ANTIALIASING,
2666                                    aa ? RenderingHints.VALUE_ANTIALIAS_ON
2667                                                    : RenderingHints.VALUE_ANTIALIAS_OFF);
2668                    java2DHints.put(RenderingHints.KEY_TEXT_ANTIALIASING,
2669                                    aa ? RenderingHints.VALUE_TEXT_ANTIALIAS_ON
2670                                                    : RenderingHints.VALUE_TEXT_ANTIALIAS_OFF);
2671                    java2DHints.put(RenderingHints.KEY_RENDERING,
2672                                    aa ? RenderingHints.VALUE_RENDER_QUALITY
2673                                                    : RenderingHints.VALUE_RENDER_SPEED);
2674    
2675            }
2676    
2677            public Point getImageOrigin() {
2678                    return imageOrigin;
2679            }
2680    
2681            /**
2682             * If {@link #maxExtend} is <code>null</code> the following rules are used
2683             * to create a default maximum.
2684             * <ul>
2685             * <li>Values &lt; 0 : don't grow to fit the monitors aspect ratio, no
2686             * margin</li>
2687             * <li>Values 0 : grow to fit the monitors aspect ratio, no margin</li>
2688             * <li>Values &gt; 0 : grow to fit the monitors aspect ratio, and add a
2689             * relative margin</li>
2690             * </ul>
2691             * **/
2692            public void setDefaultMaxMapExtendMode(double defaultMaxMapExtendMode) {
2693                    this.defaultMaxMapExtendMode = defaultMaxMapExtendMode;
2694            }
2695    
2696            /**
2697             * If {@link #maxExtend} is <code>null</code> the following rules are used
2698             * to create a default maximum.
2699             * <ul>
2700             * <li>Values &lt; 0 : don't grow to fit the monitors aspect ratio, no
2701             * margin</li>
2702             * <li>Values 0 : grow to fit the monitors aspect ratio, no margin</li>
2703             * <li>Values &gt; 0 : grow to fit the monitors aspect ratio, and add a
2704             * relative margin</li>
2705             * </ul>
2706             * **/
2707            public double getDefaultMaxMapExtendMode() {
2708                    return defaultMaxMapExtendMode;
2709            }
2710            
2711    
2712            final static int BLINK_TIMER_DEPLAY = 800;
2713            
2714            private Timer initBlinkTimer() {
2715                    Timer timer = new Timer(BLINK_TIMER_DEPLAY, new ActionListener() {
2716    
2717                            @Override
2718                            public void actionPerformed(ActionEvent e) {
2719                                    XMapPane.this.repaint(300);
2720                            }
2721                    });
2722                    timer.setDelay(BLINK_TIMER_DEPLAY);
2723                    timer.setRepeats(false);
2724                    return timer;
2725            }
2726    
2727            /**
2728             * Makes the given {@link FeatureCollection} bink in the map for a moment
2729             */
2730            public void blink(
2731                            FeatureCollection<SimpleFeatureType, SimpleFeature> features) {
2732                    {
2733                            blinkTimer.stop();
2734                            repaint();
2735                            blinkTimer = initBlinkTimer();
2736    
2737                            DefaultMapContext mc = new DefaultMapContext(getMapContext()
2738                                            .getCoordinateReferenceSystem());
2739    
2740                            Style style = StylingUtil.STYLE_FACTORY.createStyle();
2741                            style.featureTypeStyles().add(
2742                                            StylingUtil.createBlinkFeatureTypeStyle(features));
2743    
2744                            // style = StylingUtil.createStyleSimple(features, Color.pink,
2745                            // Color.WHITE);
2746    
2747                            DefaultMapLayer dml = new DefaultMapLayer(features, style);
2748                            mc.addLayer(dml);
2749    
2750                            GTRenderer renderer = new StreamingRenderer();
2751    
2752                            renderer.setJava2DHints(getJava2dHints());
2753    
2754                            renderer.setContext(mc);
2755    
2756                            Graphics2D g2d = (Graphics2D) getGraphics();
2757                            renderer.paint(g2d, getVisibleRect(), getMapArea());
2758    
2759                            blinkTimer.start();
2760    
2761                    }
2762    
2763            }
2764    
2765  }  }

Legend:
Removed from v.540  
changed lines
  Added in v.680

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26