]> git.armaanb.net Git - chorizo.git/blob - src/browser.c
Don't automatically search forwards
[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         gtk_editable_set_position(GTK_EDITABLE(c->location), -1);
864     } else {
865         search(c, 0);
866         search(c, -1);
867         search(c, direction);
868     }
869 }
870
871 int
872 def_key(char *key, unsigned int def) {
873     char *conf = g_key_file_get_string(config, "keybindings", key, NULL);
874     return (conf) ? gdk_keyval_from_name((conf) ? conf : NULL) : def;
875 }
876
877 gboolean
878 key_common(GtkWidget *widget, GdkEvent *event, gpointer data) {
879     struct Client *c = (struct Client *)data;
880     gdouble now;
881     gchar *f;
882
883     if (event->type == GDK_KEY_PRESS) {
884         if (((GdkEventKey *)event)->state & GDK_CONTROL_MASK) {
885             const char *uri =
886                 webkit_web_view_get_uri(WEBKIT_WEB_VIEW(c->web_view));
887             int key = ((GdkEventKey *)event)->keyval;
888             if (def_key("download_manager", GDK_KEY_y) == key) {
889                 downloadmanager_show();
890                 return TRUE;
891             } else if (def_key("history_back", GDK_KEY_h) == key) {
892                 webkit_web_view_go_back(WEBKIT_WEB_VIEW(c->web_view));
893                 return TRUE;
894             } else if (def_key("history_forwards", GDK_KEY_l) == key) {
895                 webkit_web_view_go_forward(WEBKIT_WEB_VIEW(c->web_view));
896                 return TRUE;
897             } else if (def_key("location", GDK_KEY_t) == key) {
898                 gtk_widget_grab_focus(c->location);
899                 const char *goal = (strcmp(cfg.home_uri, uri) == 0 || !uri)
900                                        ? cfg.default_uri
901                                        : uri;
902                 gtk_entry_set_text(GTK_ENTRY(c->location), goal);
903                 gtk_editable_set_position(GTK_EDITABLE(c->location), -1);
904                 return TRUE;
905             } else if (def_key("print", GDK_KEY_Print) == key) {
906                 WebKitPrintOperation *operation =
907                     webkit_print_operation_new(WEBKIT_WEB_VIEW(c->web_view));
908                 GtkWidget *toplevel = gtk_widget_get_toplevel(mw.win);
909                 webkit_print_operation_run_dialog(operation,
910                                                   GTK_WINDOW(toplevel));
911                 return TRUE;
912             } else if (def_key("quit", GDK_KEY_g) == key) {
913                 search(c, 2);
914                 gtk_widget_grab_focus(c->web_view);
915                 gtk_entry_set_text(GTK_ENTRY(c->location), uri);
916                 gtk_editable_set_position(GTK_EDITABLE(c->location), -1);
917                 webkit_web_view_run_javascript(
918                     WEBKIT_WEB_VIEW(c->web_view),
919                     "window.getSelection().removeAllRanges();"
920                     "document.activeElement.blur();",
921                     NULL, NULL, c);
922                 return TRUE;
923             } else if (def_key("reload", GDK_KEY_e) == key) {
924                 webkit_web_view_reload_bypass_cache(
925                     WEBKIT_WEB_VIEW(c->web_view));
926                 return TRUE;
927             } else if (def_key("scroll_line_down", GDK_KEY_j) == key) {
928                 for (int i = 0; i <= cfg.scroll_lines - 1; i++) {
929                     event->key.keyval = GDK_KEY_Down;
930                     gdk_event_put(event);
931                 }
932                 return TRUE;
933             } else if (def_key("scroll_line_up", GDK_KEY_k) == key) {
934                 for (int i = 0; i <= cfg.scroll_lines - 1; i++) {
935                     event->key.keyval = GDK_KEY_Up;
936                     gdk_event_put(event);
937                 }
938                 return TRUE;
939             } else if (def_key("scroll_page_down", GDK_KEY_f) == key) {
940                 event->key.keyval = GDK_KEY_Page_Down;
941                 gdk_event_put(event);
942                 return TRUE;
943             } else if (def_key("scroll_page_up", GDK_KEY_b) == key) {
944                 event->key.keyval = GDK_KEY_Page_Up;
945                 gdk_event_put(event);
946                 return TRUE;
947             } else if (def_key("search_forwards", GDK_KEY_s) == key) {
948                 search_init(c, 1);
949                 return TRUE;
950             } else if (def_key("search_backwards", GDK_KEY_r) == key) {
951                 search_init(c, -1);
952                 return TRUE;
953             } else if (def_key("tab_close", GDK_KEY_q) == key) {
954                 client_destroy(NULL, c);
955                 return TRUE;
956             } else if (def_key("tab_switch_1", GDK_KEY_1) == key) {
957                 gtk_notebook_set_current_page(GTK_NOTEBOOK(mw.notebook), 0);
958                 return TRUE;
959             } else if (def_key("tab_switch_2", GDK_KEY_2) == key) {
960                 gtk_notebook_set_current_page(GTK_NOTEBOOK(mw.notebook), 1);
961                 return TRUE;
962             } else if (def_key("tab_switch_3", GDK_KEY_3) == key) {
963                 gtk_notebook_set_current_page(GTK_NOTEBOOK(mw.notebook), 2);
964                 return TRUE;
965             } else if (def_key("tab_switch_4", GDK_KEY_4) == key) {
966                 gtk_notebook_set_current_page(GTK_NOTEBOOK(mw.notebook), 3);
967                 return TRUE;
968             } else if (def_key("tab_switch_5", GDK_KEY_5) == key) {
969                 gtk_notebook_set_current_page(GTK_NOTEBOOK(mw.notebook), 4);
970                 return TRUE;
971             } else if (def_key("tab_switch_6", GDK_KEY_6) == key) {
972                 gtk_notebook_set_current_page(GTK_NOTEBOOK(mw.notebook), 5);
973                 return TRUE;
974             } else if (def_key("tab_switch_7", GDK_KEY_7) == key) {
975                 gtk_notebook_set_current_page(GTK_NOTEBOOK(mw.notebook), 6);
976                 return TRUE;
977             } else if (def_key("tab_switch_8", GDK_KEY_8) == key) {
978                 gtk_notebook_set_current_page(GTK_NOTEBOOK(mw.notebook), 7);
979                 return TRUE;
980             } else if (def_key("tab_switch_9", GDK_KEY_9) == key) {
981                 gtk_notebook_set_current_page(GTK_NOTEBOOK(mw.notebook), 8);
982                 return TRUE;
983             } else if (def_key("tab_previous", GDK_KEY_u) == key) {
984                 gtk_notebook_prev_page(GTK_NOTEBOOK(mw.notebook));
985                 return TRUE;
986             } else if (def_key("tab_mute", GDK_KEY_m) == key) {
987                 gboolean muted =
988                     webkit_web_view_get_is_muted(WEBKIT_WEB_VIEW(c->web_view));
989                 webkit_web_view_set_is_muted(WEBKIT_WEB_VIEW(c->web_view),
990                                              !muted);
991                 changed_title(G_OBJECT(c->web_view), NULL, c);
992                 return TRUE;
993             } else if (def_key("tab_new", GDK_KEY_w) == key) {
994                 f = ensure_uri_scheme(cfg.home_uri);
995                 client_new(f, NULL, TRUE, TRUE);
996                 g_free(f);
997                 return TRUE;
998             } else if (def_key("tab_next", GDK_KEY_i) == key) {
999                 gtk_notebook_next_page(GTK_NOTEBOOK(mw.notebook));
1000                 return TRUE;
1001             } else if (def_key("toggle_js", GDK_KEY_o) == key) {
1002                 gboolean on =
1003                     webkit_settings_get_enable_javascript(c->settings);
1004                 webkit_settings_set_enable_javascript(c->settings, !on);
1005                 webkit_web_view_set_settings(WEBKIT_WEB_VIEW(c->web_view),
1006                                              c->settings);
1007                 gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(c->jsbutton),
1008                                              !on);
1009             } else if (def_key("toggle_img", -1) == key) {
1010                 gboolean on = webkit_settings_get_auto_load_images(c->settings);
1011                 webkit_settings_set_auto_load_images(c->settings, !on);
1012                 webkit_web_view_set_settings(WEBKIT_WEB_VIEW(c->web_view),
1013                                              c->settings);
1014                 gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(c->imgbutton),
1015                                              !on);
1016             } else if (def_key("web_search", GDK_KEY_d) == key) {
1017                 gtk_widget_grab_focus(c->location);
1018                 gtk_entry_set_text(GTK_ENTRY(c->location), "w/");
1019                 gtk_editable_set_position(GTK_EDITABLE(c->location), -1);
1020                 return TRUE;
1021             } else if (def_key("zoom_in", GDK_KEY_equal) == key) {
1022                 now = webkit_web_view_get_zoom_level(
1023                     WEBKIT_WEB_VIEW(c->web_view));
1024                 webkit_web_view_set_zoom_level(WEBKIT_WEB_VIEW(c->web_view),
1025                                                now + 0.1);
1026                 return TRUE;
1027             } else if (def_key("zoom_out", GDK_KEY_minus) == key) {
1028                 now = webkit_web_view_get_zoom_level(
1029                     WEBKIT_WEB_VIEW(c->web_view));
1030                 webkit_web_view_set_zoom_level(WEBKIT_WEB_VIEW(c->web_view),
1031                                                now - 0.1);
1032                 return TRUE;
1033             } else if (def_key("zoom_reset", GDK_KEY_0) == key) {
1034                 webkit_web_view_set_zoom_level(WEBKIT_WEB_VIEW(c->web_view),
1035                                                cfg.zoom_level);
1036                 return TRUE;
1037             }
1038         }
1039     }
1040     return FALSE;
1041 }
1042
1043 gboolean
1044 key_location(GtkWidget *widget, GdkEvent *event, gpointer data) {
1045     struct Client *c = (struct Client *)data;
1046     const gchar *t;
1047     gchar *f;
1048
1049     if (key_common(widget, event, data))
1050         return TRUE;
1051
1052     if (event->type == GDK_KEY_PRESS) {
1053         int key = ((GdkEventKey *)event)->keyval;
1054         if ((GDK_KEY_KP_Enter == key) || (GDK_KEY_Return == key)) {
1055             gtk_widget_grab_focus(c->web_view);
1056             t = gtk_entry_get_text(GTK_ENTRY(c->location));
1057             if (t != NULL && t[0] == 's' && t[1] == '/') {
1058                 if (search_text != NULL)
1059                     g_free(search_text);
1060                 search_text = g_strdup(t + 2);
1061                 search(c, 0);
1062             } else if (t != NULL && t[0] == 'w' && t[1] == '/') {
1063                 int len = strlen(cfg.search_engine) + strlen(t) - 2;
1064                 gchar *f = malloc(len + 1);
1065                 snprintf(f, len + 1, "%s%s", cfg.search_engine, t + 2);
1066                 webkit_web_view_load_uri(WEBKIT_WEB_VIEW(c->web_view), f);
1067                 g_free(f);
1068             } else {
1069                 f = ensure_uri_scheme(t);
1070                 webkit_web_view_load_uri(WEBKIT_WEB_VIEW(c->web_view), f);
1071                 g_free(f);
1072             }
1073             return TRUE;
1074         } else if (GDK_KEY_Escape == key) {
1075             t = webkit_web_view_get_uri(WEBKIT_WEB_VIEW(c->web_view));
1076             gtk_entry_set_text(GTK_ENTRY(c->location), (t == NULL) ? "" : t);
1077             return TRUE;
1078         }
1079     }
1080     return FALSE;
1081 }
1082
1083 gboolean
1084 key_tablabel(GtkWidget *widget, GdkEvent *event, gpointer data) {
1085     GdkScrollDirection direction;
1086
1087     if (event->type == GDK_BUTTON_RELEASE) {
1088         switch (((GdkEventButton *)event)->button) {
1089         case 2:
1090             client_destroy(NULL, data);
1091             return TRUE;
1092         }
1093     } else if (event->type == GDK_SCROLL) {
1094         gdk_event_get_scroll_direction(event, &direction);
1095         switch (direction) {
1096         case GDK_SCROLL_UP:
1097             gtk_notebook_prev_page(GTK_NOTEBOOK(mw.notebook));
1098             break;
1099         case GDK_SCROLL_DOWN:
1100             gtk_notebook_next_page(GTK_NOTEBOOK(mw.notebook));
1101             break;
1102         default:
1103             break;
1104         }
1105         return TRUE;
1106     }
1107     return FALSE;
1108 }
1109
1110 gboolean
1111 key_web_view(GtkWidget *widget, GdkEvent *event, gpointer data) {
1112     struct Client *c = (struct Client *)data;
1113     gdouble dx, dy;
1114     gfloat z;
1115
1116     if (key_common(widget, event, data))
1117         return TRUE;
1118
1119     if (event->type == GDK_KEY_PRESS) {
1120         if (((GdkEventKey *)event)->keyval == GDK_KEY_Escape) {
1121             webkit_web_view_stop_loading(WEBKIT_WEB_VIEW(c->web_view));
1122             gtk_entry_set_progress_fraction(GTK_ENTRY(c->location), 0);
1123         }
1124     } else if (event->type == GDK_BUTTON_RELEASE) {
1125         GdkModifierType modifiers = gtk_accelerator_get_default_mod_mask();
1126         switch (((GdkEventButton *)event)->button) {
1127         case 1:
1128             if ((((GdkEventButton *)event)->state & modifiers) ==
1129                     GDK_CONTROL_MASK &&
1130                 c->hover_uri != NULL) {
1131                 client_new(c->hover_uri, NULL, TRUE, FALSE);
1132                 return TRUE;
1133             }
1134             break;
1135         case 8:
1136             webkit_web_view_go_back(WEBKIT_WEB_VIEW(c->web_view));
1137             return TRUE;
1138         case 9:
1139             webkit_web_view_go_forward(WEBKIT_WEB_VIEW(c->web_view));
1140             return TRUE;
1141         }
1142     } else if (event->type == GDK_SCROLL) {
1143         event->scroll.delta_y *= cfg.scroll_lines;
1144         if (((GdkEventScroll *)event)->state & GDK_CONTROL_MASK) {
1145             gdk_event_get_scroll_deltas(event, &dx, &dy);
1146             z = webkit_web_view_get_zoom_level(WEBKIT_WEB_VIEW(c->web_view));
1147             z += -dy * 0.1;
1148             z = dx != 0 ? cfg.zoom_level : z;
1149             webkit_web_view_set_zoom_level(WEBKIT_WEB_VIEW(c->web_view), z);
1150             return TRUE;
1151         }
1152     }
1153
1154     return FALSE;
1155 }
1156
1157 void
1158 mainwindow_setup(void) {
1159     mw.win = gtk_window_new(GTK_WINDOW_TOPLEVEL);
1160     gtk_window_set_default_size(GTK_WINDOW(mw.win), 800, 600);
1161     g_signal_connect(G_OBJECT(mw.win), "destroy", gtk_main_quit, NULL);
1162
1163     gchar *priv = (cfg.private) ? "-private" : "";
1164     gchar *title = malloc(strlen(priv) + strlen(__NAME__) + 1);
1165     sprintf(title, "%s%s", __NAME__, priv);
1166     gtk_window_set_title(GTK_WINDOW(mw.win), title);
1167     g_free(title);
1168
1169     mw.notebook = gtk_notebook_new();
1170     gtk_notebook_set_scrollable(GTK_NOTEBOOK(mw.notebook), TRUE);
1171     gtk_container_add(GTK_CONTAINER(mw.win), mw.notebook);
1172     g_signal_connect(G_OBJECT(mw.notebook), "switch-page",
1173                      G_CALLBACK(notebook_switch_page), NULL);
1174 }
1175
1176 void
1177 mainwindow_title(gint idx) {
1178     GtkWidget *child, *widg, *tablabel;
1179     const gchar *text;
1180
1181     child = gtk_notebook_get_nth_page(GTK_NOTEBOOK(mw.notebook), idx);
1182     if (child == NULL)
1183         return;
1184
1185     widg = gtk_notebook_get_tab_label(GTK_NOTEBOOK(mw.notebook), child);
1186     tablabel =
1187         (GtkWidget *)g_object_get_data(G_OBJECT(widg), "chorizo-tab-label");
1188     text = gtk_label_get_text(GTK_LABEL(tablabel));
1189     gtk_window_set_title(GTK_WINDOW(mw.win), text);
1190 }
1191
1192 void
1193 notebook_switch_page(GtkNotebook *nb, GtkWidget *p, guint idx, gpointer data) {
1194     mainwindow_title(idx);
1195 }
1196
1197 gboolean
1198 quit_if_nothing_active(void) {
1199     if (clients == 0) {
1200         if (downloads == 0) {
1201             gtk_main_quit();
1202             return TRUE;
1203         } else {
1204             downloadmanager_show();
1205         }
1206     }
1207
1208     return FALSE;
1209 }
1210
1211 gboolean
1212 remote_msg(GIOChannel *channel, GIOCondition condition, gpointer data) {
1213     gchar *uri = NULL;
1214
1215     g_io_channel_read_line(channel, &uri, NULL, NULL, NULL);
1216     if (uri) {
1217         g_strstrip(uri);
1218         client_new(uri, NULL, TRUE, TRUE);
1219         g_free(uri);
1220     }
1221     return TRUE;
1222 }
1223
1224 void
1225 show_web_view(WebKitWebView *web_view, gpointer data) {
1226     struct Client *c = (struct Client *)data;
1227     gint idx;
1228
1229     (void)web_view;
1230
1231     gtk_widget_show_all(mw.win);
1232
1233     if (c->focus_new_tab) {
1234         idx = gtk_notebook_page_num(GTK_NOTEBOOK(mw.notebook), c->vbox);
1235         if (idx != -1)
1236             gtk_notebook_set_current_page(GTK_NOTEBOOK(mw.notebook), idx);
1237
1238         gtk_widget_grab_focus(c->web_view);
1239     }
1240 }
1241
1242 void
1243 trust_user_certs(WebKitWebContext *wc) {
1244     GTlsCertificate *cert;
1245     gchar *basedir, *absfile;
1246     const gchar *file;
1247     GDir *dir = NULL;
1248
1249     basedir = g_build_filename(g_get_user_data_dir(), __NAME__, "certs", NULL);
1250     dir = g_dir_open(basedir, 0, NULL);
1251     g_free(basedir);
1252     if (dir != NULL) {
1253         file = g_dir_read_name(dir);
1254         while (file != NULL) {
1255             absfile = g_build_filename(g_get_user_data_dir(), __NAME__, "certs",
1256                                        file, NULL);
1257             cert = g_tls_certificate_new_from_file(absfile, NULL);
1258             g_free(absfile);
1259             if (cert == NULL)
1260                 fprintf(stderr, __NAME__ ": Could not load trusted cert '%s'\n",
1261                         file);
1262             else
1263                 webkit_web_context_allow_tls_certificate_for_host(wc, cert,
1264                                                                   file);
1265             file = g_dir_read_name(dir);
1266         }
1267         g_dir_close(dir);
1268     }
1269 }
1270
1271 GKeyFile *
1272 get_ini(void) {
1273     GKeyFileFlags flags = G_KEY_FILE_NONE;
1274     config = g_key_file_new();
1275
1276     // Load user config
1277     gchar *fname = g_build_filename(g_get_user_config_dir(), __NAME__,
1278                                     "chorizo.ini", NULL);
1279     if (!g_key_file_load_from_file(config, fname, flags, NULL)) {
1280         // Load global config
1281         if (!g_key_file_load_from_file(config, "/etc/chorizo.ini", flags,
1282                                        NULL)) {
1283             fprintf(stderr, "Could not load chorizo.ini");
1284         }
1285     }
1286     g_free(fname);
1287     return config;
1288 }
1289
1290 int
1291 main(int argc, char **argv) {
1292     int opt, i;
1293
1294     while ((opt = getopt(argc, argv, "Cpv")) != -1) {
1295         switch (opt) {
1296         case 'C':
1297             cfg.cooperative_instances = FALSE;
1298             break;
1299         case 'p':
1300             cfg.private = true;
1301             break;
1302         case 'v':
1303             printf("%s %s\n", __NAME__, VERSION);
1304             exit(0);
1305         default:
1306             fprintf(stderr, "Usage: " __NAME__ " [OPTION]... [URI]...\n");
1307             exit(EXIT_FAILURE);
1308         }
1309     }
1310
1311     gtk_init(&argc, &argv);
1312
1313     // Keep clipboard contents after program closes
1314     gtk_clipboard_store(gtk_clipboard_get_for_display(gdk_display_get_default(),
1315                                                       GDK_SELECTION_CLIPBOARD));
1316
1317     get_config();
1318
1319     if (cfg.cooperative_instances)
1320         cooperation_setup();
1321
1322     if (!cfg.cooperative_instances || cfg.cooperative_alone)
1323         init_default_web_context();
1324
1325     downloadmanager_setup();
1326     mainwindow_setup();
1327
1328     client_arr = malloc(sizeof(struct Client *));
1329     if (optind >= argc) {
1330         client_new(cfg.home_uri, NULL, TRUE, TRUE);
1331     } else {
1332         for (i = optind; i < argc; i++)
1333             client_new(argv[i], NULL, TRUE, TRUE);
1334     }
1335
1336     if (!cfg.cooperative_instances || cfg.cooperative_alone)
1337         gtk_main();
1338
1339     for (int i = 0; i < clients; i++) {
1340         free(&(client_arr[i]));
1341     }
1342
1343     exit(EXIT_SUCCESS);
1344 }