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