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