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