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