]> git.armaanb.net Git - chorizo.git/blob - src/browser.c
Rename project to chorizo
[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 }
525
526 void
527 grab_feeds_finished(GObject *object, GAsyncResult *result, gpointer data)
528 {
529         struct Client *c = (struct Client *)data;
530         WebKitJavascriptResult *js_result;
531         JSCValue *value;
532         JSCException *exception;
533         GError *err = NULL;
534         gchar *str_value;
535
536         g_free(c->feed_html);
537         c->feed_html = NULL;
538
539         /* This was taken almost verbatim from the example in WebKit's
540          * documentation:
541          *
542          * https://webkitgtk.org/reference/webkit2gtk/stable/WebKitWebView.html */
543
544         js_result = webkit_web_view_run_javascript_finish(WEBKIT_WEB_VIEW(object),
545                                                                                                                                                                                                                 result, &err);
546         if (!js_result) {
547                 fprintf(stderr, __NAME__": Error running javascript: %s\n", err->message);
548                 g_error_free(err);
549                 return;
550         }
551
552         value = webkit_javascript_result_get_js_value(js_result);
553         if (jsc_value_is_string(value)) {
554                 str_value = jsc_value_to_string(value);
555                 exception = jsc_context_get_exception(jsc_value_get_context(value));
556                 if (exception != NULL) {
557                         fprintf(stderr, __NAME__": Error running javascript: %s\n",
558                                                         jsc_exception_get_message(exception));
559                 } else {
560                         c->feed_html = str_value;
561                 }
562
563                 gtk_entry_set_icon_from_icon_name(GTK_ENTRY(c->location),
564                                                                                                                                                         GTK_ENTRY_ICON_PRIMARY,
565                                                                                                                                                         "application-rss+xml-symbolic");
566                 gtk_entry_set_icon_activatable(GTK_ENTRY(c->location),
567                                                                                                                                          GTK_ENTRY_ICON_PRIMARY,
568                                                                                                                                          TRUE);
569         } else {
570                 gtk_entry_set_icon_from_icon_name(GTK_ENTRY(c->location),
571                                                                                                                                                         GTK_ENTRY_ICON_PRIMARY,
572                                                                                                                                                         NULL);
573         }
574
575         webkit_javascript_result_unref(js_result);
576 }
577
578 void
579 hover_web_view(WebKitWebView *web_view, WebKitHitTestResult *ht,
580                                                          guint modifiers, gpointer data)
581 {
582         struct Client *c = (struct Client *)data;
583         const char *to_show;
584
585         g_free(c->hover_uri);
586
587         if (webkit_hit_test_result_context_is_link(ht)) {
588                 to_show = webkit_hit_test_result_get_link_uri(ht);
589                 c->hover_uri = g_strdup(to_show);
590         } else {
591                 to_show = webkit_web_view_get_uri(WEBKIT_WEB_VIEW(c->web_view));
592                 c->hover_uri = NULL;
593         }
594
595         if (!gtk_widget_is_focus(c->location))
596                 gtk_entry_set_text(GTK_ENTRY(c->location), to_show);
597 }
598
599 void
600 icon_location(GtkEntry *entry, GtkEntryIconPosition icon_pos, GdkEvent *event,
601                                                         gpointer data)
602 {
603         struct Client *c = (struct Client *)data;
604         gchar *d;
605         gchar *data_template =
606                 "data:text/html,"
607                 "<!DOCTYPE html>"
608                 "<html>"
609                 "    <head>"
610                 "        <meta charset=\"UTF-8\">"
611                 "        <title>Feeds</title>"
612                 "    </head>"
613                 "    <body>"
614                 "        <p>Feeds found on this page:</p>"
615                 "        <ul>"
616                 "        %s"
617                 "        </ul>"
618                 "    </body>"
619                 "</html>";
620
621         if (c->feed_html != NULL)
622                 {
623                         /* What we're actually trying to do is show a simple HTML page
624                          * that lists all the feeds on the current page. The function
625                          * webkit_web_view_load_html() looks like the proper way to do
626                          * that. Sad thing is, it doesn't create a history entry, but
627                          * instead simply replaces the content of the current page. This
628                          * is not what we want.
629                          *
630                          * RFC 2397 [0] defines the data URI scheme [1]. We abuse this
631                          * mechanism to show my custom HTML snippet *and* create a
632                          * history entry.
633                          *
634                          * [0]: https://tools.ietf.org/html/rfc2397
635                          * [1]: https://en.wikipedia.org/wiki/Data_URI_scheme */
636                         d = g_strdup_printf(data_template, c->feed_html);
637                         webkit_web_view_load_uri(WEBKIT_WEB_VIEW(c->web_view), d);
638                         g_free(d);
639                 }
640 }
641
642 void
643 init_default_web_context(void)
644 {
645         gchar *p;
646         WebKitWebContext *wc;
647         WebKitCookieManager *cm;
648
649         wc = webkit_web_context_get_default();
650
651         p = g_build_filename(g_get_user_config_dir(), __NAME__, "adblock", NULL);
652         webkit_web_context_set_sandbox_enabled(wc, TRUE);
653         webkit_web_context_add_path_to_sandbox(wc, p, TRUE);
654         g_free(p);
655
656         WebKitProcessModel model = WEBKIT_PROCESS_MODEL_MULTIPLE_SECONDARY_PROCESSES;
657         webkit_web_context_set_process_model(wc, model);
658
659         p = g_build_filename(g_get_user_data_dir(), __NAME__, "web_extensions",
660                                                                                          NULL);
661         webkit_web_context_set_web_extensions_directory(wc, p);
662         g_free(p);
663
664         if (cfg.accepted_language[0] != NULL)
665                 webkit_web_context_set_preferred_languages(wc, cfg.accepted_language);
666
667         g_signal_connect(G_OBJECT(wc), "download-started",
668                                                                          G_CALLBACK(download_start), &cfg);
669
670         trust_user_certs(wc);
671
672         cm = webkit_web_context_get_cookie_manager(wc);
673         webkit_cookie_manager_set_accept_policy(cm, cfg.cookie_policy);
674
675         webkit_web_context_set_favicon_database_directory(wc, NULL);
676         gchar *fname = g_build_filename("/", g_get_user_cache_dir(), __NAME__,
677                                                                                                                                         "cookies.db", NULL);
678
679         WebKitCookiePersistentStorage type = WEBKIT_COOKIE_PERSISTENT_STORAGE_SQLITE;
680         webkit_cookie_manager_set_persistent_storage(cm, fname, type);
681
682         const gchar * const languages[2] = {(const gchar *)cfg.spellcheck_language,
683                 NULL};
684         webkit_web_context_set_spell_checking_languages(wc, languages);
685         webkit_web_context_set_spell_checking_enabled(wc, !cfg.spellcheck_disabled);
686 }
687
688 void
689 search(gpointer data, gint direction)
690 {
691         struct Client *c = (struct Client *)data;
692         WebKitWebView *web_view = WEBKIT_WEB_VIEW(c->web_view);
693         WebKitFindController *fc = webkit_web_view_get_find_controller(web_view);
694
695         if (search_text == NULL)
696                 return;
697
698         switch (direction) {
699         case 0:
700                 webkit_find_controller_search(fc, search_text,
701                                                                                                                                         WEBKIT_FIND_OPTIONS_CASE_INSENSITIVE |
702                                                                                                                                         WEBKIT_FIND_OPTIONS_WRAP_AROUND,
703                                                                                                                                         G_MAXUINT);
704                 break;
705         case 1:
706                 webkit_find_controller_search_next(fc);
707                 break;
708         case -1:
709                 webkit_find_controller_search_previous(fc);
710                 break;
711         case 2:
712                 webkit_find_controller_search_finish(fc);
713                 break;
714         }
715 }
716
717 void
718 search_init(struct Client *c, int direction)
719 {
720         gtk_widget_grab_focus(c->location);
721         const gchar *contents = gtk_entry_get_text(GTK_ENTRY(c->location));
722         if (strcspn(contents, "s/")) {
723                 gtk_entry_set_text(GTK_ENTRY(c->location), "s/");
724         }
725         gtk_editable_set_position(GTK_EDITABLE(c->location), -1);
726         search(c, 0);
727         search(c, -1);
728         search(c, direction);
729 }
730
731 int
732 def_key(char *key, unsigned int def)
733 {
734         char *conf = g_key_file_get_string(config, "keybindings", key, NULL);
735         return (conf) ? gdk_keyval_from_name((conf) ? conf : NULL) : def;
736 }
737
738 gboolean
739 key_common(GtkWidget *widget, GdkEvent *event, gpointer data)
740 {
741         struct Client *c = (struct Client *)data;
742         gdouble now;
743         gchar *f;
744
745         if (event->type == GDK_KEY_PRESS) {
746                 if (((GdkEventKey *)event)->state & GDK_CONTROL_MASK) {
747                         WebKitSettings *settings =
748                                 webkit_web_view_get_settings(WEBKIT_WEB_VIEW(c->web_view));
749                         gboolean js = webkit_settings_get_enable_javascript(settings);
750                         int key = ((GdkEventKey *)event)->keyval;
751                         if (def_key("download_manager", GDK_KEY_y) == key) {
752                                 downloadmanager_show();
753                                 return TRUE;
754                         } else if (def_key("history_back", GDK_KEY_h) == key) {
755                                 webkit_web_view_go_back(WEBKIT_WEB_VIEW(c->web_view));
756                                 return TRUE;
757                         } else if (def_key("history_forwards", GDK_KEY_l) == key) {
758                                 webkit_web_view_go_forward(WEBKIT_WEB_VIEW(c->web_view));
759                                 return TRUE;
760                         } else if (def_key("location", GDK_KEY_t) == key) {
761                                 gtk_widget_grab_focus(c->location);
762                                 const char *uri = webkit_web_view_get_uri(WEBKIT_WEB_VIEW(c->web_view));
763                                 const char *goal = (uri) ? uri : "https://";
764                                 gtk_entry_set_text(GTK_ENTRY(c->location), goal);
765                                 gtk_editable_set_position(GTK_EDITABLE(c->location), -1);
766                                 return TRUE;
767                         } else if (def_key("print", GDK_KEY_Print) == key) {
768                                 WebKitPrintOperation *operation =
769                                         webkit_print_operation_new(WEBKIT_WEB_VIEW(c->web_view));
770                                 GtkWidget *toplevel = gtk_widget_get_toplevel(mw.win);
771                                 webkit_print_operation_run_dialog(operation, GTK_WINDOW(toplevel));
772                                 return TRUE;
773                         } else if (def_key("quit", GDK_KEY_g) == key) {
774                                 search(c, 2);
775                                 gtk_widget_grab_focus(c->web_view);
776                                 const gchar *uri =
777                                         webkit_web_view_get_uri(WEBKIT_WEB_VIEW(c->web_view));
778                                 gtk_entry_set_text(GTK_ENTRY(c->location), uri);
779                                 webkit_web_view_run_javascript(WEBKIT_WEB_VIEW(c->web_view),
780                                                                                                                                                          "window.getSelection().removeAllRanges();"
781                                                                                                                                                          "document.activeElement.blur();",
782                                                                                                                                                          NULL, NULL, c);
783                                 return TRUE;
784                         } else if (def_key("reload", GDK_KEY_e) == key) {
785                                 webkit_web_view_reload_bypass_cache(WEBKIT_WEB_VIEW(c->web_view));
786                                 return TRUE;
787                         } else if (def_key("scroll_line_down", GDK_KEY_j) == key) {
788                                 for (int i = 0; i < 2; i++) {
789                                         event->key.keyval = GDK_KEY_Down;
790                                         gdk_event_put(event);
791                                 }
792                                 return TRUE;
793                         } else if (def_key("scroll_line_up", GDK_KEY_k) == key) {
794                                 event->key.keyval = GDK_KEY_Up;
795                                 gdk_event_put(event);
796                                 return TRUE;
797                         } else if (def_key("scroll_page_down", GDK_KEY_f) == key) {
798                                 event->key.keyval = GDK_KEY_Page_Down;
799                                 gdk_event_put(event);
800                                 return TRUE;
801                         } else if (def_key("scroll_page_up", GDK_KEY_b) == key) {
802                                 event->key.keyval = GDK_KEY_Page_Up;
803                                 gdk_event_put(event);
804                                 return TRUE;
805                         } else if (def_key("search_forwards", GDK_KEY_s) == key) {
806                                 search_init(c, 1);
807                                 return TRUE;
808                         } else if (def_key("search_backwards", GDK_KEY_r) == key) {
809                                 search_init(c, -1);
810                                 return TRUE;
811                         } else if (def_key("tab_close", GDK_KEY_q) == key) {
812                                 client_destroy(NULL, c);
813                                 return TRUE;
814                         } else if (def_key("tab_switch_1", GDK_KEY_1) == key) {
815                                 gtk_notebook_set_current_page(GTK_NOTEBOOK(mw.notebook), 0);
816                                 return TRUE;
817                         } else if (def_key("tab_switch_2", GDK_KEY_2) == key) {
818                                 gtk_notebook_set_current_page(GTK_NOTEBOOK(mw.notebook), 1);
819                                 return TRUE;
820                         } else if (def_key("tab_switch_3", GDK_KEY_3) == key) {
821                                 gtk_notebook_set_current_page(GTK_NOTEBOOK(mw.notebook), 2);
822                                 return TRUE;
823                         } else if (def_key("tab_switch_4", GDK_KEY_4) == key) {
824                                 gtk_notebook_set_current_page(GTK_NOTEBOOK(mw.notebook), 3);
825                                 return TRUE;
826                         } else if (def_key("tab_switch_5", GDK_KEY_5) == key) {
827                                 gtk_notebook_set_current_page(GTK_NOTEBOOK(mw.notebook), 4);
828                                 return TRUE;
829                         } else if (def_key("tab_switch_6", GDK_KEY_6) == key) {
830                                 gtk_notebook_set_current_page(GTK_NOTEBOOK(mw.notebook), 5);
831                                 return TRUE;
832                         } else if (def_key("tab_switch_7", GDK_KEY_7) == key) {
833                                 gtk_notebook_set_current_page(GTK_NOTEBOOK(mw.notebook), 6);
834                                 return TRUE;
835                         } else if (def_key("tab_switch_8", GDK_KEY_8) == key) {
836                                 gtk_notebook_set_current_page(GTK_NOTEBOOK(mw.notebook), 7);
837                                 return TRUE;
838                         } else if (def_key("tab_switch_9", GDK_KEY_9) == key) {
839                                 gtk_notebook_set_current_page(GTK_NOTEBOOK(mw.notebook), 8);
840                                 return TRUE;
841                         } else if (def_key("tab_previous", GDK_KEY_u) == key) {
842                                 gtk_notebook_prev_page(GTK_NOTEBOOK(mw.notebook));
843                                 return TRUE;
844                         } else if (def_key("tab_mute", GDK_KEY_m) == key) {
845                                 gboolean muted =
846                                         webkit_web_view_get_is_muted(WEBKIT_WEB_VIEW(c->web_view));
847                                 webkit_web_view_set_is_muted(WEBKIT_WEB_VIEW(c->web_view), !muted);
848                                 changed_title(G_OBJECT(c->web_view), NULL, c);
849                                 return TRUE;
850                         } else if (def_key("tab_new", GDK_KEY_w) == key) {
851                                 f = ensure_uri_scheme(cfg.home_uri);
852                                 client_new(f, NULL, TRUE, TRUE);
853                                 g_free(f);
854                                 return TRUE;
855                         } else if (def_key("tab_next", GDK_KEY_i) == key) {
856                                 gtk_notebook_next_page(GTK_NOTEBOOK(mw.notebook));
857                                 return TRUE;
858                         } else if (def_key("toggle_js", GDK_KEY_o) == key) {
859                                 webkit_settings_set_enable_javascript(settings, (js) ? FALSE : TRUE);
860                                 webkit_web_view_set_settings(WEBKIT_WEB_VIEW(c->web_view), settings);
861                                 return TRUE;
862                         } else if (def_key("web_search", GDK_KEY_d) == key) {
863                                 gtk_widget_grab_focus(c->location);
864                                 gtk_entry_set_text(GTK_ENTRY(c->location), "w/");
865                                 gtk_editable_set_position(GTK_EDITABLE(c->location), -1);
866                                 return TRUE;
867                         } else if (def_key("zoom_in", GDK_KEY_equal) == key) {
868                                 now = webkit_web_view_get_zoom_level(WEBKIT_WEB_VIEW(c->web_view));
869                                 webkit_web_view_set_zoom_level(WEBKIT_WEB_VIEW(c->web_view), now + 0.1);
870                                 return TRUE;
871                         } else if (def_key("zoom_out", GDK_KEY_minus) == key) {
872                                 now = webkit_web_view_get_zoom_level(WEBKIT_WEB_VIEW(c->web_view));
873                                 webkit_web_view_set_zoom_level(WEBKIT_WEB_VIEW(c->web_view), now - 0.1);
874                                 return TRUE;
875                         } else if (def_key("zoom_reset", GDK_KEY_0) == key) {
876                                 webkit_web_view_set_zoom_level(WEBKIT_WEB_VIEW(c->web_view),
877                                                                                                                                                          cfg.global_zoom);
878                                 return TRUE;
879                         }
880                 }
881         }
882         return FALSE;
883 }
884
885 gboolean
886 key_location(GtkWidget *widget, GdkEvent *event, gpointer data)
887 {
888         struct Client *c = (struct Client *)data;
889         const gchar *t;
890         gchar *f;
891
892         if (key_common(widget, event, data))
893                 return TRUE;
894
895         if (event->type == GDK_KEY_PRESS) {
896                 int key = ((GdkEventKey *)event)->keyval;
897                 if ((GDK_KEY_KP_Enter == key) || (GDK_KEY_Return == key)) {
898                         gtk_widget_grab_focus(c->web_view);
899                         t = gtk_entry_get_text(GTK_ENTRY(c->location));
900                         if (t != NULL && t[0] == 's' && t[1] == '/') {
901                                 if (search_text != NULL)
902                                         g_free(search_text);
903                                 search_text = g_strdup(t + 2);
904                                 search(c, 0);
905                         } else if (t != NULL && t[0] == 'w' && t[1] == '/') {
906                                 const char *engine = cfg.search_engine;
907                                 int len = strlen(engine) + strlen(t) - 2;
908                                 char *f = (char *) malloc(len);
909                                 snprintf(f, len + 1, "%s%s", engine, t + 2);
910                                 webkit_web_view_load_uri(WEBKIT_WEB_VIEW(c->web_view), f);
911                                 free(f);
912                         } else {
913                                 f = ensure_uri_scheme(t);
914                                 webkit_web_view_load_uri(WEBKIT_WEB_VIEW(c->web_view), f);
915                                 g_free(f);
916                         }
917                         return TRUE;
918                 } else if ((GDK_KEY_Escape == key) ||
919                                                          (def_key("quit", GDK_KEY_g) == key)) {
920                         t = webkit_web_view_get_uri(WEBKIT_WEB_VIEW(c->web_view));
921                         gtk_entry_set_text(GTK_ENTRY(c->location),
922                                                                                                  (t == NULL ? __NAME__ : t));
923                         return TRUE;
924                 }
925         }
926         return FALSE;
927 }
928
929 gboolean
930 key_tablabel(GtkWidget *widget, GdkEvent *event, gpointer data)
931 {
932         GdkScrollDirection direction;
933
934         if (event->type == GDK_BUTTON_RELEASE) {
935                 switch (((GdkEventButton *)event)->button) {
936                 case 2:
937                         client_destroy(NULL, data);
938                         return TRUE;
939                 }
940         } else if (event->type == GDK_SCROLL) {
941                 gdk_event_get_scroll_direction(event, &direction);
942                 switch (direction) {
943                 case GDK_SCROLL_UP:
944                         gtk_notebook_prev_page(GTK_NOTEBOOK(mw.notebook));
945                         break;
946                 case GDK_SCROLL_DOWN:
947                         gtk_notebook_next_page(GTK_NOTEBOOK(mw.notebook));
948                         break;
949                 default:
950                         break;
951                 }
952                 return TRUE;
953         }
954         return FALSE;
955 }
956
957 gboolean
958 key_web_view(GtkWidget *widget, GdkEvent *event, gpointer data)
959 {
960         struct Client *c = (struct Client *)data;
961         gdouble dx, dy;
962         gfloat z;
963
964         if (key_common(widget, event, data))
965                 return TRUE;
966
967         if (event->type == GDK_KEY_PRESS) {
968                 if (((GdkEventKey *)event)->keyval == GDK_KEY_Escape) {
969                         webkit_web_view_stop_loading(WEBKIT_WEB_VIEW(c->web_view));
970                         gtk_entry_set_progress_fraction(GTK_ENTRY(c->location), 0);
971                 }
972         } else if (event->type == GDK_BUTTON_RELEASE) {
973                 switch (((GdkEventButton *)event)->button) {
974                 case 2:
975                         if (c->hover_uri != NULL) {
976                                 client_new(c->hover_uri, NULL, TRUE, FALSE);
977                                 return TRUE;
978                         }
979                         break;
980                 case 8:
981                         webkit_web_view_go_back(WEBKIT_WEB_VIEW(c->web_view));
982                         return TRUE;
983                 case 9:
984                         webkit_web_view_go_forward(WEBKIT_WEB_VIEW(c->web_view));
985                         return TRUE;
986                 }
987         } else if (event->type == GDK_SCROLL) {
988                 if (((GdkEventScroll *)event)->state & GDK_CONTROL_MASK ||
989                                 ((GdkEventScroll *)event)->state & GDK_CONTROL_MASK) {
990                         gdk_event_get_scroll_deltas(event, &dx, &dy);
991                         z = webkit_web_view_get_zoom_level(WEBKIT_WEB_VIEW(c->web_view));
992                         z += -dy * 0.1;
993                         z = dx != 0 ? cfg.global_zoom : z;
994                         webkit_web_view_set_zoom_level(WEBKIT_WEB_VIEW(c->web_view), z);
995                         return TRUE;
996                 }
997         }
998
999         return FALSE;
1000 }
1001
1002 void
1003 mainwindow_setup(void)
1004 {
1005         mw.win = gtk_window_new(GTK_WINDOW_TOPLEVEL);
1006         gtk_window_set_default_size(GTK_WINDOW(mw.win), 800, 600);
1007         g_signal_connect(G_OBJECT(mw.win), "destroy", gtk_main_quit, NULL);
1008         gtk_window_set_title(GTK_WINDOW(mw.win), __NAME__);
1009
1010         mw.notebook = gtk_notebook_new();
1011         gtk_notebook_set_scrollable(GTK_NOTEBOOK(mw.notebook), TRUE);
1012         gtk_container_add(GTK_CONTAINER(mw.win), mw.notebook);
1013         g_signal_connect(G_OBJECT(mw.notebook), "switch-page",
1014                                                                          G_CALLBACK(notebook_switch_page), NULL);
1015 }
1016
1017 void
1018 mainwindow_title(gint idx)
1019 {
1020         GtkWidget *child, *widg, *tablabel;
1021         const gchar *text;
1022
1023         child = gtk_notebook_get_nth_page(GTK_NOTEBOOK(mw.notebook), idx);
1024         if (child == NULL)
1025                 return;
1026
1027         widg = gtk_notebook_get_tab_label(GTK_NOTEBOOK(mw.notebook), child);
1028         tablabel = (GtkWidget *)g_object_get_data(G_OBJECT(widg), "chorizo-tab-label");
1029         text = gtk_label_get_text(GTK_LABEL(tablabel));
1030         gtk_window_set_title(GTK_WINDOW(mw.win), text);
1031 }
1032
1033 void
1034 notebook_switch_page(GtkNotebook *nb, GtkWidget *p, guint idx, gpointer data)
1035 {
1036         mainwindow_title(idx);
1037 }
1038
1039 gboolean
1040 quit_if_nothing_active(void)
1041 {
1042         if (clients == 0) {
1043                 if (downloads == 0) {
1044                         gtk_main_quit();
1045                         return TRUE;
1046                 } else {
1047                         downloadmanager_show();
1048                 }
1049         }
1050
1051         return FALSE;
1052 }
1053
1054 gboolean
1055 remote_msg(GIOChannel *channel, GIOCondition condition, gpointer data)
1056 {
1057         gchar *uri = NULL;
1058
1059         g_io_channel_read_line(channel, &uri, NULL, NULL, NULL);
1060         if (uri) {
1061                 g_strstrip(uri);
1062                 client_new(uri, NULL, TRUE, TRUE);
1063                 g_free(uri);
1064         }
1065         return TRUE;
1066 }
1067
1068 void
1069 run_user_scripts(WebKitWebView *web_view)
1070 {
1071         gchar *base = NULL, *path = NULL, *contents = NULL;
1072         const gchar *entry = NULL;
1073         GDir *scriptdir = NULL;
1074
1075         base = g_build_filename(g_get_user_data_dir(), __NAME__, "user-scripts",
1076                                                                                                         NULL);
1077         scriptdir = g_dir_open(base, 0, NULL);
1078         if (scriptdir != NULL) {
1079                 while ((entry = g_dir_read_name(scriptdir)) != NULL) {
1080                         path = g_build_filename(base, entry, NULL);
1081                         char *jscmd = malloc(strlen(path) + 36);
1082                         sprintf(jscmd, "console.log(\"Running userscript %s\");", path);
1083                         if (g_str_has_suffix(path, ".js")) {
1084                                 if (g_file_get_contents(path, &contents, NULL, NULL)) {
1085                                         webkit_web_view_run_javascript(web_view, jscmd, NULL, NULL, NULL);
1086                                         webkit_web_view_run_javascript(web_view, contents, NULL, NULL, NULL);
1087                                         g_free(contents);
1088                                         g_free(jscmd);
1089                                 }
1090                         }
1091                         g_free(path);
1092                 }
1093                 g_dir_close(scriptdir);
1094         }
1095
1096         g_free(base);
1097 }
1098
1099 void
1100 show_web_view(WebKitWebView *web_view, gpointer data)
1101 {
1102         struct Client *c = (struct Client *)data;
1103         gint idx;
1104
1105         (void)web_view;
1106
1107         gtk_widget_show_all(mw.win);
1108
1109         if (c->focus_new_tab) {
1110                 idx = gtk_notebook_page_num(GTK_NOTEBOOK(mw.notebook), c->vbox);
1111                 if (idx != -1)
1112                         gtk_notebook_set_current_page(GTK_NOTEBOOK(mw.notebook), idx);
1113
1114                 gtk_widget_grab_focus(c->web_view);
1115         }
1116 }
1117
1118 void
1119 trust_user_certs(WebKitWebContext *wc)
1120 {
1121         GTlsCertificate *cert;
1122         const gchar *basedir, *file, *absfile;
1123         GDir *dir;
1124
1125         basedir = g_build_filename(g_get_user_data_dir(), __NAME__, "certs", NULL);
1126         dir = g_dir_open(basedir, 0, NULL);
1127         if (dir != NULL) {
1128                 file = g_dir_read_name(dir);
1129                 while (file != NULL) {
1130                         absfile = g_build_filename(g_get_user_data_dir(), __NAME__, "certs",
1131
1132                                                                                                                                  file, NULL);
1133                         cert = g_tls_certificate_new_from_file(absfile, NULL);
1134                         if (cert == NULL)
1135                                 fprintf(stderr, __NAME__": Could not load trusted cert '%s'\n", file);
1136                         else
1137                                 webkit_web_context_allow_tls_certificate_for_host(wc, cert, file);
1138                         file = g_dir_read_name(dir);
1139                 }
1140                 g_dir_close(dir);
1141         }
1142 }
1143
1144 GKeyFile *
1145 get_ini(void)
1146 {
1147         GKeyFileFlags flags = G_KEY_FILE_NONE;
1148         config = g_key_file_new();
1149
1150         // Load user config
1151         if (!g_key_file_load_from_file(config,
1152                                                                                                                                  g_build_filename(g_get_user_config_dir(),
1153                                                                                                                                                                                                         __NAME__, "chorizo.ini",
1154                                                                                                                                                                                                         NULL), flags, NULL)) {
1155                 // Load global config
1156                 if (!g_key_file_load_from_file(config, "/etc/chorizo.ini", flags,
1157                                                                                                                                          NULL)) {
1158                         fprintf(stderr, "Could not load chorizo.ini");
1159                 }
1160         }
1161         return config;
1162 }
1163
1164 int
1165 main(int argc, char **argv)
1166 {
1167         int opt, i;
1168
1169         while ((opt = getopt(argc, argv, "Cv")) != -1) {
1170                 switch (opt) {
1171                 case 'C':
1172                         cfg.cooperative_instances = FALSE;
1173                         break;
1174                 case 'v':
1175                         printf("%s %s\n", __NAME__, VERSION);
1176                         exit(0);
1177                 default:
1178                         fprintf(stderr, "Usage: "__NAME__" [OPTION]... [URI]...\n");
1179                         exit(EXIT_FAILURE);
1180                 }
1181         }
1182
1183         gtk_init(&argc, &argv);
1184         get_config();
1185
1186         if (cfg.cooperative_instances)
1187                 cooperation_setup();
1188
1189         if (!cfg.cooperative_instances || cfg.cooperative_alone)
1190                 init_default_web_context();
1191
1192         downloadmanager_setup();
1193         mainwindow_setup();
1194
1195         if (optind >= argc) {
1196                 client_new(cfg.home_uri, NULL, TRUE, TRUE);
1197         } else {
1198                 for (i = optind; i < argc; i++)
1199                         client_new(argv[i], NULL, TRUE, TRUE);
1200         }
1201
1202         if (!cfg.cooperative_instances || cfg.cooperative_alone)
1203                 gtk_main();
1204
1205         exit(EXIT_SUCCESS);
1206 }