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