]> Pileus Git - aweather/blob - src/plugins/alert.c
73cb56451cbab60f55242a6c5903d42b60ef7a8b
[aweather] / src / plugins / alert.c
1 /*
2  * Copyright (C) 2010-2011 Andy Spencer <andy753421@gmail.com>
3  * 
4  * This program is free software: you can redistribute it and/or modify
5  * it under the terms of the GNU General Public License as published by
6  * the Free Software Foundation, either version 3 of the License, or
7  * (at your option) any later version.
8  * 
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  * 
14  * You should have received a copy of the GNU General Public License
15  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
16  */
17
18
19 #include <time.h>
20 #include <grits.h>
21 #include <stdio.h>
22 #include <string.h>
23
24 #include "alert.h"
25 #include "alert-info.h"
26
27 #include "compat.h"
28
29 #define MSG_INDEX "http://alerts.weather.gov/cap/us.php?x=0"
30 #define CONFIG_HEIGHT 3
31
32 /* Format for single cap alert:
33  *   "http://alerts.weather.gov/cap/wwacapget.php?x="
34  *   "AK20111012000500CoastalFloodWarning20111012151500"
35  *   "AKAFGCFWAFG.6258a84eb1e8c34cd888057248224d10" */
36
37 /************
38  * AlertMsg *
39  ************/
40 /* AlertMsg data types */
41 typedef struct {
42         char sep0;
43         char class [1 ]; char sep1;
44         char action[3 ]; char sep2;
45         char office[4 ]; char sep3;
46         char phenom[2 ]; char sep4;
47         char signif[1 ]; char sep5;
48         char event [4 ]; char sep6;
49         char begin [12]; char sep7;
50         char end   [12]; char sep8;
51 } AlertVtec;
52
53 typedef struct {
54         /* Basic info (from alert index) */
55         char *title;   // Winter Weather Advisory issued December 19 at 8:51PM
56         char *link;    // http://www.weather.gov/alerts-beta/wwacapget.php?x=AK20101219205100AFGWinterWeatherAdvisoryAFG20101220030000AK
57         char *summary; // ...WINTER WEATHER ADVISORY REMAINS IN EFFECT UNTIL 6
58         struct {
59                 time_t     effective; // 2010-12-19T20:51:00-09:00
60                 time_t     expires;   // 2010-12-20T03:00:00-09:00
61                 char      *status;    // Actual
62                 char      *urgency;   // Expected
63                 char      *severity;  // Minor
64                 char      *certainty; // Likely
65                 char      *area_desc; // Northeastern Brooks Range; Northwestern Brooks Range
66                 char      *fips6;     // 006015 006023 006045 006105
67                 AlertVtec *vtec;      // /X.CON.PAFG.WW.Y.0064.000000T0000Z-101220T0300Z/
68         } cap;
69
70         /* Advanced info (from CAP file) */
71         char *description;
72         char *instruction;
73         char *polygon;
74
75         /* Internal state */
76         AlertInfo *info;         // Link to info structure for this alert
77         GritsPoly *county_based; // Polygon for county-based warning
78         GritsPoly *storm_based;  // Polygon for storm-based warning
79 } AlertMsg;
80
81 /* AlertMsg parsing */
82 typedef struct {
83         time_t    updated;
84         AlertMsg *msg;
85         GList    *msgs;
86         gchar    *text;
87         gchar    *value_name;
88 } ParseData;
89 time_t msg_parse_time(gchar *iso8601)
90 {
91         GTimeVal tv = {};
92         g_time_val_from_iso8601(iso8601, &tv);
93         return tv.tv_sec;
94 }
95 AlertVtec *msg_parse_vtec(char *buf)
96 {
97         AlertVtec *vtec = g_new0(AlertVtec, 1);
98         strncpy((char*)vtec, buf, sizeof(AlertVtec));
99         vtec->sep0 = vtec->sep1 = vtec->sep2 = '\0';
100         vtec->sep3 = vtec->sep4 = vtec->sep5 = '\0';
101         vtec->sep6 = vtec->sep7 = vtec->sep8 = '\0';
102         return vtec;
103 }
104 void msg_parse_text(GMarkupParseContext *context, const gchar *text,
105                 gsize len, gpointer user_data, GError **error)
106 {
107         //g_debug("text %s", text);
108         ParseData *data = user_data;
109         if (data->text)
110                 g_free(data->text);
111         data->text = g_strndup(text, len);
112 }
113 void msg_parse_index_start(GMarkupParseContext *context, const gchar *name,
114                 const gchar **keys, const gchar **vals,
115                 gpointer user_data, GError **error)
116 {
117         //g_debug("start %s", name);
118         ParseData *data = user_data;
119         if (g_str_equal(name, "entry"))
120                 data->msg  = g_new0(AlertMsg, 1);
121 }
122 void msg_parse_index_end(GMarkupParseContext *context, const gchar *name,
123                 gpointer user_data, GError **error)
124 {
125         //g_debug("end %s", name);
126         ParseData *data = user_data;
127         AlertMsg  *msg  = data->msg;
128         char      *text = data->text;
129
130         if (g_str_equal(name, "updated") && text && !data->updated)
131                 data->updated = msg_parse_time(text);
132
133         if (g_str_equal(name, "entry"))
134                 data->msgs = g_list_prepend(data->msgs, data->msg);
135
136         if (!text || !msg) return;
137         else if (g_str_equal(name, "title"))         msg->title         = g_strdup(text);
138         else if (g_str_equal(name, "id"))            msg->link          = g_strdup(text); // hack
139         else if (g_str_equal(name, "summary"))       msg->summary       = g_strdup(text);
140         else if (g_str_equal(name, "cap:effective")) msg->cap.effective = msg_parse_time(text);
141         else if (g_str_equal(name, "cap:expires"))   msg->cap.expires   = msg_parse_time(text);
142         else if (g_str_equal(name, "cap:status"))    msg->cap.status    = g_strdup(text);
143         else if (g_str_equal(name, "cap:urgency"))   msg->cap.urgency   = g_strdup(text);
144         else if (g_str_equal(name, "cap:severity"))  msg->cap.severity  = g_strdup(text);
145         else if (g_str_equal(name, "cap:certainty")) msg->cap.certainty = g_strdup(text);
146         else if (g_str_equal(name, "cap:areaDesc"))  msg->cap.area_desc = g_strdup(text);
147
148         if (g_str_equal(name, "title"))
149                 msg->info = alert_info_find(msg->title);
150
151         if (g_str_equal(name, "valueName")) {
152                 if (data->value_name)
153                         g_free(data->value_name);
154                 data->value_name = g_strdup(text);
155         }
156
157         if (g_str_equal(name, "value") && data->value_name) {
158                 if (g_str_equal(data->value_name, "FIPS6")) msg->cap.fips6 = g_strdup(text);
159                 if (g_str_equal(data->value_name, "VTEC"))  msg->cap.vtec  = msg_parse_vtec(text);
160         }
161 }
162 void msg_parse_cap_end(GMarkupParseContext *context, const gchar *name,
163                 gpointer user_data, GError **error)
164 {
165         ParseData *data = user_data;
166         AlertMsg  *msg  = data->msg;
167         char      *text = data->text;
168         if (!text || !msg) return;
169         if      (g_str_equal(name, "description")) msg->description = g_strdup(text);
170         else if (g_str_equal(name, "instruction")) msg->instruction = g_strdup(text);
171         else if (g_str_equal(name, "polygon"))     msg->polygon     = g_strdup(text);
172 }
173
174 /* AlertMsg methods */
175 GList *msg_parse_index(gchar *text, gsize len, time_t *updated)
176 {
177         g_debug("GritsPluginAlert: msg_parse");
178         GMarkupParser parser = {
179                 .start_element = msg_parse_index_start,
180                 .end_element   = msg_parse_index_end,
181                 .text          = msg_parse_text,
182         };
183         ParseData data = {};
184         GMarkupParseContext *context =
185                 g_markup_parse_context_new(&parser, 0, &data, NULL);
186         g_markup_parse_context_parse(context, text, len, NULL);
187         g_markup_parse_context_free(context);
188         if (data.text)
189                 g_free(data.text);
190         if (data.value_name)
191                 g_free(data.value_name);
192         *updated = data.updated;
193         return data.msgs;
194 }
195
196 void msg_parse_cap(AlertMsg *msg, gchar *text, gsize len)
197 {
198         g_debug("GritsPluginAlert: msg_parse_cap");
199         GMarkupParser parser = {
200                 .end_element   = msg_parse_cap_end,
201                 .text          = msg_parse_text,
202         };
203         ParseData data = { .msg = msg };
204         GMarkupParseContext *context =
205                 g_markup_parse_context_new(&parser, 0, &data, NULL);
206         g_markup_parse_context_parse(context, text, len, NULL);
207         g_markup_parse_context_free(context);
208         if (data.text)
209                 g_free(data.text);
210
211         /* Add spaces to description... */
212         static GRegex *regex = NULL;
213         if (regex == NULL)
214                 regex = g_regex_new("\\.\\n", 0, G_REGEX_MATCH_NEWLINE_ANY, NULL);
215         if (msg->description && regex) {
216                 char *old = msg->description;
217                 msg->description = g_regex_replace_literal(
218                                 regex, old, -1, 0, ".\n\n", 0, NULL);
219                 g_free(old);
220         }
221 }
222
223 void msg_free(AlertMsg *msg)
224 {
225         g_free(msg->title);
226         g_free(msg->link);
227         g_free(msg->summary);
228         g_free(msg->cap.status);
229         g_free(msg->cap.urgency);
230         g_free(msg->cap.severity);
231         g_free(msg->cap.certainty);
232         g_free(msg->cap.area_desc);
233         g_free(msg->cap.fips6);
234         g_free(msg->cap.vtec);
235         g_free(msg->description);
236         g_free(msg->instruction);
237         g_free(msg->polygon);
238         g_free(msg);
239 }
240
241 void msg_print(GList *msgs)
242 {
243         g_message("msg_print");
244         for (GList *cur = msgs; cur; cur = cur->next) {
245                 AlertMsg *msg = cur->data;
246                 g_message("alert:");
247                 g_message("     title         = %s",  msg->title        );
248                 g_message("     link          = %s",  msg->link         );
249                 g_message("     summary       = %s",  msg->summary      );
250                 g_message("     cat.effective = %lu", msg->cap.effective);
251                 g_message("     cat.expires   = %lu", msg->cap.expires  );
252                 g_message("     cat.status    = %s",  msg->cap.status   );
253                 g_message("     cat.urgency   = %s",  msg->cap.urgency  );
254                 g_message("     cat.severity  = %s",  msg->cap.severity );
255                 g_message("     cat.certainty = %s",  msg->cap.certainty);
256                 g_message("     cat.area_desc = %s",  msg->cap.area_desc);
257                 g_message("     cat.fips6     = %s",  msg->cap.fips6    );
258                 g_message("     cat.vtec      = %p",  msg->cap.vtec     );
259         }
260 }
261
262 gchar *msg_find_nearest(GritsHttp *http, time_t when, gboolean offline)
263 {
264         GList *files = grits_http_available(http,
265                         "^[0-9]*.xml$", "index", NULL, NULL);
266
267         time_t  this_time    = 0;
268         time_t  nearest_time = offline ? 0 : time(NULL);
269         char   *nearest_file = NULL;
270
271         for (GList *cur = files; cur; cur = cur->next) {
272                 gchar *file = cur->data;
273                 sscanf(file, "%ld", &this_time);
274                 if (ABS(when - this_time) <
275                     ABS(when - nearest_time)) {
276                         nearest_file = file;
277                         nearest_time = this_time;
278                 }
279         }
280
281         if (nearest_file)
282                 return g_strconcat("index/", nearest_file, NULL);
283         else if (!offline)
284                 return g_strdup_printf("index/%ld.xml", time(NULL));
285         else
286                 return NULL;
287 }
288
289 GList *msg_load_index(GritsHttp *http, time_t when, time_t *updated, gboolean offline)
290 {
291         /* Fetch current alerts */
292         gchar *tmp = msg_find_nearest(http, when, offline);
293         if (!tmp)
294                 return NULL;
295         gchar *file = grits_http_fetch(http, MSG_INDEX, tmp, GRITS_ONCE, NULL, NULL);
296         g_free(tmp);
297         if (!file)
298                 return NULL;
299
300         /* Load file */
301         gchar *text; gsize len;
302         g_file_get_contents(file, &text, &len, NULL);
303         GList *msgs = msg_parse_index(text, len, updated);
304         //msg_print(msgs);
305         g_free(file);
306         g_free(text);
307
308         /* Delete unrecognized messages */
309         GList *dead = NULL;
310         for (GList *cur = msgs; cur; cur = cur->next)
311                 if (!((AlertMsg*)cur->data)->info)
312                         dead = g_list_prepend(dead, cur->data);
313         for (GList *cur = dead; cur; cur = cur->next) {
314                 AlertMsg *msg = cur->data;
315                 g_warning("GritsPluginAlert: unknown msg type - %s", msg->title);
316                 msgs = g_list_remove(msgs, msg);
317                 msg_free(msg);
318         }
319         g_list_free(dead);
320
321         return msgs;
322 }
323
324 void msg_load_cap(GritsHttp *http, AlertMsg *msg)
325 {
326         if (msg->description || msg->instruction || msg->polygon)
327                 return;
328         g_debug("GritsPlguinAlert: update_cap");
329
330         /* Download */
331         gchar *id = strrchr(msg->link, '=');
332         if (!id) return; id++;
333         gchar *dir  = g_strdelimit(g_strdup(msg->info->abbr), " ", '_');
334         gchar *tmp  = g_strdup_printf("%s/%s.xml", dir, id);
335         gchar *file = grits_http_fetch(http, msg->link, tmp, GRITS_ONCE, NULL, NULL);
336         g_free(tmp);
337         g_free(dir);
338         if (!file)
339                 return;
340
341         /* Parse */
342         gchar *text; gsize len;
343         g_file_get_contents(file, &text, &len, NULL);
344         msg_parse_cap(msg, text, len);
345         g_free(file);
346         g_free(text);
347 }
348
349
350 /********
351  * FIPS *
352  ********/
353 int fips_compare(int a, int b)
354 {
355         return (a <  b) ? -1 :
356                (a == b) ?  0 : 1;
357 }
358
359 GritsPoly *fips_combine(GList *polys)
360 {
361         /* Create points list */
362         GPtrArray *array = g_ptr_array_new();
363         for (GList *cur = polys; cur; cur = cur->next) {
364                 GritsPoly *poly       = cur->data;
365                 gdouble (**points)[3] = poly->points;
366                 for (int i = 0; points[i]; i++)
367                         g_ptr_array_add(array, points[i]);
368         }
369         g_ptr_array_add(array, NULL);
370         gdouble (**points)[3] = (gpointer)g_ptr_array_free(array, FALSE);
371
372         /* Calculate center */
373         GritsBounds bounds = {-90, 90, -180, 180};
374         for (GList *cur = polys; cur; cur = cur->next) {
375                 GritsObject *poly = cur->data;
376                 gdouble lat = poly->center.lat;
377                 gdouble lon = poly->center.lon;
378                 if (lat > bounds.n) bounds.n = lat;
379                 if (lat < bounds.s) bounds.s = lat;
380                 if (lon > bounds.e) bounds.e = lon;
381                 if (lon < bounds.w) bounds.w = lon;
382         }
383         GritsPoint center = {
384                 .lat = (bounds.n + bounds.s)/2,
385                 .lon = lon_avg(bounds.e, bounds.w),
386         };
387
388         /* Create polygon */
389         GritsPoly *poly = grits_poly_new(points);
390         GRITS_OBJECT(poly)->skip  |= GRITS_SKIP_CENTER;
391         GRITS_OBJECT(poly)->skip  |= GRITS_SKIP_STATE;
392         GRITS_OBJECT(poly)->center = center;
393         g_object_weak_ref(G_OBJECT(poly), (GWeakNotify)g_free, points);
394         return poly;
395 }
396
397 gboolean fips_group_state(gpointer key, gpointer value, gpointer data)
398 {
399         GList  *counties = value;
400         GList **states   = data;
401         GritsPoly *poly  = fips_combine(counties);
402         GRITS_OBJECT(poly)->lod = EARTH_R/10;
403         *states = g_list_prepend(*states, poly);
404         g_list_free(counties);
405         return FALSE;
406 }
407
408 void fips_parse(gchar *text, GTree **_counties, GList **_states)
409 {
410         g_debug("GritsPluginAlert: fips_parse");
411         GTree *counties = g_tree_new((GCompareFunc)fips_compare);
412         GTree *states   = g_tree_new_full((GCompareDataFunc)g_strcmp0,
413                         NULL, g_free, NULL);
414         gchar **lines = g_strsplit(text, "\n", -1);
415         for (gint li = 0; lines[li]; li++) {
416                 /* Split line */
417                 gchar **sparts = g_strsplit(lines[li], "\t", 4);
418                 int     nparts = g_strv_length(sparts);
419                 if (nparts < 4) {
420                         g_strfreev(sparts);
421                         continue;
422                 }
423
424                 /* Create GritsPoly */
425                 GritsPoly *poly = grits_poly_parse(sparts[3], "\t", " ", ",");
426
427                 /* Insert polys into the tree */
428                 glong id = g_ascii_strtoll(sparts[0], NULL, 10);
429                 g_tree_insert(counties, (gpointer)id, poly);
430
431                 /* Insert into states list */
432                 GList *list = g_tree_lookup(states, sparts[2]);
433                 list = g_list_prepend(list, poly);
434                 g_tree_replace(states, g_strdup(sparts[2]), list);
435
436                 g_strfreev(sparts);
437         }
438         g_strfreev(lines);
439
440         /* Group state counties */
441         *_counties = counties;
442         *_states   = NULL;
443         g_tree_foreach(states, (GTraverseFunc)fips_group_state, _states);
444         g_tree_destroy(states);
445 }
446
447 /********************
448  * GritsPluginAlert *
449  ********************/
450 static GtkWidget *_make_msg_details(AlertMsg *msg)
451 {
452
453         GtkWidget *title     = gtk_label_new("");
454         gchar     *title_str = g_markup_printf_escaped("<big><b>%s</b></big>",
455                         msg->title ?: "No title provided");
456         gtk_label_set_use_markup(GTK_LABEL(title), TRUE);
457         gtk_label_set_markup(GTK_LABEL(title), title_str);
458         gtk_label_set_line_wrap(GTK_LABEL(title), TRUE);
459         gtk_misc_set_alignment(GTK_MISC(title), 0, 0);
460         gtk_widget_set_size_request(GTK_WIDGET(title), 500, -1);
461         g_free(title_str);
462
463         GtkWidget     *alert      = gtk_scrolled_window_new(NULL, NULL);
464         GtkWidget     *alert_view = gtk_text_view_new();
465         GtkTextBuffer *alert_buf  = gtk_text_buffer_new(NULL);
466         gchar         *alert_str  = g_markup_printf_escaped("%s\n\n%s",
467                         msg->description ?: "No description provided",
468                         msg->instruction ?: "No instructions provided");
469         PangoFontDescription *alert_font = pango_font_description_from_string(
470                         "monospace");
471         gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(alert),
472                         GTK_POLICY_AUTOMATIC, GTK_POLICY_AUTOMATIC);
473         gtk_scrolled_window_set_shadow_type(GTK_SCROLLED_WINDOW(alert),
474                         GTK_SHADOW_IN);
475         gtk_text_buffer_set_text(alert_buf, alert_str, -1);
476         gtk_text_view_set_buffer(GTK_TEXT_VIEW(alert_view), alert_buf);
477         gtk_widget_modify_font(GTK_WIDGET(alert_view), alert_font);
478         gtk_container_add(GTK_CONTAINER(alert), alert_view);
479         g_free(alert_str);
480
481         GtkWidget *align = gtk_alignment_new(0, 0, 1, 1);
482         GtkWidget *box   = gtk_box_new(GTK_ORIENTATION_VERTICAL, 10);
483         gtk_alignment_set_padding(GTK_ALIGNMENT(align), 10, 10, 10, 10);
484         gtk_container_add(GTK_CONTAINER(align), box);
485         gtk_box_pack_start(GTK_BOX(box), title, FALSE, FALSE, 0);
486         gtk_box_pack_start(GTK_BOX(box), alert, TRUE,  TRUE,  0);
487
488         return align;
489 }
490
491 static GtkWidget *_find_details(GtkNotebook *notebook, AlertMsg *msg)
492 {
493         int pages = gtk_notebook_get_n_pages(GTK_NOTEBOOK(notebook));
494         for (int i = 0; i < pages; i++) {
495                 GtkWidget *page = gtk_notebook_get_nth_page(GTK_NOTEBOOK(notebook), i);
496                 if (msg == g_object_get_data(G_OBJECT(page), "msg"))
497                         return page;
498         }
499         return NULL;
500 }
501
502 static gboolean _show_details(GritsPoly *county, GdkEvent *_, GritsPluginAlert *alert)
503 {
504         /* Add details for this messages */
505         AlertMsg *msg = g_object_get_data(G_OBJECT(county), "msg");
506         msg_load_cap(alert->http, msg);
507
508         GtkWidget *dialog   = alert->details;
509         GtkWidget *content  = gtk_dialog_get_content_area(GTK_DIALOG(dialog));
510         GList     *list     = gtk_container_get_children(GTK_CONTAINER(content));
511         GtkWidget *notebook = list->data;
512         GtkWidget *details  = _find_details(GTK_NOTEBOOK(notebook), msg);
513         g_list_free(list);
514
515         if (details == NULL) {
516                 details          = _make_msg_details(msg);
517                 GtkWidget *label = gtk_label_new(msg->info->abbr);
518                 g_object_set_data(G_OBJECT(details), "msg", msg);
519                 gtk_notebook_append_page(GTK_NOTEBOOK(notebook), details, label);
520         }
521
522         gtk_widget_show_all(dialog);
523         gint num = gtk_notebook_page_num(GTK_NOTEBOOK(notebook), details);
524         gtk_notebook_set_current_page(GTK_NOTEBOOK(notebook), num);
525
526         return FALSE;
527 }
528
529 /* Update counties */
530 static gboolean _alert_leave(GritsPoly *county, GdkEvent *_, GritsPluginAlert *alert)
531 {
532         g_debug("_alert_leave");
533         if (county->width == 3) {
534                 county->color[3]  = 0;
535         } else {
536                 county->border[3] = 0.25;
537                 county->width     = 1;
538         }
539         grits_object_queue_draw(GRITS_OBJECT(county));
540         return FALSE;
541 }
542
543 static gboolean _alert_enter(GritsPoly *county, GdkEvent *_, GritsPluginAlert *alert)
544 {
545         g_debug("_alert_enter");
546         if (county->width == 3) {
547                 county->color[3]  = 0.25;
548         } else {
549                 county->border[3] = 1.0;
550                 county->width     = 2;
551         }
552         grits_object_queue_draw(GRITS_OBJECT(county));
553         return FALSE;
554 }
555
556 /* Update polygons */
557 static void _load_common(GritsPluginAlert *alert, AlertMsg *msg, GritsPoly *poly,
558                 float color, float border, int width, gchar *hidden)
559 {
560         g_object_set_data(G_OBJECT(poly), "msg", msg);
561         poly->color[0]  = poly->border[0] = (float)msg->info->color[0] / 256;
562         poly->color[1]  = poly->border[1] = (float)msg->info->color[1] / 256;
563         poly->color[2]  = poly->border[2] = (float)msg->info->color[2] / 256;
564         poly->color[3]  = color;
565         poly->border[3] = border;
566         poly->width     = width;
567         GRITS_OBJECT(poly)->lod    = 0;
568         GRITS_OBJECT(poly)->hidden = msg->info->hidden ||
569                 grits_prefs_get_boolean(alert->prefs, hidden, NULL);
570         g_signal_connect(poly, "enter",   G_CALLBACK(_alert_enter),  alert);
571         g_signal_connect(poly, "leave",   G_CALLBACK(_alert_leave),  alert);
572         g_signal_connect(poly, "clicked", G_CALLBACK(_show_details), alert);
573 }
574
575 static GritsPoly *_load_storm_based(GritsPluginAlert *alert, AlertMsg *msg)
576 {
577         if (!msg->info->ispoly)
578                 return NULL;
579
580         msg_load_cap(alert->http, msg);
581
582         GritsPoly *poly = grits_poly_parse(msg->polygon, "\t", " ", ",");
583         _load_common(alert, msg, poly, 0, 1, 3, "alert/hide_storm_based");
584         grits_viewer_add(alert->viewer, GRITS_OBJECT(poly), GRITS_LEVEL_WORLD+4, FALSE);
585
586         return poly;
587 }
588
589 static GritsPoly *_load_county_based(GritsPluginAlert *alert, AlertMsg *msg)
590 {
591         /* Locate counties in the path of the storm */
592         gchar **fipses  = g_strsplit(msg->cap.fips6, " ", -1);
593         GList *counties = NULL;
594         for (int i = 0; fipses[i]; i++) {
595                 glong fips = g_ascii_strtoll(fipses[i], NULL, 10);
596                 GritsPoly *county = g_tree_lookup(alert->counties, (gpointer)fips);
597                 if (!county)
598                         continue;
599                 counties = g_list_prepend(counties, county);
600         }
601         g_strfreev(fipses);
602
603         /* No county based warning.. */
604         if (!counties)
605                 return NULL;
606
607         /* Create new county based warning */
608         GritsPoly *poly = fips_combine(counties);
609         _load_common(alert, msg, poly, 0.25, 0.25, 0, "alert/hide_county_based");
610         grits_viewer_add(alert->viewer, GRITS_OBJECT(poly), GRITS_LEVEL_WORLD+1, FALSE);
611
612         g_list_free(counties);
613         return poly;
614 }
615
616 /* Update buttons */
617 static gboolean _show_hide(GtkToggleButton *button, GritsPluginAlert *alert)
618 {
619         g_debug("GritsPluginAlert: _show_hide - alert=%p, config=%p", alert, alert->config);
620
621         /* Check if we've clicked a alert type button */
622         AlertInfo *info = g_object_get_data(G_OBJECT(button), "info");
623         if (info)
624                 info->hidden = !gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(button));
625
626         /* Update county/storm based hiding */
627         GtkWidget *ctoggle = g_object_get_data(G_OBJECT(alert->config), "county_based");
628         GtkWidget *stoggle = g_object_get_data(G_OBJECT(alert->config), "storm_based");
629
630         gboolean   cshow   = gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(ctoggle));
631         gboolean   sshow   = gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(stoggle));
632
633         grits_prefs_set_boolean(alert->prefs, "alert/hide_county_based", !cshow);
634         grits_prefs_set_boolean(alert->prefs, "alert/hide_storm_based",  !sshow);
635
636         /* Show/hide each message */
637         for (GList *cur = alert->msgs; cur; cur = cur->next) {
638                 AlertMsg *msg = cur->data;
639                 gboolean hide = msg->info->hidden;
640                 if (msg->county_based)
641                         GRITS_OBJECT(msg->county_based)->hidden = !cshow || hide;
642                 if (msg->storm_based)
643                         GRITS_OBJECT(msg->storm_based)->hidden  = !sshow || hide;
644         }
645
646         grits_viewer_queue_draw(alert->viewer);
647         return TRUE;
648 }
649
650
651 static GtkWidget *_button_new(AlertInfo *info)
652 {
653         g_debug("GritsPluginAlert: _button_new - %s", info->title);
654         GdkColor black = {0, 0, 0, 0};
655         GdkColor color = {0, info->color[0]<<8, info->color[1]<<8, info->color[2]<<8};
656
657         gchar text[64];
658         g_snprintf(text, sizeof(text), "<b>%.10s</b>", info->abbr);
659
660         GtkWidget *button = gtk_toggle_button_new();
661         GtkWidget *align  = gtk_alignment_new(0.5, 0.5, 1, 1);
662         GtkWidget *cbox   = gtk_event_box_new();
663         GtkWidget *label  = gtk_label_new(text);
664         for (int state = 0; state < GTK_STATE_INSENSITIVE; state++) {
665                 gtk_widget_modify_fg(label, state, &black);
666                 gtk_widget_modify_bg(cbox,  state, &color);
667         } /* Yuck.. */
668         g_object_set_data(G_OBJECT(button), "info", info);
669         gtk_label_set_use_markup(GTK_LABEL(label), TRUE);
670         gtk_alignment_set_padding(GTK_ALIGNMENT(align), 2, 2, 4, 4);
671         gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(button), !info->hidden);
672         gtk_widget_set_tooltip_text(GTK_WIDGET(button), info->title);
673         gtk_container_add(GTK_CONTAINER(cbox), label);
674         gtk_container_add(GTK_CONTAINER(align), cbox);
675         gtk_container_add(GTK_CONTAINER(button), align);
676         return button;
677 }
678
679 static gboolean _update_buttons(GritsPluginAlert *alert)
680 {
681         g_debug("GritsPluginAlert: _update_buttons");
682         GtkWidget *alerts  = g_object_get_data(G_OBJECT(alert->config), "alerts");
683         GtkWidget *updated = g_object_get_data(G_OBJECT(alert->config), "updated");
684
685         /* Determine which buttons to show */
686         for (int i = 0; alert_info[i].title; i++)
687                 alert_info[i].current = FALSE;
688         for (GList *cur = alert->msgs; cur; cur = cur->next) {
689                 AlertMsg *msg = cur->data;
690                 msg->info->current = TRUE;
691         }
692
693         /* Delete old buttons */
694         GList *frames = gtk_container_get_children(GTK_CONTAINER(alerts));
695         for (GList *frame = frames; frame; frame = frame->next) {
696                 GtkWidget *table = gtk_bin_get_child(GTK_BIN(frame->data));
697                 GList *btns = gtk_container_get_children(GTK_CONTAINER(table));
698                 g_list_foreach(btns, (GFunc)gtk_widget_destroy, NULL);
699                 g_list_free(btns);
700         }
701         g_list_free(frames);
702
703         /* Add new buttons */
704         for (int i = 0; alert_info[i].title; i++) {
705                 if (!alert_info[i].current)
706                         continue;
707
708                 GtkWidget *table = g_object_get_data(G_OBJECT(alerts),
709                                 alert_info[i].category);
710                 GList *kids = gtk_container_get_children(GTK_CONTAINER(table));
711                 gint  nkids = g_list_length(kids);
712                 gint x = nkids / CONFIG_HEIGHT;
713                 gint y = nkids % CONFIG_HEIGHT;
714                 g_list_free(kids);
715
716                 GtkWidget *button = _button_new(&alert_info[i]);
717                 gtk_table_attach(GTK_TABLE(table), button, x, x+1, y, y+1,
718                                 GTK_FILL|GTK_EXPAND, GTK_FILL, 0, 0);
719                 g_signal_connect(button, "clicked", G_CALLBACK(_show_hide), alert);
720         }
721
722         /* Set time widget */
723         struct tm *tm = gmtime(&alert->updated);
724         gchar *date_str = g_strdup_printf(" <b><i>%04d-%02d-%02d %02d:%02d</i></b>",
725                         tm->tm_year+1900, tm->tm_mon+1, tm->tm_mday,
726                         tm->tm_hour,      tm->tm_min);
727         gtk_label_set_markup(GTK_LABEL(updated), date_str);
728         g_free(date_str);
729
730         gtk_widget_show_all(GTK_WIDGET(alert->config));
731         alert->update_source = 0;
732         return FALSE;
733 }
734
735 static gint _sort_warnings(gconstpointer _a, gconstpointer _b)
736 {
737         const AlertMsg *a=_a, *b=_b;
738         return (a->info->prior <  b->info->prior) ? -1 :
739                (a->info->prior == b->info->prior) ?  0 : 1;
740 }
741
742 static void _update_warnings(GritsPluginAlert *alert, GList *old)
743 {
744         g_debug("GritsPluginAlert: _update_warnings");
745
746         /* Sort by priority:
747          *   reversed here since they're added
748          *   to the viewer in reverse order */
749         alert->msgs = g_list_sort(alert->msgs, _sort_warnings);
750
751         /* Remove old messages */
752         for (GList *cur = old; cur; cur = cur->next) {
753                 AlertMsg *msg = cur->data;
754                 if (msg->county_based) grits_viewer_remove(alert->viewer,
755                                 GRITS_OBJECT(msg->county_based));
756                 if (msg->storm_based) grits_viewer_remove(alert->viewer,
757                                 GRITS_OBJECT(msg->storm_based));
758         }
759
760         /* Add new messages */
761         /* Load counties first since it does not require network access */
762         for (GList *cur = alert->msgs; cur; cur = cur->next) {
763                 AlertMsg *msg = cur->data;
764                 msg->county_based = _load_county_based(alert, msg);
765         }
766         grits_viewer_queue_draw(alert->viewer);
767         for (GList *cur = alert->msgs; cur; cur = cur->next) {
768                 AlertMsg *msg = cur->data;
769                 msg->storm_based  = _load_storm_based(alert, msg);
770         }
771         grits_viewer_queue_draw(alert->viewer);
772
773         g_debug("GritsPluginAlert: _load_warnings - end");
774 }
775
776 /* Callbacks */
777 static void _update(gpointer _, gpointer _alert)
778 {
779         GritsPluginAlert *alert = _alert;
780         GList *old = alert->msgs;
781         g_debug("GritsPluginAlert: _update");
782
783         time_t   when    = grits_viewer_get_time(alert->viewer);
784         gboolean offline = grits_viewer_get_offline(alert->viewer);
785         if (!(alert->msgs = msg_load_index(alert->http, when, &alert->updated, offline)))
786                 return;
787
788         if (!alert->update_source)
789                 alert->update_source = g_idle_add((GSourceFunc)_update_buttons, alert);
790         _update_warnings(alert, old);
791
792         g_list_foreach(old, (GFunc)msg_free, NULL);
793         g_list_free(old);
794
795         g_debug("GritsPluginAlert: _update - end");
796 }
797
798 static void _on_update(GritsPluginAlert *alert)
799 {
800         g_thread_pool_push(alert->threads, NULL+1, NULL);
801 }
802
803 /* Init helpers */
804 static GtkWidget *_make_config(GritsPluginAlert *alert)
805 {
806         GtkWidget *config = gtk_box_new(GTK_ORIENTATION_VERTICAL, 0);
807
808         /* Setup tools area */
809         GtkWidget *tools   = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 10);
810         GtkWidget *updated = gtk_label_new(" Loading...");
811         GtkWidget *storm_based  = gtk_toggle_button_new_with_label("Storm based");
812         GtkWidget *county_based = gtk_toggle_button_new_with_label("County based");
813         gtk_label_set_use_markup(GTK_LABEL(updated), TRUE);
814         gtk_box_pack_start(GTK_BOX(tools), updated,      FALSE, FALSE, 0);
815         gtk_box_pack_end  (GTK_BOX(tools), storm_based,  FALSE, FALSE, 0);
816         gtk_box_pack_end  (GTK_BOX(tools), county_based, FALSE, FALSE, 0);
817         gtk_box_pack_start(GTK_BOX(config), tools, FALSE, FALSE, 0);
818         g_object_set_data(G_OBJECT(config), "updated",      updated);
819         g_object_set_data(G_OBJECT(config), "storm_based",  storm_based);
820         g_object_set_data(G_OBJECT(config), "county_based", county_based);
821         g_signal_connect(storm_based,  "toggled", G_CALLBACK(_show_hide), alert);
822         g_signal_connect(county_based, "toggled", G_CALLBACK(_show_hide), alert);
823
824         /* Setup alerts */
825         gchar *labels[] = {"<b>Warnings</b>", "<b>Watches</b>",
826                            "<b>Advisories</b>", "<b>Other</b>"};
827         gchar *keys[]   = {"warning",  "watch",   "advisory",   "other"};
828         GtkWidget *alerts = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 10);
829         for (int i = 0; i < G_N_ELEMENTS(labels); i++) {
830                 GtkWidget *frame = gtk_frame_new(labels[i]);
831                 GtkWidget *table = gtk_table_new(1, 1, TRUE);
832                 GtkWidget *label = gtk_frame_get_label_widget(GTK_FRAME(frame));
833                 gtk_label_set_use_markup(GTK_LABEL(label), TRUE);
834                 gtk_frame_set_shadow_type(GTK_FRAME(frame), GTK_SHADOW_NONE);
835                 gtk_container_add(GTK_CONTAINER(frame), table);
836                 gtk_box_pack_start(GTK_BOX(alerts), frame, TRUE, TRUE, 0);
837                 g_object_set_data(G_OBJECT(alerts), keys[i], table);
838         }
839         gtk_box_pack_start(GTK_BOX(config), alerts, TRUE, TRUE, 0);
840         g_object_set_data(G_OBJECT(config), "alerts",  alerts);
841
842         return config;
843 }
844
845 static gboolean _clear_details(GtkWidget *dialog)
846 {
847         GtkWidget *content  = gtk_dialog_get_content_area(GTK_DIALOG(dialog));
848         GList     *list     = gtk_container_get_children(GTK_CONTAINER(content));
849         GtkWidget *notebook = list->data;
850         g_list_free(list);
851         gtk_widget_hide(dialog);
852         while (gtk_notebook_get_n_pages(GTK_NOTEBOOK(notebook)))
853                 gtk_notebook_remove_page(GTK_NOTEBOOK(notebook), 0);
854         return TRUE;
855 }
856
857 static gboolean _set_details_uri(GtkWidget *notebook, gpointer _,
858                 guint num, GtkWidget *button)
859 {
860         g_debug("_set_details_uri");
861         GtkWidget *page = gtk_notebook_get_nth_page(GTK_NOTEBOOK(notebook), num);
862         AlertMsg  *msg  = g_object_get_data(G_OBJECT(page), "msg");
863         gtk_link_button_set_uri(GTK_LINK_BUTTON(button), msg->link);
864         return FALSE;
865 }
866
867 static GtkWidget *_make_details(GritsViewer *viewer)
868 {
869         GtkWidget *dialog   = gtk_dialog_new();
870         GtkWidget *action   = gtk_dialog_get_action_area (GTK_DIALOG(dialog));
871         GtkWidget *content  = gtk_dialog_get_content_area(GTK_DIALOG(dialog));
872         GtkWidget *notebook = gtk_notebook_new();
873         GtkWidget *win      = gtk_widget_get_toplevel(GTK_WIDGET(viewer));
874         GtkWidget *link     = gtk_link_button_new_with_label("", "Full Text");
875
876         gtk_window_set_transient_for(GTK_WINDOW(dialog), GTK_WINDOW(win));
877         gtk_window_set_title(GTK_WINDOW(dialog), "Alert Details - AWeather");
878         gtk_window_set_default_size(GTK_WINDOW(dialog), 625, 500);
879         gtk_notebook_set_scrollable(GTK_NOTEBOOK(notebook), TRUE);
880         gtk_container_add(GTK_CONTAINER(content), notebook);
881         gtk_box_pack_end(GTK_BOX(action), link, 0, 0, 0);
882         gtk_dialog_add_button(GTK_DIALOG(dialog), GTK_STOCK_CLOSE, GTK_RESPONSE_CLOSE);
883
884         g_signal_connect(dialog,   "response",     G_CALLBACK(_clear_details),   NULL);
885         g_signal_connect(dialog,   "delete-event", G_CALLBACK(_clear_details),   NULL);
886         g_signal_connect(notebook, "switch-page",  G_CALLBACK(_set_details_uri), link);
887
888         return dialog;
889 }
890
891 /* Methods */
892 GritsPluginAlert *grits_plugin_alert_new(GritsViewer *viewer, GritsPrefs *prefs)
893 {
894         g_debug("GritsPluginAlert: new");
895         GritsPluginAlert *alert = g_object_new(GRITS_TYPE_PLUGIN_ALERT, NULL);
896         alert->details = _make_details(viewer);
897         alert->viewer  = g_object_ref(viewer);
898         alert->prefs   = g_object_ref(prefs);
899
900         alert->refresh_id      = g_signal_connect_swapped(alert->viewer, "refresh",
901                         G_CALLBACK(_on_update), alert);
902         alert->time_changed_id = g_signal_connect_swapped(alert->viewer, "time_changed",
903                         G_CALLBACK(_on_update), alert);
904
905         for (GList *cur = alert->states; cur; cur = cur->next)
906                 grits_viewer_add(viewer, cur->data, GRITS_LEVEL_WORLD+1, FALSE);
907
908         gboolean   chide   = grits_prefs_get_boolean(alert->prefs, "alert/hide_county_based", NULL);
909         gboolean   shide   = grits_prefs_get_boolean(alert->prefs, "alert/hide_storm_based",  NULL);
910         GtkWidget *ctoggle = g_object_get_data(G_OBJECT(alert->config), "county_based");
911         GtkWidget *stoggle = g_object_get_data(G_OBJECT(alert->config), "storm_based");
912         gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(ctoggle), !chide);
913         gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(stoggle), !shide);
914
915         _on_update(alert);
916         return alert;
917 }
918
919 static GtkWidget *grits_plugin_alert_get_config(GritsPlugin *_alert)
920 {
921         GritsPluginAlert *alert = GRITS_PLUGIN_ALERT(_alert);
922         return alert->config;
923 }
924
925
926 /* GObject code */
927 static void grits_plugin_alert_plugin_init(GritsPluginInterface *iface);
928 G_DEFINE_TYPE_WITH_CODE(GritsPluginAlert, grits_plugin_alert, G_TYPE_OBJECT,
929                 G_IMPLEMENT_INTERFACE(GRITS_TYPE_PLUGIN,
930                         grits_plugin_alert_plugin_init));
931 static void grits_plugin_alert_plugin_init(GritsPluginInterface *iface)
932 {
933         g_debug("GritsPluginAlert: plugin_init");
934         /* Add methods to the interface */
935         iface->get_config = grits_plugin_alert_get_config;
936 }
937 static void grits_plugin_alert_init(GritsPluginAlert *alert)
938 {
939         g_debug("GritsPluginAlert: init");
940         /* Set defaults */
941         alert->threads = g_thread_pool_new(_update, alert, 1, FALSE, NULL);
942         alert->config  = _make_config(alert);
943         alert->http    = grits_http_new(G_DIR_SEPARATOR_S
944                         "alerts" G_DIR_SEPARATOR_S
945                         "cap"    G_DIR_SEPARATOR_S);
946
947         /* Load counties */
948         gchar *text; gsize len;
949         const gchar *file = PKGDATADIR G_DIR_SEPARATOR_S "fips.txt";
950         if (!g_file_get_contents(file, &text, &len, NULL))
951                 g_error("GritsPluginAlert: init - error loading fips polygons");
952         fips_parse(text, &alert->counties, &alert->states);
953         g_free(text);
954 }
955 static void grits_plugin_alert_dispose(GObject *gobject)
956 {
957         g_debug("GritsPluginAlert: dispose");
958         GritsPluginAlert *alert = GRITS_PLUGIN_ALERT(gobject);
959         /* Drop references */
960         if (alert->viewer) {
961                 GritsViewer *viewer = alert->viewer;
962                 g_signal_handler_disconnect(viewer, alert->refresh_id);
963                 g_signal_handler_disconnect(viewer, alert->time_changed_id);
964                 soup_session_abort(alert->http->soup);
965                 g_thread_pool_free(alert->threads, TRUE, TRUE);
966                 if (alert->update_source)
967                         g_source_remove(alert->update_source);
968                 alert->viewer = NULL;
969                 for (GList *cur = alert->msgs; cur; cur = cur->next) {
970                         AlertMsg *msg = cur->data;
971                         if (msg->county_based) grits_viewer_remove(viewer,
972                                         GRITS_OBJECT(msg->county_based));
973                         if (msg->storm_based) grits_viewer_remove(viewer,
974                                         GRITS_OBJECT(msg->storm_based));
975                 }
976                 for (GList *cur = alert->states; cur; cur = cur->next)
977                         grits_viewer_remove(viewer, cur->data);
978                 gtk_widget_destroy(alert->details);
979                 g_object_unref(alert->prefs);
980                 g_object_unref(viewer);
981         }
982         G_OBJECT_CLASS(grits_plugin_alert_parent_class)->dispose(gobject);
983 }
984 static gboolean _unref_county(gpointer key, gpointer val, gpointer data)
985 {
986         g_object_unref(val);
987         return FALSE;
988 }
989 static void grits_plugin_alert_finalize(GObject *gobject)
990 {
991         g_debug("GritsPluginAlert: finalize");
992         GritsPluginAlert *alert = GRITS_PLUGIN_ALERT(gobject);
993         g_list_foreach(alert->msgs, (GFunc)msg_free, NULL);
994         g_list_free(alert->msgs);
995         g_list_free(alert->states);
996         g_tree_foreach(alert->counties, (GTraverseFunc)_unref_county, NULL);
997         g_tree_destroy(alert->counties);
998         grits_http_free(alert->http);
999         G_OBJECT_CLASS(grits_plugin_alert_parent_class)->finalize(gobject);
1000 }
1001 static void grits_plugin_alert_class_init(GritsPluginAlertClass *klass)
1002 {
1003         g_debug("GritsPluginAlert: class_init");
1004         GObjectClass *gobject_class = (GObjectClass*)klass;
1005         gobject_class->dispose  = grits_plugin_alert_dispose;
1006         gobject_class->finalize = grits_plugin_alert_finalize;
1007 }