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