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