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