]> git.armaanb.net Git - chorizo.git/blob - src/browser.c
05a05eab64b42891eb470ffa528b4a70f5aa7761
[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 = webkit_web_view_get_settings(WEBKIT_WEB_VIEW(c->web_view));
137         webkit_settings_set_enable_javascript(settings, !cfg.javascript_disabled);
138         g_signal_connect(G_OBJECT(c->web_view), "notify::favicon",
139                                                                          G_CALLBACK(changed_favicon), c);
140         g_signal_connect(G_OBJECT(c->web_view), "notify::title",
141                                                                          G_CALLBACK(changed_title), c);
142         g_signal_connect(G_OBJECT(c->web_view), "notify::uri",
143                                                                          G_CALLBACK(changed_uri), c);
144         g_signal_connect(G_OBJECT(c->web_view), "notify::estimated-load-progress",
145                                                                          G_CALLBACK(changed_load_progress), c);
146         g_signal_connect(G_OBJECT(c->web_view), "create",
147                                                                          G_CALLBACK(client_new_request), NULL);
148         g_signal_connect(G_OBJECT(c->web_view), "close",
149                                                                          G_CALLBACK(client_destroy), c);
150         g_signal_connect(G_OBJECT(c->web_view), "decide-policy",
151                                                                          G_CALLBACK(decide_policy), NULL);
152         g_signal_connect(G_OBJECT(c->web_view), "key-press-event",
153                                                                          G_CALLBACK(key_web_view), c);
154         g_signal_connect(G_OBJECT(c->web_view), "button-release-event",
155                                                                          G_CALLBACK(key_web_view), c);
156         g_signal_connect(G_OBJECT(c->web_view), "scroll-event",
157                                                                          G_CALLBACK(key_web_view), c);
158         g_signal_connect(G_OBJECT(c->web_view), "mouse-target-changed",
159                                                                          G_CALLBACK(hover_web_view), c);
160         g_signal_connect(G_OBJECT(c->web_view), "web-process-crashed",
161                                                                          G_CALLBACK(crashed_web_view), c);
162
163         if (cfg.user_agent != NULL)
164                 g_object_set(G_OBJECT(webkit_web_view_get_settings(WEBKIT_WEB_VIEW(c->web_view))),
165                                                                  "user-agent", cfg.user_agent, NULL);
166
167         if (cfg.enable_console_to_stdout)
168                 webkit_settings_set_enable_write_console_messages_to_stdout(webkit_web_view_get_settings(WEBKIT_WEB_VIEW(c->web_view)), TRUE);
169
170         webkit_settings_set_enable_developer_extras(webkit_web_view_get_settings(WEBKIT_WEB_VIEW(c->web_view)), TRUE);
171
172         c->location = gtk_entry_new();
173         g_signal_connect(G_OBJECT(c->location), "key-press-event",
174                                                                          G_CALLBACK(key_location), c);
175         g_signal_connect(G_OBJECT(c->location), "icon-release",
176                                                                          G_CALLBACK(icon_location), c);
177         /* XXX This is a workaround. Setting this to NULL (which is done in
178          * grab_feeds_finished() if no feed has been detected) adds a little
179          * padding left of the text. Not sure why. The point of this call
180          * right here is to have that padding right from the start. This
181          * avoids a graphical artifact. */
182         gtk_entry_set_icon_from_icon_name(GTK_ENTRY(c->location),
183                                                                                                                                                 GTK_ENTRY_ICON_PRIMARY,
184                                                                                                                                                 NULL);
185
186         c->vbox = gtk_box_new(GTK_ORIENTATION_VERTICAL, 0);
187         gtk_box_pack_start(GTK_BOX(c->vbox), c->location, FALSE, FALSE, 0);
188         gtk_box_pack_start(GTK_BOX(c->vbox), c->web_view, TRUE, TRUE, 0);
189         gtk_container_set_focus_child(GTK_CONTAINER(c->vbox), c->web_view);
190
191         c->tabicon = gtk_image_new_from_icon_name("text-html", GTK_ICON_SIZE_SMALL_TOOLBAR);
192
193         c->tablabel = gtk_label_new(__NAME__);
194         gtk_label_set_ellipsize(GTK_LABEL(c->tablabel), PANGO_ELLIPSIZE_END);
195         gtk_label_set_width_chars(GTK_LABEL(c->tablabel), cfg.tab_width_chars);
196         gtk_widget_set_has_tooltip(c->tablabel, TRUE);
197
198         /* XXX I don't own a HiDPI screen, so I don't know if scale_factor
199          * does the right thing. */
200         tabbox = gtk_box_new(GTK_ORIENTATION_HORIZONTAL,
201                                                                                          5 * gtk_widget_get_scale_factor(mw.win));
202         gtk_box_pack_start(GTK_BOX(tabbox), c->tabicon, FALSE, FALSE, 0);
203         gtk_box_pack_start(GTK_BOX(tabbox), c->tablabel, TRUE, TRUE, 0);
204
205         evbox = gtk_event_box_new();
206         gtk_container_add(GTK_CONTAINER(evbox), tabbox);
207         g_signal_connect(G_OBJECT(evbox), "button-release-event",
208                                                                          G_CALLBACK(key_tablabel), c);
209
210         gtk_widget_add_events(evbox, GDK_SCROLL_MASK);
211         g_signal_connect(G_OBJECT(evbox), "scroll-event",
212                                                                          G_CALLBACK(key_tablabel), c);
213
214         /* For easy access, store a reference to our label. */
215         g_object_set_data(G_OBJECT(evbox), "lariza-tab-label", c->tablabel);
216
217         /* This only shows the event box and the label inside, nothing else.
218          * Needed because the evbox/label is "internal" to the notebook and
219          * not part of the normal "widget tree" (IIUC). */
220         gtk_widget_show_all(evbox);
221
222         gtk_notebook_insert_page(GTK_NOTEBOOK(mw.notebook), c->vbox, evbox,
223                                                                                                          gtk_notebook_get_current_page(GTK_NOTEBOOK(mw.notebook)) + 1);
224         gtk_notebook_set_tab_reorderable(GTK_NOTEBOOK(mw.notebook), c->vbox, TRUE);
225
226         if (show)
227                 show_web_view(NULL, c);
228         else
229                 g_signal_connect(G_OBJECT(c->web_view), "ready-to-show",
230                                                                                  G_CALLBACK(show_web_view), c);
231
232         if (uri != NULL) {
233                 f = ensure_uri_scheme(uri);
234                 webkit_web_view_load_uri(WEBKIT_WEB_VIEW(c->web_view), f);
235                 g_free(f);
236         }
237
238         clients++;
239
240         return WEBKIT_WEB_VIEW(c->web_view);
241 }
242
243 WebKitWebView *
244 client_new_request(WebKitWebView *web_view,
245                                                                          WebKitNavigationAction *navigation_action, gpointer data)
246 {
247         return client_new(NULL, web_view, FALSE, FALSE);
248 }
249
250 void
251 cooperation_setup(void)
252 {
253         GIOChannel *towatch;
254         gchar *fifofilename, *fifopath;
255
256         fifofilename = g_strdup_printf("%s-%s", __NAME__".fifo", cfg.fifo_suffix);
257         fifopath = g_build_filename(g_get_user_runtime_dir(), fifofilename, NULL);
258         g_free(fifofilename);
259
260         if (!g_file_test(fifopath, G_FILE_TEST_EXISTS))
261                 mkfifo(fifopath, 0600);
262
263         cooperative_pipe_fp = open(fifopath, O_WRONLY | O_NONBLOCK);
264         if (!cooperative_pipe_fp) {
265                 fprintf(stderr, __NAME__": Can't open FIFO at all.\n");
266         } else {
267                 if (write(cooperative_pipe_fp, "", 0) == -1) {
268                         /* Could not do an empty write to the FIFO which means there's
269                          * no one listening. */
270                         close(cooperative_pipe_fp);
271                         towatch = g_io_channel_new_file(fifopath, "r+", NULL);
272                         g_io_add_watch(towatch, G_IO_IN, (GIOFunc)remote_msg, NULL);
273                 } else {
274                         cfg.cooperative_alone = FALSE;
275                 }
276         }
277
278         g_free(fifopath);
279 }
280
281 void
282 changed_load_progress(GObject *obj, GParamSpec *pspec, gpointer data)
283 {
284         struct Client *c = (struct Client *)data;
285         gdouble p;
286         gchar *grab_feeds =
287                 "a = document.querySelectorAll('"
288                 "    html > head > link[rel=\"alternate\"][href][type=\"application/atom+xml\"],"
289                 "    html > head > link[rel=\"alternate\"][href][type=\"application/rss+xml\"]"
290                 "');"
291                 "if (a.length == 0)"
292                 "    null;"
293                 "else"
294                 "{"
295                 "    out = '';"
296                 "    for (i = 0; i < a.length; i++)"
297                 "    {"
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#webkit-web-view-run-javascript-finish */
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, guint modifiers,
580                                                          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         webkit_web_context_set_process_model(wc,
657                                                                                                                                                          WEBKIT_PROCESS_MODEL_MULTIPLE_SECONDARY_PROCESSES);
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         webkit_cookie_manager_set_persistent_storage(cm,
677                                                                                                                                                                                          g_build_filename("/",
678                                                                                                                                                                                                                                                                 g_get_user_cache_dir(),
679                                                                                                                                                                                                                                                                 __NAME__,
680                                                                                                                                                                                                                                                                 "cookies.db",
681                                                                                                                                                                                                                                                                 NULL),
682                                                                                                                                                                                          WEBKIT_COOKIE_PERSISTENT_STORAGE_SQLITE);
683
684         const gchar * const languages[2] = {(const gchar *)cfg.spellcheck_language,
685                 NULL};
686         webkit_web_context_set_spell_checking_languages(wc, languages);
687         webkit_web_context_set_spell_checking_enabled(wc, !cfg.spellcheck_disabled);
688 }
689
690 void
691 search(gpointer data, gint direction)
692 {
693         struct Client *c = (struct Client *)data;
694         WebKitWebView *web_view = WEBKIT_WEB_VIEW(c->web_view);
695         WebKitFindController *fc = webkit_web_view_get_find_controller(web_view);
696
697         if (search_text == NULL)
698                 return;
699
700         switch (direction) {
701         case 0:
702                 webkit_find_controller_search(fc, search_text,
703                                                                                                                                         WEBKIT_FIND_OPTIONS_CASE_INSENSITIVE |
704                                                                                                                                         WEBKIT_FIND_OPTIONS_WRAP_AROUND,
705                                                                                                                                         G_MAXUINT);
706                 break;
707         case 1:
708                 webkit_find_controller_search_next(fc);
709                 break;
710         case -1:
711                 webkit_find_controller_search_previous(fc);
712                 break;
713         case 2:
714                 webkit_find_controller_search_finish(fc);
715                 break;
716         }
717 }
718
719 void
720 search_init(struct Client *c, int direction)
721 {
722         gtk_widget_grab_focus(c->location);
723         const gchar *contents = gtk_entry_get_text(GTK_ENTRY(c->location));
724         if (strcspn(contents, "s/")) {
725                 gtk_entry_set_text(GTK_ENTRY(c->location), "s/");
726         }
727         gtk_editable_set_position(GTK_EDITABLE(c->location), -1);
728         search(c, 0);
729         search(c, -1);
730         search(c, direction);
731 }
732
733 int
734 def_key(char *key, unsigned int def)
735 {
736         char *conf = g_key_file_get_string(config, "keybindings", key, NULL);
737         return (conf) ? gdk_keyval_from_name((conf) ? conf : NULL) : def;
738 }
739
740 gboolean
741 key_common(GtkWidget *widget, GdkEvent *event, gpointer data)
742 {
743         struct Client *c = (struct Client *)data;
744         gdouble now;
745         gchar *f;
746
747         if (event->type == GDK_KEY_PRESS) {
748                 if (((GdkEventKey *)event)->state & GDK_CONTROL_MASK) {
749                         WebKitSettings *settings = webkit_web_view_get_settings(WEBKIT_WEB_VIEW(c->web_view));
750                         gboolean js = webkit_settings_get_enable_javascript(settings);
751                         int key = ((GdkEventKey *)event)->keyval;
752                         if (def_key("download_manager", GDK_KEY_y) == key) {
753                                 downloadmanager_show();
754                                 return TRUE;
755                         } else if (def_key("history_back", GDK_KEY_h) == key) {
756                                 webkit_web_view_go_back(WEBKIT_WEB_VIEW(c->web_view));
757                                 return TRUE;
758                         } else if (def_key("history_forwards", GDK_KEY_l) == key) {
759                                 webkit_web_view_go_forward(WEBKIT_WEB_VIEW(c->web_view));
760                                 return TRUE;
761                         } else if (def_key("location", GDK_KEY_t) == key) {
762                                 gtk_widget_grab_focus(c->location);
763                                 const char *uri = webkit_web_view_get_uri(WEBKIT_WEB_VIEW(c->web_view));
764                                 const char *goal = (uri) ? uri : "https://";
765                                 gtk_entry_set_text(GTK_ENTRY(c->location), goal);
766                                 gtk_editable_set_position(GTK_EDITABLE(c->location), -1);
767                                 return TRUE;
768                         } else if (def_key("print", GDK_KEY_Print) == key) {
769                                 webkit_print_operation_run_dialog(webkit_print_operation_new(WEBKIT_WEB_VIEW(c->web_view)),
770                                                                                                                                                                         GTK_WINDOW(gtk_widget_get_toplevel(mw.win)));
771                                 return TRUE;
772                         } else if (def_key("quit", GDK_KEY_g) == key) {
773                                 search(c, 2);
774                                 gtk_widget_grab_focus(c->web_view);
775                                 gtk_entry_set_text(GTK_ENTRY(c->location),
776                                                                                                          webkit_web_view_get_uri(WEBKIT_WEB_VIEW(c->web_view)));
777                                 webkit_web_view_run_javascript(WEBKIT_WEB_VIEW(c->web_view),
778                                                                                                                                                          "window.getSelection().removeAllRanges();"
779                                                                                                                                                          "document.activeElement.blur();",
780                                                                                                                                                          NULL, NULL, c);
781                                 return TRUE;
782                         } else if (def_key("reload", GDK_KEY_e) == key) {
783                                 webkit_web_view_reload_bypass_cache(WEBKIT_WEB_VIEW(c->web_view));
784                                 return TRUE;
785                         } else if (def_key("scroll_line_down", GDK_KEY_j) == key) {
786                                 for (int i = 0; i < 2; i++) {
787                                         event->key.keyval = GDK_KEY_Down;
788                                         gdk_event_put(event);
789                                 }
790                                 return TRUE;
791                         } else if (def_key("scroll_line_up", GDK_KEY_k) == key) {
792                                 event->key.keyval = GDK_KEY_Up;
793                                 gdk_event_put(event);
794                                 return TRUE;
795                         } else if (def_key("scroll_page_down", GDK_KEY_f) == key) {
796                                 event->key.keyval = GDK_KEY_Page_Down;
797                                 gdk_event_put(event);
798                                 return TRUE;
799                         } else if (def_key("scroll_page_up", GDK_KEY_b) == key) {
800                                 event->key.keyval = GDK_KEY_Page_Up;
801                                 gdk_event_put(event);
802                                 return TRUE;
803                         } else if (def_key("search_forwards", GDK_KEY_s) == key) {
804                                 search_init(c, 1);
805                                 return TRUE;
806                         } else if (def_key("search_backwards", GDK_KEY_r) == key) {
807                                 search_init(c, -1);
808                                 return TRUE;
809                         } else if (def_key("tab_close", GDK_KEY_q) == key) {
810                                 client_destroy(NULL, c);
811                                 return TRUE;
812                         } else if (def_key("tab_switch_1", GDK_KEY_1) == key) {
813                                 gtk_notebook_set_current_page(GTK_NOTEBOOK(mw.notebook), 0);
814                                 return TRUE;
815                         } else if (def_key("tab_switch_2", GDK_KEY_2) == key) {
816                                 gtk_notebook_set_current_page(GTK_NOTEBOOK(mw.notebook), 1);
817                                 return TRUE;
818                         } else if (def_key("tab_switch_3", GDK_KEY_3) == key) {
819                                 gtk_notebook_set_current_page(GTK_NOTEBOOK(mw.notebook), 2);
820                                 return TRUE;
821                         } else if (def_key("tab_switch_4", GDK_KEY_4) == key) {
822                                 gtk_notebook_set_current_page(GTK_NOTEBOOK(mw.notebook), 3);
823                                 return TRUE;
824                         } else if (def_key("tab_switch_5", GDK_KEY_5) == key) {
825                                 gtk_notebook_set_current_page(GTK_NOTEBOOK(mw.notebook), 4);
826                                 return TRUE;
827                         } else if (def_key("tab_switch_6", GDK_KEY_6) == key) {
828                                 gtk_notebook_set_current_page(GTK_NOTEBOOK(mw.notebook), 5);
829                                 return TRUE;
830                         } else if (def_key("tab_switch_7", GDK_KEY_7) == key) {
831                                 gtk_notebook_set_current_page(GTK_NOTEBOOK(mw.notebook), 6);
832                                 return TRUE;
833                         } else if (def_key("tab_switch_8", GDK_KEY_8) == key) {
834                                 gtk_notebook_set_current_page(GTK_NOTEBOOK(mw.notebook), 7);
835                                 return TRUE;
836                         } else if (def_key("tab_switch_9", GDK_KEY_9) == key) {
837                                 gtk_notebook_set_current_page(GTK_NOTEBOOK(mw.notebook), 8);
838                                 return TRUE;
839                         } else if (def_key("tab_previous", GDK_KEY_u) == key) {
840                                 gtk_notebook_prev_page(GTK_NOTEBOOK(mw.notebook));
841                                 return TRUE;
842                         } else if (def_key("tab_mute", GDK_KEY_m) == key) {
843                                 gboolean muted =
844                                         webkit_web_view_get_is_muted(WEBKIT_WEB_VIEW(c->web_view));
845                                 webkit_web_view_set_is_muted(WEBKIT_WEB_VIEW(c->web_view), !muted);
846                                 changed_title(G_OBJECT(c->web_view), NULL, c);
847                                 return TRUE;
848                         } else if (def_key("tab_new", GDK_KEY_w) == key) {
849                                 f = ensure_uri_scheme(cfg.home_uri);
850                                 client_new(f, NULL, TRUE, TRUE);
851                                 g_free(f);
852                                 return TRUE;
853                         } else if (def_key("tab_next", GDK_KEY_i) == key) {
854                                 gtk_notebook_next_page(GTK_NOTEBOOK(mw.notebook));
855                                 return TRUE;
856                         } else if (def_key("toggle_js", GDK_KEY_o) == key) {
857                                 webkit_settings_set_enable_javascript(settings, (js) ? FALSE : TRUE);
858                                 webkit_web_view_set_settings(WEBKIT_WEB_VIEW(c->web_view), settings);
859                                 return TRUE;
860                         } else if (def_key("web_search", GDK_KEY_d) == key) {
861                                 gtk_widget_grab_focus(c->location);
862                                 gtk_entry_set_text(GTK_ENTRY(c->location), "w/");
863                                 gtk_editable_set_position(GTK_EDITABLE(c->location), -1);
864                                 return TRUE;
865                         } else if (def_key("zoom_in", GDK_KEY_equal) == key) {
866                                 now = webkit_web_view_get_zoom_level(WEBKIT_WEB_VIEW(c->web_view));
867                                 webkit_web_view_set_zoom_level(WEBKIT_WEB_VIEW(c->web_view), now + 0.1);
868                                 return TRUE;
869                         } else if (def_key("zoom_out", GDK_KEY_minus) == key) {
870                                 now = webkit_web_view_get_zoom_level(WEBKIT_WEB_VIEW(c->web_view));
871                                 webkit_web_view_set_zoom_level(WEBKIT_WEB_VIEW(c->web_view), now - 0.1);
872                                 return TRUE;
873                         } else if (def_key("zoom_reset", GDK_KEY_0) == key) {
874                                 webkit_web_view_set_zoom_level(WEBKIT_WEB_VIEW(c->web_view),
875                                                                                                                                                          cfg.global_zoom);
876                                 return TRUE;
877                         }
878                 }
879         }
880         return FALSE;
881 }
882
883 gboolean
884 key_location(GtkWidget *widget, GdkEvent *event, gpointer data)
885 {
886         struct Client *c = (struct Client *)data;
887         const gchar *t;
888         gchar *f;
889
890         if (key_common(widget, event, data))
891                 return TRUE;
892
893         if (event->type == GDK_KEY_PRESS) {
894                 int key = ((GdkEventKey *)event)->keyval;
895                 if ((GDK_KEY_KP_Enter == key) || (GDK_KEY_Return == key)) {
896                         gtk_widget_grab_focus(c->web_view);
897                         t = gtk_entry_get_text(GTK_ENTRY(c->location));
898                         if (t != NULL && t[0] == 's' && t[1] == '/') {
899                                 if (search_text != NULL)
900                                         g_free(search_text);
901                                 search_text = g_strdup(t + 2);
902                                 search(c, 0);
903                         } else if (t != NULL && t[0] == 'w' && t[1] == '/') {
904                                 const char *engine = cfg.search_engine;
905                                 int len = strlen(engine) + strlen(t) - 2;
906                                 char *f = (char *) malloc(len);
907                                 snprintf(f, len + 1, "%s%s", engine, t + 2);
908                                 webkit_web_view_load_uri(WEBKIT_WEB_VIEW(c->web_view), f);
909                                 free(f);
910                         } else {
911                                 f = ensure_uri_scheme(t);
912                                 webkit_web_view_load_uri(WEBKIT_WEB_VIEW(c->web_view), f);
913                                 g_free(f);
914                         }
915                         return TRUE;
916                 } else if ((GDK_KEY_Escape == key) ||
917                                                          (def_key("quit", GDK_KEY_g) == key)) {
918                         t = webkit_web_view_get_uri(WEBKIT_WEB_VIEW(c->web_view));
919                         gtk_entry_set_text(GTK_ENTRY(c->location),
920                                                                                                  (t == NULL ? __NAME__ : t));
921                         return TRUE;
922                 }
923         }
924         return FALSE;
925 }
926
927 gboolean
928 key_tablabel(GtkWidget *widget, GdkEvent *event, gpointer data)
929 {
930         GdkScrollDirection direction;
931
932         if (event->type == GDK_BUTTON_RELEASE) {
933                 switch (((GdkEventButton *)event)->button) {
934                 case 2:
935                         client_destroy(NULL, data);
936                         return TRUE;
937                 }
938         } else if (event->type == GDK_SCROLL) {
939                 gdk_event_get_scroll_direction(event, &direction);
940                 switch (direction) {
941                 case GDK_SCROLL_UP:
942                         gtk_notebook_prev_page(GTK_NOTEBOOK(mw.notebook));
943                         break;
944                 case GDK_SCROLL_DOWN:
945                         gtk_notebook_next_page(GTK_NOTEBOOK(mw.notebook));
946                         break;
947                 default:
948                         break;
949                 }
950                 return TRUE;
951         }
952         return FALSE;
953 }
954
955 gboolean
956 key_web_view(GtkWidget *widget, GdkEvent *event, gpointer data)
957 {
958         struct Client *c = (struct Client *)data;
959         gdouble dx, dy;
960         gfloat z;
961
962         if (key_common(widget, event, data))
963                 return TRUE;
964
965         if (event->type == GDK_KEY_PRESS) {
966                 if (((GdkEventKey *)event)->keyval == GDK_KEY_Escape) {
967                         webkit_web_view_stop_loading(WEBKIT_WEB_VIEW(c->web_view));
968                         gtk_entry_set_progress_fraction(GTK_ENTRY(c->location), 0);
969                 }
970         } else if (event->type == GDK_BUTTON_RELEASE) {
971                 switch (((GdkEventButton *)event)->button) {
972                 case 2:
973                         if (c->hover_uri != NULL) {
974                                 client_new(c->hover_uri, NULL, TRUE, FALSE);
975                                 return TRUE;
976                         }
977                         break;
978                 case 8:
979                         webkit_web_view_go_back(WEBKIT_WEB_VIEW(c->web_view));
980                         return TRUE;
981                 case 9:
982                         webkit_web_view_go_forward(WEBKIT_WEB_VIEW(c->web_view));
983                         return TRUE;
984                 }
985         } else if (event->type == GDK_SCROLL) {
986                 if (((GdkEventScroll *)event)->state & GDK_CONTROL_MASK ||
987                                 ((GdkEventScroll *)event)->state & GDK_CONTROL_MASK) {
988                         gdk_event_get_scroll_deltas(event, &dx, &dy);
989                         z = webkit_web_view_get_zoom_level(WEBKIT_WEB_VIEW(c->web_view));
990                         z += -dy * 0.1;
991                         z = dx != 0 ? cfg.global_zoom : z;
992                         webkit_web_view_set_zoom_level(WEBKIT_WEB_VIEW(c->web_view), z);
993                         return TRUE;
994                 }
995         }
996
997         return FALSE;
998 }
999
1000 void
1001 mainwindow_setup(void)
1002 {
1003         mw.win = gtk_window_new(GTK_WINDOW_TOPLEVEL);
1004         gtk_window_set_default_size(GTK_WINDOW(mw.win), 800, 600);
1005         g_signal_connect(G_OBJECT(mw.win), "destroy", gtk_main_quit, NULL);
1006         gtk_window_set_title(GTK_WINDOW(mw.win), __NAME__);
1007
1008         mw.notebook = gtk_notebook_new();
1009         gtk_notebook_set_scrollable(GTK_NOTEBOOK(mw.notebook), TRUE);
1010         gtk_container_add(GTK_CONTAINER(mw.win), mw.notebook);
1011         g_signal_connect(G_OBJECT(mw.notebook), "switch-page",
1012                                                                          G_CALLBACK(notebook_switch_page), NULL);
1013 }
1014
1015 void
1016 mainwindow_title(gint idx)
1017 {
1018         GtkWidget *child, *widg, *tablabel;
1019         const gchar *text;
1020
1021         child = gtk_notebook_get_nth_page(GTK_NOTEBOOK(mw.notebook), idx);
1022         if (child == NULL)
1023                 return;
1024
1025         widg = gtk_notebook_get_tab_label(GTK_NOTEBOOK(mw.notebook), child);
1026         tablabel = (GtkWidget *)g_object_get_data(G_OBJECT(widg), "lariza-tab-label");
1027         text = gtk_label_get_text(GTK_LABEL(tablabel));
1028         gtk_window_set_title(GTK_WINDOW(mw.win), text);
1029 }
1030
1031 void
1032 notebook_switch_page(GtkNotebook *nb, GtkWidget *p, guint idx, gpointer data)
1033 {
1034         mainwindow_title(idx);
1035 }
1036
1037 gboolean
1038 quit_if_nothing_active(void)
1039 {
1040         if (clients == 0) {
1041                 if (downloads == 0) {
1042                         gtk_main_quit();
1043                         return TRUE;
1044                 } else {
1045                         downloadmanager_show();
1046                 }
1047         }
1048
1049         return FALSE;
1050 }
1051
1052 gboolean
1053 remote_msg(GIOChannel *channel, GIOCondition condition, gpointer data)
1054 {
1055         gchar *uri = NULL;
1056
1057         g_io_channel_read_line(channel, &uri, NULL, NULL, NULL);
1058         if (uri) {
1059                 g_strstrip(uri);
1060                 client_new(uri, NULL, TRUE, TRUE);
1061                 g_free(uri);
1062         }
1063         return TRUE;
1064 }
1065
1066 void
1067 run_user_scripts(WebKitWebView *web_view)
1068 {
1069         gchar *base = NULL, *path = NULL, *contents = NULL;
1070         const gchar *entry = NULL;
1071         GDir *scriptdir = NULL;
1072
1073         base = g_build_filename(g_get_user_data_dir(), __NAME__, "user-scripts",
1074                                                                                                         NULL);
1075         scriptdir = g_dir_open(base, 0, NULL);
1076         if (scriptdir != NULL) {
1077                 while ((entry = g_dir_read_name(scriptdir)) != NULL) {
1078                         path = g_build_filename(base, entry, NULL);
1079                         char *jscmd = malloc(strlen(path) + 36);
1080                         sprintf(jscmd, "console.log(\"Running userscript %s\");", path);
1081                         if (g_str_has_suffix(path, ".js")) {
1082                                 if (g_file_get_contents(path, &contents, NULL, NULL)) {
1083                                         webkit_web_view_run_javascript(web_view, jscmd, NULL, NULL, NULL);
1084                                         webkit_web_view_run_javascript(web_view, contents, NULL, NULL, NULL);
1085                                         g_free(contents);
1086                                         g_free(jscmd);
1087                                 }
1088                         }
1089                         g_free(path);
1090                 }
1091                 g_dir_close(scriptdir);
1092         }
1093
1094         g_free(base);
1095 }
1096
1097 void
1098 show_web_view(WebKitWebView *web_view, gpointer data)
1099 {
1100         struct Client *c = (struct Client *)data;
1101         gint idx;
1102
1103         (void)web_view;
1104
1105         gtk_widget_show_all(mw.win);
1106
1107         if (c->focus_new_tab) {
1108                 idx = gtk_notebook_page_num(GTK_NOTEBOOK(mw.notebook), c->vbox);
1109                 if (idx != -1)
1110                         gtk_notebook_set_current_page(GTK_NOTEBOOK(mw.notebook), idx);
1111
1112                 gtk_widget_grab_focus(c->web_view);
1113         }
1114 }
1115
1116 void
1117 trust_user_certs(WebKitWebContext *wc)
1118 {
1119         GTlsCertificate *cert;
1120         const gchar *basedir, *file, *absfile;
1121         GDir *dir;
1122
1123         basedir = g_build_filename(g_get_user_data_dir(), __NAME__, "certs", NULL);
1124         dir = g_dir_open(basedir, 0, NULL);
1125         if (dir != NULL) {
1126                 file = g_dir_read_name(dir);
1127                 while (file != NULL) {
1128                         absfile = g_build_filename(g_get_user_data_dir(), __NAME__, "certs",
1129
1130                                                                                                                                  file, NULL);
1131                         cert = g_tls_certificate_new_from_file(absfile, NULL);
1132                         if (cert == NULL)
1133                                 fprintf(stderr, __NAME__": Could not load trusted cert '%s'\n", file);
1134                         else
1135                                 webkit_web_context_allow_tls_certificate_for_host(wc, cert, file);
1136                         file = g_dir_read_name(dir);
1137                 }
1138                 g_dir_close(dir);
1139         }
1140 }
1141
1142 GKeyFile *
1143 get_ini(void)
1144 {
1145         GKeyFileFlags flags = G_KEY_FILE_NONE;
1146         g_autoptr(GError) error = NULL;
1147         config = g_key_file_new();
1148
1149         // Load user config
1150         if (!g_key_file_load_from_file(config,
1151                                                                                                                                  g_build_filename(g_get_user_config_dir(),
1152                                                                                                                                                                                                         __NAME__, "lariza.ini",
1153                                                                                                                                                                                                         NULL), flags, &error)) {
1154                 // Load global config
1155                 if (!g_key_file_load_from_file(config, "/etc/lariza.ini", flags,
1156                                                                                                                                          &error)) {
1157                         fprintf(stderr, "Could not load lariza.ini: %s", error->message);
1158                 }
1159         }
1160         return config;
1161 }
1162
1163 int
1164 main(int argc, char **argv)
1165 {
1166         int opt, i;
1167
1168         gtk_init(&argc, &argv);
1169         get_config();
1170
1171         while ((opt = getopt(argc, argv, "C")) != -1) {
1172                 switch (opt) {
1173                 case 'C':
1174                         cfg.cooperative_instances = FALSE;
1175                         break;
1176                 default:
1177                         fprintf(stderr, "Usage: "__NAME__" [OPTION]... [URI]...\n");
1178                         exit(EXIT_FAILURE);
1179                 }
1180         }
1181
1182         if (cfg.cooperative_instances)
1183                 cooperation_setup();
1184
1185         if (!cfg.cooperative_instances || cfg.cooperative_alone)
1186                 init_default_web_context();
1187
1188         downloadmanager_setup();
1189         mainwindow_setup();
1190
1191         if (optind >= argc) {
1192                 client_new(cfg.home_uri, NULL, TRUE, TRUE);
1193         } else {
1194                 for (i = optind; i < argc; i++)
1195                         client_new(argv[i], NULL, TRUE, TRUE);
1196         }
1197
1198         if (!cfg.cooperative_instances || cfg.cooperative_alone)
1199                 gtk_main();
1200
1201         exit(EXIT_SUCCESS);
1202 }