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