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