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