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