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