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