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