altosuilib: Rewrite map GUI bits
[fw/altos] / altosuilib / AltosSiteMap.java
1 /*
2  * Copyright © 2010 Anthony Towns <aj@erisian.com.au>
3  *
4  * This program is free software; you can redistribute it and/or modify
5  * it under the terms of the GNU General Public License as published by
6  * the Free Software Foundation; version 2 of the License.
7  *
8  * This program is distributed in the hope that it will be useful, but
9  * WITHOUT ANY WARRANTY; without even the implied warranty of
10  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11  * General Public License for more details.
12  *
13  * You should have received a copy of the GNU General Public License along
14  * with this program; if not, write to the Free Software Foundation, Inc.,
15  * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
16  */
17
18 package org.altusmetrum.altosuilib_2;
19
20 import java.awt.*;
21 import java.awt.event.*;
22 import javax.swing.*;
23 import java.io.*;
24 import java.lang.Math;
25 import java.awt.geom.*;
26 import java.util.*;
27 import java.util.concurrent.*;
28 import org.altusmetrum.altoslib_4.*;
29
30 class MapPoint {
31         double  lat, lon;
32         int     state;
33
34         public MapPoint(double lat, double lon, int state) {
35                 this.lat = lat;
36                 this.lon = lon;
37                 this.state = state;
38         }
39
40         public boolean equals(MapPoint other) {
41                 if (other == null)
42                         return false;
43                 if (other.lat != lat)
44                         return false;
45                 if (other.lon != lon)
46                         return false;
47                 if (other.state != state)
48                         return false;
49                 return true;
50         }
51 }
52
53 public class AltosSiteMap extends JComponent implements AltosFlightDisplay, MouseMotionListener, MouseListener, HierarchyBoundsListener {
54         // preferred vertical step in a tile in naut. miles
55         // will actually choose a step size between x and 2x, where this
56         // is 1.5x
57         static final double tile_size_nmi = 0.75;
58
59         static final int px_size = 512;
60
61         static final int MAX_TILE_DELTA = 100;
62
63         static final int maptype_hybrid = 0;
64         static final int maptype_roadmap = 1;
65         static final int maptype_satellite = 2;
66         static final int maptype_terrain = 3;
67
68         int maptype = maptype_hybrid;
69
70         static final String[] maptype_names = {
71                 "hybrid",
72                 "roadmap",
73                 "satellite",
74                 "terrain"
75         };
76
77         public static final String[] maptype_labels = {
78                 "Hybrid",
79                 "Roadmap",
80                 "Satellite",
81                 "Terrain"
82         };
83
84         LinkedList<MapPoint> points = new LinkedList<MapPoint>();
85
86         private static Point2D.Double translatePoint(Point2D.Double p,
87                         Point2D.Double d)
88         {
89                 return new Point2D.Double(p.x + d.x, p.y + d.y);
90         }
91
92         static class LatLng {
93                 public double lat, lng;
94                 public LatLng(double lat, double lng) {
95                         this.lat = lat;
96                         this.lng = lng;
97                 }
98         }
99
100         // based on google js
101         //  http://maps.gstatic.com/intl/en_us/mapfiles/api-3/2/10/main.js
102         // search for fromLatLngToPoint and fromPointToLatLng
103         /*
104         private static Point2D.Double pt(LatLng latlng, int zoom) {
105                 double scale_x = 256/360.0 * Math.pow(2, zoom);
106                 double scale_y = 256/(2.0*Math.PI) * Math.pow(2, zoom);
107                 return pt(latlng, scale_x, scale_y);
108         }
109         */
110
111         private static Point2D.Double pt(LatLng latlng,
112                                          double scale_x, double scale_y)
113         {
114                 Point2D.Double res = new Point2D.Double();
115                 double e;
116
117                 res.x = latlng.lng * scale_x;
118
119                 e = Math.sin(Math.toRadians(latlng.lat));
120                 e = Math.max(e,-(1-1.0E-15));
121                 e = Math.min(e,  1-1.0E-15 );
122
123                 res.y = 0.5*Math.log((1+e)/(1-e))*-scale_y;
124                 return res;
125         }
126
127         static private LatLng latlng(Point2D.Double pt,
128                                      double scale_x, double scale_y)
129         {
130                 double lat, lng;
131                 double rads;
132
133                 lng = pt.x/scale_x;
134                 rads = 2 * Math.atan(Math.exp(-pt.y/scale_y));
135                 lat = Math.toDegrees(rads - Math.PI/2);
136
137                 return new LatLng(lat,lng);
138         }
139
140         static final int default_zoom = 15;
141         static final int min_zoom = 3;
142         static final int max_zoom = 21;
143
144         int zoom = default_zoom;
145
146         double scale_x, scale_y;
147
148         int radius;     /* half width/height of tiles to load */
149
150         private Point2D.Double pt(double lat, double lng) {
151                 return pt(new LatLng(lat, lng), scale_x, scale_y);
152         }
153
154         private LatLng latlng(double x, double y) {
155                 return latlng(new Point2D.Double(x,y), scale_x, scale_y);
156         }
157         /*
158         private LatLng latlng(Point2D.Double pt) {
159                 return latlng(pt, scale_x, scale_y);
160         }
161         */
162
163         private LatLng latlng(Point pt) {
164                 return latlng(new Point2D.Double(pt.x, pt.y), scale_x, scale_y);
165         }
166
167         ConcurrentHashMap<Point,AltosSiteMapTile> mapTiles = new ConcurrentHashMap<Point,AltosSiteMapTile>();
168         Point2D.Double centre;
169
170         private Point2D.Double tileCoordOffset(Point p) {
171                 return new Point2D.Double(centre.x - p.x*px_size,
172                                           centre.y - p.y*px_size);
173         }
174
175         private Point tileOffset(Point2D.Double p) {
176                 return new Point((int)Math.floor((centre.x+p.x)/px_size),
177                                  (int)Math.floor((centre.y+p.y)/px_size));
178         }
179
180         private Point2D.Double getBaseLocation(double lat, double lng) {
181                 Point2D.Double locn = pt(0,0), north_step;
182
183                 scale_x = 256/360.0 * Math.pow(2, zoom);
184                 scale_y = 256/(2.0*Math.PI) * Math.pow(2, zoom);
185                 locn = pt(lat, lng);
186                 locn.x = -px_size * Math.floor(locn.x/px_size);
187                 locn.y = -px_size * Math.floor(locn.y/px_size);
188                 return locn;
189         }
190
191         public void reset() {
192                 // nothing
193         }
194
195         public void font_size_changed(int font_size) {
196                 for (AltosSiteMapTile tile : mapTiles.values())
197                         tile.set_font(AltosUILib.value_font);
198         }
199
200         public void units_changed(boolean imperial_units) {
201                 set_line();
202         }
203
204         static final int load_mode_cached = 1;
205         static final int load_mode_uncached = 2;
206
207         private boolean load_map(final AltosSiteMapTile tile,
208                                  final File pngfile, String pngurl,
209                                  int load_mode)
210         {
211                 boolean has_map = AltosSiteMapCache.has_map(pngfile, pngurl);
212                 if ((load_mode & load_mode_uncached) == 0 && !has_map)
213                         return false;
214                 if ((load_mode & load_mode_cached) == 0 && has_map)
215                         return false;
216
217                 tile.set_status(AltosSiteMapCache.loading);
218                 int status = AltosSiteMapCache.fetch_map(pngfile, pngurl);
219                 if (status == AltosSiteMapCache.success) {
220                         if (SwingUtilities.isEventDispatchThread())
221                                 tile.load_map(pngfile);
222                         else {
223                                 SwingUtilities.invokeLater(new Runnable() {
224                                                 public void run() {
225                                                         tile.load_map(pngfile);
226                                                 }
227                                         });
228                         }
229                 } else {
230                         tile.set_status(status);
231                         System.out.printf("# Failed to fetch file %s (status %d)\n", pngfile, status);
232                         System.out.printf(" wget -O '%s' '%s'\n", pngfile, pngurl);
233                         System.out.printf(" sleep 1\n");
234                 }
235                 return true;
236         }
237
238
239         class AltosSiteMapPrefetch {
240                 int     x;
241                 int     y;
242                 int     result;
243                 File    pngfile;
244                 String  pngurl;
245         }
246
247         private AltosSiteMapPrefetch prefetchMap(int x, int y) {
248                 AltosSiteMapPrefetch    prefetch = new AltosSiteMapPrefetch();
249                 LatLng map_latlng = latlng(
250                         -centre.x + x*px_size + px_size/2,
251                         -centre.y + y*px_size + px_size/2);
252                 prefetch.pngfile = MapFile(map_latlng.lat, map_latlng.lng, zoom, maptype_hybrid);
253                 prefetch.pngurl = MapURL(map_latlng.lat, map_latlng.lng, zoom, maptype_hybrid);
254                 if (AltosSiteMapCache.has_map(prefetch.pngfile, prefetch.pngurl)) {
255                         prefetch.result = 1;
256                 } else if (AltosSiteMapCache.fetch_map(prefetch.pngfile, prefetch.pngurl) == AltosSiteMapCache.success) {
257                         prefetch.result = 0;
258                 } else {
259                         prefetch.result = -1;
260                 }
261                 return prefetch;
262         }
263
264         public static void prefetchMaps(double lat, double lng, int radius, int maptypes, int min_zoom, int max_zoom) {
265                 AltosSiteMap asm = new AltosSiteMap(true);
266
267                 for (int z = min_zoom; z <= max_zoom; z++) {
268                         asm.zoom = z;
269                         asm.set_radius(radius);
270                         asm.centre = asm.getBaseLocation(lat, lng);
271                         for (int t = maptype_hybrid; t <= maptype_terrain; t++) {
272                                 if ((maptypes & (1 << t)) !=0) {
273                                         asm.maptype = t;
274                                         for (int y = -radius; y <= radius; y++) {
275                                                 for (int x = -radius; x <= radius; x++) {
276                                                         AltosSiteMapPrefetch prefetch = asm.prefetchMap(x, y);
277                                                         switch (prefetch.result) {
278                                                         case 1:
279                                                                 System.out.printf("Already have %s\n", prefetch.pngfile);
280                                                                 break;
281                                                         case 0:
282                                                                 System.out.printf("Fetched map %s\n", prefetch.pngfile);
283                                                                 break;
284                                                         case -1:
285                                                                 System.out.printf("# Failed to fetch file %s\n", prefetch.pngfile);
286                                                                 System.out.printf(" wget -O '%s' ''\n",
287                                                                                   prefetch.pngfile, prefetch.pngurl);
288                                                                 break;
289                                                         }
290                                                 }
291                                         }
292                                 }
293                         }
294                 }
295         }
296
297         public static void prefetchMaps(double lat, double lon) {
298                 prefetchMaps(lat, lon, 2, 1 << maptype_hybrid, 0, 0);
299         }
300
301         public File init_map(Point offset, int load_mode) {
302                 AltosSiteMapTile tile = mapTiles.get(offset);
303                 Point2D.Double coord = tileCoordOffset(offset);
304
305                 LatLng map_latlng = latlng(px_size/2-coord.x, px_size/2-coord.y);
306
307                 File pngfile = MapFile(map_latlng.lat, map_latlng.lng, zoom, maptype);
308                 String pngurl = MapURL(map_latlng.lat, map_latlng.lng, zoom, maptype);
309                 load_map(tile, pngfile, pngurl, load_mode);
310                 return pngfile;
311         }
312
313         private void initAndFinishMapAsync (final AltosSiteMapTile tile, final Point offset) {
314                 Thread thread = new Thread() {
315                                 public void run() {
316                                         init_map(offset, load_mode_cached|load_mode_uncached);
317                                         SwingUtilities.invokeLater( new Runnable() {
318                                                         public void run() {
319                                                                 addTileAt(tile, offset);
320                                                         }
321                                                 } );
322                                 }
323                         };
324                 thread.start();
325         }
326
327         double  lat, lon;
328         boolean base_location_set = false;
329
330         public void clear_base_location() {
331                 base_location_set = false;
332                 circle_set = false;
333                 points = new LinkedList<MapPoint>();
334                 line_start = line_end = null;
335                 for (AltosSiteMapTile tile : mapTiles.values()) {
336                         tile.clearMap();
337                         tile.set_status(AltosSiteMapCache.loading);
338                 }
339         }
340
341         public void setBaseLocation(double lat, double lng) {
342                 this.lat = lat;
343                 this.lon = lng;
344                 base_location_set = true;
345
346                 centre = getBaseLocation(lat, lng);
347                 scrollRocketToVisible(pt(lat,lng));
348         }
349
350         private void initMaps(double lat, double lng) {
351                 setBaseLocation(lat, lng);
352
353                 for (AltosSiteMapTile tile : mapTiles.values()) {
354                         tile.clearMap();
355                         tile.set_status(AltosSiteMapCache.loading);
356                 }
357                 Thread thread = new Thread() {
358                                 public void run() {
359                                         for (Point k : mapTiles.keySet())
360                                                 init_map(k, load_mode_cached);
361                                         for (Point k : mapTiles.keySet())
362                                                 init_map(k, load_mode_uncached);
363                                 }
364                         };
365                 thread.start();
366         }
367
368         private static File MapFile(double lat, double lng, int zoom, int maptype) {
369                 char chlat = lat < 0 ? 'S' : 'N';
370                 char chlng = lng < 0 ? 'W' : 'E';
371                 if (lat < 0) lat = -lat;
372                 if (lng < 0) lng = -lng;
373                 String maptype_string = String.format("%s-", maptype_names[maptype]);
374                 String format_string;
375                 if (maptype == maptype_hybrid || maptype == maptype_satellite || maptype == maptype_terrain)
376                         format_string = "jpg";
377                 else
378                         format_string = "png";
379                 return new File(AltosUIPreferences.mapdir(),
380                                 String.format("map-%c%.6f,%c%.6f-%s%d.%s",
381                                               chlat, lat, chlng, lng, maptype_string, zoom, format_string));
382         }
383
384         private static String MapURL(double lat, double lng, int zoom, int maptype) {
385                 String format_string;
386                 if (maptype == maptype_hybrid || maptype == maptype_satellite || maptype == maptype_terrain)
387                         format_string = "jpg";
388                 else
389                         format_string = "png32";
390
391                 if (AltosUIVersion.has_google_maps_api_key())
392                         return String.format("http://maps.google.com/maps/api/staticmap?center=%.6f,%.6f&zoom=%d&size=%dx%d&sensor=false&maptype=%s&format=%s&key=%s",
393                                              lat, lng, zoom, px_size, px_size, maptype_names[maptype], format_string, AltosUIVersion.google_maps_api_key);
394                 else
395                         return String.format("http://maps.google.com/maps/api/staticmap?center=%.6f,%.6f&zoom=%d&size=%dx%d&sensor=false&maptype=%s&format=%s",
396                                              lat, lng, zoom, px_size, px_size, maptype_names[maptype], format_string);
397         }
398
399         boolean initialised = false;
400         MapPoint last_point = null;
401         int last_state = -1;
402
403         private void show(double lat, double lon) {
404                 System.out.printf ("show %g %g\n", lat, lon);
405                 return;
406 //              initMaps(lat, lon);
407 //              scrollRocketToVisible(pt(lat, lon));
408         }
409
410         JLabel  zoom_label;
411
412         private void set_zoom_label() {
413                 zoom_label.setText(String.format("Zoom %d", zoom - default_zoom));
414         }
415
416         public void set_zoom(int zoom) {
417                 if (min_zoom <= zoom && zoom <= max_zoom) {
418                         this.zoom = zoom;
419                         if (base_location_set) {
420                                 set_tiles();
421                                 initMaps(lat, lon);
422                         }
423                         redraw();
424                         set_zoom_label();
425                 }
426         }
427
428         public int get_zoom() {
429                 return zoom;
430         }
431
432         public void set_maptype(int type) {
433                 maptype = type;
434                 maptype_combo.setSelectedIndex(type);
435                 if (base_location_set)
436                         initMaps(lat, lon);
437                 redraw();
438         }
439
440         private void draw(MapPoint last_point, MapPoint point) {
441                 boolean force_ensure = false;
442                 if (last_point == null) {
443                         force_ensure = true;
444                         last_point = point;
445                 }
446
447                 Point2D.Double pt = pt(point.lat, point.lon);
448                 Point2D.Double last_pt = pt(last_point.lat, last_point.lon);
449
450                 boolean in_any = false;
451                 for (Point offset : mapTiles.keySet()) {
452                         AltosSiteMapTile tile = mapTiles.get(offset);
453                         Point2D.Double ref, lref;
454                         ref = translatePoint(pt, tileCoordOffset(offset));
455                         lref = translatePoint(last_pt, tileCoordOffset(offset));
456                         tile.show(point.state, lref, ref);
457                         if (0 <= ref.x && ref.x < px_size)
458                                 if (0 <= ref.y && ref.y < px_size)
459                                         in_any = true;
460                 }
461
462                 Point offset = tileOffset(pt);
463                 if (!in_any) {
464                         Point2D.Double ref, lref;
465                         ref = translatePoint(pt, tileCoordOffset(offset));
466                         lref = translatePoint(last_pt, tileCoordOffset(offset));
467
468                         AltosSiteMapTile tile = createTile(offset);
469                         tile.show(point.state, lref, ref);
470                         initAndFinishMapAsync(tile, offset);
471                 }
472
473                 scrollRocketToVisible(pt);
474
475                 if (force_ensure || offset != tileOffset(last_pt)) {
476                         ensureTilesAround(offset);
477                 }
478         }
479
480         private void redraw() {
481                 MapPoint        last_point = null;
482
483                 for (MapPoint point : points) {
484                         draw(last_point, point);
485                         last_point = point;
486                 }
487                 if (circle_set)
488                         draw_circle(circle_lat, circle_lon);
489                 if (line_start != null)
490                         set_line();
491         }
492
493         public void show(final AltosState state, final AltosListenerState listener_state) {
494                 // if insufficient gps data, nothing to update
495                 AltosGPS        gps = state.gps;
496
497                 if (gps == null)
498                         return;
499
500                 if (!gps.locked && gps.nsat < 4)
501                         return;
502
503                 if (!initialised) {
504                         if (state.pad_lat != AltosLib.MISSING && state.pad_lon != AltosLib.MISSING) {
505                                 initMaps(state.pad_lat, state.pad_lon);
506                                 initialised = true;
507                         } else if (gps.lat != AltosLib.MISSING && gps.lon != AltosLib.MISSING) {
508                                 initMaps(gps.lat, gps.lon);
509                                 initialised = true;
510                         } else {
511                                 return;
512                         }
513                 }
514
515                 MapPoint        point = new MapPoint(gps.lat, gps.lon, state.state);
516
517                 if (point.equals(last_point))
518                         return;
519
520                 points.add(point);
521
522                 draw(last_point, point);
523
524                 last_point = point;
525         }
526
527         public void centre(Point2D.Double pt) {
528                 Rectangle r = comp.getVisibleRect();
529                 Point2D.Double copt = translatePoint(pt, tileCoordOffset(topleft));
530                 int dx = (int)copt.x - r.width/2 - r.x;
531                 int dy = (int)copt.y - r.height/2 - r.y;
532                 r.x += dx;
533                 r.y += dy;
534                 r.width = 1;
535                 r.height = 1;
536                 comp.scrollRectToVisible(r);
537         }
538
539         public void centre(AltosState state) {
540                 if (!state.gps.locked && state.gps.nsat < 4)
541                         return;
542                 centre(pt(state.gps.lat, state.gps.lon));
543         }
544
545         private double circle_lat, circle_lon;
546         private boolean circle_set = false;
547
548         public void draw_circle(double lat, double lon) {
549                 circle_lat = lat;
550                 circle_lon = lon;
551                 circle_set = true;
552
553                 Point2D.Double pt = pt(lat, lon);
554
555                 for (Point offset : mapTiles.keySet()) {
556                         AltosSiteMapTile tile = mapTiles.get(offset);
557                         Point2D.Double ref = translatePoint(pt, tileCoordOffset(offset));
558                         tile.set_boost(ref);
559                 }
560         }
561
562         private AltosSiteMapTile createTile(Point offset) {
563                 AltosSiteMapTile tile = new AltosSiteMapTile(px_size);
564                 tile.set_font(AltosUILib.value_font);
565                 mapTiles.put(offset, tile);
566                 return tile;
567         }
568
569         private void ensureTilesAround(Point base_offset) {
570                 for (int x = -radius; x <= radius; x++) {
571                         for (int y = -radius; y <= radius; y++) {
572                                 Point offset = new Point(base_offset.x + x, base_offset.y + y);
573                                 if (mapTiles.containsKey(offset))
574                                         continue;
575                                 AltosSiteMapTile tile = createTile(offset);
576                                 initAndFinishMapAsync(tile, offset);
577                         }
578                 }
579         }
580
581         private void set_tiles() {
582                 for (int x = -radius; x <= radius; x++) {
583                         for (int y = -radius; y <= radius; y++) {
584                                 Point offset = new Point(x, y);
585                                 if (mapTiles.containsKey(offset))
586                                         continue;
587                                 AltosSiteMapTile t = createTile(offset);
588                                 addTileAt(t, offset);
589                         }
590                 }
591                 for (Point offset : mapTiles.keySet()) {
592                         if (offset.x < -radius || offset.x > radius ||
593                             offset.y < -radius || offset.y > radius)
594                         {
595                                 removeTileAt(offset);
596                         }
597                 }
598         }
599
600         public void set_radius(int radius) {
601                 if (radius != this.radius) {
602                         this.radius = radius;
603                         set_tiles();
604                 }
605         }
606
607         private Point topleft = new Point(0,0);
608         private void scrollRocketToVisible(Point2D.Double pt) {
609                 Rectangle r = comp.getVisibleRect();
610                 Point2D.Double copt = translatePoint(pt, tileCoordOffset(topleft));
611
612                 int dx = (int)copt.x - r.width/2 - r.x;
613                 int dy = (int)copt.y - r.height/2 - r.y;
614                 if (Math.abs(dx) > r.width/4 || Math.abs(dy) > r.height/4) {
615                         r.x += dx;
616                         r.y += dy;
617                         comp.scrollRectToVisible(r);
618                 }
619         }
620
621         private void addTileAt(AltosSiteMapTile tile, Point offset) {
622                 if (Math.abs(offset.x) >= MAX_TILE_DELTA ||
623                                 Math.abs(offset.y) >= MAX_TILE_DELTA)
624                 {
625                         System.out.printf("Rocket too far away from pad (tile %d,%d)\n",
626                                           offset.x, offset.y);
627                         return;
628                 }
629
630                 if (offset.x < topleft.x)
631                         topleft.x = offset.x;
632                 if (offset.y < topleft.y)
633                         topleft.y = offset.y;
634
635                 GridBagConstraints c = new GridBagConstraints();
636                 c.anchor = GridBagConstraints.CENTER;
637                 c.fill = GridBagConstraints.BOTH;
638                 // put some space between the map tiles, debugging only
639                 // c.insets = new Insets(5, 5, 5, 5);
640
641                 c.gridx = offset.x + MAX_TILE_DELTA;
642                 c.gridy = offset.y + MAX_TILE_DELTA;
643                 layout.setConstraints(tile, c);
644
645                 comp.add(tile);
646         }
647
648         private AltosSiteMap(boolean knowWhatYouAreDoing) {
649                 if (!knowWhatYouAreDoing) {
650                         throw new RuntimeException("Arggh.");
651                 }
652         }
653
654         private void removeTileAt(Point offset) {
655                 AltosSiteMapTile        tile = mapTiles.get(offset);
656
657                 mapTiles.remove(offset);
658                 comp.remove(tile);
659
660                 topleft = new Point(MAX_TILE_DELTA, MAX_TILE_DELTA);
661                 for (Point o : mapTiles.keySet()) {
662                         if (o.x < topleft.x)
663                                 topleft.x = o.x;
664                         if (o.y < topleft.y)
665                                 topleft.y = o.y;
666                 }
667         }
668
669         JComponent comp;
670
671         private GridBagLayout layout = new GridBagLayout();
672
673         LatLng  line_start, line_end;
674
675         private void set_line() {
676                 if (line_start != null && line_end != null) {
677                         Point2D.Double  start = pt(line_start.lat, line_start.lng);
678                         Point2D.Double  end = pt(line_end.lat, line_end.lng);
679                         AltosGreatCircle        g = new AltosGreatCircle(line_start.lat, line_start.lng,
680                                                                          line_end.lat, line_end.lng);
681
682                         for (Point offset : mapTiles.keySet()) {
683                                 AltosSiteMapTile tile = mapTiles.get(offset);
684                                 Point2D.Double s, e;
685                                 s = translatePoint(start, tileCoordOffset(offset));
686                                 e = translatePoint(end, tileCoordOffset(offset));
687                                 tile.set_line(new Line2D.Double(s.x, s.y, e.x, e.y), g.distance);
688                         }
689                 } else {
690                         for (AltosSiteMapTile tile : mapTiles.values())
691                                 tile.set_line(null, 0);
692                 }
693         }
694
695         static void debug_component(Component who, String where) {
696 /*
697                 Rectangle       r = who.getBounds();
698                 int             x = r.x / px_size;
699                 int             y = r.y / px_size;
700
701                 System.out.printf ("%3d, %3d: %s\n", x, y, where);
702 */
703         }
704
705         LatLng latlng(MouseEvent e) {
706                 if (!base_location_set)
707                         return null;
708
709                 Rectangle       zerozero = mapTiles.get(new Point(0, 0)).getBounds();
710
711                 return latlng(-centre.x + e.getPoint().x - zerozero.x, -centre.y + e.getPoint().y - zerozero.y);
712         }
713
714         /* MouseMotionListener methods */
715         public void mouseDragged(MouseEvent e) {
716                 if (!GrabNDrag.grab_n_drag(e)) {
717                         LatLng  loc = latlng(e);
718                         line_end = loc;
719                         set_line();
720                 }
721         }
722
723         public void mouseMoved(MouseEvent e) {
724         }
725
726         /* MouseListener methods */
727         public void mouseClicked(MouseEvent e) {
728         }
729
730         public void mouseEntered(MouseEvent e) {
731         }
732
733         public void mouseExited(MouseEvent e) {
734         }
735
736         public void mousePressed(MouseEvent e) {
737                 if (!GrabNDrag.grab_n_drag(e)) {
738                         LatLng  loc = latlng(e);
739                         line_start = loc;
740                         line_end = null;
741                         set_line();
742                 }
743         }
744
745         public void mouseReleased(MouseEvent e) {
746         }
747
748         private void set_cache_size() {
749                 Rectangle       r = comp.getVisibleRect();
750
751                 int     width_tiles = (r.width + 2*px_size) / px_size;
752                 int     height_tiles = (r.height + 2*px_size) / px_size;
753                 int     tiles = width_tiles * height_tiles;
754                 AltosSiteMapCache.set_cache_size(tiles);
755         }
756
757         /* HierarchyBoundsListener methods */
758         public void ancestorMoved(HierarchyEvent e) {
759                 set_cache_size();
760         }
761
762         public void ancestorResized(HierarchyEvent e) {
763                 set_cache_size();
764         }
765
766         JScrollPane     pane = new JScrollPane();
767
768         JComboBox<String>       maptype_combo;
769
770         public AltosSiteMap(int in_radius) {
771                 radius = in_radius;
772
773                 comp = new JComponent() { };
774
775                 comp.addMouseMotionListener(this);
776                 comp.addMouseListener(this);
777                 comp.addHierarchyBoundsListener(this);
778
779                 GrabNDrag scroller = new GrabNDrag(comp);
780
781                 comp.setLayout(layout);
782
783                 set_tiles();
784
785                 pane.setViewportView(comp);
786                 pane.setPreferredSize(new Dimension(500,500));
787                 pane.setVisible(true);
788                 pane.setEnabled(true);
789
790                 GridBagLayout   my_layout = new GridBagLayout();
791
792                 setLayout(my_layout);
793
794                 GridBagConstraints c = new GridBagConstraints();
795                 c.anchor = GridBagConstraints.CENTER;
796                 c.fill = GridBagConstraints.BOTH;
797                 c.gridx = 0;
798                 c.gridy = 0;
799                 c.gridwidth = 1;
800                 c.gridheight = 10;
801                 c.weightx = 1;
802                 c.weighty = 1;
803                 add(pane, c);
804
805                 int     y = 0;
806
807                 zoom_label = new JLabel("", JLabel.CENTER);
808                 set_zoom_label();
809
810                 c = new GridBagConstraints();
811                 c.anchor = GridBagConstraints.CENTER;
812                 c.fill = GridBagConstraints.HORIZONTAL;
813                 c.gridx = 1;
814                 c.gridy = y++;
815                 c.weightx = 0;
816                 c.weighty = 0;
817                 add(zoom_label, c);
818
819                 JButton zoom_reset = new JButton("0");
820                 zoom_reset.addActionListener(new ActionListener() {
821                                 public void actionPerformed(ActionEvent e) {
822                                         set_zoom(default_zoom);
823                                 }
824                         });
825
826                 c = new GridBagConstraints();
827                 c.anchor = GridBagConstraints.CENTER;
828                 c.fill = GridBagConstraints.HORIZONTAL;
829                 c.gridx = 1;
830                 c.gridy = y++;
831                 c.weightx = 0;
832                 c.weighty = 0;
833                 add(zoom_reset, c);
834
835                 JButton zoom_in = new JButton("+");
836                 zoom_in.addActionListener(new ActionListener() {
837                                 public void actionPerformed(ActionEvent e) {
838                                         set_zoom(get_zoom() + 1);
839                                 }
840                         });
841
842                 c = new GridBagConstraints();
843                 c.anchor = GridBagConstraints.CENTER;
844                 c.fill = GridBagConstraints.HORIZONTAL;
845                 c.gridx = 1;
846                 c.gridy = y++;
847                 c.weightx = 0;
848                 c.weighty = 0;
849                 add(zoom_in, c);
850
851                 JButton zoom_out = new JButton("-");
852                 zoom_out.addActionListener(new ActionListener() {
853                                 public void actionPerformed(ActionEvent e) {
854                                         set_zoom(get_zoom() - 1);
855                                 }
856                         });
857                 c = new GridBagConstraints();
858                 c.anchor = GridBagConstraints.CENTER;
859                 c.fill = GridBagConstraints.HORIZONTAL;
860                 c.gridx = 1;
861                 c.gridy = y++;
862                 c.weightx = 0;
863                 c.weighty = 0;
864                 add(zoom_out, c);
865
866                 maptype_combo = new JComboBox<String>(maptype_labels);
867
868                 maptype_combo.setEditable(false);
869                 maptype_combo.setMaximumRowCount(maptype_combo.getItemCount());
870                 maptype_combo.addItemListener(new ItemListener() {
871                                 public void itemStateChanged(ItemEvent e) {
872                                         maptype = maptype_combo.getSelectedIndex();
873                                         if (base_location_set)
874                                                 initMaps(lat, lon);
875                                         redraw();
876                                 }
877                         });
878
879                 c = new GridBagConstraints();
880                 c.anchor = GridBagConstraints.CENTER;
881                 c.fill = GridBagConstraints.HORIZONTAL;
882                 c.gridx = 1;
883                 c.gridy = y++;
884                 c.weightx = 0;
885                 c.weighty = 0;
886                 add(maptype_combo, c);
887         }
888
889         public AltosSiteMap() {
890                 this(1);
891         }
892 }