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