]> git.armaanb.net Git - chorizo.git/blob - browser.c
Indicate RSS/Atom feeds on web sites
[chorizo.git] / browser.c
1 #include <limits.h>
2 #include <stdio.h>
3 #include <stdlib.h>
4 #include <sys/types.h>
5 #include <sys/stat.h>
6 #include <fcntl.h>
7 #include <string.h>
8
9 #include <gtk/gtk.h>
10 #include <gtk/gtkx.h>
11 #include <gdk/gdkkeysyms.h>
12 #include <gio/gio.h>
13 #include <webkit2/webkit2.h>
14 #include <JavaScriptCore/JavaScript.h>
15
16
17 static void client_destroy(GtkWidget *, gpointer);
18 static gboolean client_destroy_request(WebKitWebView *, gpointer);
19 static WebKitWebView *client_new(const gchar *, WebKitWebView *, gboolean);
20 static WebKitWebView *client_new_request(WebKitWebView *, WebKitNavigationAction *,
21                                          gpointer);
22 static void cooperation_setup(void);
23 static void changed_download_progress(GObject *, GParamSpec *, gpointer);
24 static void changed_load_progress(GObject *, GParamSpec *, gpointer);
25 static void changed_title(GObject *, GParamSpec *, gpointer);
26 static void changed_uri(GObject *, GParamSpec *, gpointer);
27 static gboolean crashed_web_view(WebKitWebView *, gpointer);
28 static gboolean decide_policy(WebKitWebView *, WebKitPolicyDecision *,
29                               WebKitPolicyDecisionType, gpointer);
30 static gboolean download_handle(WebKitDownload *, gchar *, gpointer);
31 static void download_handle_start(WebKitWebView *, WebKitDownload *, gpointer);
32 static void downloadmanager_cancel(GtkToolButton *, gpointer);
33 static gboolean downloadmanager_delete(GtkWidget *, gpointer);
34 static void downloadmanager_setup(void);
35 static gchar *ensure_uri_scheme(const gchar *);
36 static void external_handler_run(GSimpleAction *, GVariant *, gpointer);
37 static void feed_icon(gpointer, gchar *);
38 static void grab_environment_configuration(void);
39 static void grab_feeds_finished(GObject *, GAsyncResult *, gpointer);
40 static void hover_web_view(WebKitWebView *, WebKitHitTestResult *, guint, gpointer);
41 static void icon_location(GtkEntry *, GtkEntryIconPosition, GdkEvent *, gpointer);
42 static gboolean key_common(GtkWidget *, GdkEvent *, gpointer);
43 static gboolean key_downloadmanager(GtkWidget *, GdkEvent *, gpointer);
44 static gboolean key_location(GtkWidget *, GdkEvent *, gpointer);
45 static gboolean key_web_view(GtkWidget *, GdkEvent *, gpointer);
46 static void keywords_load(void);
47 static gboolean keywords_try_search(WebKitWebView *, const gchar *);
48 static gboolean menu_web_view(WebKitWebView *, WebKitContextMenu *, GdkEvent *,
49                               WebKitHitTestResult *, gpointer);
50 static gboolean quit_if_nothing_active(void);
51 static gboolean remote_msg(GIOChannel *, GIOCondition, gpointer);
52 static void search(gpointer, gint);
53 static void show_web_view(WebKitWebView *, gpointer);
54 static Window tabbed_launch(void);
55 static void trust_user_certs(WebKitWebContext *);
56
57
58 struct Client
59 {
60     gchar *external_handler_uri;
61     gchar *hover_uri;
62     gchar *feed_html;
63     GtkWidget *location;
64     GtkWidget *vbox;
65     GtkWidget *web_view;
66     GtkWidget *win;
67 };
68
69 struct DownloadManager
70 {
71     GtkWidget *scroll;
72     GtkWidget *toolbar;
73     GtkWidget *win;
74 } dm;
75
76
77 static const gchar *accepted_language[2] = { NULL, NULL };
78 static gint clients = 0, downloads = 0;
79 static gboolean cooperative_alone = TRUE;
80 static gboolean cooperative_instances = TRUE;
81 static int cooperative_pipe_fp = 0;
82 static gchar *download_dir = "/var/tmp";
83 static gboolean enable_webgl = FALSE;
84 static gboolean enable_console_to_stdout = FALSE;
85 static Window embed = 0;
86 static gchar *fifo_suffix = "main";
87 static gdouble global_zoom = 1.0;
88 static gchar *history_file = NULL;
89 static gchar *home_uri = "about:blank";
90 static gboolean initial_wc_setup_done = FALSE;
91 static GHashTable *keywords = NULL;
92 static gchar *search_text = NULL;
93 static gboolean tabbed_automagic = TRUE;
94 static gchar *user_agent = NULL;
95
96 static gchar *feed_html_header =
97 "<!DOCTYPE html>"
98 "<html>"
99 "    <head>"
100 "        <title>Feeds</title>"
101 "    </head>"
102 "    <body>"
103 "        <p>Feeds found on this page:</p>"
104 "        <ul>"
105 ;
106
107 static gchar *feed_html_footer =
108 "        </ul>"
109 "    </body>"
110 "</html>"
111 ;
112
113 static gchar *grab_feeds =
114 "a = document.querySelectorAll('"
115 "    html > head > link[rel=\"alternate\"][href][type=\"application/atom+xml\"],"
116 "    html > head > link[rel=\"alternate\"][href][type=\"application/rss+xml\"]"
117 "');"
118 "if (a.length == 0)"
119 "    null;"
120 "else"
121 "{"
122 "    out = '';"
123 "    for (i = 0; i < a.length; i++)"
124 "    {"
125 "        url = encodeURIComponent(a[i].href);"
126 "        if ('title' in a[i] && a[i].title != '')"
127 "            title = encodeURIComponent(a[i].title);"
128 "        else"
129 "            title = url;"
130 "        out += '<li><a href=\"' + url + '\">' + title + '</a></li>';"
131 "    }"
132 "    out;"
133 "}"
134 ;
135
136
137 void
138 client_destroy(GtkWidget *widget, gpointer data)
139 {
140     struct Client *c = (struct Client *)data;
141
142     g_signal_handlers_disconnect_by_func(G_OBJECT(c->web_view),
143                                          changed_load_progress, c);
144
145     free(c);
146     clients--;
147
148     quit_if_nothing_active();
149 }
150
151 gboolean
152 client_destroy_request(WebKitWebView *web_view, gpointer data)
153 {
154     struct Client *c = (struct Client *)data;
155
156     gtk_widget_destroy(c->win);
157
158     return TRUE;
159 }
160
161 WebKitWebView *
162 client_new(const gchar *uri, WebKitWebView *related_wv, gboolean show)
163 {
164     struct Client *c;
165     WebKitWebContext *wc;
166     gchar *f;
167
168     if (uri != NULL && cooperative_instances && !cooperative_alone)
169     {
170         f = ensure_uri_scheme(uri);
171         write(cooperative_pipe_fp, f, strlen(f));
172         write(cooperative_pipe_fp, "\n", 1);
173         g_free(f);
174         return NULL;
175     }
176
177     c = calloc(1, sizeof(struct Client));
178     if (!c)
179     {
180         fprintf(stderr, __NAME__": fatal: calloc failed\n");
181         exit(EXIT_FAILURE);
182     }
183
184     if (embed != 0)
185     {
186         c->win = gtk_plug_new(embed);
187         if (!gtk_plug_get_embedded(GTK_PLUG(c->win)))
188         {
189             fprintf(stderr, __NAME__": Can't plug-in to XID %ld.\n", embed);
190             gtk_widget_destroy(c->win);
191             c->win = NULL;
192             embed = 0;
193         }
194     }
195
196     if (c->win == NULL)
197         c->win = gtk_window_new(GTK_WINDOW_TOPLEVEL);
198
199     gtk_window_set_default_size(GTK_WINDOW(c->win), 800, 600);
200
201     g_signal_connect(G_OBJECT(c->win), "destroy", G_CALLBACK(client_destroy), c);
202     gtk_window_set_title(GTK_WINDOW(c->win), __NAME__);
203
204     if (related_wv == NULL)
205         c->web_view = webkit_web_view_new();
206     else
207         c->web_view = webkit_web_view_new_with_related_view(related_wv);
208     wc = webkit_web_view_get_context(WEBKIT_WEB_VIEW(c->web_view));
209
210     webkit_web_view_set_zoom_level(WEBKIT_WEB_VIEW(c->web_view), global_zoom);
211     g_signal_connect(G_OBJECT(c->web_view), "notify::title",
212                      G_CALLBACK(changed_title), c);
213     g_signal_connect(G_OBJECT(c->web_view), "notify::uri",
214                      G_CALLBACK(changed_uri), c);
215     g_signal_connect(G_OBJECT(c->web_view), "notify::estimated-load-progress",
216                      G_CALLBACK(changed_load_progress), c);
217     g_signal_connect(G_OBJECT(c->web_view), "create",
218                      G_CALLBACK(client_new_request), NULL);
219     g_signal_connect(G_OBJECT(c->web_view), "context-menu",
220                      G_CALLBACK(menu_web_view), c);
221     g_signal_connect(G_OBJECT(c->web_view), "close",
222                      G_CALLBACK(client_destroy_request), c);
223     g_signal_connect(G_OBJECT(c->web_view), "decide-policy",
224                      G_CALLBACK(decide_policy), NULL);
225     g_signal_connect(G_OBJECT(c->web_view), "key-press-event",
226                      G_CALLBACK(key_web_view), c);
227     g_signal_connect(G_OBJECT(c->web_view), "button-release-event",
228                      G_CALLBACK(key_web_view), c);
229     g_signal_connect(G_OBJECT(c->web_view), "scroll-event",
230                      G_CALLBACK(key_web_view), c);
231     g_signal_connect(G_OBJECT(c->web_view), "mouse-target-changed",
232                      G_CALLBACK(hover_web_view), c);
233     g_signal_connect(G_OBJECT(c->web_view), "web-process-crashed",
234                      G_CALLBACK(crashed_web_view), c);
235
236     if (!initial_wc_setup_done)
237     {
238         if (accepted_language[0] != NULL)
239             webkit_web_context_set_preferred_languages(wc, accepted_language);
240
241         g_signal_connect(G_OBJECT(wc), "download-started",
242                          G_CALLBACK(download_handle_start), NULL);
243
244         trust_user_certs(wc);
245
246         initial_wc_setup_done = TRUE;
247     }
248
249     if (user_agent != NULL)
250         g_object_set(G_OBJECT(webkit_web_view_get_settings(WEBKIT_WEB_VIEW(c->web_view))),
251                      "user-agent", user_agent, NULL);
252
253     if (enable_console_to_stdout)
254         webkit_settings_set_enable_write_console_messages_to_stdout(webkit_web_view_get_settings(WEBKIT_WEB_VIEW(c->web_view)), TRUE);
255
256     if (enable_webgl)
257         webkit_settings_set_enable_webgl(webkit_web_view_get_settings(WEBKIT_WEB_VIEW(c->web_view)), TRUE);
258
259     c->location = gtk_entry_new();
260     g_signal_connect(G_OBJECT(c->location), "key-press-event",
261                      G_CALLBACK(key_location), c);
262     g_signal_connect(G_OBJECT(c->location), "icon-release",
263                      G_CALLBACK(icon_location), c);
264
265     c->vbox = gtk_box_new(GTK_ORIENTATION_VERTICAL, 0);
266     gtk_box_pack_start(GTK_BOX(c->vbox), c->location, FALSE, FALSE, 0);
267     gtk_box_pack_start(GTK_BOX(c->vbox), c->web_view, TRUE, TRUE, 0);
268
269     gtk_container_add(GTK_CONTAINER(c->win), c->vbox);
270
271     if (show)
272         show_web_view(NULL, c);
273     else
274         g_signal_connect(G_OBJECT(c->web_view), "ready-to-show",
275                          G_CALLBACK(show_web_view), c);
276
277     if (uri != NULL)
278     {
279         f = ensure_uri_scheme(uri);
280         webkit_web_view_load_uri(WEBKIT_WEB_VIEW(c->web_view), f);
281         g_free(f);
282     }
283
284     clients++;
285
286     return WEBKIT_WEB_VIEW(c->web_view);
287 }
288
289 WebKitWebView *
290 client_new_request(WebKitWebView *web_view,
291                    WebKitNavigationAction *navigation_action, gpointer data)
292 {
293     return client_new(NULL, web_view, FALSE);
294 }
295
296 void
297 cooperation_setup(void)
298 {
299     GIOChannel *towatch;
300     gchar *fifofilename, *fifopath;
301
302     fifofilename = g_strdup_printf("%s-%s", __NAME__".fifo", fifo_suffix);
303     fifopath = g_build_filename(g_get_user_runtime_dir(), fifofilename, NULL);
304     g_free(fifofilename);
305
306     if (!g_file_test(fifopath, G_FILE_TEST_EXISTS))
307         mkfifo(fifopath, 0600);
308
309     cooperative_pipe_fp = open(fifopath, O_WRONLY | O_NONBLOCK);
310     if (!cooperative_pipe_fp)
311     {
312         fprintf(stderr, __NAME__": Can't open FIFO at all.\n");
313     }
314     else
315     {
316         if (write(cooperative_pipe_fp, "", 0) == -1)
317         {
318             /* Could not do an empty write to the FIFO which means there's
319              * no one listening. */
320             close(cooperative_pipe_fp);
321             towatch = g_io_channel_new_file(fifopath, "r+", NULL);
322             g_io_add_watch(towatch, G_IO_IN, (GIOFunc)remote_msg, NULL);
323         }
324         else
325             cooperative_alone = FALSE;
326     }
327
328     g_free(fifopath);
329 }
330
331 void
332 changed_download_progress(GObject *obj, GParamSpec *pspec, gpointer data)
333 {
334     WebKitDownload *download = WEBKIT_DOWNLOAD(obj);
335     WebKitURIResponse *resp;
336     GtkToolItem *tb = GTK_TOOL_ITEM(data);
337     gdouble p, size_mb;
338     const gchar *uri;
339     gchar *t, *filename, *base;
340
341     p = webkit_download_get_estimated_progress(download);
342     p = p > 1 ? 1 : p;
343     p = p < 0 ? 0 : p;
344     p *= 100;
345     resp = webkit_download_get_response(download);
346     size_mb = webkit_uri_response_get_content_length(resp) / 1e6;
347
348     uri = webkit_download_get_destination(download);
349     filename = g_filename_from_uri(uri, NULL, NULL);
350     if (filename == NULL)
351     {
352         /* This really should not happen because WebKit uses that URI to
353          * write to a file... */
354         fprintf(stderr, __NAME__": Could not construct file name from URI!\n");
355         t = g_strdup_printf("%s (%.0f%% of %.1f MB)",
356                             webkit_uri_response_get_uri(resp), p, size_mb);
357     }
358     else
359     {
360         base = g_path_get_basename(filename);
361         t = g_strdup_printf("%s (%.0f%% of %.1f MB)", base, p, size_mb);
362         g_free(filename);
363         g_free(base);
364     }
365     gtk_tool_button_set_label(GTK_TOOL_BUTTON(tb), t);
366     g_free(t);
367 }
368
369 void
370 changed_load_progress(GObject *obj, GParamSpec *pspec, gpointer data)
371 {
372     struct Client *c = (struct Client *)data;
373     gdouble p;
374
375     p = webkit_web_view_get_estimated_load_progress(WEBKIT_WEB_VIEW(c->web_view));
376     if (p == 1)
377     {
378         p = 0;
379
380         /* The page has loaded fully. We now run a short JavaScript
381          * snippet that operates on the DOM. It tries to grab all
382          * occurences of <link rel="alternate" ...>, i.e. RSS/Atom feed
383          * references. */
384         webkit_web_view_run_javascript(WEBKIT_WEB_VIEW(c->web_view),
385                                        grab_feeds, NULL,
386                                        grab_feeds_finished, c);
387     }
388     gtk_entry_set_progress_fraction(GTK_ENTRY(c->location), p);
389 }
390
391 void
392 changed_title(GObject *obj, GParamSpec *pspec, gpointer data)
393 {
394     const gchar *t, *u;
395     struct Client *c = (struct Client *)data;
396
397     u = webkit_web_view_get_uri(WEBKIT_WEB_VIEW(c->web_view));
398     t = webkit_web_view_get_title(WEBKIT_WEB_VIEW(c->web_view));
399
400     u = u == NULL ? __NAME__ : u;
401     u = u[0] == 0 ? __NAME__ : u;
402
403     t = t == NULL ? u : t;
404     t = t[0] == 0 ? u : t;
405
406     gtk_window_set_title(GTK_WINDOW(c->win), t);
407 }
408
409 void
410 changed_uri(GObject *obj, GParamSpec *pspec, gpointer data)
411 {
412     const gchar *t;
413     struct Client *c = (struct Client *)data;
414     FILE *fp;
415
416     t = webkit_web_view_get_uri(WEBKIT_WEB_VIEW(c->web_view));
417
418     /* When a web process crashes, we get a "notify::uri" signal, but we
419      * can no longer read a meaningful URI. It's just an empty string
420      * now. Not updating the location bar in this scenario is important,
421      * because we would override the "WEB PROCESS CRASHED" message. */
422     if (t != NULL && strlen(t) > 0)
423     {
424         gtk_entry_set_text(GTK_ENTRY(c->location), t);
425
426         if (history_file != NULL)
427         {
428             fp = fopen(history_file, "a");
429             if (fp != NULL)
430             {
431                 fprintf(fp, "%s\n", t);
432                 fclose(fp);
433             }
434             else
435                 perror(__NAME__": Error opening history file");
436         }
437     }
438 }
439
440 gboolean
441 crashed_web_view(WebKitWebView *web_view, gpointer data)
442 {
443     gchar *t;
444     struct Client *c = (struct Client *)data;
445
446     t = g_strdup_printf("WEB PROCESS CRASHED: %s",
447                         webkit_web_view_get_uri(WEBKIT_WEB_VIEW(web_view)));
448     gtk_entry_set_text(GTK_ENTRY(c->location), t);
449     g_free(t);
450
451     return TRUE;
452 }
453
454 gboolean
455 decide_policy(WebKitWebView *web_view, WebKitPolicyDecision *decision,
456               WebKitPolicyDecisionType type, gpointer data)
457 {
458     WebKitResponsePolicyDecision *r;
459
460     switch (type)
461     {
462         case WEBKIT_POLICY_DECISION_TYPE_RESPONSE:
463             r = WEBKIT_RESPONSE_POLICY_DECISION(decision);
464             if (!webkit_response_policy_decision_is_mime_type_supported(r))
465                 webkit_policy_decision_download(decision);
466             else
467                 webkit_policy_decision_use(decision);
468             break;
469         default:
470             /* Use whatever default there is. */
471             return FALSE;
472     }
473     return TRUE;
474 }
475
476 void
477 download_handle_finished(WebKitDownload *download, gpointer data)
478 {
479     downloads--;
480 }
481
482 void
483 download_handle_start(WebKitWebView *web_view, WebKitDownload *download,
484                       gpointer data)
485 {
486     g_signal_connect(G_OBJECT(download), "decide-destination",
487                      G_CALLBACK(download_handle), data);
488 }
489
490 gboolean
491 download_handle(WebKitDownload *download, gchar *suggested_filename, gpointer data)
492 {
493     gchar *sug_clean, *path, *path2 = NULL, *uri;
494     GtkToolItem *tb;
495     int suffix = 1;
496     size_t i;
497
498     sug_clean = g_strdup(suggested_filename);
499     for (i = 0; i < strlen(sug_clean); i++)
500         if (sug_clean[i] == G_DIR_SEPARATOR)
501             sug_clean[i] = '_';
502
503     path = g_build_filename(download_dir, sug_clean, NULL);
504     path2 = g_strdup(path);
505     while (g_file_test(path2, G_FILE_TEST_EXISTS) && suffix < 1000)
506     {
507         g_free(path2);
508
509         path2 = g_strdup_printf("%s.%d", path, suffix);
510         suffix++;
511     }
512
513     if (suffix == 1000)
514     {
515         fprintf(stderr, __NAME__": Suffix reached limit for download.\n");
516         webkit_download_cancel(download);
517     }
518     else
519     {
520         uri = g_filename_to_uri(path2, NULL, NULL);
521         webkit_download_set_destination(download, uri);
522         g_free(uri);
523
524         tb = gtk_tool_button_new(NULL, NULL);
525         gtk_tool_button_set_icon_name(GTK_TOOL_BUTTON(tb), "gtk-delete");
526         gtk_tool_button_set_label(GTK_TOOL_BUTTON(tb), sug_clean);
527         gtk_toolbar_insert(GTK_TOOLBAR(dm.toolbar), tb, 0);
528         gtk_widget_show_all(dm.win);
529
530         g_signal_connect(G_OBJECT(download), "notify::estimated-progress",
531                          G_CALLBACK(changed_download_progress), tb);
532
533         downloads++;
534         g_signal_connect(G_OBJECT(download), "finished",
535                          G_CALLBACK(download_handle_finished), NULL);
536
537         g_object_ref(download);
538         g_signal_connect(G_OBJECT(tb), "clicked",
539                          G_CALLBACK(downloadmanager_cancel), download);
540     }
541
542     g_free(sug_clean);
543     g_free(path);
544     g_free(path2);
545
546     /* Propagate -- to whom it may concern. */
547     return FALSE;
548 }
549
550 void
551 downloadmanager_cancel(GtkToolButton *tb, gpointer data)
552 {
553     WebKitDownload *download = WEBKIT_DOWNLOAD(data);
554
555     webkit_download_cancel(download);
556     g_object_unref(download);
557
558     gtk_widget_destroy(GTK_WIDGET(tb));
559 }
560
561 gboolean
562 downloadmanager_delete(GtkWidget *obj, gpointer data)
563 {
564     if (!quit_if_nothing_active())
565         gtk_widget_hide(dm.win);
566
567     return TRUE;
568 }
569
570 void
571 downloadmanager_setup(void)
572 {
573     dm.win = gtk_window_new(GTK_WINDOW_TOPLEVEL);
574     gtk_window_set_type_hint(GTK_WINDOW(dm.win), GDK_WINDOW_TYPE_HINT_DIALOG);
575     gtk_window_set_default_size(GTK_WINDOW(dm.win), 500, 250);
576     gtk_window_set_title(GTK_WINDOW(dm.win), __NAME__" - Download Manager");
577     g_signal_connect(G_OBJECT(dm.win), "delete-event",
578                      G_CALLBACK(downloadmanager_delete), NULL);
579     g_signal_connect(G_OBJECT(dm.win), "key-press-event",
580                      G_CALLBACK(key_downloadmanager), NULL);
581
582     dm.toolbar = gtk_toolbar_new();
583     gtk_orientable_set_orientation(GTK_ORIENTABLE(dm.toolbar),
584                                    GTK_ORIENTATION_VERTICAL);
585     gtk_toolbar_set_style(GTK_TOOLBAR(dm.toolbar), GTK_TOOLBAR_BOTH_HORIZ);
586     gtk_toolbar_set_show_arrow(GTK_TOOLBAR(dm.toolbar), FALSE);
587
588     dm.scroll = gtk_scrolled_window_new(NULL, NULL);
589     gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(dm.scroll),
590                                    GTK_POLICY_AUTOMATIC, GTK_POLICY_AUTOMATIC);
591     gtk_container_add(GTK_CONTAINER(dm.scroll), dm.toolbar);
592
593     gtk_container_add(GTK_CONTAINER(dm.win), dm.scroll);
594 }
595
596 gchar *
597 ensure_uri_scheme(const gchar *t)
598 {
599     gchar *f, *fabs;
600
601     f = g_ascii_strdown(t, -1);
602     if (!g_str_has_prefix(f, "http:") &&
603         !g_str_has_prefix(f, "https:") &&
604         !g_str_has_prefix(f, "file:") &&
605         !g_str_has_prefix(f, "about:") &&
606         !g_str_has_prefix(f, "data:"))
607     {
608         g_free(f);
609         fabs = realpath(t, NULL);
610         if (fabs != NULL)
611         {
612             f = g_strdup_printf("file://%s", fabs);
613             free(fabs);
614         }
615         else
616             f = g_strdup_printf("http://%s", t);
617         return f;
618     }
619     else
620         return g_strdup(t);
621 }
622
623 void
624 external_handler_run(GSimpleAction *simple, GVariant *param, gpointer data)
625 {
626     struct Client *c = (struct Client *)data;
627     gchar *argv[] = { "lariza-external-handler", "-u", NULL, NULL };
628     GPid pid;
629     GError *err = NULL;
630
631     (void)simple;
632     (void)param;
633
634     argv[2] = c->external_handler_uri;
635     if (!g_spawn_async(NULL, argv, NULL, G_SPAWN_SEARCH_PATH, NULL, NULL,
636                        &pid, &err))
637     {
638         fprintf(stderr, __NAME__": Could not launch key handler: %s\n",
639                 err->message);
640         g_error_free(err);
641     }
642     else
643         g_spawn_close_pid(pid);
644 }
645
646 void feed_icon(gpointer user_data, gchar *feed_html)
647 {
648     struct Client *c = (struct Client *)user_data;
649
650     if (feed_html != NULL)
651     {
652         gtk_entry_set_icon_from_icon_name(GTK_ENTRY(c->location),
653                                           GTK_ENTRY_ICON_PRIMARY,
654                                           "application-rss+xml-symbolic");
655         gtk_entry_set_icon_activatable(GTK_ENTRY(c->location),
656                                        GTK_ENTRY_ICON_PRIMARY,
657                                        TRUE);
658
659         if (c->feed_html != NULL)
660             g_free(c->feed_html);
661         c->feed_html = g_strdup(feed_html);
662     }
663     else
664     {
665         gtk_entry_set_icon_from_icon_name(GTK_ENTRY(c->location),
666                                           GTK_ENTRY_ICON_PRIMARY,
667                                           NULL);
668     }
669 }
670
671 void
672 grab_environment_configuration(void)
673 {
674     const gchar *e;
675
676     e = g_getenv(__NAME_UPPERCASE__"_ACCEPTED_LANGUAGE");
677     if (e != NULL)
678         accepted_language[0] = g_strdup(e);
679
680     e = g_getenv(__NAME_UPPERCASE__"_DOWNLOAD_DIR");
681     if (e != NULL)
682         download_dir = g_strdup(e);
683
684     e = g_getenv(__NAME_UPPERCASE__"_ENABLE_CONSOLE_TO_STDOUT");
685     if (e != NULL)
686         enable_console_to_stdout = TRUE;
687
688     e = g_getenv(__NAME_UPPERCASE__"_ENABLE_EXPERIMENTAL_WEBGL");
689     if (e != NULL)
690         enable_webgl = TRUE;
691
692     e = g_getenv(__NAME_UPPERCASE__"_FIFO_SUFFIX");
693     if (e != NULL)
694         fifo_suffix = g_strdup(e);
695
696     e = g_getenv(__NAME_UPPERCASE__"_HISTORY_FILE");
697     if (e != NULL)
698         history_file = g_strdup(e);
699
700     e = g_getenv(__NAME_UPPERCASE__"_HOME_URI");
701     if (e != NULL)
702         home_uri = g_strdup(e);
703
704     e = g_getenv(__NAME_UPPERCASE__"_USER_AGENT");
705     if (e != NULL)
706         user_agent = g_strdup(e);
707
708     e = g_getenv(__NAME_UPPERCASE__"_ZOOM");
709     if (e != NULL)
710         global_zoom = atof(e);
711 }
712
713 void
714 grab_feeds_finished(GObject *object, GAsyncResult *result, gpointer data)
715 {
716     WebKitJavascriptResult *js_result;
717     JSValueRef value;
718     JSGlobalContextRef context;
719     GError *err = NULL;
720     JSStringRef js_str_value;
721     gchar *str_value;
722     gsize str_length;
723
724     /* This was taken almost verbatim from the example in WebKit's
725      * documentation. */
726
727     js_result = webkit_web_view_run_javascript_finish(WEBKIT_WEB_VIEW(object),
728                                                       result, &err);
729     if (!js_result)
730     {
731         fprintf(stderr, __NAME__": Error running javascript: %s\n", err->message);
732         g_error_free(err);
733         return;
734     }
735
736     context = webkit_javascript_result_get_global_context(js_result);
737     value = webkit_javascript_result_get_value(js_result);
738
739     if (JSValueIsString(context, value))
740     {
741         js_str_value = JSValueToStringCopy(context, value, NULL);
742         str_length = JSStringGetMaximumUTF8CStringSize(js_str_value);
743         str_value = (gchar *)g_malloc(str_length);
744         JSStringGetUTF8CString(js_str_value, str_value, str_length);
745         JSStringRelease(js_str_value);
746         feed_icon(data, str_value);
747         g_free(str_value);
748     }
749     else
750         feed_icon(data, NULL);
751
752     webkit_javascript_result_unref(js_result);
753 }
754
755 void
756 hover_web_view(WebKitWebView *web_view, WebKitHitTestResult *ht, guint modifiers,
757                gpointer data)
758 {
759     struct Client *c = (struct Client *)data;
760
761     if (!gtk_widget_is_focus(c->location))
762     {
763         if (webkit_hit_test_result_context_is_link(ht))
764         {
765             gtk_entry_set_text(GTK_ENTRY(c->location),
766                                webkit_hit_test_result_get_link_uri(ht));
767
768             if (c->hover_uri != NULL)
769                 g_free(c->hover_uri);
770             c->hover_uri = g_strdup(webkit_hit_test_result_get_link_uri(ht));
771         }
772         else
773         {
774             gtk_entry_set_text(GTK_ENTRY(c->location),
775                                webkit_web_view_get_uri(WEBKIT_WEB_VIEW(c->web_view)));
776
777             if (c->hover_uri != NULL)
778                 g_free(c->hover_uri);
779             c->hover_uri = NULL;
780         }
781     }
782 }
783
784 void
785 icon_location(GtkEntry *entry, GtkEntryIconPosition icon_pos, GdkEvent *event, gpointer data)
786 {
787     struct Client *c = (struct Client *)data;
788     gchar *d;
789
790     if (c->feed_html != NULL)
791     {
792         /* What we're actually trying to do is show a simple HTML page
793          * that lists all the feeds on the current page. The function
794          * webkit_web_view_load_html() looks like the proper way to do
795          * that. Sad thing is, it doesn't create a history entry, but
796          * instead simply replaces the content of the current page. This
797          * is not what we want.
798          *
799          * RFC 2397 [0] defines the data URI scheme [1]. We abuse this
800          * mechanism to show my custom HTML snippet *and* create a
801          * history entry.
802          *
803          * [0]: https://tools.ietf.org/html/rfc2397
804          * [1]: https://en.wikipedia.org/wiki/Data_URI_scheme */
805         d = g_strdup_printf("data:text/html,%s%s%s",
806                             feed_html_header,
807                             c->feed_html,
808                             feed_html_footer);
809         webkit_web_view_load_uri(WEBKIT_WEB_VIEW(c->web_view), d);
810         g_free(d);
811     }
812 }
813
814 gboolean
815 key_common(GtkWidget *widget, GdkEvent *event, gpointer data)
816 {
817     struct Client *c = (struct Client *)data;
818     WebKitWebContext *wc = webkit_web_view_get_context(WEBKIT_WEB_VIEW(c->web_view));
819     gchar *f;
820
821     if (event->type == GDK_KEY_PRESS)
822     {
823         if (((GdkEventKey *)event)->state & GDK_MOD1_MASK)
824         {
825             switch (((GdkEventKey *)event)->keyval)
826             {
827                 case GDK_KEY_q:  /* close window (left hand) */
828                     gtk_widget_destroy(c->win);
829                     return TRUE;
830                 case GDK_KEY_w:  /* home (left hand) */
831                     f = ensure_uri_scheme(home_uri);
832                     webkit_web_view_load_uri(WEBKIT_WEB_VIEW(c->web_view), f);
833                     g_free(f);
834                     return TRUE;
835                 case GDK_KEY_e:  /* new tab (left hand) */
836                     f = ensure_uri_scheme(home_uri);
837                     client_new(f, NULL, TRUE);
838                     g_free(f);
839                     return TRUE;
840                 case GDK_KEY_r:  /* reload (left hand) */
841                     webkit_web_view_reload_bypass_cache(WEBKIT_WEB_VIEW(
842                                                         c->web_view));
843                     return TRUE;
844                 case GDK_KEY_d:  /* download manager (left hand) */
845                     gtk_widget_show_all(dm.win);
846                     return TRUE;
847                 case GDK_KEY_2:  /* search forward (left hand) */
848                 case GDK_KEY_n:  /* search forward (maybe both hands) */
849                     search(c, 1);
850                     return TRUE;
851                 case GDK_KEY_3:  /* search backward (left hand) */
852                     search(c, -1);
853                     return TRUE;
854                 case GDK_KEY_l:  /* location (BOTH hands) */
855                     gtk_widget_grab_focus(c->location);
856                     return TRUE;
857                 case GDK_KEY_k:  /* initiate search (BOTH hands) */
858                     gtk_widget_grab_focus(c->location);
859                     gtk_entry_set_text(GTK_ENTRY(c->location), ":/");
860                     gtk_editable_set_position(GTK_EDITABLE(c->location), -1);
861                     return TRUE;
862                 case GDK_KEY_c:  /* reload trusted certs (left hand) */
863                     trust_user_certs(wc);
864                     return TRUE;
865                 case GDK_KEY_x:  /* launch external handler (left hand) */
866                     if (c->external_handler_uri != NULL)
867                         g_free(c->external_handler_uri);
868                     c->external_handler_uri = g_strdup(
869                         webkit_web_view_get_uri(WEBKIT_WEB_VIEW(c->web_view)));
870                     external_handler_run(NULL, NULL, c);
871                     return TRUE;
872             }
873         }
874         /* navigate backward (left hand) */
875         else if (((GdkEventKey *)event)->keyval == GDK_KEY_F2)
876         {
877             webkit_web_view_go_back(WEBKIT_WEB_VIEW(c->web_view));
878             return TRUE;
879         }
880         /* navigate forward (left hand) */
881         else if (((GdkEventKey *)event)->keyval == GDK_KEY_F3)
882         {
883             webkit_web_view_go_forward(WEBKIT_WEB_VIEW(c->web_view));
884             return TRUE;
885         }
886     }
887
888     return FALSE;
889 }
890
891 gboolean
892 key_downloadmanager(GtkWidget *widget, GdkEvent *event, gpointer data)
893 {
894     if (event->type == GDK_KEY_PRESS)
895     {
896         if (((GdkEventKey *)event)->state & GDK_MOD1_MASK)
897         {
898             switch (((GdkEventKey *)event)->keyval)
899             {
900                 case GDK_KEY_d:  /* close window (left hand) */
901                 case GDK_KEY_q:
902                     downloadmanager_delete(dm.win, NULL);
903                     return TRUE;
904             }
905         }
906     }
907
908     return FALSE;
909 }
910
911 gboolean
912 key_location(GtkWidget *widget, GdkEvent *event, gpointer data)
913 {
914     struct Client *c = (struct Client *)data;
915     const gchar *t;
916     gchar *f;
917
918     if (key_common(widget, event, data))
919         return TRUE;
920
921     if (event->type == GDK_KEY_PRESS)
922     {
923         switch (((GdkEventKey *)event)->keyval)
924         {
925             case GDK_KEY_KP_Enter:
926             case GDK_KEY_Return:
927                 gtk_widget_grab_focus(c->web_view);
928                 t = gtk_entry_get_text(GTK_ENTRY(c->location));
929                 if (t != NULL && t[0] == ':' && t[1] == '/')
930                 {
931                     if (search_text != NULL)
932                         g_free(search_text);
933                     search_text = g_strdup(t + 2);
934                     search(c, 0);
935                 }
936                 else if (!keywords_try_search(WEBKIT_WEB_VIEW(c->web_view), t))
937                 {
938                     f = ensure_uri_scheme(t);
939                     webkit_web_view_load_uri(WEBKIT_WEB_VIEW(c->web_view), f);
940                     g_free(f);
941                 }
942                 return TRUE;
943             case GDK_KEY_Escape:
944                 t = webkit_web_view_get_uri(WEBKIT_WEB_VIEW(c->web_view));
945                 gtk_entry_set_text(GTK_ENTRY(c->location),
946                                    (t == NULL ? __NAME__ : t));
947                 return TRUE;
948         }
949     }
950
951     return FALSE;
952 }
953
954 gboolean
955 key_web_view(GtkWidget *widget, GdkEvent *event, gpointer data)
956 {
957     struct Client *c = (struct Client *)data;
958     gdouble dx, dy;
959     gfloat z;
960
961     if (key_common(widget, event, data))
962         return TRUE;
963
964     if (event->type == GDK_KEY_PRESS)
965     {
966         if (((GdkEventKey *)event)->keyval == GDK_KEY_Escape)
967         {
968             webkit_web_view_stop_loading(WEBKIT_WEB_VIEW(c->web_view));
969             gtk_entry_set_progress_fraction(GTK_ENTRY(c->location), 0);
970         }
971     }
972     else if (event->type == GDK_BUTTON_RELEASE)
973     {
974         switch (((GdkEventButton *)event)->button)
975         {
976             case 2:
977                 if (c->hover_uri != NULL)
978                 {
979                     client_new(c->hover_uri, NULL, TRUE);
980                     return TRUE;
981                 }
982                 break;
983             case 8:
984                 webkit_web_view_go_back(WEBKIT_WEB_VIEW(c->web_view));
985                 return TRUE;
986             case 9:
987                 webkit_web_view_go_forward(WEBKIT_WEB_VIEW(c->web_view));
988                 return TRUE;
989         }
990     }
991     else if (event->type == GDK_SCROLL)
992     {
993         if (((GdkEventScroll *)event)->state & GDK_MOD1_MASK ||
994             ((GdkEventScroll *)event)->state & GDK_CONTROL_MASK)
995         {
996             gdk_event_get_scroll_deltas(event, &dx, &dy);
997             z = webkit_web_view_get_zoom_level(WEBKIT_WEB_VIEW(c->web_view));
998             z += -dy * 0.1;
999             z = dx != 0 ? global_zoom : z;
1000             webkit_web_view_set_zoom_level(WEBKIT_WEB_VIEW(c->web_view), z);
1001             return TRUE;
1002         }
1003     }
1004
1005     return FALSE;
1006 }
1007
1008 void
1009 keywords_load(void)
1010 {
1011     GError *err = NULL;
1012     GIOChannel *channel = NULL;
1013     gchar *path = NULL, *buf = NULL;
1014     gchar **tokens = NULL;
1015
1016     keywords = g_hash_table_new(g_str_hash, g_str_equal);
1017
1018     path = g_build_filename(g_get_user_config_dir(), __NAME__, "keywordsearch",
1019                             NULL);
1020     channel = g_io_channel_new_file(path, "r", &err);
1021     if (channel != NULL)
1022     {
1023         while (g_io_channel_read_line(channel, &buf, NULL, NULL, NULL)
1024                == G_IO_STATUS_NORMAL)
1025         {
1026             g_strstrip(buf);
1027             if (buf[0] != '#')
1028             {
1029                 tokens = g_strsplit(buf, " ", 2);
1030                 if (tokens[0] != NULL && tokens[1] != NULL)
1031                     g_hash_table_insert(keywords, g_strdup(tokens[0]),
1032                                         g_strdup(tokens[1]));
1033                 g_strfreev(tokens);
1034             }
1035             g_free(buf);
1036         }
1037         g_io_channel_shutdown(channel, FALSE, NULL);
1038     }
1039     g_free(path);
1040 }
1041
1042 gboolean
1043 keywords_try_search(WebKitWebView *web_view, const gchar *t)
1044 {
1045     gboolean ret = FALSE;
1046     gchar **tokens = NULL;
1047     gchar *val = NULL, *escaped = NULL, *uri = NULL;
1048
1049     tokens = g_strsplit(t, " ", 2);
1050     if (tokens[0] != NULL && tokens[1] != NULL)
1051     {
1052         val = g_hash_table_lookup(keywords, tokens[0]);
1053         if (val != NULL)
1054         {
1055             escaped = g_uri_escape_string(tokens[1], NULL, TRUE);
1056             uri = g_strdup_printf((gchar *)val, escaped);
1057             webkit_web_view_load_uri(web_view, uri);
1058             g_free(uri);
1059             g_free(escaped);
1060             ret = TRUE;
1061         }
1062     }
1063     g_strfreev(tokens);
1064
1065     return ret;
1066 }
1067
1068 gboolean
1069 menu_web_view(WebKitWebView *web_view, WebKitContextMenu *menu, GdkEvent *ev,
1070               WebKitHitTestResult *ht, gpointer data)
1071 {
1072     struct Client *c = (struct Client *)data;
1073     GSimpleAction *action = NULL;
1074     WebKitContextMenuItem *mi = NULL;
1075     const gchar *uri = NULL;
1076
1077     (void)ev;
1078
1079     if (webkit_hit_test_result_context_is_link(ht))
1080         uri = webkit_hit_test_result_get_link_uri(ht);
1081     else if (webkit_hit_test_result_context_is_image(ht))
1082         uri = webkit_hit_test_result_get_image_uri(ht);
1083     else if (webkit_hit_test_result_context_is_media(ht))
1084         uri = webkit_hit_test_result_get_media_uri(ht);
1085
1086     if (uri != NULL)
1087     {
1088         webkit_context_menu_append(menu, webkit_context_menu_item_new_separator());
1089
1090         if (c->external_handler_uri != NULL)
1091             g_free(c->external_handler_uri);
1092         c->external_handler_uri = g_strdup(uri);
1093         action = g_simple_action_new("external_handler", NULL);
1094         g_signal_connect(G_OBJECT(action), "activate",
1095                          G_CALLBACK(external_handler_run), data);
1096         mi = webkit_context_menu_item_new_from_gaction(G_ACTION(action),
1097                                                        "Open with external handler",
1098                                                        NULL);
1099         webkit_context_menu_append(menu, mi);
1100         g_object_unref(action);
1101     }
1102
1103     /* FALSE = Show the menu. (TRUE = Don't ever show it.) */
1104     return FALSE;
1105 }
1106
1107 gboolean
1108 quit_if_nothing_active(void)
1109 {
1110     if (clients == 0)
1111     {
1112         if (downloads == 0)
1113         {
1114             gtk_main_quit();
1115             return TRUE;
1116         }
1117         else
1118             gtk_widget_show_all(dm.win);
1119     }
1120
1121     return FALSE;
1122 }
1123
1124 gboolean
1125 remote_msg(GIOChannel *channel, GIOCondition condition, gpointer data)
1126 {
1127     gchar *uri = NULL;
1128
1129     g_io_channel_read_line(channel, &uri, NULL, NULL, NULL);
1130     if (uri)
1131     {
1132         g_strstrip(uri);
1133         client_new(uri, NULL, TRUE);
1134         g_free(uri);
1135     }
1136     return TRUE;
1137 }
1138
1139 void
1140 search(gpointer data, gint direction)
1141 {
1142     struct Client *c = (struct Client *)data;
1143     WebKitWebView *web_view = WEBKIT_WEB_VIEW(c->web_view);
1144     WebKitFindController *fc = webkit_web_view_get_find_controller(web_view);
1145
1146     if (search_text == NULL)
1147         return;
1148
1149     switch (direction)
1150     {
1151         case 0:
1152             webkit_find_controller_search(fc, search_text,
1153                                           WEBKIT_FIND_OPTIONS_CASE_INSENSITIVE |
1154                                           WEBKIT_FIND_OPTIONS_WRAP_AROUND,
1155                                           G_MAXUINT);
1156             break;
1157         case 1:
1158             webkit_find_controller_search_next(fc);
1159             break;
1160         case -1:
1161             webkit_find_controller_search_previous(fc);
1162             break;
1163     }
1164 }
1165
1166 void
1167 show_web_view(WebKitWebView *web_view, gpointer data)
1168 {
1169     struct Client *c = (struct Client *)data;
1170
1171     (void)web_view;
1172
1173     gtk_widget_grab_focus(c->web_view);
1174     gtk_widget_show_all(c->win);
1175 }
1176
1177 Window
1178 tabbed_launch(void)
1179 {
1180     gint tabbed_stdout;
1181     GIOChannel *tabbed_stdout_channel;
1182     GError *err = NULL;
1183     gchar *output = NULL;
1184     char *argv[] = { "tabbed", "-c", "-d", "-p", "s1", "-n", __NAME__, NULL };
1185     Window plug_into;
1186
1187     if (!g_spawn_async_with_pipes(NULL, argv, NULL, G_SPAWN_SEARCH_PATH, NULL,
1188                                   NULL, NULL, NULL, &tabbed_stdout, NULL,
1189                                   &err))
1190     {
1191         fprintf(stderr, __NAME__": Could not launch tabbed: %s\n", err->message);
1192         g_error_free(err);
1193         return 0;
1194     }
1195
1196     tabbed_stdout_channel = g_io_channel_unix_new(tabbed_stdout);
1197     if (tabbed_stdout_channel == NULL)
1198     {
1199         fprintf(stderr, __NAME__": Could open tabbed's stdout\n");
1200         return 0;
1201     }
1202     g_io_channel_read_line(tabbed_stdout_channel, &output, NULL, NULL, NULL);
1203     g_io_channel_shutdown(tabbed_stdout_channel, FALSE, NULL);
1204     if (output == NULL)
1205     {
1206         fprintf(stderr, __NAME__": Could not read XID from tabbed\n");
1207         return 0;
1208     }
1209     g_strstrip(output);
1210     plug_into = strtol(output, NULL, 16);
1211     g_free(output);
1212     if (plug_into == 0)
1213         fprintf(stderr, __NAME__": The XID from tabbed is 0\n");
1214     return plug_into;
1215 }
1216
1217 void
1218 trust_user_certs(WebKitWebContext *wc)
1219 {
1220     GTlsCertificate *cert;
1221     const gchar *basedir, *file, *absfile;
1222     GDir *dir;
1223
1224     basedir = g_build_filename(g_get_user_config_dir(), __NAME__, "certs", NULL);
1225     dir = g_dir_open(basedir, 0, NULL);
1226     if (dir != NULL)
1227     {
1228         file = g_dir_read_name(dir);
1229         while (file != NULL)
1230         {
1231             absfile = g_build_filename(g_get_user_config_dir(), __NAME__, "certs",
1232                                        file, NULL);
1233             cert = g_tls_certificate_new_from_file(absfile, NULL);
1234             if (cert == NULL)
1235                 fprintf(stderr, __NAME__": Could not load trusted cert '%s'\n", file);
1236             else
1237                 webkit_web_context_allow_tls_certificate_for_host(wc, cert, file);
1238             file = g_dir_read_name(dir);
1239         }
1240         g_dir_close(dir);
1241     }
1242 }
1243
1244
1245 int
1246 main(int argc, char **argv)
1247 {
1248     gchar *c;
1249     int opt, i;
1250
1251     gtk_init(&argc, &argv);
1252     webkit_web_context_set_process_model(webkit_web_context_get_default(),
1253         WEBKIT_PROCESS_MODEL_MULTIPLE_SECONDARY_PROCESSES);
1254
1255     grab_environment_configuration();
1256
1257     while ((opt = getopt(argc, argv, "e:CT")) != -1)
1258     {
1259         switch (opt)
1260         {
1261             case 'e':
1262                 embed = atol(optarg);
1263                 tabbed_automagic = FALSE;
1264                 break;
1265             case 'C':
1266                 cooperative_instances = FALSE;
1267                 break;
1268             case 'T':
1269                 tabbed_automagic = FALSE;
1270                 break;
1271             default:
1272                 fprintf(stderr, "Usage: "__NAME__" [OPTION]... [URI]...\n");
1273                 exit(EXIT_FAILURE);
1274         }
1275     }
1276
1277     keywords_load();
1278     if (cooperative_instances)
1279         cooperation_setup();
1280     downloadmanager_setup();
1281
1282     if (tabbed_automagic && !(cooperative_instances && !cooperative_alone))
1283         embed = tabbed_launch();
1284
1285     if (!cooperative_instances || cooperative_alone)
1286     {
1287         c = g_build_filename(g_get_user_config_dir(), __NAME__, "web_extensions",
1288                              NULL);
1289         webkit_web_context_set_web_extensions_directory(
1290             webkit_web_context_get_default(), c
1291         );
1292     }
1293
1294     if (optind >= argc)
1295         client_new(home_uri, NULL, TRUE);
1296     else
1297     {
1298         for (i = optind; i < argc; i++)
1299             client_new(argv[i], NULL, TRUE);
1300     }
1301
1302     if (!cooperative_instances || cooperative_alone)
1303         gtk_main();
1304     exit(EXIT_SUCCESS);
1305 }