]> git.armaanb.net Git - chorizo.git/blob - src/browser.c
Patch leaks
[chorizo.git] / src / browser.c
1 #include <fcntl.h>
2 #include <sys/stat.h>
3 #include <webkit2/webkit2.h>
4
5 #include "downloads.h"
6
7 void client_destroy(GtkWidget *, gpointer);
8 WebKitWebView *client_new(const gchar *, WebKitWebView *, gboolean, gboolean);
9 WebKitWebView *client_new_request(WebKitWebView *, WebKitNavigationAction *,
10                                   gpointer);
11 void cooperation_setup(void);
12 void changed_load_progress(GObject *, GParamSpec *, gpointer);
13 void changed_favicon(GObject *, GParamSpec *, gpointer);
14 void changed_title(GObject *, GParamSpec *, gpointer);
15 void changed_uri(GObject *, GParamSpec *, gpointer);
16 gboolean crashed_web_view(WebKitWebView *, gpointer);
17 gboolean decide_policy(WebKitWebView *, WebKitPolicyDecision *,
18                        WebKitPolicyDecisionType, gpointer);
19 gchar *ensure_uri_scheme(const gchar *);
20 void grab_environment_configuration(void);
21 void grab_feeds_finished(GObject *, GAsyncResult *, gpointer);
22 void hover_web_view(WebKitWebView *, WebKitHitTestResult *, guint, gpointer);
23 void icon_location(GtkEntry *, GtkEntryIconPosition, GdkEvent *, gpointer);
24 void init_default_web_context(void);
25 gboolean key_common(GtkWidget *, GdkEvent *, gpointer);
26 gboolean key_location(GtkWidget *, GdkEvent *, gpointer);
27 gboolean key_tablabel(GtkWidget *, GdkEvent *, gpointer);
28 gboolean key_web_view(GtkWidget *, GdkEvent *, gpointer);
29 void mainwindow_setup(void);
30 void mainwindow_title(gint);
31 void notebook_switch_page(GtkNotebook *, GtkWidget *, guint, gpointer);
32 gboolean remote_msg(GIOChannel *, GIOCondition, gpointer);
33 void run_user_scripts(WebKitWebView *);
34 void search(gpointer, gint);
35 void show_web_view(WebKitWebView *, gpointer);
36 void trust_user_certs(WebKitWebContext *);
37 GKeyFile *get_ini(void);
38 GKeyFile *config;
39
40 struct Client {
41     GtkWidget *imgbutton;
42     GtkWidget *jsbutton;
43     GtkWidget *location;
44     GtkWidget *tabicon;
45     GtkWidget *tablabel;
46     GtkWidget *vbox;
47     GtkWidget *web_view;
48     WebKitSettings *settings;
49     gboolean focus_new_tab;
50     gchar *external_handler_uri;
51     gchar *feed_html;
52     gchar *hover_uri;
53 };
54
55 struct Configuration {
56     WebKitCookieAcceptPolicy cookie_policy;
57     const gchar *accepted_language[2];
58     gboolean cooperative_alone;
59     gboolean cooperative_instances;
60     gboolean enable_console_to_stdout;
61     gboolean images_disabled;
62     gboolean javascript_disabled;
63     gboolean private;
64     gboolean spellcheck_disabled;
65     gchar *default_uri;
66     gchar *download_dir;
67     gchar *fifo_suffix;
68     gchar *history_file;
69     gchar *home_uri;
70     gchar *search_engine;
71     gchar *spellcheck_language;
72     gchar *user_agent;
73     gdouble global_zoom;
74     gint scroll_lines;
75     gint tab_width_chars;
76 } cfg;
77
78 struct MainWindow {
79     GtkWidget *win;
80     GtkWidget *notebook;
81 } mw;
82
83 gint clients = 0;
84 struct Client **client_arr;
85
86 int cooperative_pipe_fp = 0;
87 gchar *search_text;
88
89 void
90 togglejs(GtkButton *jsbutton, gpointer data) {
91     struct Client *c = (struct Client *)data;
92     webkit_settings_set_enable_javascript(
93         c->settings, !webkit_settings_get_enable_javascript(c->settings));
94     webkit_web_view_set_settings(WEBKIT_WEB_VIEW(c->web_view), c->settings);
95 }
96
97 void
98 toggleimg(GtkButton *imgbutton, gpointer data) {
99     struct Client *c = (struct Client *)data;
100     webkit_settings_set_auto_load_images(
101         c->settings, !webkit_settings_get_auto_load_images(c->settings));
102     webkit_web_view_set_settings(WEBKIT_WEB_VIEW(c->web_view), c->settings);
103 }
104
105 void
106 client_destroy(GtkWidget *widget, gpointer data) {
107     struct Client *c = (struct Client *)data;
108     gint idx;
109
110     g_signal_handlers_disconnect_by_func(G_OBJECT(c->web_view),
111                                          changed_load_progress, c);
112
113     idx = gtk_notebook_page_num(GTK_NOTEBOOK(mw.notebook), c->vbox);
114     if (idx == -1)
115         fprintf(stderr, __NAME__ ": Tab index was -1, bamboozled\n");
116     else
117         gtk_notebook_remove_page(GTK_NOTEBOOK(mw.notebook), idx);
118
119     free(c);
120     clients--;
121
122     quit_if_nothing_active();
123 }
124
125 void
126 set_uri(const char *uri, struct Client *c) {
127     if (!gtk_widget_is_focus(c->location)) {
128         gtk_entry_set_text(GTK_ENTRY(c->location), uri);
129     }
130 }
131
132 WebKitWebView *
133 client_new(const gchar *uri, WebKitWebView *related_wv, gboolean show,
134            gboolean focus_tab) {
135     struct Client *c;
136     gchar *f;
137     GtkWidget *evbox, *tabbox;
138
139     if (uri != NULL && cfg.cooperative_instances && !cfg.cooperative_alone) {
140         f = ensure_uri_scheme(uri);
141         write(cooperative_pipe_fp, f, strlen(f));
142         write(cooperative_pipe_fp, "\n", 1);
143         g_free(f);
144         return NULL;
145     }
146
147     c = calloc(1, sizeof(struct Client));
148     if (!c) {
149         fprintf(stderr, __NAME__ ": fatal: calloc failed\n");
150         exit(EXIT_FAILURE);
151     }
152
153     c->focus_new_tab = focus_tab;
154
155     if (related_wv == NULL)
156         c->web_view = webkit_web_view_new();
157     else
158         c->web_view = webkit_web_view_new_with_related_view(related_wv);
159
160     c->settings = webkit_web_view_get_settings(WEBKIT_WEB_VIEW(c->web_view));
161
162     webkit_web_view_set_zoom_level(WEBKIT_WEB_VIEW(c->web_view),
163                                    cfg.global_zoom);
164     webkit_settings_set_enable_javascript(c->settings,
165                                           !cfg.javascript_disabled);
166     webkit_settings_set_auto_load_images(c->settings, !cfg.images_disabled);
167     g_signal_connect(G_OBJECT(c->web_view), "notify::favicon",
168                      G_CALLBACK(changed_favicon), c);
169     g_signal_connect(G_OBJECT(c->web_view), "notify::title",
170                      G_CALLBACK(changed_title), c);
171     g_signal_connect(G_OBJECT(c->web_view), "notify::uri",
172                      G_CALLBACK(changed_uri), c);
173     g_signal_connect(G_OBJECT(c->web_view), "notify::estimated-load-progress",
174                      G_CALLBACK(changed_load_progress), c);
175     g_signal_connect(G_OBJECT(c->web_view), "create",
176                      G_CALLBACK(client_new_request), NULL);
177     g_signal_connect(G_OBJECT(c->web_view), "close", G_CALLBACK(client_destroy),
178                      c);
179     g_signal_connect(G_OBJECT(c->web_view), "decide-policy",
180                      G_CALLBACK(decide_policy), NULL);
181     g_signal_connect(G_OBJECT(c->web_view), "key-press-event",
182                      G_CALLBACK(key_web_view), c);
183     g_signal_connect(G_OBJECT(c->web_view), "button-release-event",
184                      G_CALLBACK(key_web_view), c);
185     g_signal_connect(G_OBJECT(c->web_view), "scroll-event",
186                      G_CALLBACK(key_web_view), c);
187     g_signal_connect(G_OBJECT(c->web_view), "mouse-target-changed",
188                      G_CALLBACK(hover_web_view), c);
189     g_signal_connect(G_OBJECT(c->web_view), "web-process-crashed",
190                      G_CALLBACK(crashed_web_view), c);
191
192     if (cfg.user_agent != NULL) {
193         g_object_set(c->settings, "user-agent", cfg.user_agent, NULL);
194     }
195
196     if (cfg.enable_console_to_stdout)
197         webkit_settings_set_enable_write_console_messages_to_stdout(c->settings,
198                                                                     TRUE);
199
200     webkit_settings_set_enable_developer_extras(c->settings, TRUE);
201
202     GtkWidget *locbox = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 0);
203
204     c->jsbutton = gtk_toggle_button_new_with_label("JS");
205     gtk_widget_set_tooltip_text(c->jsbutton, "Toggle JavaScript execution");
206     gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(c->jsbutton),
207                                  !cfg.javascript_disabled);
208     g_signal_connect(G_OBJECT(c->jsbutton), "toggled", G_CALLBACK(togglejs), c);
209
210     c->imgbutton = gtk_toggle_button_new_with_label("IMG");
211     gtk_widget_set_tooltip_text(c->imgbutton, "Toggle image loading");
212     gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(c->imgbutton),
213                                  !cfg.images_disabled);
214     g_signal_connect(G_OBJECT(c->imgbutton), "toggled", G_CALLBACK(toggleimg),
215                      c);
216
217     c->location = gtk_entry_new();
218     gtk_box_pack_start(GTK_BOX(locbox), c->location, TRUE, TRUE, 0);
219
220     if (cfg.private) {
221         GtkWidget *privindicator = gtk_label_new("Private mode");
222         gtk_widget_set_tooltip_text(
223             privindicator, "You are in private mode. No history, caches, or "
224                            "cookies will be saved beyond this session.");
225         gtk_box_pack_end(GTK_BOX(locbox), privindicator, FALSE, FALSE, 5);
226     }
227
228     gtk_box_pack_start(GTK_BOX(locbox), c->jsbutton, FALSE, FALSE, 5);
229     gtk_box_pack_start(GTK_BOX(locbox), c->imgbutton, FALSE, FALSE, 0);
230
231     g_signal_connect(G_OBJECT(c->location), "key-press-event",
232                      G_CALLBACK(key_location), c);
233     g_signal_connect(G_OBJECT(c->location), "icon-release",
234                      G_CALLBACK(icon_location), c);
235     /* XXX This is a workaround. Setting this to NULL (which is done in
236      * grab_feeds_finished() if no feed has been detected) adds a little
237      * padding left of the text. Not sure why. The point of this call
238      * right here is to have that padding right from the start. This
239      * avoids a graphical artifact. */
240     gtk_entry_set_icon_from_icon_name(GTK_ENTRY(c->location),
241                                       GTK_ENTRY_ICON_SECONDARY, NULL);
242
243     c->vbox = gtk_box_new(GTK_ORIENTATION_VERTICAL, 0);
244     gtk_box_pack_start(GTK_BOX(c->vbox), locbox, FALSE, FALSE, 0);
245     gtk_box_pack_start(GTK_BOX(c->vbox), c->web_view, TRUE, TRUE, 0);
246     gtk_container_set_focus_child(GTK_CONTAINER(c->vbox), c->web_view);
247
248     c->tabicon =
249         gtk_image_new_from_icon_name("text-html", GTK_ICON_SIZE_SMALL_TOOLBAR);
250
251     c->tablabel = gtk_label_new(__NAME__);
252     gtk_label_set_ellipsize(GTK_LABEL(c->tablabel), PANGO_ELLIPSIZE_END);
253     gtk_label_set_width_chars(GTK_LABEL(c->tablabel), cfg.tab_width_chars);
254     gtk_widget_set_has_tooltip(c->tablabel, TRUE);
255
256     /* XXX I don't own a HiDPI screen, so I don't know if scale_factor
257      * does the right thing. */
258     tabbox = gtk_box_new(GTK_ORIENTATION_HORIZONTAL,
259                          5 * gtk_widget_get_scale_factor(mw.win));
260     gtk_box_pack_start(GTK_BOX(tabbox), c->tabicon, FALSE, FALSE, 0);
261     gtk_box_pack_start(GTK_BOX(tabbox), c->tablabel, TRUE, TRUE, 0);
262
263     evbox = gtk_event_box_new();
264     gtk_container_add(GTK_CONTAINER(evbox), tabbox);
265     g_signal_connect(G_OBJECT(evbox), "button-release-event",
266                      G_CALLBACK(key_tablabel), c);
267
268     gtk_widget_add_events(evbox, GDK_SCROLL_MASK);
269     g_signal_connect(G_OBJECT(evbox), "scroll-event", G_CALLBACK(key_tablabel),
270                      c);
271
272     // For easy access, store a reference to our label.
273     g_object_set_data(G_OBJECT(evbox), "chorizo-tab-label", c->tablabel);
274
275     /* This only shows the event box and the label inside, nothing else.
276      * Needed because the evbox/label is "internal" to the notebook and
277      * not part of the normal "widget tree" (IIUC). */
278     gtk_widget_show_all(evbox);
279
280     int page = gtk_notebook_get_current_page(GTK_NOTEBOOK(mw.notebook)) + 1;
281     gtk_notebook_insert_page(GTK_NOTEBOOK(mw.notebook), c->vbox, evbox, page);
282     gtk_notebook_set_tab_reorderable(GTK_NOTEBOOK(mw.notebook), c->vbox, TRUE);
283
284     if (show)
285         show_web_view(NULL, c);
286     else
287         g_signal_connect(G_OBJECT(c->web_view), "ready-to-show",
288                          G_CALLBACK(show_web_view), c);
289
290     if (uri != NULL) {
291         f = ensure_uri_scheme(uri);
292         webkit_web_view_load_uri(WEBKIT_WEB_VIEW(c->web_view), f);
293         g_free(f);
294     }
295
296     set_uri(uri, c);
297
298     clients++;
299     client_arr = realloc(client_arr, (clients + 1) * sizeof(client_arr[0]));
300     client_arr[clients] = c;
301
302     return WEBKIT_WEB_VIEW(c->web_view);
303 }
304
305 WebKitWebView *
306 client_new_request(WebKitWebView *web_view,
307                    WebKitNavigationAction *navigation_action, gpointer data) {
308     return client_new(NULL, web_view, FALSE, FALSE);
309 }
310
311 void
312 cooperation_setup(void) {
313     GIOChannel *towatch;
314     gchar *fifofilename, *fifopath;
315
316     gchar *priv = (cfg.private) ? "-private" : "";
317     fifofilename =
318         g_strdup_printf("%s%s%s-%s", __NAME__, priv, ".fifo", cfg.fifo_suffix);
319     fifopath = g_build_filename(g_get_user_runtime_dir(), fifofilename, NULL);
320     g_free(fifofilename);
321
322     if (!g_file_test(fifopath, G_FILE_TEST_EXISTS))
323         mkfifo(fifopath, 0600);
324
325     cooperative_pipe_fp = open(fifopath, O_WRONLY | O_NONBLOCK);
326     if (!cooperative_pipe_fp) {
327         fprintf(stderr, __NAME__ ": Can't open FIFO at all.\n");
328     } else {
329         if (write(cooperative_pipe_fp, "", 0) == -1) {
330             /* Could not do an empty write to the FIFO which means there's
331              * no one listening. */
332             close(cooperative_pipe_fp);
333             towatch = g_io_channel_new_file(fifopath, "r+", NULL);
334             g_io_add_watch(towatch, G_IO_IN, (GIOFunc)remote_msg, NULL);
335         } else {
336             cfg.cooperative_alone = FALSE;
337         }
338     }
339
340     g_free(fifopath);
341 }
342
343 void
344 changed_load_progress(GObject *obj, GParamSpec *pspec, gpointer data) {
345     struct Client *c = (struct Client *)data;
346     gdouble p;
347     gchar *grab_feeds =
348         "a = document.querySelectorAll('"
349         "    html > head > "
350         "link[rel=\"alternate\"][href][type=\"application/atom+xml\"],"
351         "    html > head > "
352         "link[rel=\"alternate\"][href][type=\"application/rss+xml\"]"
353         "');"
354         "if (a.length == 0)"
355         "    null;"
356         "else {"
357         "    out = '';"
358         "    for (i = 0; i < a.length; i++) {"
359         "        url = encodeURIComponent(a[i].href);"
360         "        if ('title' in a[i] && a[i].title != '')"
361         "            title = encodeURIComponent(a[i].title);"
362         "        else"
363         "            title = url;"
364         "        out += '<li><a href=\"' + url + '\">' + title + "
365         "'</a></li>';"
366         "    }"
367         "    out;"
368         "}";
369
370     p = webkit_web_view_get_estimated_load_progress(
371         WEBKIT_WEB_VIEW(c->web_view));
372     if (p == 1) {
373         p = 0;
374
375         /* The page has loaded fully. We now run the short JavaScript
376          * snippet above that operates on the DOM. It tries to grab all
377          * occurences of <link rel="alternate" ...>, i.e. RSS/Atom feed
378          * references. */
379         webkit_web_view_run_javascript(WEBKIT_WEB_VIEW(c->web_view), grab_feeds,
380                                        NULL, grab_feeds_finished, c);
381
382         run_user_scripts(WEBKIT_WEB_VIEW(c->web_view));
383     }
384     gtk_entry_set_progress_fraction(GTK_ENTRY(c->location), p);
385 }
386
387 void
388 changed_favicon(GObject *obj, GParamSpec *pspec, gpointer data) {
389     struct Client *c = (struct Client *)data;
390     cairo_surface_t *f;
391     int w, h, w_should, h_should;
392     GdkPixbuf *pb, *pb_scaled;
393
394     f = webkit_web_view_get_favicon(WEBKIT_WEB_VIEW(c->web_view));
395     if (f == NULL) {
396         gtk_image_set_from_icon_name(GTK_IMAGE(c->tabicon), "text-html",
397                                      GTK_ICON_SIZE_SMALL_TOOLBAR);
398     } else {
399         w = cairo_image_surface_get_width(f);
400         h = cairo_image_surface_get_height(f);
401         pb = gdk_pixbuf_get_from_surface(f, 0, 0, w, h);
402         if (pb != NULL) {
403             w_should = 16 * gtk_widget_get_scale_factor(c->tabicon);
404             h_should = 16 * gtk_widget_get_scale_factor(c->tabicon);
405             pb_scaled = gdk_pixbuf_scale_simple(pb, w_should, h_should,
406                                                 GDK_INTERP_BILINEAR);
407             gtk_image_set_from_pixbuf(GTK_IMAGE(c->tabicon), pb_scaled);
408
409             g_object_unref(pb_scaled);
410             g_object_unref(pb);
411         }
412     }
413 }
414
415 void
416 changed_title(GObject *obj, GParamSpec *pspec, gpointer data) {
417     const gchar *t, *u;
418     struct Client *c = (struct Client *)data;
419
420     u = webkit_web_view_get_uri(WEBKIT_WEB_VIEW(c->web_view));
421     t = webkit_web_view_get_title(WEBKIT_WEB_VIEW(c->web_view));
422
423     u = u == NULL ? __NAME__ : u;
424     u = u[0] == 0 ? __NAME__ : u;
425
426     t = t == NULL ? u : t;
427     t = t[0] == 0 ? u : t;
428
429     gchar *name = malloc(strlen(t) + 4);
430     gboolean mute = webkit_web_view_get_is_muted(WEBKIT_WEB_VIEW(c->web_view));
431     gchar *muted = (mute) ? "[m] " : "";
432     sprintf(name, "%s%s", muted, t);
433     gtk_label_set_text(GTK_LABEL(c->tablabel), name);
434     g_free(name);
435
436     gtk_widget_set_tooltip_text(c->tablabel, t);
437     mainwindow_title(gtk_notebook_get_current_page(GTK_NOTEBOOK(mw.notebook)));
438 }
439
440 void
441 changed_uri(GObject *obj, GParamSpec *pspec, gpointer data) {
442     const gchar *t;
443     struct Client *c = (struct Client *)data;
444     FILE *fp;
445
446     t = webkit_web_view_get_uri(WEBKIT_WEB_VIEW(c->web_view));
447
448     /* When a web process crashes, we get a "notify::uri" signal, but we
449      * can no longer read a meaningful URI. It's just an empty string
450      * now. Not updating the location bar in this scenario is important,
451      * because we would override the "WEB PROCESS CRASHED" message. */
452     if (t != NULL && strlen(t) > 0) {
453         set_uri(t, c);
454
455         if (cfg.history_file != NULL && !cfg.private) {
456             fp = fopen(cfg.history_file, "a");
457             if (fp != NULL) {
458                 fprintf(fp, "%s\n", t);
459                 fclose(fp);
460             } else {
461                 perror(__NAME__ ": Error opening history file");
462             }
463         }
464     }
465 }
466
467 gboolean
468 crashed_web_view(WebKitWebView *web_view, gpointer data) {
469     gchar *t;
470     struct Client *c = (struct Client *)data;
471
472     t = g_strdup_printf("WEB PROCESS CRASHED: %s",
473                         webkit_web_view_get_uri(WEBKIT_WEB_VIEW(web_view)));
474     gtk_entry_set_text(GTK_ENTRY(c->location), t);
475     g_free(t);
476
477     return TRUE;
478 }
479
480 gboolean
481 decide_policy(WebKitWebView *web_view, WebKitPolicyDecision *decision,
482               WebKitPolicyDecisionType type, gpointer data) {
483     WebKitResponsePolicyDecision *r;
484
485     switch (type) {
486     case WEBKIT_POLICY_DECISION_TYPE_RESPONSE:
487         r = WEBKIT_RESPONSE_POLICY_DECISION(decision);
488         if (!webkit_response_policy_decision_is_mime_type_supported(r))
489             webkit_policy_decision_download(decision);
490         else
491             webkit_policy_decision_use(decision);
492         break;
493     default:
494         // Use whatever default there is.
495         return FALSE;
496     }
497     return TRUE;
498 }
499
500 gchar *
501 ensure_uri_scheme(const gchar *t) {
502     gchar *f, *fabs;
503
504     f = g_ascii_strdown(t, -1);
505     if (!g_str_has_prefix(f, "http:") && !g_str_has_prefix(f, "https:") &&
506         !g_str_has_prefix(f, "file:") && !g_str_has_prefix(f, "about:") &&
507         !g_str_has_prefix(f, "data:") && !g_str_has_prefix(f, "webkit:")) {
508         g_free(f);
509         fabs = realpath(t, NULL);
510         if (fabs != NULL) {
511             f = g_strdup_printf("file://%s", fabs);
512             free(fabs);
513         } else {
514             f = g_strdup_printf("http://%s", t);
515         }
516         return f;
517     } else
518         return g_strdup(t);
519 }
520
521 void
522 get_config(void) {
523     cfg.accepted_language[0] = NULL;
524     cfg.accepted_language[1] = NULL;
525     cfg.cooperative_alone = TRUE;
526     cfg.cooperative_instances = TRUE;
527     cfg.fifo_suffix = "main";
528
529     const char *e = g_getenv(__NAME_UPPERCASE__ "_FIFO_SUFFIX");
530     if (e != NULL)
531         cfg.fifo_suffix = g_strdup(e);
532
533     char *xdg_down = getenv("XDG_DOWNLOAD_DIR");
534     cfg.download_dir = (xdg_down) ? xdg_down : "/var/tmp";
535
536     config = get_ini();
537     cfg.accepted_language[0] =
538         g_key_file_get_string(config, "browser", "accepted_language", NULL);
539     cfg.history_file =
540         g_key_file_get_string(config, "browser", "history_file", NULL);
541     cfg.home_uri = g_key_file_get_string(config, "browser", "homepage", NULL);
542     cfg.home_uri = (cfg.home_uri) ? cfg.home_uri : "about:blank";
543     cfg.enable_console_to_stdout =
544         g_key_file_get_boolean(config, "browser", "console_to_stdout", NULL);
545     cfg.user_agent =
546         g_key_file_get_string(config, "browser", "user_agent", NULL);
547     cfg.javascript_disabled =
548         g_key_file_get_boolean(config, "browser", "javascript_disabled", NULL);
549     cfg.images_disabled =
550         g_key_file_get_boolean(config, "browser", "images_disabled", NULL);
551     char *input_cookie_policy =
552         g_key_file_get_string(config, "browser", "cookie_policy", NULL);
553     cfg.cookie_policy = WEBKIT_COOKIE_POLICY_ACCEPT_NO_THIRD_PARTY;
554     if (input_cookie_policy) {
555         if (strcmp(input_cookie_policy, "all") == 0) {
556             cfg.cookie_policy = WEBKIT_COOKIE_POLICY_ACCEPT_ALWAYS;
557         } else if (strcmp(input_cookie_policy, "none") == 0) {
558             cfg.cookie_policy = WEBKIT_COOKIE_POLICY_ACCEPT_NEVER;
559         }
560     }
561
562     cfg.default_uri = g_key_file_get_string(config, "ui", "default_uri", NULL);
563     cfg.default_uri = (cfg.default_uri) ? cfg.default_uri : "https://";
564     cfg.tab_width_chars =
565         g_key_file_get_integer(config, "ui", "tab_width", NULL);
566     cfg.tab_width_chars = (cfg.tab_width_chars) ? cfg.tab_width_chars : 20;
567     cfg.global_zoom = g_key_file_get_double(config, "ui", "zoom_level", NULL);
568     cfg.global_zoom = (cfg.global_zoom) ? cfg.global_zoom : 1.0;
569     cfg.search_engine =
570         g_key_file_get_string(config, "ui", "search_engine", NULL);
571     cfg.search_engine =
572         (cfg.search_engine) ? cfg.search_engine : "https://duckduckgo.com?q=";
573     cfg.spellcheck_disabled =
574         g_key_file_get_boolean(config, "ui", "spellcheck_disabled", NULL);
575     cfg.spellcheck_language =
576         g_key_file_get_string(config, "ui", "spellcheck_language", NULL);
577     cfg.spellcheck_language =
578         (cfg.spellcheck_language) ? cfg.spellcheck_language : "en_US";
579     cfg.scroll_lines =
580         g_key_file_get_integer(config, "ui", "scroll_lines", NULL);
581     cfg.scroll_lines = (cfg.scroll_lines) ? cfg.scroll_lines : 3;
582 }
583
584 void
585 grab_feeds_finished(GObject *object, GAsyncResult *result, gpointer data) {
586     struct Client *c = (struct Client *)data;
587     WebKitJavascriptResult *js_result;
588     JSCValue *value;
589     JSCException *exception;
590     GError *err = NULL;
591     gchar *str_value;
592
593     g_free(c->feed_html);
594     c->feed_html = NULL;
595
596     /* This was taken almost verbatim from the example in WebKit's
597      * documentation:
598      *
599      * https://webkitgtk.org/reference/webkit2gtk/stable/WebKitWebView.html
600      */
601
602     js_result = webkit_web_view_run_javascript_finish(WEBKIT_WEB_VIEW(object),
603                                                       result, &err);
604     if (!js_result) {
605         fprintf(stderr, __NAME__ ": Error running javascript: %s\n",
606                 err->message);
607         g_error_free(err);
608         return;
609     }
610
611     value = webkit_javascript_result_get_js_value(js_result);
612     if (jsc_value_is_string(value)) {
613         str_value = jsc_value_to_string(value);
614         exception = jsc_context_get_exception(jsc_value_get_context(value));
615         if (exception != NULL) {
616             fprintf(stderr, __NAME__ ": Error running javascript: %s\n",
617                     jsc_exception_get_message(exception));
618         } else {
619             c->feed_html = str_value;
620         }
621
622         gtk_entry_set_icon_from_icon_name(GTK_ENTRY(c->location),
623                                           GTK_ENTRY_ICON_SECONDARY,
624                                           "application-rss+xml-symbolic");
625         gtk_entry_set_icon_activatable(GTK_ENTRY(c->location),
626                                        GTK_ENTRY_ICON_PRIMARY, TRUE);
627     } else {
628         gtk_entry_set_icon_from_icon_name(GTK_ENTRY(c->location),
629                                           GTK_ENTRY_ICON_SECONDARY, NULL);
630     }
631
632     webkit_javascript_result_unref(js_result);
633 }
634
635 void
636 hover_web_view(WebKitWebView *web_view, WebKitHitTestResult *ht,
637                guint modifiers, gpointer data) {
638     struct Client *c = (struct Client *)data;
639     const char *to_show;
640
641     g_free(c->hover_uri);
642
643     if (webkit_hit_test_result_context_is_link(ht)) {
644         to_show = webkit_hit_test_result_get_link_uri(ht);
645         c->hover_uri = g_strdup(to_show);
646     } else {
647         to_show = webkit_web_view_get_uri(WEBKIT_WEB_VIEW(c->web_view));
648         c->hover_uri = NULL;
649     }
650
651     if (!gtk_widget_is_focus(c->location))
652         set_uri(to_show, c);
653 }
654
655 void
656 icon_location(GtkEntry *entry, GtkEntryIconPosition icon_pos, GdkEvent *event,
657               gpointer data) {
658     struct Client *c = (struct Client *)data;
659     gchar *d;
660     gchar *data_template = "data:text/html,"
661                            "<!DOCTYPE html>"
662                            "<html>"
663                            "    <head>"
664                            "        <meta charset=\"UTF-8\">"
665                            "        <title>Feeds</title>"
666                            "    </head>"
667                            "    <body>"
668                            "        <p>Feeds found on this page:</p>"
669                            "        <ul>"
670                            "        %s"
671                            "        </ul>"
672                            "    </body>"
673                            "</html>";
674
675     if (c->feed_html != NULL) {
676         /* What we're actually trying to do is show a simple HTML page
677          * that lists all the feeds on the current page. The function
678          * webkit_web_view_load_html() looks like the proper way to do
679          * that. Sad thing is, it doesn't create a history entry, but
680          * instead simply replaces the content of the current page. This
681          * is not what we want.
682          *
683          * RFC 2397 [0] defines the data URI scheme [1]. We abuse this
684          * mechanism to show my custom HTML snippet *and* create a
685          * history entry.
686          *
687          * [0]: https://tools.ietf.org/html/rfc2397
688          * [1]: https://en.wikipedia.org/wiki/Data_URI_scheme */
689         d = g_strdup_printf(data_template, c->feed_html);
690         webkit_web_view_load_uri(WEBKIT_WEB_VIEW(c->web_view), d);
691         g_free(d);
692     }
693 }
694
695 void
696 init_default_web_context(void) {
697     gchar *p;
698     WebKitWebContext *wc;
699     WebKitCookieManager *cm;
700
701     wc = (cfg.private) ? webkit_web_context_new_ephemeral()
702                        : webkit_web_context_get_default();
703
704     p = g_build_filename(g_get_user_config_dir(), __NAME__, "adblock", NULL);
705     webkit_web_context_set_sandbox_enabled(wc, TRUE);
706     webkit_web_context_add_path_to_sandbox(wc, p, TRUE);
707     g_free(p);
708
709     WebKitProcessModel model =
710         WEBKIT_PROCESS_MODEL_MULTIPLE_SECONDARY_PROCESSES;
711     webkit_web_context_set_process_model(wc, model);
712
713     p = g_build_filename(g_get_user_data_dir(), __NAME__, "web_extensions",
714                          NULL);
715     webkit_web_context_set_web_extensions_directory(wc, p);
716     g_free(p);
717
718     if (cfg.accepted_language[0] != NULL)
719         webkit_web_context_set_preferred_languages(wc, cfg.accepted_language);
720
721     g_signal_connect(G_OBJECT(wc), "download-started",
722                      G_CALLBACK(download_start), &cfg);
723
724     trust_user_certs(wc);
725
726     cm = webkit_web_context_get_cookie_manager(wc);
727     webkit_cookie_manager_set_accept_policy(cm, cfg.cookie_policy);
728
729     if (!cfg.private) {
730         webkit_web_context_set_favicon_database_directory(wc, NULL);
731
732         gchar *fname = g_build_filename("/", g_get_user_data_dir(), __NAME__,
733                                         "cookies.db", NULL);
734         WebKitCookiePersistentStorage type =
735             WEBKIT_COOKIE_PERSISTENT_STORAGE_SQLITE;
736         webkit_cookie_manager_set_persistent_storage(cm, fname, type);
737         g_free(fname);
738     }
739
740     const gchar *const languages[2] = {(const gchar *)cfg.spellcheck_language,
741                                        NULL};
742     webkit_web_context_set_spell_checking_languages(wc, languages);
743     webkit_web_context_set_spell_checking_enabled(wc, !cfg.spellcheck_disabled);
744 }
745
746 void
747 search(gpointer data, gint direction) {
748     struct Client *c = (struct Client *)data;
749     WebKitWebView *web_view = WEBKIT_WEB_VIEW(c->web_view);
750     WebKitFindController *fc = webkit_web_view_get_find_controller(web_view);
751
752     if (search_text == NULL)
753         return;
754
755     switch (direction) {
756     case 0:
757         webkit_find_controller_search(fc, search_text,
758                                       WEBKIT_FIND_OPTIONS_CASE_INSENSITIVE |
759                                           WEBKIT_FIND_OPTIONS_WRAP_AROUND,
760                                       G_MAXUINT);
761         break;
762     case 1:
763         webkit_find_controller_search_next(fc);
764         break;
765     case -1:
766         webkit_find_controller_search_previous(fc);
767         break;
768     case 2:
769         webkit_find_controller_search_finish(fc);
770         break;
771     }
772 }
773
774 void
775 search_init(struct Client *c, int direction) {
776     gtk_widget_grab_focus(c->location);
777     const gchar *contents = gtk_entry_get_text(GTK_ENTRY(c->location));
778     if (strcspn(contents, "s/")) {
779         gtk_entry_set_text(GTK_ENTRY(c->location), "s/");
780     }
781     gtk_editable_set_position(GTK_EDITABLE(c->location), -1);
782     search(c, 0);
783     search(c, -1);
784     search(c, direction);
785 }
786
787 int
788 def_key(char *key, unsigned int def) {
789     char *conf = g_key_file_get_string(config, "keybindings", key, NULL);
790     return (conf) ? gdk_keyval_from_name((conf) ? conf : NULL) : def;
791 }
792
793 gboolean
794 key_common(GtkWidget *widget, GdkEvent *event, gpointer data) {
795     struct Client *c = (struct Client *)data;
796     gdouble now;
797     gchar *f;
798
799     if (event->type == GDK_KEY_PRESS) {
800         if (((GdkEventKey *)event)->state & GDK_CONTROL_MASK) {
801             const char *uri =
802                 webkit_web_view_get_uri(WEBKIT_WEB_VIEW(c->web_view));
803             int key = ((GdkEventKey *)event)->keyval;
804             if (def_key("download_manager", GDK_KEY_y) == key) {
805                 downloadmanager_show();
806                 return TRUE;
807             } else if (def_key("history_back", GDK_KEY_h) == key) {
808                 webkit_web_view_go_back(WEBKIT_WEB_VIEW(c->web_view));
809                 return TRUE;
810             } else if (def_key("history_forwards", GDK_KEY_l) == key) {
811                 webkit_web_view_go_forward(WEBKIT_WEB_VIEW(c->web_view));
812                 return TRUE;
813             } else if (def_key("location", GDK_KEY_t) == key) {
814                 gtk_widget_grab_focus(c->location);
815                 const char *goal = (strcmp(cfg.home_uri, uri) == 0 || !uri)
816                                        ? cfg.default_uri
817                                        : uri;
818                 gtk_entry_set_text(GTK_ENTRY(c->location), goal);
819                 gtk_editable_set_position(GTK_EDITABLE(c->location), -1);
820                 return TRUE;
821             } else if (def_key("print", GDK_KEY_Print) == key) {
822                 WebKitPrintOperation *operation =
823                     webkit_print_operation_new(WEBKIT_WEB_VIEW(c->web_view));
824                 GtkWidget *toplevel = gtk_widget_get_toplevel(mw.win);
825                 webkit_print_operation_run_dialog(operation,
826                                                   GTK_WINDOW(toplevel));
827                 return TRUE;
828             } else if (def_key("quit", GDK_KEY_g) == key) {
829                 search(c, 2);
830                 gtk_widget_grab_focus(c->web_view);
831                 gtk_entry_set_text(GTK_ENTRY(c->location), uri);
832                 gtk_editable_set_position(GTK_EDITABLE(c->location), -1);
833                 webkit_web_view_run_javascript(
834                     WEBKIT_WEB_VIEW(c->web_view),
835                     "window.getSelection().removeAllRanges();"
836                     "document.activeElement.blur();",
837                     NULL, NULL, c);
838                 return TRUE;
839             } else if (def_key("reload", GDK_KEY_e) == key) {
840                 webkit_web_view_reload_bypass_cache(
841                     WEBKIT_WEB_VIEW(c->web_view));
842                 return TRUE;
843             } else if (def_key("scroll_line_down", GDK_KEY_j) == key) {
844                 for (int i = 0; i <= cfg.scroll_lines - 1; i++) {
845                     event->key.keyval = GDK_KEY_Down;
846                     gdk_event_put(event);
847                 }
848                 return TRUE;
849             } else if (def_key("scroll_line_up", GDK_KEY_k) == key) {
850                 for (int i = 0; i <= cfg.scroll_lines - 1; i++) {
851                     event->key.keyval = GDK_KEY_Up;
852                     gdk_event_put(event);
853                 }
854                 return TRUE;
855             } else if (def_key("scroll_page_down", GDK_KEY_f) == key) {
856                 event->key.keyval = GDK_KEY_Page_Down;
857                 gdk_event_put(event);
858                 return TRUE;
859             } else if (def_key("scroll_page_up", GDK_KEY_b) == key) {
860                 event->key.keyval = GDK_KEY_Page_Up;
861                 gdk_event_put(event);
862                 return TRUE;
863             } else if (def_key("search_forwards", GDK_KEY_s) == key) {
864                 search_init(c, 1);
865                 return TRUE;
866             } else if (def_key("search_backwards", GDK_KEY_r) == key) {
867                 search_init(c, -1);
868                 return TRUE;
869             } else if (def_key("tab_close", GDK_KEY_q) == key) {
870                 client_destroy(NULL, c);
871                 return TRUE;
872             } else if (def_key("tab_switch_1", GDK_KEY_1) == key) {
873                 gtk_notebook_set_current_page(GTK_NOTEBOOK(mw.notebook), 0);
874                 return TRUE;
875             } else if (def_key("tab_switch_2", GDK_KEY_2) == key) {
876                 gtk_notebook_set_current_page(GTK_NOTEBOOK(mw.notebook), 1);
877                 return TRUE;
878             } else if (def_key("tab_switch_3", GDK_KEY_3) == key) {
879                 gtk_notebook_set_current_page(GTK_NOTEBOOK(mw.notebook), 2);
880                 return TRUE;
881             } else if (def_key("tab_switch_4", GDK_KEY_4) == key) {
882                 gtk_notebook_set_current_page(GTK_NOTEBOOK(mw.notebook), 3);
883                 return TRUE;
884             } else if (def_key("tab_switch_5", GDK_KEY_5) == key) {
885                 gtk_notebook_set_current_page(GTK_NOTEBOOK(mw.notebook), 4);
886                 return TRUE;
887             } else if (def_key("tab_switch_6", GDK_KEY_6) == key) {
888                 gtk_notebook_set_current_page(GTK_NOTEBOOK(mw.notebook), 5);
889                 return TRUE;
890             } else if (def_key("tab_switch_7", GDK_KEY_7) == key) {
891                 gtk_notebook_set_current_page(GTK_NOTEBOOK(mw.notebook), 6);
892                 return TRUE;
893             } else if (def_key("tab_switch_8", GDK_KEY_8) == key) {
894                 gtk_notebook_set_current_page(GTK_NOTEBOOK(mw.notebook), 7);
895                 return TRUE;
896             } else if (def_key("tab_switch_9", GDK_KEY_9) == key) {
897                 gtk_notebook_set_current_page(GTK_NOTEBOOK(mw.notebook), 8);
898                 return TRUE;
899             } else if (def_key("tab_previous", GDK_KEY_u) == key) {
900                 gtk_notebook_prev_page(GTK_NOTEBOOK(mw.notebook));
901                 return TRUE;
902             } else if (def_key("tab_mute", GDK_KEY_m) == key) {
903                 gboolean muted =
904                     webkit_web_view_get_is_muted(WEBKIT_WEB_VIEW(c->web_view));
905                 webkit_web_view_set_is_muted(WEBKIT_WEB_VIEW(c->web_view),
906                                              !muted);
907                 changed_title(G_OBJECT(c->web_view), NULL, c);
908                 return TRUE;
909             } else if (def_key("tab_new", GDK_KEY_w) == key) {
910                 f = ensure_uri_scheme(cfg.home_uri);
911                 client_new(f, NULL, TRUE, TRUE);
912                 g_free(f);
913                 return TRUE;
914             } else if (def_key("tab_next", GDK_KEY_i) == key) {
915                 gtk_notebook_next_page(GTK_NOTEBOOK(mw.notebook));
916                 return TRUE;
917             } else if (def_key("toggle_js", GDK_KEY_o) == key) {
918                 gboolean on =
919                     webkit_settings_get_enable_javascript(c->settings);
920                 webkit_settings_set_enable_javascript(c->settings, !on);
921                 webkit_web_view_set_settings(WEBKIT_WEB_VIEW(c->web_view),
922                                              c->settings);
923                 gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(c->jsbutton),
924                                              !on);
925             } else if (def_key("toggle_img", -1) == key) {
926                 gboolean on = webkit_settings_get_auto_load_images(c->settings);
927                 webkit_settings_set_auto_load_images(c->settings, !on);
928                 webkit_web_view_set_settings(WEBKIT_WEB_VIEW(c->web_view),
929                                              c->settings);
930                 gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(c->imgbutton),
931                                              !on);
932             } else if (def_key("web_search", GDK_KEY_d) == key) {
933                 gtk_widget_grab_focus(c->location);
934                 gtk_entry_set_text(GTK_ENTRY(c->location), "w/");
935                 gtk_editable_set_position(GTK_EDITABLE(c->location), -1);
936                 return TRUE;
937             } else if (def_key("zoom_in", GDK_KEY_equal) == key) {
938                 now = webkit_web_view_get_zoom_level(
939                     WEBKIT_WEB_VIEW(c->web_view));
940                 webkit_web_view_set_zoom_level(WEBKIT_WEB_VIEW(c->web_view),
941                                                now + 0.1);
942                 return TRUE;
943             } else if (def_key("zoom_out", GDK_KEY_minus) == key) {
944                 now = webkit_web_view_get_zoom_level(
945                     WEBKIT_WEB_VIEW(c->web_view));
946                 webkit_web_view_set_zoom_level(WEBKIT_WEB_VIEW(c->web_view),
947                                                now - 0.1);
948                 return TRUE;
949             } else if (def_key("zoom_reset", GDK_KEY_0) == key) {
950                 webkit_web_view_set_zoom_level(WEBKIT_WEB_VIEW(c->web_view),
951                                                cfg.global_zoom);
952                 return TRUE;
953             }
954         }
955     }
956     return FALSE;
957 }
958
959 gboolean
960 key_location(GtkWidget *widget, GdkEvent *event, gpointer data) {
961     struct Client *c = (struct Client *)data;
962     const gchar *t;
963     gchar *f;
964
965     if (key_common(widget, event, data))
966         return TRUE;
967
968     if (event->type == GDK_KEY_PRESS) {
969         int key = ((GdkEventKey *)event)->keyval;
970         if ((GDK_KEY_KP_Enter == key) || (GDK_KEY_Return == key)) {
971             gtk_widget_grab_focus(c->web_view);
972             t = gtk_entry_get_text(GTK_ENTRY(c->location));
973             if (t != NULL && t[0] == 's' && t[1] == '/') {
974                 if (search_text != NULL)
975                     g_free(search_text);
976                 search_text = g_strdup(t + 2);
977                 search(c, 0);
978             } else if (t != NULL && t[0] == 'w' && t[1] == '/') {
979                 int len = strlen(cfg.search_engine) + strlen(t) - 2;
980                 gchar *f = malloc(len + 1);
981                 snprintf(f, len + 1, "%s%s", cfg.search_engine, t + 2);
982                 webkit_web_view_load_uri(WEBKIT_WEB_VIEW(c->web_view), f);
983                 g_free(f);
984             } else {
985                 f = ensure_uri_scheme(t);
986                 webkit_web_view_load_uri(WEBKIT_WEB_VIEW(c->web_view), f);
987                 g_free(f);
988             }
989             return TRUE;
990         } else if (GDK_KEY_Escape == key) {
991             t = webkit_web_view_get_uri(WEBKIT_WEB_VIEW(c->web_view));
992             gtk_entry_set_text(GTK_ENTRY(c->location), (t == NULL) ? "" : t);
993             return TRUE;
994         }
995     }
996     return FALSE;
997 }
998
999 gboolean
1000 key_tablabel(GtkWidget *widget, GdkEvent *event, gpointer data) {
1001     GdkScrollDirection direction;
1002
1003     if (event->type == GDK_BUTTON_RELEASE) {
1004         switch (((GdkEventButton *)event)->button) {
1005         case 2:
1006             client_destroy(NULL, data);
1007             return TRUE;
1008         }
1009     } else if (event->type == GDK_SCROLL) {
1010         gdk_event_get_scroll_direction(event, &direction);
1011         switch (direction) {
1012         case GDK_SCROLL_UP:
1013             gtk_notebook_prev_page(GTK_NOTEBOOK(mw.notebook));
1014             break;
1015         case GDK_SCROLL_DOWN:
1016             gtk_notebook_next_page(GTK_NOTEBOOK(mw.notebook));
1017             break;
1018         default:
1019             break;
1020         }
1021         return TRUE;
1022     }
1023     return FALSE;
1024 }
1025
1026 gboolean
1027 key_web_view(GtkWidget *widget, GdkEvent *event, gpointer data) {
1028     struct Client *c = (struct Client *)data;
1029     gdouble dx, dy;
1030     gfloat z;
1031
1032     if (key_common(widget, event, data))
1033         return TRUE;
1034
1035     if (event->type == GDK_KEY_PRESS) {
1036         if (((GdkEventKey *)event)->keyval == GDK_KEY_Escape) {
1037             webkit_web_view_stop_loading(WEBKIT_WEB_VIEW(c->web_view));
1038             gtk_entry_set_progress_fraction(GTK_ENTRY(c->location), 0);
1039         }
1040     } else if (event->type == GDK_BUTTON_RELEASE) {
1041         switch (((GdkEventButton *)event)->button) {
1042         case 2:
1043             if (c->hover_uri != NULL) {
1044                 client_new(c->hover_uri, NULL, TRUE, FALSE);
1045                 return TRUE;
1046             }
1047             break;
1048         case 8:
1049             webkit_web_view_go_back(WEBKIT_WEB_VIEW(c->web_view));
1050             return TRUE;
1051         case 9:
1052             webkit_web_view_go_forward(WEBKIT_WEB_VIEW(c->web_view));
1053             return TRUE;
1054         }
1055     } else if (event->type == GDK_SCROLL) {
1056         event->scroll.delta_y *= cfg.scroll_lines;
1057         if (((GdkEventScroll *)event)->state & GDK_CONTROL_MASK) {
1058             gdk_event_get_scroll_deltas(event, &dx, &dy);
1059             z = webkit_web_view_get_zoom_level(WEBKIT_WEB_VIEW(c->web_view));
1060             z += -dy * 0.1;
1061             z = dx != 0 ? cfg.global_zoom : z;
1062             webkit_web_view_set_zoom_level(WEBKIT_WEB_VIEW(c->web_view), z);
1063             return TRUE;
1064         }
1065     }
1066
1067     return FALSE;
1068 }
1069
1070 void
1071 mainwindow_setup(void) {
1072     mw.win = gtk_window_new(GTK_WINDOW_TOPLEVEL);
1073     gtk_window_set_default_size(GTK_WINDOW(mw.win), 800, 600);
1074     g_signal_connect(G_OBJECT(mw.win), "destroy", gtk_main_quit, NULL);
1075
1076     gchar *priv = (cfg.private) ? "-private" : "";
1077     gchar *title = malloc(strlen(priv) + strlen(__NAME__) + 1);
1078     sprintf(title, "%s%s", __NAME__, priv);
1079     gtk_window_set_title(GTK_WINDOW(mw.win), title);
1080     g_free(title);
1081
1082     mw.notebook = gtk_notebook_new();
1083     gtk_notebook_set_scrollable(GTK_NOTEBOOK(mw.notebook), TRUE);
1084     gtk_container_add(GTK_CONTAINER(mw.win), mw.notebook);
1085     g_signal_connect(G_OBJECT(mw.notebook), "switch-page",
1086                      G_CALLBACK(notebook_switch_page), NULL);
1087 }
1088
1089 void
1090 mainwindow_title(gint idx) {
1091     GtkWidget *child, *widg, *tablabel;
1092     const gchar *text;
1093
1094     child = gtk_notebook_get_nth_page(GTK_NOTEBOOK(mw.notebook), idx);
1095     if (child == NULL)
1096         return;
1097
1098     widg = gtk_notebook_get_tab_label(GTK_NOTEBOOK(mw.notebook), child);
1099     tablabel =
1100         (GtkWidget *)g_object_get_data(G_OBJECT(widg), "chorizo-tab-label");
1101     text = gtk_label_get_text(GTK_LABEL(tablabel));
1102     gtk_window_set_title(GTK_WINDOW(mw.win), text);
1103 }
1104
1105 void
1106 notebook_switch_page(GtkNotebook *nb, GtkWidget *p, guint idx, gpointer data) {
1107     mainwindow_title(idx);
1108 }
1109
1110 gboolean
1111 quit_if_nothing_active(void) {
1112     if (clients == 0) {
1113         if (downloads == 0) {
1114             gtk_main_quit();
1115             return TRUE;
1116         } else {
1117             downloadmanager_show();
1118         }
1119     }
1120
1121     return FALSE;
1122 }
1123
1124 gboolean
1125 remote_msg(GIOChannel *channel, GIOCondition condition, gpointer data) {
1126     gchar *uri = NULL;
1127
1128     g_io_channel_read_line(channel, &uri, NULL, NULL, NULL);
1129     if (uri) {
1130         g_strstrip(uri);
1131         client_new(uri, NULL, TRUE, TRUE);
1132         g_free(uri);
1133     }
1134     return TRUE;
1135 }
1136
1137 void
1138 run_user_scripts(WebKitWebView *web_view) {
1139     gchar *base = NULL, *path = NULL, *contents = NULL;
1140     const gchar *entry = NULL;
1141     GDir *scriptdir = NULL;
1142
1143     base =
1144         g_build_filename(g_get_user_data_dir(), __NAME__, "user-scripts", NULL);
1145     scriptdir = g_dir_open(base, 0, NULL);
1146     if (scriptdir != NULL) {
1147         while ((entry = g_dir_read_name(scriptdir)) != NULL) {
1148             path = g_build_filename(base, entry, NULL);
1149             char *jscmd = malloc(strlen(path) + 36);
1150             sprintf(jscmd, "console.log(\"Running userscript %s\");", path);
1151             if (g_str_has_suffix(path, ".js")) {
1152                 if (g_file_get_contents(path, &contents, NULL, NULL)) {
1153                     webkit_web_view_run_javascript(web_view, jscmd, NULL, NULL,
1154                                                    NULL);
1155                     webkit_web_view_run_javascript(web_view, contents, NULL,
1156                                                    NULL, NULL);
1157                     g_free(contents);
1158                     g_free(jscmd);
1159                 }
1160             }
1161             g_free(path);
1162         }
1163         g_dir_close(scriptdir);
1164     }
1165
1166     g_free(base);
1167 }
1168
1169 void
1170 show_web_view(WebKitWebView *web_view, gpointer data) {
1171     struct Client *c = (struct Client *)data;
1172     gint idx;
1173
1174     (void)web_view;
1175
1176     gtk_widget_show_all(mw.win);
1177
1178     if (c->focus_new_tab) {
1179         idx = gtk_notebook_page_num(GTK_NOTEBOOK(mw.notebook), c->vbox);
1180         if (idx != -1)
1181             gtk_notebook_set_current_page(GTK_NOTEBOOK(mw.notebook), idx);
1182
1183         gtk_widget_grab_focus(c->web_view);
1184     }
1185 }
1186
1187 void
1188 trust_user_certs(WebKitWebContext *wc) {
1189     GTlsCertificate *cert;
1190     gchar *basedir, *absfile;
1191     const gchar *file;
1192     GDir *dir;
1193
1194     basedir = g_build_filename(g_get_user_data_dir(), __NAME__, "certs", NULL);
1195     dir = g_dir_open(basedir, 0, NULL);
1196     g_free(basedir);
1197     if (dir != NULL) {
1198         file = g_dir_read_name(dir);
1199         while (file != NULL) {
1200             absfile = g_build_filename(g_get_user_data_dir(), __NAME__, "certs",
1201                                        file, NULL);
1202             cert = g_tls_certificate_new_from_file(absfile, NULL);
1203             g_free(absfile);
1204             if (cert == NULL)
1205                 fprintf(stderr, __NAME__ ": Could not load trusted cert '%s'\n",
1206                         file);
1207             else
1208                 webkit_web_context_allow_tls_certificate_for_host(wc, cert,
1209                                                                   file);
1210             file = g_dir_read_name(dir);
1211         }
1212         g_dir_close(dir);
1213     }
1214 }
1215
1216 GKeyFile *
1217 get_ini(void) {
1218     GKeyFileFlags flags = G_KEY_FILE_NONE;
1219     config = g_key_file_new();
1220
1221     // Load user config
1222     gchar *fname = g_build_filename(g_get_user_config_dir(), __NAME__,
1223                                     "chorizo.ini", NULL);
1224     if (!g_key_file_load_from_file(config, fname, flags, NULL)) {
1225         // Load global config
1226         if (!g_key_file_load_from_file(config, "/etc/chorizo.ini", flags,
1227                                        NULL)) {
1228             fprintf(stderr, "Could not load chorizo.ini");
1229         }
1230     }
1231     g_free(fname);
1232     return config;
1233 }
1234
1235 int
1236 main(int argc, char **argv) {
1237     int opt, i;
1238
1239     while ((opt = getopt(argc, argv, "Cpv")) != -1) {
1240         switch (opt) {
1241         case 'C':
1242             cfg.cooperative_instances = FALSE;
1243             break;
1244         case 'p':
1245             cfg.private = true;
1246             break;
1247         case 'v':
1248             printf("%s %s\n", __NAME__, VERSION);
1249             exit(0);
1250         default:
1251             fprintf(stderr, "Usage: " __NAME__ " [OPTION]... [URI]...\n");
1252             exit(EXIT_FAILURE);
1253         }
1254     }
1255
1256     gtk_init(&argc, &argv);
1257     get_config();
1258
1259     if (cfg.cooperative_instances)
1260         cooperation_setup();
1261
1262     if (!cfg.cooperative_instances || cfg.cooperative_alone)
1263         init_default_web_context();
1264
1265     downloadmanager_setup();
1266     mainwindow_setup();
1267
1268     client_arr = malloc(sizeof(struct Client *));
1269     if (optind >= argc) {
1270         client_new(cfg.home_uri, NULL, TRUE, TRUE);
1271     } else {
1272         for (i = optind; i < argc; i++)
1273             client_new(argv[i], NULL, TRUE, TRUE);
1274     }
1275
1276     if (!cfg.cooperative_instances || cfg.cooperative_alone)
1277         gtk_main();
1278
1279     for (int i = 0; i < clients; i++) {
1280         free(&(client_arr[i]));
1281     }
1282
1283     exit(EXIT_SUCCESS);
1284 }