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