]> Pileus Git - aweather/blob - src/plugins/radar.c
Update San Juan site
[aweather] / src / plugins / radar.c
1 /*
2  * Copyright (C) 2009-2010 Andy Spencer <andy753421@gmail.com>
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, either version 3 of the License, or
7  * (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
16  */
17
18 #define _XOPEN_SOURCE
19 #include <sys/time.h>
20 #include <config.h>
21 #include <glib/gstdio.h>
22 #include <gtk/gtk.h>
23 #include <gio/gio.h>
24 #include <GL/gl.h>
25 #include <math.h>
26 #include <rsl.h>
27
28 #include <grits.h>
29
30 #include "radar.h"
31 #include "level2.h"
32 #include "../aweather-location.h"
33
34 static void _gtk_bin_set_child(GtkBin *bin, GtkWidget *new)
35 {
36         GtkWidget *old = gtk_bin_get_child(bin);
37         if (old)
38                 gtk_widget_destroy(old);
39         gtk_container_add(GTK_CONTAINER(bin), new);
40         gtk_widget_show_all(new);
41 }
42
43 static gchar *_find_nearest(time_t time, GList *files,
44                 gsize offset, gchar *format)
45 {
46         g_debug("RadarSite: find_nearest ...");
47         time_t  nearest_time = 0;
48         char   *nearest_file = NULL;
49
50         struct tm tm = {};
51         for (GList *cur = files; cur; cur = cur->next) {
52                 gchar *file = cur->data;
53                 strptime(file+offset, format, &tm);
54                 if (ABS(time - mktime(&tm)) <
55                     ABS(time - nearest_time)) {
56                         nearest_file = file;
57                         nearest_time = mktime(&tm);
58                 }
59         }
60
61         g_debug("RadarSite: find_nearest = %s", nearest_file);
62         if (nearest_file)
63                 return g_strdup(nearest_file);
64         else
65                 return NULL;
66 }
67
68
69 /**************
70  * RadarSites *
71  **************/
72 typedef enum {
73         STATUS_UNLOADED,
74         STATUS_LOADING,
75         STATUS_LOADED,
76 } RadarSiteStatus;
77 struct _RadarSite {
78         /* Information */
79         city_t         *city;
80         GritsMarker    *marker;      // Map marker for grits
81
82         /* Stuff from the parents */
83         GritsViewer    *viewer;
84         GritsHttp      *http;
85         GritsPrefs     *prefs;
86         GtkWidget      *pconfig;
87
88         /* When loaded */
89         gboolean        hidden;
90         RadarSiteStatus status;      // Loading status for the site
91         GtkWidget      *config;
92         AWeatherLevel2 *level2;      // The Level2 structure for the current volume
93
94         /* Internal data */
95         time_t          time;        // Current timestamp of the level2
96         gchar          *message;     // Error message set while updating
97         guint           time_id;     // "time-changed"     callback ID
98         guint           refresh_id;  // "refresh"          callback ID
99         guint           location_id; // "locaiton-changed" callback ID
100 };
101
102 /* format: http://mesonet.agron.iastate.edu/data/nexrd2/raw/KABR/KABR_20090510_0323 */
103 void _site_update_loading(gchar *file, goffset cur,
104                 goffset total, gpointer _site)
105 {
106         RadarSite *site = _site;
107         GtkWidget *progress_bar = gtk_bin_get_child(GTK_BIN(site->config));
108         double percent = (double)cur/total;
109         gtk_progress_bar_set_fraction(GTK_PROGRESS_BAR(progress_bar), MIN(percent, 1.0));
110         gchar *msg = g_strdup_printf("Loading... %5.1f%% (%.2f/%.2f MB)",
111                         percent*100, (double)cur/1000000, (double)total/1000000);
112         gtk_progress_bar_set_text(GTK_PROGRESS_BAR(progress_bar), msg);
113         g_free(msg);
114 }
115 gboolean _site_update_end(gpointer _site)
116 {
117         RadarSite *site = _site;
118         if (site->message) {
119                 g_warning("RadarSite: update_end - %s", site->message);
120                 _gtk_bin_set_child(GTK_BIN(site->config),
121                                 gtk_label_new(site->message));
122         } else {
123                 _gtk_bin_set_child(GTK_BIN(site->config),
124                                 aweather_level2_get_config(site->level2));
125         }
126         site->status = STATUS_LOADED;
127         return FALSE;
128 }
129 gpointer _site_update_thread(gpointer _site)
130 {
131         RadarSite *site = _site;
132         g_debug("RadarSite: update_thread - %s", site->city->code);
133         site->message = NULL;
134
135         gboolean offline = grits_viewer_get_offline(site->viewer);
136         gchar *nexrad_url = grits_prefs_get_string(site->prefs,
137                         "aweather/nexrad_url", NULL);
138
139         /* Find nearest volume (temporally) */
140         g_debug("RadarSite: update_thread - find nearest - %s", site->city->code);
141         gchar *dir_list = g_strconcat(nexrad_url, "/", site->city->code,
142                         "/", "dir.list", NULL);
143         GList *files = grits_http_available(site->http,
144                         "^\\w{4}_\\d{8}_\\d{4}$", site->city->code,
145                         "\\d+ (.*)", (offline ? NULL : dir_list));
146         g_free(dir_list);
147         gchar *nearest = _find_nearest(site->time, files, 5, "%Y%m%d_%H%M");
148         g_list_foreach(files, (GFunc)g_free, NULL);
149         g_list_free(files);
150         if (!nearest) {
151                 site->message = "No suitable files found";
152                 goto out;
153         }
154
155         /* Fetch new volume */
156         g_debug("RadarSite: update_thread - fetch");
157         gchar *local = g_strconcat(site->city->code, "/", nearest, NULL);
158         gchar *uri   = g_strconcat(nexrad_url, "/", local,   NULL);
159         gchar *file  = grits_http_fetch(site->http, uri, local,
160                         offline ? GRITS_LOCAL : GRITS_UPDATE,
161                         _site_update_loading, site);
162         g_free(nexrad_url);
163         g_free(nearest);
164         g_free(local);
165         g_free(uri);
166         if (!file) {
167                 site->message = "Fetch failed";
168                 goto out;
169         }
170
171         /* Load and add new volume */
172         g_debug("RadarSite: update_thread - load - %s", site->city->code);
173         site->level2 = aweather_level2_new_from_file(
174                         file, site->city->code, colormaps);
175         g_free(file);
176         if (!site->level2) {
177                 site->message = "Load failed";
178                 goto out;
179         }
180         grits_object_hide(GRITS_OBJECT(site->level2), site->hidden);
181         grits_viewer_add(site->viewer, GRITS_OBJECT(site->level2),
182                         GRITS_LEVEL_WORLD, TRUE);
183
184 out:
185         g_idle_add(_site_update_end, site);
186         return NULL;
187 }
188 void _site_update(RadarSite *site)
189 {
190         if (site->status == STATUS_LOADING)
191                 return;
192         site->status = STATUS_LOADING;
193
194         site->time = grits_viewer_get_time(site->viewer);
195         g_debug("RadarSite: update %s - %d",
196                         site->city->code, (gint)site->time);
197
198         /* Add a progress bar */
199         GtkWidget *progress = gtk_progress_bar_new();
200         gtk_progress_bar_set_text(GTK_PROGRESS_BAR(progress), "Loading...");
201         _gtk_bin_set_child(GTK_BIN(site->config), progress);
202
203         /* Remove old volume */
204         g_debug("RadarSite: update - remove - %s", site->city->code);
205         if (site->level2) {
206                 grits_viewer_remove(site->viewer, site->level2);
207                 site->level2 = NULL;
208         }
209
210         /* Fork loading right away so updating the
211          * list of times doesn't take too long */
212         g_thread_create(_site_update_thread, site, FALSE, NULL);
213 }
214
215 /* RadarSite methods */
216 void radar_site_unload(RadarSite *site)
217 {
218         if (site->status != STATUS_LOADED)
219                 return; // Abort if it's still loading
220
221         g_debug("RadarSite: unload %s", site->city->code);
222
223         if (site->time_id)
224                 g_signal_handler_disconnect(site->viewer, site->time_id);
225         if (site->refresh_id)
226                 g_signal_handler_disconnect(site->viewer, site->refresh_id);
227
228         /* Remove tab */
229         if (site->config)
230                 gtk_widget_destroy(site->config);
231
232         /* Remove radar */
233         if (site->level2) {
234                 grits_viewer_remove(site->viewer, site->level2);
235                 site->level2 = NULL;
236         }
237
238         site->status = STATUS_UNLOADED;
239 }
240
241 void radar_site_load(RadarSite *site)
242 {
243         g_debug("RadarSite: load %s", site->city->code);
244
245         /* Add tab page */
246         site->config = gtk_alignment_new(0, 0, 1, 1);
247         g_object_set_data(G_OBJECT(site->config), "site", site);
248         gtk_notebook_append_page(GTK_NOTEBOOK(site->pconfig), site->config,
249                         gtk_label_new(site->city->name));
250         gtk_widget_show_all(site->config);
251
252         /* Set up radar loading */
253         site->time_id = g_signal_connect_swapped(site->viewer, "time-changed",
254                         G_CALLBACK(_site_update), site);
255         site->refresh_id = g_signal_connect_swapped(site->viewer, "refresh",
256                         G_CALLBACK(_site_update), site);
257         _site_update(site);
258 }
259
260 void _site_on_location_changed(GritsViewer *viewer,
261                 gdouble lat, gdouble lon, gdouble elev,
262                 gpointer _site)
263 {
264         static gdouble min_dist = EARTH_R / 30;
265         RadarSite *site = _site;
266
267         /* Calculate distance, could cache xyz values */
268         gdouble eye_xyz[3], site_xyz[3];
269         lle2xyz(lat, lon, elev, &eye_xyz[0], &eye_xyz[1], &eye_xyz[2]);
270         lle2xyz(site->city->pos.lat, site->city->pos.lon, site->city->pos.elev,
271                         &site_xyz[0], &site_xyz[1], &site_xyz[2]);
272         gdouble dist = distd(site_xyz, eye_xyz);
273
274         /* Load or unload the site if necessasairy */
275         if (dist <= min_dist && dist < elev*1.25 && site->status == STATUS_UNLOADED)
276                 radar_site_load(site);
277         else if (dist > 2*min_dist &&  site->status != STATUS_UNLOADED)
278                 radar_site_unload(site);
279 }
280
281 gboolean _site_add_marker(gpointer _site)
282 {
283         RadarSite *site = _site;
284         site->marker = grits_marker_new(site->city->name);
285         GRITS_OBJECT(site->marker)->center = site->city->pos;
286         GRITS_OBJECT(site->marker)->lod    = EARTH_R*site->city->lod;
287         grits_viewer_add(site->viewer, GRITS_OBJECT(site->marker),
288                         GRITS_LEVEL_OVERLAY, FALSE);
289         return FALSE;
290 }
291 RadarSite *radar_site_new(city_t *city, GtkWidget *pconfig,
292                 GritsViewer *viewer, GritsPrefs *prefs, GritsHttp *http)
293 {
294         RadarSite *site = g_new0(RadarSite, 1);
295         site->viewer  = g_object_ref(viewer);
296         site->prefs   = g_object_ref(prefs);
297         //site->http    = http;
298         site->http    = grits_http_new(G_DIR_SEPARATOR_S
299                         "nexrad" G_DIR_SEPARATOR_S
300                         "level2" G_DIR_SEPARATOR_S);
301         site->city    = city;
302         site->pconfig = pconfig;
303
304         /* Set initial location */
305         gdouble lat, lon, elev;
306         grits_viewer_get_location(viewer, &lat, &lon, &elev);
307         _site_on_location_changed(viewer, lat, lon, elev, site);
308
309         /* Add marker */
310         g_idle_add_full(G_PRIORITY_LOW, _site_add_marker, site, NULL);
311
312         /* Connect signals */
313         site->location_id  = g_signal_connect(viewer, "location-changed",
314                         G_CALLBACK(_site_on_location_changed), site);
315         return site;
316 }
317
318 void radar_site_free(RadarSite *site)
319 {
320         radar_site_unload(site);
321         grits_viewer_remove(site->viewer, site->marker);
322         if (site->location_id)
323                 g_signal_handler_disconnect(site->viewer, site->location_id);
324         grits_http_free(site->http);
325         g_object_unref(site->viewer);
326         g_object_unref(site->prefs);
327         g_free(site);
328 }
329
330
331 /**************
332  * RadarConus *
333  **************/
334 #define CONUS_NORTH       50.406626367301044
335 #define CONUS_WEST       -127.620375523875420
336 #define CONUS_WIDTH       3400.0
337 #define CONUS_HEIGHT      1600.0
338 #define CONUS_DEG_PER_PX  0.017971305190311
339
340 struct _RadarConus {
341         GritsViewer *viewer;
342         GritsHttp   *http;
343         GtkWidget   *config;
344         time_t       time;
345         const gchar *message;
346         GStaticMutex loading;
347
348         gchar       *path;
349         GritsTile   *tile[2];
350
351         guint        time_id;     // "time-changed"     callback ID
352         guint        refresh_id;  // "refresh"          callback ID
353 };
354
355 void _conus_update_loading(gchar *file, goffset cur,
356                 goffset total, gpointer _conus)
357 {
358         RadarConus *conus = _conus;
359         GtkWidget *progress_bar = gtk_bin_get_child(GTK_BIN(conus->config));
360         double percent = (double)cur/total;
361         gtk_progress_bar_set_fraction(GTK_PROGRESS_BAR(progress_bar), MIN(percent, 1.0));
362         gchar *msg = g_strdup_printf("Loading... %5.1f%% (%.2f/%.2f MB)",
363                         percent*100, (double)cur/1000000, (double)total/1000000);
364         gtk_progress_bar_set_text(GTK_PROGRESS_BAR(progress_bar), msg);
365         g_free(msg);
366 }
367
368 /* Copy images to graphics memory */
369 static void _conus_update_end_copy(GritsTile *tile, guchar *pixels)
370 {
371         if (!tile->data) {
372                 tile->data = g_new0(guint, 1);
373                 glGenTextures(1, tile->data);
374         }
375
376         guint *tex = tile->data;
377         glBindTexture(GL_TEXTURE_2D, *tex);
378
379         glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
380         glPixelStorei(GL_PACK_ALIGNMENT, 1);
381         glTexImage2D(GL_TEXTURE_2D, 0, 4, 2048, 2048, 0,
382                         GL_RGBA, GL_UNSIGNED_BYTE, NULL);
383         glTexSubImage2D(GL_TEXTURE_2D, 0, 1,1, CONUS_WIDTH/2,CONUS_HEIGHT,
384                         GL_RGBA, GL_UNSIGNED_BYTE, pixels);
385         tile->coords.n = 1.0/(CONUS_WIDTH/2);
386         tile->coords.w = 1.0/ CONUS_HEIGHT;
387         tile->coords.s = tile->coords.n +  CONUS_HEIGHT   / 2048.0;
388         tile->coords.e = tile->coords.w + (CONUS_WIDTH/2) / 2048.0;
389         glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
390         glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
391         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
392         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
393         glFlush();
394 }
395
396 /* Split the pixbuf into east and west halves (with 2K sides)
397  * Also map the pixbuf's alpha values */
398 static void _conus_update_end_split(guchar *pixels, guchar *west, guchar *east,
399                 gint width, gint height, gint pxsize)
400 {
401         g_debug("Conus: update_end_split");
402         guchar *out[] = {west,east};
403         const guchar alphamap[][4] = {
404                 {0x04, 0xe9, 0xe7, 0x30},
405                 {0x01, 0x9f, 0xf4, 0x60},
406                 {0x03, 0x00, 0xf4, 0x90},
407         };
408         for (int y = 0; y < height; y++)
409         for (int x = 0; x < width;  x++) {
410                 gint subx = x % (width/2);
411                 gint idx  = x / (width/2);
412                 guchar *src = &pixels[(y*width+x)*pxsize];
413                 guchar *dst = &out[idx][(y*(width/2)+subx)*4];
414                 if (src[0] > 0xe0 &&
415                     src[1] > 0xe0 &&
416                     src[2] > 0xe0) {
417                         dst[3] = 0x00;
418                 } else {
419                         dst[0] = src[0];
420                         dst[1] = src[1];
421                         dst[2] = src[2];
422                         dst[3] = 0xff;
423                         for (int j = 0; j < G_N_ELEMENTS(alphamap); j++)
424                                 if (src[0] == alphamap[j][0] &&
425                                     src[1] == alphamap[j][1] &&
426                                     src[2] == alphamap[j][2])
427                                         dst[3] = alphamap[j][3];
428                 }
429         }
430 }
431
432 gboolean _conus_update_end(gpointer _conus)
433 {
434         RadarConus *conus = _conus;
435         g_debug("Conus: update_end");
436
437         /* Check error status */
438         if (conus->message) {
439                 g_warning("Conus: update_end - %s", conus->message);
440                 _gtk_bin_set_child(GTK_BIN(conus->config), gtk_label_new(conus->message));
441                 goto out;
442         }
443
444         /* Load and pixbuf */
445         GError *error = NULL;
446         GdkPixbuf *pixbuf = gdk_pixbuf_new_from_file(conus->path, &error);
447         if (!pixbuf || error) {
448                 g_warning("Conus: update_end - error loading pixbuf: %s", conus->path);
449                 _gtk_bin_set_child(GTK_BIN(conus->config), gtk_label_new("Error loading pixbuf"));
450                 g_remove(conus->path);
451                 goto out;
452         }
453
454         /* Split pixels into east/west parts */
455         guchar *pixels = gdk_pixbuf_get_pixels(pixbuf);
456         gint    width  = gdk_pixbuf_get_width(pixbuf);
457         gint    height = gdk_pixbuf_get_height(pixbuf);
458         gint    pxsize = gdk_pixbuf_get_has_alpha(pixbuf) ? 4 : 3;
459         guchar *pixels_west = g_malloc(4*(width/2)*height);
460         guchar *pixels_east = g_malloc(4*(width/2)*height);
461         _conus_update_end_split(pixels, pixels_west, pixels_east,
462                         width, height, pxsize);
463         g_object_unref(pixbuf);
464
465         /* Copy pixels to graphics memory */
466         _conus_update_end_copy(conus->tile[0], pixels_west);
467         _conus_update_end_copy(conus->tile[1], pixels_east);
468         g_free(pixels_west);
469         g_free(pixels_east);
470
471         /* Update GUI */
472         gchar *label = g_path_get_basename(conus->path);
473         _gtk_bin_set_child(GTK_BIN(conus->config), gtk_label_new(label));
474         gtk_widget_queue_draw(GTK_WIDGET(conus->viewer));
475         g_free(label);
476
477 out:
478         g_free(conus->path);
479         g_static_mutex_unlock(&conus->loading);
480         return FALSE;
481 }
482
483 gpointer _conus_update_thread(gpointer _conus)
484 {
485         RadarConus *conus = _conus;
486         conus->message = NULL;
487
488         /* Find nearest */
489         g_debug("Conus: update_thread - nearest");
490         gboolean offline = grits_viewer_get_offline(conus->viewer);
491         gchar *conus_url = "http://radar.weather.gov/Conus/RadarImg/";
492         gchar *nearest;
493         if (time(NULL) - conus->time < 60*60*5 && !offline) {
494                 /* radar.weather.gov is full of lies.
495                  * the index pages get cached and out of date */
496                 struct tm tm;
497                 gmtime_r(&conus->time, &tm);
498                 time_t onthe8 = conus->time - 60*((tm.tm_min+1)%10+1);
499                 gmtime_r(&onthe8, &tm);
500                 nearest = g_strdup_printf("Conus_%04d%02d%02d_%02d%02d_N0Ronly.gif",
501                                 tm.tm_year+1900, tm.tm_mon+1, tm.tm_mday,
502                                 tm.tm_hour, tm.tm_min);
503         } else {
504                 GList *files = grits_http_available(conus->http,
505                                 "^Conus_[^\"]*_N0Ronly.gif$", "", NULL, NULL);
506                 nearest = _find_nearest(conus->time, files, 6, "%Y%m%d_%H%M");
507                 g_list_foreach(files, (GFunc)g_free, NULL);
508                 g_list_free(files);
509                 if (!nearest) {
510                         conus->message = "No suitable files";
511                         goto out;
512                 }
513         }
514
515         /* Fetch the image */
516         g_debug("Conus: update_thread - fetch");
517         gchar *uri  = g_strconcat(conus_url, nearest, NULL);
518         conus->path = grits_http_fetch(conus->http, uri, nearest,
519                         offline ? GRITS_LOCAL : GRITS_ONCE,
520                         _conus_update_loading, conus);
521         g_free(nearest);
522         g_free(uri);
523         if (!conus->path) {
524                 conus->message = "Fetch failed";
525                 goto out;
526         }
527
528 out:
529         g_debug("Conus: update_thread - done");
530         g_idle_add(_conus_update_end, conus);
531         return NULL;
532 }
533
534 void _conus_update(RadarConus *conus)
535 {
536         if (!g_static_mutex_trylock(&conus->loading))
537                 return;
538         conus->time = grits_viewer_get_time(conus->viewer);
539         g_debug("Conus: update - %d",
540                         (gint)conus->time);
541
542         /* Add a progress bar */
543         GtkWidget *progress = gtk_progress_bar_new();
544         gtk_progress_bar_set_text(GTK_PROGRESS_BAR(progress), "Loading...");
545         _gtk_bin_set_child(GTK_BIN(conus->config), progress);
546
547         g_thread_create(_conus_update_thread, conus, FALSE, NULL);
548 }
549
550 RadarConus *radar_conus_new(GtkWidget *pconfig,
551                 GritsViewer *viewer, GritsHttp *http)
552 {
553         RadarConus *conus = g_new0(RadarConus, 1);
554         conus->viewer  = g_object_ref(viewer);
555         conus->http    = http;
556         conus->config  = gtk_alignment_new(0, 0, 1, 1);
557         g_static_mutex_init(&conus->loading);
558
559         gdouble south =  CONUS_NORTH - CONUS_DEG_PER_PX*CONUS_HEIGHT;
560         gdouble east  =  CONUS_WEST  + CONUS_DEG_PER_PX*CONUS_WIDTH;
561         gdouble mid   =  CONUS_WEST  + CONUS_DEG_PER_PX*CONUS_WIDTH/2;
562         conus->tile[0] = grits_tile_new(NULL, CONUS_NORTH, south, mid, CONUS_WEST);
563         conus->tile[1] = grits_tile_new(NULL, CONUS_NORTH, south, east, mid);
564         conus->tile[0]->zindex = 2;
565         conus->tile[1]->zindex = 1;
566         grits_viewer_add(viewer, GRITS_OBJECT(conus->tile[0]), GRITS_LEVEL_WORLD, TRUE);
567         grits_viewer_add(viewer, GRITS_OBJECT(conus->tile[1]), GRITS_LEVEL_WORLD, TRUE);
568
569         conus->time_id = g_signal_connect_swapped(viewer, "time-changed",
570                         G_CALLBACK(_conus_update), conus);
571         conus->refresh_id = g_signal_connect_swapped(viewer, "refresh",
572                         G_CALLBACK(_conus_update), conus);
573
574         g_object_set_data(G_OBJECT(conus->config), "conus", conus);
575         gtk_notebook_append_page(GTK_NOTEBOOK(pconfig), conus->config,
576                         gtk_label_new("Conus"));
577
578         _conus_update(conus);
579         return conus;
580 }
581
582 void radar_conus_free(RadarConus *conus)
583 {
584         g_signal_handler_disconnect(conus->viewer, conus->time_id);
585         g_signal_handler_disconnect(conus->viewer, conus->refresh_id);
586
587         for (int i = 0; i < 2; i++) {
588                 GritsTile *tile = conus->tile[i];
589                 if (tile->data) {
590                         glDeleteTextures(1, tile->data);
591                         g_free(tile->data);
592                 }
593                 grits_viewer_remove(conus->viewer, tile);
594         }
595
596         g_object_unref(conus->viewer);
597         g_free(conus);
598 }
599
600
601 /********************
602  * GritsPluginRadar *
603  ********************/
604 static void _draw_hud(GritsCallback *callback, GritsOpenGL *opengl, gpointer _self)
605 {
606         g_debug("GritsPluginRadar: _draw_hud");
607         /* Setup OpenGL */
608         glMatrixMode(GL_MODELVIEW ); glLoadIdentity();
609         glMatrixMode(GL_PROJECTION); glLoadIdentity();
610         glDisable(GL_TEXTURE_2D);
611         glDisable(GL_ALPHA_TEST);
612         glDisable(GL_CULL_FACE);
613         glDisable(GL_LIGHTING);
614         glEnable(GL_COLOR_MATERIAL);
615
616         GHashTableIter iter;
617         gpointer name, _site;
618         GritsPluginRadar *self = GRITS_PLUGIN_RADAR(_self);
619         g_hash_table_iter_init(&iter, self->sites);
620         while (g_hash_table_iter_next(&iter, &name, &_site)) {
621                 /* Pick correct colormaps */
622                 RadarSite *site = _site;
623                 if (site->hidden || !site->level2)
624                         continue;
625                 AWeatherColormap *colormap = site->level2->sweep_colors;
626
627                 /* Print the color table */
628                 glBegin(GL_QUADS);
629                 int len = colormap->len;
630                 for (int i = 0; i < len; i++) {
631                         glColor4ubv(colormap->data[i]);
632                         glVertex3f(-1.0, (float)((i  ) - len/2)/(len/2), 0.0); // bot left
633                         glVertex3f(-1.0, (float)((i+1) - len/2)/(len/2), 0.0); // top left
634                         glVertex3f(-0.9, (float)((i+1) - len/2)/(len/2), 0.0); // top right
635                         glVertex3f(-0.9, (float)((i  ) - len/2)/(len/2), 0.0); // bot right
636                 }
637                 glEnd();
638         }
639 }
640
641 static void _load_colormap(gchar *filename, AWeatherColormap *cm)
642 {
643         g_debug("GritsPluginRadar: _load_colormap - %s", filename);
644         FILE *file = fopen(filename, "r");
645         if (!file)
646                 g_error("GritsPluginRadar: open failed");
647         guint8 color[4];
648         GArray *array = g_array_sized_new(FALSE, TRUE, sizeof(color), 256);
649         if (!fgets(cm->name, sizeof(cm->name), file)) goto out;
650         if (!fscanf(file, "%f\n", &cm->scale))        goto out;
651         if (!fscanf(file, "%f\n", &cm->shift))        goto out;
652         int r, g, b, a;
653         while (fscanf(file, "%d %d %d %d\n", &r, &g, &b, &a) == 4) {
654                 color[0] = r;
655                 color[1] = g;
656                 color[2] = b;
657                 color[3] = a;
658                 g_array_append_val(array, color);
659         }
660         cm->len  = (gint )array->len;
661         cm->data = (void*)array->data;
662 out:
663         g_array_free(array, FALSE);
664         fclose(file);
665 }
666
667 static void _update_hidden(GtkNotebook *notebook,
668                 GtkNotebookPage *page, guint page_num, gpointer viewer)
669 {
670         g_debug("GritsPluginRadar: _update_hidden - 0..%d = %d",
671                         gtk_notebook_get_n_pages(notebook), page_num);
672
673         for (gint i = 0; i < gtk_notebook_get_n_pages(notebook); i++) {
674                 gboolean is_hidden = (i != page_num);
675                 GtkWidget  *config = gtk_notebook_get_nth_page(notebook, i);
676                 RadarConus *conus  = g_object_get_data(G_OBJECT(config), "conus");
677                 RadarSite  *site   = g_object_get_data(G_OBJECT(config), "site");
678
679                 /* Conus */
680                 if (conus) {
681                         grits_object_hide(GRITS_OBJECT(conus->tile[0]), is_hidden);
682                         grits_object_hide(GRITS_OBJECT(conus->tile[1]), is_hidden);
683                 } else if (site) {
684                         site->hidden = is_hidden;
685                         if (site->level2)
686                                 grits_object_hide(GRITS_OBJECT(site->level2), is_hidden);
687                 } else {
688                         g_warning("GritsPluginRadar: _update_hidden - no site or counus found");
689                 }
690         }
691         gtk_widget_queue_draw(GTK_WIDGET(viewer));
692 }
693
694 /* Methods */
695 GritsPluginRadar *grits_plugin_radar_new(GritsViewer *viewer, GritsPrefs *prefs)
696 {
697         /* TODO: move to constructor if possible */
698         g_debug("GritsPluginRadar: new");
699         GritsPluginRadar *self = g_object_new(GRITS_TYPE_PLUGIN_RADAR, NULL);
700         self->viewer = viewer;
701         self->prefs  = prefs;
702
703         /* Setup page switching */
704         self->tab_id = g_signal_connect(self->config, "switch-page",
705                         G_CALLBACK(_update_hidden), viewer);
706
707         /* Load HUD */
708         self->hud = grits_callback_new(_draw_hud, self);
709         grits_viewer_add(viewer, GRITS_OBJECT(self->hud), GRITS_LEVEL_HUD, FALSE);
710
711         /* Load Conus */
712         self->conus = radar_conus_new(self->config, self->viewer, self->conus_http);
713
714         /* Load radar sites */
715         for (city_t *city = cities; city->type; city++) {
716                 if (city->type != LOCATION_CITY)
717                         continue;
718                 RadarSite *site = radar_site_new(city, self->config,
719                                 self->viewer, self->prefs, self->sites_http);
720                 g_hash_table_insert(self->sites, city->code, site);
721         }
722
723         return self;
724 }
725
726 static GtkWidget *grits_plugin_radar_get_config(GritsPlugin *_self)
727 {
728         GritsPluginRadar *self = GRITS_PLUGIN_RADAR(_self);
729         return self->config;
730 }
731
732 /* GObject code */
733 static void grits_plugin_radar_plugin_init(GritsPluginInterface *iface);
734 G_DEFINE_TYPE_WITH_CODE(GritsPluginRadar, grits_plugin_radar, G_TYPE_OBJECT,
735                 G_IMPLEMENT_INTERFACE(GRITS_TYPE_PLUGIN,
736                         grits_plugin_radar_plugin_init));
737 static void grits_plugin_radar_plugin_init(GritsPluginInterface *iface)
738 {
739         g_debug("GritsPluginRadar: plugin_init");
740         /* Add methods to the interface */
741         iface->get_config = grits_plugin_radar_get_config;
742 }
743 static void grits_plugin_radar_init(GritsPluginRadar *self)
744 {
745         g_debug("GritsPluginRadar: class_init");
746         /* Set defaults */
747         self->sites_http = grits_http_new(G_DIR_SEPARATOR_S
748                         "nexrad" G_DIR_SEPARATOR_S
749                         "level2" G_DIR_SEPARATOR_S);
750         self->conus_http = grits_http_new(G_DIR_SEPARATOR_S
751                         "nexrad" G_DIR_SEPARATOR_S
752                         "conus"  G_DIR_SEPARATOR_S);
753         self->sites      = g_hash_table_new_full(g_str_hash, g_str_equal,
754                                 NULL, (GDestroyNotify)radar_site_free);
755         self->config     = gtk_notebook_new();
756
757         /* Load colormaps */
758         for (int i = 0; colormaps[i].file; i++) {
759                 gchar *file = g_build_filename(PKGDATADIR,
760                                 "colors", colormaps[i].file, NULL);
761                 _load_colormap(file, &colormaps[i]);
762                 g_free(file);
763         }
764
765         /* Need to position on the top because of Win32 bug */
766         gtk_notebook_set_tab_pos(GTK_NOTEBOOK(self->config), GTK_POS_LEFT);
767 }
768 static void grits_plugin_radar_dispose(GObject *gobject)
769 {
770         g_debug("GritsPluginRadar: dispose");
771         GritsPluginRadar *self = GRITS_PLUGIN_RADAR(gobject);
772         g_signal_handler_disconnect(self->config, self->tab_id);
773         grits_viewer_remove(self->viewer, self->hud);
774         radar_conus_free(self->conus);
775         /* Drop references */
776         G_OBJECT_CLASS(grits_plugin_radar_parent_class)->dispose(gobject);
777 }
778 static void grits_plugin_radar_finalize(GObject *gobject)
779 {
780         g_debug("GritsPluginRadar: finalize");
781         GritsPluginRadar *self = GRITS_PLUGIN_RADAR(gobject);
782         /* Free data */
783         grits_http_free(self->conus_http);
784         grits_http_free(self->sites_http);
785         g_hash_table_destroy(self->sites);
786         gtk_widget_destroy(self->config);
787         G_OBJECT_CLASS(grits_plugin_radar_parent_class)->finalize(gobject);
788
789 }
790 static void grits_plugin_radar_class_init(GritsPluginRadarClass *klass)
791 {
792         g_debug("GritsPluginRadar: class_init");
793         GObjectClass *gobject_class = (GObjectClass*)klass;
794         gobject_class->dispose  = grits_plugin_radar_dispose;
795         gobject_class->finalize = grits_plugin_radar_finalize;
796 }