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