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