461886c7f0e3f2e53f2160d19dd73da87d58153e
[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 set_font() {
196                 for (AltosSiteMapTile tile : mapTiles.values())
197                         tile.set_font(AltosUILib.value_font);
198         }
199
200         static final int load_mode_cached = 1;
201         static final int load_mode_uncached = 2;
202
203         private boolean load_map(final AltosSiteMapTile tile,
204                                  final File pngfile, String pngurl,
205                                  int load_mode)
206         {
207                 boolean has_map = AltosSiteMapCache.has_map(pngfile, pngurl);
208                 if ((load_mode & load_mode_uncached) == 0 && !has_map)
209                         return false;
210                 if ((load_mode & load_mode_cached) == 0 && has_map)
211                         return false;
212
213                 tile.set_status(AltosSiteMapCache.loading);
214                 int status = AltosSiteMapCache.fetch_map(pngfile, pngurl);
215                 if (status == AltosSiteMapCache.success) {
216                         if (SwingUtilities.isEventDispatchThread())
217                                 tile.load_map(pngfile);
218                         else {
219                                 SwingUtilities.invokeLater(new Runnable() {
220                                                 public void run() {
221                                                         tile.load_map(pngfile);
222                                                 }
223                                         });
224                         }
225                 } else {
226                         tile.set_status(status);
227                         System.out.printf("# Failed to fetch file %s (status %d)\n", pngfile, status);
228                         System.out.printf(" wget -O '%s' '%s'\n", pngfile, pngurl);
229                         System.out.printf(" sleep 1\n");
230                 }
231                 return true;
232         }
233
234
235         class AltosSiteMapPrefetch {
236                 int     x;
237                 int     y;
238                 int     result;
239                 File    pngfile;
240                 String  pngurl;
241         }
242
243         private AltosSiteMapPrefetch prefetchMap(int x, int y) {
244                 AltosSiteMapPrefetch    prefetch = new AltosSiteMapPrefetch();
245                 LatLng map_latlng = latlng(
246                         -centre.x + x*px_size + px_size/2,
247                         -centre.y + y*px_size + px_size/2);
248                 prefetch.pngfile = MapFile(map_latlng.lat, map_latlng.lng, zoom, maptype_hybrid);
249                 prefetch.pngurl = MapURL(map_latlng.lat, map_latlng.lng, zoom, maptype_hybrid);
250                 if (AltosSiteMapCache.has_map(prefetch.pngfile, prefetch.pngurl)) {
251                         prefetch.result = 1;
252                 } else if (AltosSiteMapCache.fetch_map(prefetch.pngfile, prefetch.pngurl) == AltosSiteMapCache.success) {
253                         prefetch.result = 0;
254                 } else {
255                         prefetch.result = -1;
256                 }
257                 return prefetch;
258         }
259
260         public static void prefetchMaps(double lat, double lng, int radius, int maptypes, int min_zoom, int max_zoom) {
261                 AltosSiteMap asm = new AltosSiteMap(true);
262
263                 for (int z = min_zoom; z <= max_zoom; z++) {
264                         asm.zoom = z;
265                         asm.set_radius(radius);
266                         asm.centre = asm.getBaseLocation(lat, lng);
267                         for (int t = maptype_hybrid; t <= maptype_terrain; t++) {
268                                 if ((maptypes & (1 << t)) !=0) {
269                                         asm.maptype = t;
270                                         for (int y = -radius; y <= radius; y++) {
271                                                 for (int x = -radius; x <= radius; x++) {
272                                                         AltosSiteMapPrefetch prefetch = asm.prefetchMap(x, y);
273                                                         switch (prefetch.result) {
274                                                         case 1:
275                                                                 System.out.printf("Already have %s\n", prefetch.pngfile);
276                                                                 break;
277                                                         case 0:
278                                                                 System.out.printf("Fetched map %s\n", prefetch.pngfile);
279                                                                 break;
280                                                         case -1:
281                                                                 System.out.printf("# Failed to fetch file %s\n", prefetch.pngfile);
282                                                                 System.out.printf(" wget -O '%s' ''\n",
283                                                                                   prefetch.pngfile, prefetch.pngurl);
284                                                                 break;
285                                                         }
286                                                 }
287                                         }
288                                 }
289                         }
290                 }
291         }
292
293         public File init_map(Point offset, int load_mode) {
294                 AltosSiteMapTile tile = mapTiles.get(offset);
295                 Point2D.Double coord = tileCoordOffset(offset);
296
297                 LatLng map_latlng = latlng(px_size/2-coord.x, px_size/2-coord.y);
298
299                 File pngfile = MapFile(map_latlng.lat, map_latlng.lng, zoom, maptype);
300                 String pngurl = MapURL(map_latlng.lat, map_latlng.lng, zoom, maptype);
301                 load_map(tile, pngfile, pngurl, load_mode);
302                 return pngfile;
303         }
304
305         private void initAndFinishMapAsync (final AltosSiteMapTile tile, final Point offset) {
306                 Thread thread = new Thread() {
307                                 public void run() {
308                                         init_map(offset, load_mode_cached|load_mode_uncached);
309                                         SwingUtilities.invokeLater( new Runnable() {
310                                                         public void run() {
311                                                                 addTileAt(tile, offset);
312                                                         }
313                                                 } );
314                                 }
315                         };
316                 thread.start();
317         }
318
319         double  lat, lon;
320         boolean base_location_set = false;
321
322         public void clear_base_location() {
323                 base_location_set = false;
324                 circle_set = false;
325                 points = new LinkedList<MapPoint>();
326                 line_start = line_end = null;
327                 for (AltosSiteMapTile tile : mapTiles.values()) {
328                         tile.clearMap();
329                         tile.set_status(AltosSiteMapCache.loading);
330                 }
331         }
332
333         public void setBaseLocation(double lat, double lng) {
334                 this.lat = lat;
335                 this.lon = lng;
336                 base_location_set = true;
337
338                 centre = getBaseLocation(lat, lng);
339                 scrollRocketToVisible(pt(lat,lng));
340         }
341
342         private void initMaps(double lat, double lng) {
343                 setBaseLocation(lat, lng);
344
345                 for (AltosSiteMapTile tile : mapTiles.values()) {
346                         tile.clearMap();
347                         tile.set_status(AltosSiteMapCache.loading);
348                 }
349                 Thread thread = new Thread() {
350                                 public void run() {
351                                         for (Point k : mapTiles.keySet())
352                                                 init_map(k, load_mode_cached);
353                                         for (Point k : mapTiles.keySet())
354                                                 init_map(k, load_mode_uncached);
355                                 }
356                         };
357                 thread.start();
358         }
359
360         private static File MapFile(double lat, double lng, int zoom, int maptype) {
361                 char chlat = lat < 0 ? 'S' : 'N';
362                 char chlng = lng < 0 ? 'W' : 'E';
363                 if (lat < 0) lat = -lat;
364                 if (lng < 0) lng = -lng;
365                 String maptype_string = String.format("%s-", maptype_names[maptype]);
366                 String format_string;
367                 if (maptype == maptype_hybrid || maptype == maptype_satellite || maptype == maptype_terrain)
368                         format_string = "jpg";
369                 else
370                         format_string = "png";
371                 return new File(AltosUIPreferences.mapdir(),
372                                 String.format("map-%c%.6f,%c%.6f-%s%d.%s",
373                                               chlat, lat, chlng, lng, maptype_string, zoom, format_string));
374         }
375
376         private static String MapURL(double lat, double lng, int zoom, int maptype) {
377                 String format_string;
378                 if (maptype == maptype_hybrid || maptype == maptype_satellite || maptype == maptype_terrain)
379                         format_string = "jpg";
380                 else
381                         format_string = "png32";
382
383                 if (AltosUIVersion.has_google_maps_api_key())
384                         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",
385                                              lat, lng, zoom, px_size, px_size, maptype_names[maptype], format_string, AltosUIVersion.google_maps_api_key);
386                 else
387                         return String.format("http://maps.google.com/maps/api/staticmap?center=%.6f,%.6f&zoom=%d&size=%dx%d&sensor=false&maptype=%s&format=%s",
388                                              lat, lng, zoom, px_size, px_size, maptype_names[maptype], format_string);
389         }
390
391         boolean initialised = false;
392         MapPoint last_point = null;
393         int last_state = -1;
394
395         private void show(double lat, double lon) {
396                 System.out.printf ("show %g %g\n", lat, lon);
397                 return;
398 //              initMaps(lat, lon);
399 //              scrollRocketToVisible(pt(lat, lon));
400         }
401
402         JLabel  zoom_label;
403
404         private void set_zoom_label() {
405                 zoom_label.setText(String.format("Zoom %d", zoom - default_zoom));
406         }
407
408         public void set_zoom(int zoom) {
409                 if (min_zoom <= zoom && zoom <= max_zoom) {
410                         this.zoom = zoom;
411                         if (base_location_set) {
412                                 set_tiles();
413                                 initMaps(lat, lon);
414                         }
415                         redraw();
416                         set_zoom_label();
417                 }
418         }
419
420         public int get_zoom() {
421                 return zoom;
422         }
423
424         public void set_maptype(int type) {
425                 maptype = type;
426                 maptype_combo.setSelectedIndex(type);
427                 if (base_location_set)
428                         initMaps(lat, lon);
429                 redraw();
430         }
431
432         private void draw(MapPoint last_point, MapPoint point) {
433                 boolean force_ensure = false;
434                 if (last_point == null) {
435                         force_ensure = true;
436                         last_point = point;
437                 }
438
439                 Point2D.Double pt = pt(point.lat, point.lon);
440                 Point2D.Double last_pt = pt(last_point.lat, last_point.lon);
441
442                 boolean in_any = false;
443                 for (Point offset : mapTiles.keySet()) {
444                         AltosSiteMapTile tile = mapTiles.get(offset);
445                         Point2D.Double ref, lref;
446                         ref = translatePoint(pt, tileCoordOffset(offset));
447                         lref = translatePoint(last_pt, tileCoordOffset(offset));
448                         tile.show(point.state, lref, ref);
449                         if (0 <= ref.x && ref.x < px_size)
450                                 if (0 <= ref.y && ref.y < px_size)
451                                         in_any = true;
452                 }
453
454                 Point offset = tileOffset(pt);
455                 if (!in_any) {
456                         Point2D.Double ref, lref;
457                         ref = translatePoint(pt, tileCoordOffset(offset));
458                         lref = translatePoint(last_pt, tileCoordOffset(offset));
459
460                         AltosSiteMapTile tile = createTile(offset);
461                         tile.show(point.state, lref, ref);
462                         initAndFinishMapAsync(tile, offset);
463                 }
464
465                 scrollRocketToVisible(pt);
466
467                 if (force_ensure || offset != tileOffset(last_pt)) {
468                         ensureTilesAround(offset);
469                 }
470         }
471
472         private void redraw() {
473                 MapPoint        last_point = null;
474
475                 for (MapPoint point : points) {
476                         draw(last_point, point);
477                         last_point = point;
478                 }
479                 if (circle_set)
480                         draw_circle(circle_lat, circle_lon);
481                 if (line_start != null)
482                         set_line();
483         }
484
485         public void show(final AltosState state, final AltosListenerState listener_state) {
486                 // if insufficient gps data, nothing to update
487                 AltosGPS        gps = state.gps;
488
489                 if (gps == null)
490                         return;
491
492                 if (!gps.locked && gps.nsat < 4)
493                         return;
494
495                 if (!initialised) {
496                         if (state.pad_lat != AltosLib.MISSING && state.pad_lon != AltosLib.MISSING) {
497                                 initMaps(state.pad_lat, state.pad_lon);
498                                 initialised = true;
499                         } else if (gps.lat != AltosLib.MISSING && gps.lon != AltosLib.MISSING) {
500                                 initMaps(gps.lat, gps.lon);
501                                 initialised = true;
502                         } else {
503                                 return;
504                         }
505                 }
506
507                 MapPoint        point = new MapPoint(gps.lat, gps.lon, state.state);
508
509                 if (point.equals(last_point))
510                         return;
511
512                 points.add(point);
513
514                 draw(last_point, point);
515
516                 last_point = point;
517         }
518
519         private void centre(Point2D.Double pt) {
520                 Rectangle r = comp.getVisibleRect();
521                 Point2D.Double copt = translatePoint(pt, tileCoordOffset(topleft));
522                 int dx = (int)copt.x - r.width/2 - r.x;
523                 int dy = (int)copt.y - r.height/2 - r.y;
524                 r.x += dx;
525                 r.y += dy;
526                 r.width = 1;
527                 r.height = 1;
528                 comp.scrollRectToVisible(r);
529         }
530
531         private void centre(AltosState state) {
532                 if (!state.gps.locked && state.gps.nsat < 4)
533                         return;
534                 centre(pt(state.gps.lat, state.gps.lon));
535         }
536
537         private double circle_lat, circle_lon;
538         private boolean circle_set = false;
539
540         public void draw_circle(double lat, double lon) {
541                 circle_lat = lat;
542                 circle_lon = lon;
543                 circle_set = true;
544
545                 Point2D.Double pt = pt(lat, lon);
546
547                 for (Point offset : mapTiles.keySet()) {
548                         AltosSiteMapTile tile = mapTiles.get(offset);
549                         Point2D.Double ref = translatePoint(pt, tileCoordOffset(offset));
550                         tile.set_boost(ref);
551                 }
552         }
553
554         private AltosSiteMapTile createTile(Point offset) {
555                 AltosSiteMapTile tile = new AltosSiteMapTile(px_size);
556                 tile.set_font(AltosUILib.value_font);
557                 mapTiles.put(offset, tile);
558                 return tile;
559         }
560
561         private void ensureTilesAround(Point base_offset) {
562                 for (int x = -radius; x <= radius; x++) {
563                         for (int y = -radius; y <= radius; y++) {
564                                 Point offset = new Point(base_offset.x + x, base_offset.y + y);
565                                 if (mapTiles.containsKey(offset))
566                                         continue;
567                                 AltosSiteMapTile tile = createTile(offset);
568                                 initAndFinishMapAsync(tile, offset);
569                         }
570                 }
571         }
572
573         private void set_tiles() {
574                 for (int x = -radius; x <= radius; x++) {
575                         for (int y = -radius; y <= radius; y++) {
576                                 Point offset = new Point(x, y);
577                                 if (mapTiles.containsKey(offset))
578                                         continue;
579                                 AltosSiteMapTile t = createTile(offset);
580                                 addTileAt(t, offset);
581                         }
582                 }
583                 for (Point offset : mapTiles.keySet()) {
584                         if (offset.x < -radius || offset.x > radius ||
585                             offset.y < -radius || offset.y > radius)
586                         {
587                                 removeTileAt(offset);
588                         }
589                 }
590         }
591
592         public void set_radius(int radius) {
593                 if (radius != this.radius) {
594                         this.radius = radius;
595                         set_tiles();
596                 }
597         }
598
599         private Point topleft = new Point(0,0);
600         private void scrollRocketToVisible(Point2D.Double pt) {
601                 Rectangle r = comp.getVisibleRect();
602                 Point2D.Double copt = translatePoint(pt, tileCoordOffset(topleft));
603
604                 int dx = (int)copt.x - r.width/2 - r.x;
605                 int dy = (int)copt.y - r.height/2 - r.y;
606                 if (Math.abs(dx) > r.width/4 || Math.abs(dy) > r.height/4) {
607                         r.x += dx;
608                         r.y += dy;
609                         comp.scrollRectToVisible(r);
610                 }
611         }
612
613         private void addTileAt(AltosSiteMapTile tile, Point offset) {
614                 if (Math.abs(offset.x) >= MAX_TILE_DELTA ||
615                                 Math.abs(offset.y) >= MAX_TILE_DELTA)
616                 {
617                         System.out.printf("Rocket too far away from pad (tile %d,%d)\n",
618                                           offset.x, offset.y);
619                         return;
620                 }
621
622                 if (offset.x < topleft.x)
623                         topleft.x = offset.x;
624                 if (offset.y < topleft.y)
625                         topleft.y = offset.y;
626
627                 GridBagConstraints c = new GridBagConstraints();
628                 c.anchor = GridBagConstraints.CENTER;
629                 c.fill = GridBagConstraints.BOTH;
630                 // put some space between the map tiles, debugging only
631                 // c.insets = new Insets(5, 5, 5, 5);
632
633                 c.gridx = offset.x + MAX_TILE_DELTA;
634                 c.gridy = offset.y + MAX_TILE_DELTA;
635                 layout.setConstraints(tile, c);
636
637                 comp.add(tile);
638         }
639
640         private AltosSiteMap(boolean knowWhatYouAreDoing) {
641                 if (!knowWhatYouAreDoing) {
642                         throw new RuntimeException("Arggh.");
643                 }
644         }
645
646         private void removeTileAt(Point offset) {
647                 AltosSiteMapTile        tile = mapTiles.get(offset);
648
649                 mapTiles.remove(offset);
650                 comp.remove(tile);
651
652                 topleft = new Point(MAX_TILE_DELTA, MAX_TILE_DELTA);
653                 for (Point o : mapTiles.keySet()) {
654                         if (o.x < topleft.x)
655                                 topleft.x = o.x;
656                         if (o.y < topleft.y)
657                                 topleft.y = o.y;
658                 }
659         }
660
661         JComponent comp;
662
663         private GridBagLayout layout = new GridBagLayout();
664
665         LatLng  line_start, line_end;
666
667         private void set_line() {
668                 if (line_start != null && line_end != null) {
669                         Point2D.Double  start = pt(line_start.lat, line_start.lng);
670                         Point2D.Double  end = pt(line_end.lat, line_end.lng);
671                         AltosGreatCircle        g = new AltosGreatCircle(line_start.lat, line_start.lng,
672                                                                          line_end.lat, line_end.lng);
673
674                         for (Point offset : mapTiles.keySet()) {
675                                 AltosSiteMapTile tile = mapTiles.get(offset);
676                                 Point2D.Double s, e;
677                                 s = translatePoint(start, tileCoordOffset(offset));
678                                 e = translatePoint(end, tileCoordOffset(offset));
679                                 tile.set_line(new Line2D.Double(s.x, s.y, e.x, e.y), g.distance);
680                         }
681                 } else {
682                         for (AltosSiteMapTile tile : mapTiles.values())
683                                 tile.set_line(null, 0);
684                 }
685         }
686
687         static void debug_component(Component who, String where) {
688 /*
689                 Rectangle       r = who.getBounds();
690                 int             x = r.x / px_size;
691                 int             y = r.y / px_size;
692
693                 System.out.printf ("%3d, %3d: %s\n", x, y, where);
694 */
695         }
696
697         LatLng latlng(MouseEvent e) {
698                 if (!base_location_set)
699                         return null;
700
701                 Rectangle       zerozero = mapTiles.get(new Point(0, 0)).getBounds();
702
703                 return latlng(-centre.x + e.getPoint().x - zerozero.x, -centre.y + e.getPoint().y - zerozero.y);
704         }
705
706         /* MouseMotionListener methods */
707         public void mouseDragged(MouseEvent e) {
708                 if (!GrabNDrag.grab_n_drag(e)) {
709                         LatLng  loc = latlng(e);
710                         line_end = loc;
711                         set_line();
712                 }
713         }
714
715         public void mouseMoved(MouseEvent e) {
716         }
717
718         /* MouseListener methods */
719         public void mouseClicked(MouseEvent e) {
720         }
721
722         public void mouseEntered(MouseEvent e) {
723         }
724
725         public void mouseExited(MouseEvent e) {
726         }
727
728         public void mousePressed(MouseEvent e) {
729                 if (!GrabNDrag.grab_n_drag(e)) {
730                         LatLng  loc = latlng(e);
731                         line_start = loc;
732                         line_end = null;
733                         set_line();
734                 }
735         }
736
737         public void mouseReleased(MouseEvent e) {
738         }
739
740         private void set_cache_size() {
741                 Rectangle       r = comp.getVisibleRect();
742
743                 int     width_tiles = (r.width + 2*px_size) / px_size;
744                 int     height_tiles = (r.height + 2*px_size) / px_size;
745                 int     tiles = width_tiles * height_tiles;
746                 AltosSiteMapCache.set_cache_size(tiles);
747         }
748
749         /* HierarchyBoundsListener methods */
750         public void ancestorMoved(HierarchyEvent e) {
751                 set_cache_size();
752         }
753
754         public void ancestorResized(HierarchyEvent e) {
755                 set_cache_size();
756         }
757
758         JScrollPane     pane = new JScrollPane();
759
760         JComboBox<String>       maptype_combo;
761
762         public AltosSiteMap(int in_radius) {
763                 radius = in_radius;
764
765                 comp = new JComponent() { };
766
767                 comp.addMouseMotionListener(this);
768                 comp.addMouseListener(this);
769                 comp.addHierarchyBoundsListener(this);
770
771                 GrabNDrag scroller = new GrabNDrag(comp);
772
773                 comp.setLayout(layout);
774
775                 set_tiles();
776
777                 pane.setViewportView(comp);
778                 pane.setPreferredSize(new Dimension(500,500));
779                 pane.setVisible(true);
780                 pane.setEnabled(true);
781
782                 GridBagLayout   my_layout = new GridBagLayout();
783
784                 setLayout(my_layout);
785
786                 GridBagConstraints c = new GridBagConstraints();
787                 c.anchor = GridBagConstraints.CENTER;
788                 c.fill = GridBagConstraints.BOTH;
789                 c.gridx = 0;
790                 c.gridy = 0;
791                 c.gridwidth = 1;
792                 c.gridheight = 10;
793                 c.weightx = 1;
794                 c.weighty = 1;
795                 add(pane, c);
796
797                 int     y = 0;
798
799                 zoom_label = new JLabel("", JLabel.CENTER);
800                 set_zoom_label();
801
802                 c = new GridBagConstraints();
803                 c.anchor = GridBagConstraints.CENTER;
804                 c.fill = GridBagConstraints.HORIZONTAL;
805                 c.gridx = 1;
806                 c.gridy = y++;
807                 c.weightx = 0;
808                 c.weighty = 0;
809                 add(zoom_label, c);
810
811                 JButton zoom_reset = new JButton("0");
812                 zoom_reset.addActionListener(new ActionListener() {
813                                 public void actionPerformed(ActionEvent e) {
814                                         set_zoom(default_zoom);
815                                 }
816                         });
817
818                 c = new GridBagConstraints();
819                 c.anchor = GridBagConstraints.CENTER;
820                 c.fill = GridBagConstraints.HORIZONTAL;
821                 c.gridx = 1;
822                 c.gridy = y++;
823                 c.weightx = 0;
824                 c.weighty = 0;
825                 add(zoom_reset, c);
826
827                 JButton zoom_in = new JButton("+");
828                 zoom_in.addActionListener(new ActionListener() {
829                                 public void actionPerformed(ActionEvent e) {
830                                         set_zoom(get_zoom() + 1);
831                                 }
832                         });
833
834                 c = new GridBagConstraints();
835                 c.anchor = GridBagConstraints.CENTER;
836                 c.fill = GridBagConstraints.HORIZONTAL;
837                 c.gridx = 1;
838                 c.gridy = y++;
839                 c.weightx = 0;
840                 c.weighty = 0;
841                 add(zoom_in, c);
842
843                 JButton zoom_out = new JButton("-");
844                 zoom_out.addActionListener(new ActionListener() {
845                                 public void actionPerformed(ActionEvent e) {
846                                         set_zoom(get_zoom() - 1);
847                                 }
848                         });
849                 c = new GridBagConstraints();
850                 c.anchor = GridBagConstraints.CENTER;
851                 c.fill = GridBagConstraints.HORIZONTAL;
852                 c.gridx = 1;
853                 c.gridy = y++;
854                 c.weightx = 0;
855                 c.weighty = 0;
856                 add(zoom_out, c);
857
858                 maptype_combo = new JComboBox<String>(maptype_labels);
859
860                 maptype_combo.setEditable(false);
861                 maptype_combo.setMaximumRowCount(maptype_combo.getItemCount());
862                 maptype_combo.addItemListener(new ItemListener() {
863                                 public void itemStateChanged(ItemEvent e) {
864                                         maptype = maptype_combo.getSelectedIndex();
865                                         if (base_location_set)
866                                                 initMaps(lat, lon);
867                                         redraw();
868                                 }
869                         });
870
871                 c = new GridBagConstraints();
872                 c.anchor = GridBagConstraints.CENTER;
873                 c.fill = GridBagConstraints.HORIZONTAL;
874                 c.gridx = 1;
875                 c.gridy = y++;
876                 c.weightx = 0;
877                 c.weighty = 0;
878                 add(maptype_combo, c);
879         }
880
881         public AltosSiteMap() {
882                 this(1);
883         }
884 }