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