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