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