]> git.armaanb.net Git - chorizo.git/blob - browser.c
ca8eb37485825635b4d7440f3cdb6f54aae1e8fc
[chorizo.git] / browser.c
1 #include <limits.h>
2 #include <stdio.h>
3 #include <stdlib.h>
4 #include <sys/types.h>
5 #include <sys/stat.h>
6 #include <fcntl.h>
7 #include <string.h>
8
9 #include <gtk/gtk.h>
10 #include <gtk/gtkx.h>
11 #include <gdk/gdkkeysyms.h>
12 #include <gio/gio.h>
13 #include <webkit2/webkit2.h>
14 #include <JavaScriptCore/JavaScript.h>
15
16
17 static gboolean button_tablabel(GtkWidget *, GdkEvent *, gpointer);
18 static void client_destroy(GtkWidget *, gpointer);
19 static WebKitWebView *client_new(const gchar *, WebKitWebView *, gboolean);
20 static WebKitWebView *client_new_request(WebKitWebView *, WebKitNavigationAction *,
21                                          gpointer);
22 static void cooperation_setup(void);
23 static void changed_download_progress(GObject *, GParamSpec *, gpointer);
24 static void changed_load_progress(GObject *, GParamSpec *, gpointer);
25 static void changed_title(GObject *, GParamSpec *, gpointer);
26 static void changed_uri(GObject *, GParamSpec *, gpointer);
27 static gboolean crashed_web_view(WebKitWebView *, gpointer);
28 static gboolean decide_policy(WebKitWebView *, WebKitPolicyDecision *,
29                               WebKitPolicyDecisionType, gpointer);
30 static gboolean download_handle(WebKitDownload *, gchar *, gpointer);
31 static void download_handle_start(WebKitWebView *, WebKitDownload *, gpointer);
32 static void downloadmanager_cancel(GtkToolButton *, gpointer);
33 static gboolean downloadmanager_delete(GtkWidget *, gpointer);
34 static void downloadmanager_setup(void);
35 static gchar *ensure_uri_scheme(const gchar *);
36 static void external_handler_run(GSimpleAction *, GVariant *, gpointer);
37 static void grab_environment_configuration(void);
38 static void grab_feeds_finished(GObject *, GAsyncResult *, gpointer);
39 static void hover_web_view(WebKitWebView *, WebKitHitTestResult *, guint, gpointer);
40 static void icon_location(GtkEntry *, GtkEntryIconPosition, GdkEvent *, gpointer);
41 static gboolean key_common(GtkWidget *, GdkEvent *, gpointer);
42 static gboolean key_downloadmanager(GtkWidget *, GdkEvent *, gpointer);
43 static gboolean key_location(GtkWidget *, GdkEvent *, gpointer);
44 static gboolean key_web_view(GtkWidget *, GdkEvent *, gpointer);
45 static void keywords_load(void);
46 static gboolean keywords_try_search(WebKitWebView *, const gchar *);
47 static void mainwindow_setup(void);
48 static void mainwindow_title(gint);
49 static void mainwindow_title_before(GtkNotebook *, GtkWidget *, guint, gpointer);
50 static gboolean menu_web_view(WebKitWebView *, WebKitContextMenu *, GdkEvent *,
51                               WebKitHitTestResult *, gpointer);
52 static gboolean quit_if_nothing_active(void);
53 static gboolean remote_msg(GIOChannel *, GIOCondition, gpointer);
54 static void run_user_scripts(WebKitWebView *);
55 static void search(gpointer, gint);
56 static void show_web_view(WebKitWebView *, gpointer);
57 static void trust_user_certs(WebKitWebContext *);
58
59
60 struct Client
61 {
62     gchar *external_handler_uri;
63     gchar *hover_uri;
64     gchar *feed_html;
65     GtkWidget *location;
66     GtkWidget *tablabel;
67     GtkWidget *vbox;
68     GtkWidget *web_view;
69 };
70
71 struct MainWindow
72 {
73     GtkWidget *win;
74     GtkWidget *notebook;
75 } mw;
76
77 struct DownloadManager
78 {
79     GtkWidget *scroll;
80     GtkWidget *toolbar;
81     GtkWidget *win;
82 } dm;
83
84
85 static const gchar *accepted_language[2] = { NULL, NULL };
86 static gint clients = 0, downloads = 0;
87 static gboolean cooperative_alone = TRUE;
88 static gboolean cooperative_instances = TRUE;
89 static int cooperative_pipe_fp = 0;
90 static gchar *download_dir = "/var/tmp";
91 static gboolean enable_console_to_stdout = FALSE;
92 static gchar *fifo_suffix = "main";
93 static gdouble global_zoom = 1.0;
94 static gchar *history_file = NULL;
95 static gchar *home_uri = "about:blank";
96 static gboolean initial_wc_setup_done = FALSE;
97 static GHashTable *keywords = NULL;
98 static gchar *search_text = NULL;
99 static GtkPositionType tab_pos = GTK_POS_TOP;
100 static gint tab_width_chars = 20;
101 static gchar *user_agent = NULL;
102
103
104 gboolean
105 button_tablabel(GtkWidget *widget, GdkEvent *event, gpointer data)
106 {
107     if (event->type == GDK_BUTTON_RELEASE)
108     {
109         switch (((GdkEventButton *)event)->button)
110         {
111             case 2:
112                 client_destroy(NULL, data);
113                 return TRUE;
114         }
115     }
116     return FALSE;
117 }
118
119 void
120 client_destroy(GtkWidget *widget, gpointer data)
121 {
122     struct Client *c = (struct Client *)data;
123     gint idx;
124
125     g_signal_handlers_disconnect_by_func(G_OBJECT(c->web_view),
126                                          changed_load_progress, c);
127
128     idx = gtk_notebook_page_num(GTK_NOTEBOOK(mw.notebook), c->vbox);
129     if (idx == -1)
130         fprintf(stderr, __NAME__": Tab index was -1, bamboozled\n");
131     else
132         gtk_notebook_remove_page(GTK_NOTEBOOK(mw.notebook), idx);
133
134     free(c);
135     clients--;
136
137     quit_if_nothing_active();
138 }
139
140 WebKitWebView *
141 client_new(const gchar *uri, WebKitWebView *related_wv, gboolean show)
142 {
143     struct Client *c;
144     WebKitWebContext *wc;
145     gchar *f;
146     GtkWidget *evbox;
147
148     if (uri != NULL && cooperative_instances && !cooperative_alone)
149     {
150         f = ensure_uri_scheme(uri);
151         write(cooperative_pipe_fp, f, strlen(f));
152         write(cooperative_pipe_fp, "\n", 1);
153         g_free(f);
154         return NULL;
155     }
156
157     c = calloc(1, sizeof(struct Client));
158     if (!c)
159     {
160         fprintf(stderr, __NAME__": fatal: calloc failed\n");
161         exit(EXIT_FAILURE);
162     }
163
164     if (related_wv == NULL)
165         c->web_view = webkit_web_view_new();
166     else
167         c->web_view = webkit_web_view_new_with_related_view(related_wv);
168     wc = webkit_web_view_get_context(WEBKIT_WEB_VIEW(c->web_view));
169
170     webkit_web_view_set_zoom_level(WEBKIT_WEB_VIEW(c->web_view), global_zoom);
171     g_signal_connect(G_OBJECT(c->web_view), "notify::title",
172                      G_CALLBACK(changed_title), c);
173     g_signal_connect(G_OBJECT(c->web_view), "notify::uri",
174                      G_CALLBACK(changed_uri), c);
175     g_signal_connect(G_OBJECT(c->web_view), "notify::estimated-load-progress",
176                      G_CALLBACK(changed_load_progress), c);
177     g_signal_connect(G_OBJECT(c->web_view), "create",
178                      G_CALLBACK(client_new_request), NULL);
179     g_signal_connect(G_OBJECT(c->web_view), "context-menu",
180                      G_CALLBACK(menu_web_view), c);
181     g_signal_connect(G_OBJECT(c->web_view), "close",
182                      G_CALLBACK(client_destroy), c);
183     g_signal_connect(G_OBJECT(c->web_view), "decide-policy",
184                      G_CALLBACK(decide_policy), NULL);
185     g_signal_connect(G_OBJECT(c->web_view), "key-press-event",
186                      G_CALLBACK(key_web_view), c);
187     g_signal_connect(G_OBJECT(c->web_view), "button-release-event",
188                      G_CALLBACK(key_web_view), c);
189     g_signal_connect(G_OBJECT(c->web_view), "scroll-event",
190                      G_CALLBACK(key_web_view), c);
191     g_signal_connect(G_OBJECT(c->web_view), "mouse-target-changed",
192                      G_CALLBACK(hover_web_view), c);
193     g_signal_connect(G_OBJECT(c->web_view), "web-process-crashed",
194                      G_CALLBACK(crashed_web_view), c);
195
196     if (!initial_wc_setup_done)
197     {
198         if (accepted_language[0] != NULL)
199             webkit_web_context_set_preferred_languages(wc, accepted_language);
200
201         g_signal_connect(G_OBJECT(wc), "download-started",
202                          G_CALLBACK(download_handle_start), NULL);
203
204         trust_user_certs(wc);
205
206         initial_wc_setup_done = TRUE;
207     }
208
209     if (user_agent != NULL)
210         g_object_set(G_OBJECT(webkit_web_view_get_settings(WEBKIT_WEB_VIEW(c->web_view))),
211                      "user-agent", user_agent, NULL);
212
213     if (enable_console_to_stdout)
214         webkit_settings_set_enable_write_console_messages_to_stdout(webkit_web_view_get_settings(WEBKIT_WEB_VIEW(c->web_view)), TRUE);
215
216     webkit_settings_set_enable_developer_extras(webkit_web_view_get_settings(WEBKIT_WEB_VIEW(c->web_view)), TRUE);
217
218     c->location = gtk_entry_new();
219     g_signal_connect(G_OBJECT(c->location), "key-press-event",
220                      G_CALLBACK(key_location), c);
221     g_signal_connect(G_OBJECT(c->location), "icon-release",
222                      G_CALLBACK(icon_location), c);
223     /* XXX This is a workaround. Setting this to NULL (which is done in
224      * grab_feeds_finished() if no feed has been detected) adds a little
225      * padding left of the text. Not sure why. The point of this call
226      * right here is to have that padding right from the start. This
227      * avoids a graphical artifact. */
228     gtk_entry_set_icon_from_icon_name(GTK_ENTRY(c->location),
229                                       GTK_ENTRY_ICON_PRIMARY,
230                                       NULL);
231
232     c->vbox = gtk_box_new(GTK_ORIENTATION_VERTICAL, 0);
233     gtk_box_pack_start(GTK_BOX(c->vbox), c->location, FALSE, FALSE, 0);
234     gtk_box_pack_start(GTK_BOX(c->vbox), c->web_view, TRUE, TRUE, 0);
235
236     c->tablabel = gtk_label_new(__NAME__);
237     gtk_label_set_ellipsize(GTK_LABEL(c->tablabel), PANGO_ELLIPSIZE_END);
238     gtk_label_set_width_chars(GTK_LABEL(c->tablabel), tab_width_chars);
239
240     evbox = gtk_event_box_new();
241     gtk_container_add(GTK_CONTAINER(evbox), c->tablabel);
242     g_signal_connect(G_OBJECT(evbox), "button-release-event",
243                      G_CALLBACK(button_tablabel), c);
244
245     /* This only shows the event box and the label inside, nothing else.
246      * Needed because the evbox/label is "internal" to the notebook and
247      * not part of the normal "widget tree" (IIUC). */
248     gtk_widget_show_all(evbox);
249
250     gtk_notebook_append_page(GTK_NOTEBOOK(mw.notebook), c->vbox, evbox);
251     gtk_notebook_set_tab_reorderable(GTK_NOTEBOOK(mw.notebook), c->vbox, TRUE);
252
253     if (show)
254         show_web_view(NULL, c);
255     else
256         g_signal_connect(G_OBJECT(c->web_view), "ready-to-show",
257                          G_CALLBACK(show_web_view), c);
258
259     if (uri != NULL)
260     {
261         f = ensure_uri_scheme(uri);
262         webkit_web_view_load_uri(WEBKIT_WEB_VIEW(c->web_view), f);
263         g_free(f);
264     }
265
266     clients++;
267
268     return WEBKIT_WEB_VIEW(c->web_view);
269 }
270
271 WebKitWebView *
272 client_new_request(WebKitWebView *web_view,
273                    WebKitNavigationAction *navigation_action, gpointer data)
274 {
275     return client_new(NULL, web_view, FALSE);
276 }
277
278 void
279 cooperation_setup(void)
280 {
281     GIOChannel *towatch;
282     gchar *fifofilename, *fifopath;
283
284     fifofilename = g_strdup_printf("%s-%s", __NAME__".fifo", fifo_suffix);
285     fifopath = g_build_filename(g_get_user_runtime_dir(), fifofilename, NULL);
286     g_free(fifofilename);
287
288     if (!g_file_test(fifopath, G_FILE_TEST_EXISTS))
289         mkfifo(fifopath, 0600);
290
291     cooperative_pipe_fp = open(fifopath, O_WRONLY | O_NONBLOCK);
292     if (!cooperative_pipe_fp)
293     {
294         fprintf(stderr, __NAME__": Can't open FIFO at all.\n");
295     }
296     else
297     {
298         if (write(cooperative_pipe_fp, "", 0) == -1)
299         {
300             /* Could not do an empty write to the FIFO which means there's
301              * no one listening. */
302             close(cooperative_pipe_fp);
303             towatch = g_io_channel_new_file(fifopath, "r+", NULL);
304             g_io_add_watch(towatch, G_IO_IN, (GIOFunc)remote_msg, NULL);
305         }
306         else
307             cooperative_alone = FALSE;
308     }
309
310     g_free(fifopath);
311 }
312
313 void
314 changed_download_progress(GObject *obj, GParamSpec *pspec, gpointer data)
315 {
316     WebKitDownload *download = WEBKIT_DOWNLOAD(obj);
317     WebKitURIResponse *resp;
318     GtkToolItem *tb = GTK_TOOL_ITEM(data);
319     gdouble p, size_mb;
320     const gchar *uri;
321     gchar *t, *filename, *base;
322
323     p = webkit_download_get_estimated_progress(download);
324     p = p > 1 ? 1 : p;
325     p = p < 0 ? 0 : p;
326     p *= 100;
327     resp = webkit_download_get_response(download);
328     size_mb = webkit_uri_response_get_content_length(resp) / 1e6;
329
330     uri = webkit_download_get_destination(download);
331     filename = g_filename_from_uri(uri, NULL, NULL);
332     if (filename == NULL)
333     {
334         /* This really should not happen because WebKit uses that URI to
335          * write to a file... */
336         fprintf(stderr, __NAME__": Could not construct file name from URI!\n");
337         t = g_strdup_printf("%s (%.0f%% of %.1f MB)",
338                             webkit_uri_response_get_uri(resp), p, size_mb);
339     }
340     else
341     {
342         base = g_path_get_basename(filename);
343         t = g_strdup_printf("%s (%.0f%% of %.1f MB)", base, p, size_mb);
344         g_free(filename);
345         g_free(base);
346     }
347     gtk_tool_button_set_label(GTK_TOOL_BUTTON(tb), t);
348     g_free(t);
349 }
350
351 void
352 changed_load_progress(GObject *obj, GParamSpec *pspec, gpointer data)
353 {
354     struct Client *c = (struct Client *)data;
355     gdouble p;
356     gchar *grab_feeds =
357         "a = document.querySelectorAll('"
358         "    html > head > link[rel=\"alternate\"][href][type=\"application/atom+xml\"],"
359         "    html > head > link[rel=\"alternate\"][href][type=\"application/rss+xml\"]"
360         "');"
361         "if (a.length == 0)"
362         "    null;"
363         "else"
364         "{"
365         "    out = '';"
366         "    for (i = 0; i < a.length; i++)"
367         "    {"
368         "        url = encodeURIComponent(a[i].href);"
369         "        if ('title' in a[i] && a[i].title != '')"
370         "            title = encodeURIComponent(a[i].title);"
371         "        else"
372         "            title = url;"
373         "        out += '<li><a href=\"' + url + '\">' + title + '</a></li>';"
374         "    }"
375         "    out;"
376         "}";
377
378     p = webkit_web_view_get_estimated_load_progress(WEBKIT_WEB_VIEW(c->web_view));
379     if (p == 1)
380     {
381         p = 0;
382
383         /* The page has loaded fully. We now run the short JavaScript
384          * snippet above that operates on the DOM. It tries to grab all
385          * occurences of <link rel="alternate" ...>, i.e. RSS/Atom feed
386          * references. */
387         webkit_web_view_run_javascript(WEBKIT_WEB_VIEW(c->web_view),
388                                        grab_feeds, NULL,
389                                        grab_feeds_finished, c);
390
391         run_user_scripts(WEBKIT_WEB_VIEW(c->web_view));
392     }
393     gtk_entry_set_progress_fraction(GTK_ENTRY(c->location), p);
394 }
395
396 void
397 changed_title(GObject *obj, GParamSpec *pspec, gpointer data)
398 {
399     const gchar *t, *u;
400     struct Client *c = (struct Client *)data;
401
402     u = webkit_web_view_get_uri(WEBKIT_WEB_VIEW(c->web_view));
403     t = webkit_web_view_get_title(WEBKIT_WEB_VIEW(c->web_view));
404
405     u = u == NULL ? __NAME__ : u;
406     u = u[0] == 0 ? __NAME__ : u;
407
408     t = t == NULL ? u : t;
409     t = t[0] == 0 ? u : t;
410
411     gtk_label_set_text(GTK_LABEL(c->tablabel), t);
412     mainwindow_title(-1);
413 }
414
415 void
416 changed_uri(GObject *obj, GParamSpec *pspec, gpointer data)
417 {
418     const gchar *t;
419     struct Client *c = (struct Client *)data;
420     FILE *fp;
421
422     t = webkit_web_view_get_uri(WEBKIT_WEB_VIEW(c->web_view));
423
424     /* When a web process crashes, we get a "notify::uri" signal, but we
425      * can no longer read a meaningful URI. It's just an empty string
426      * now. Not updating the location bar in this scenario is important,
427      * because we would override the "WEB PROCESS CRASHED" message. */
428     if (t != NULL && strlen(t) > 0)
429     {
430         gtk_entry_set_text(GTK_ENTRY(c->location), t);
431
432         if (history_file != NULL)
433         {
434             fp = fopen(history_file, "a");
435             if (fp != NULL)
436             {
437                 fprintf(fp, "%s\n", t);
438                 fclose(fp);
439             }
440             else
441                 perror(__NAME__": Error opening history file");
442         }
443     }
444 }
445
446 gboolean
447 crashed_web_view(WebKitWebView *web_view, gpointer data)
448 {
449     gchar *t;
450     struct Client *c = (struct Client *)data;
451
452     t = g_strdup_printf("WEB PROCESS CRASHED: %s",
453                         webkit_web_view_get_uri(WEBKIT_WEB_VIEW(web_view)));
454     gtk_entry_set_text(GTK_ENTRY(c->location), t);
455     g_free(t);
456
457     return TRUE;
458 }
459
460 gboolean
461 decide_policy(WebKitWebView *web_view, WebKitPolicyDecision *decision,
462               WebKitPolicyDecisionType type, gpointer data)
463 {
464     WebKitResponsePolicyDecision *r;
465
466     switch (type)
467     {
468         case WEBKIT_POLICY_DECISION_TYPE_RESPONSE:
469             r = WEBKIT_RESPONSE_POLICY_DECISION(decision);
470             if (!webkit_response_policy_decision_is_mime_type_supported(r))
471                 webkit_policy_decision_download(decision);
472             else
473                 webkit_policy_decision_use(decision);
474             break;
475         default:
476             /* Use whatever default there is. */
477             return FALSE;
478     }
479     return TRUE;
480 }
481
482 void
483 download_handle_finished(WebKitDownload *download, gpointer data)
484 {
485     downloads--;
486 }
487
488 void
489 download_handle_start(WebKitWebView *web_view, WebKitDownload *download,
490                       gpointer data)
491 {
492     g_signal_connect(G_OBJECT(download), "decide-destination",
493                      G_CALLBACK(download_handle), data);
494 }
495
496 gboolean
497 download_handle(WebKitDownload *download, gchar *suggested_filename, gpointer data)
498 {
499     gchar *sug_clean, *path, *path2 = NULL, *uri;
500     GtkToolItem *tb;
501     int suffix = 1;
502     size_t i;
503
504     sug_clean = g_strdup(suggested_filename);
505     for (i = 0; i < strlen(sug_clean); i++)
506         if (sug_clean[i] == G_DIR_SEPARATOR)
507             sug_clean[i] = '_';
508
509     path = g_build_filename(download_dir, sug_clean, NULL);
510     path2 = g_strdup(path);
511     while (g_file_test(path2, G_FILE_TEST_EXISTS) && suffix < 1000)
512     {
513         g_free(path2);
514
515         path2 = g_strdup_printf("%s.%d", path, suffix);
516         suffix++;
517     }
518
519     if (suffix == 1000)
520     {
521         fprintf(stderr, __NAME__": Suffix reached limit for download.\n");
522         webkit_download_cancel(download);
523     }
524     else
525     {
526         uri = g_filename_to_uri(path2, NULL, NULL);
527         webkit_download_set_destination(download, uri);
528         g_free(uri);
529
530         tb = gtk_tool_button_new(NULL, NULL);
531         gtk_tool_button_set_icon_name(GTK_TOOL_BUTTON(tb), "gtk-delete");
532         gtk_tool_button_set_label(GTK_TOOL_BUTTON(tb), sug_clean);
533         gtk_toolbar_insert(GTK_TOOLBAR(dm.toolbar), tb, 0);
534         gtk_widget_show_all(dm.win);
535
536         g_signal_connect(G_OBJECT(download), "notify::estimated-progress",
537                          G_CALLBACK(changed_download_progress), tb);
538
539         downloads++;
540         g_signal_connect(G_OBJECT(download), "finished",
541                          G_CALLBACK(download_handle_finished), NULL);
542
543         g_object_ref(download);
544         g_signal_connect(G_OBJECT(tb), "clicked",
545                          G_CALLBACK(downloadmanager_cancel), download);
546     }
547
548     g_free(sug_clean);
549     g_free(path);
550     g_free(path2);
551
552     /* Propagate -- to whom it may concern. */
553     return FALSE;
554 }
555
556 void
557 downloadmanager_cancel(GtkToolButton *tb, gpointer data)
558 {
559     WebKitDownload *download = WEBKIT_DOWNLOAD(data);
560
561     webkit_download_cancel(download);
562     g_object_unref(download);
563
564     gtk_widget_destroy(GTK_WIDGET(tb));
565 }
566
567 gboolean
568 downloadmanager_delete(GtkWidget *obj, gpointer data)
569 {
570     if (!quit_if_nothing_active())
571         gtk_widget_hide(dm.win);
572
573     return TRUE;
574 }
575
576 void
577 downloadmanager_setup(void)
578 {
579     dm.win = gtk_window_new(GTK_WINDOW_TOPLEVEL);
580     gtk_window_set_type_hint(GTK_WINDOW(dm.win), GDK_WINDOW_TYPE_HINT_DIALOG);
581     gtk_window_set_default_size(GTK_WINDOW(dm.win), 500, 250);
582     gtk_window_set_title(GTK_WINDOW(dm.win), __NAME__" - Download Manager");
583     g_signal_connect(G_OBJECT(dm.win), "delete-event",
584                      G_CALLBACK(downloadmanager_delete), NULL);
585     g_signal_connect(G_OBJECT(dm.win), "key-press-event",
586                      G_CALLBACK(key_downloadmanager), NULL);
587
588     dm.toolbar = gtk_toolbar_new();
589     gtk_orientable_set_orientation(GTK_ORIENTABLE(dm.toolbar),
590                                    GTK_ORIENTATION_VERTICAL);
591     gtk_toolbar_set_style(GTK_TOOLBAR(dm.toolbar), GTK_TOOLBAR_BOTH_HORIZ);
592     gtk_toolbar_set_show_arrow(GTK_TOOLBAR(dm.toolbar), FALSE);
593
594     dm.scroll = gtk_scrolled_window_new(NULL, NULL);
595     gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(dm.scroll),
596                                    GTK_POLICY_AUTOMATIC, GTK_POLICY_AUTOMATIC);
597     gtk_container_add(GTK_CONTAINER(dm.scroll), dm.toolbar);
598
599     gtk_container_add(GTK_CONTAINER(dm.win), dm.scroll);
600 }
601
602 gchar *
603 ensure_uri_scheme(const gchar *t)
604 {
605     gchar *f, *fabs;
606
607     f = g_ascii_strdown(t, -1);
608     if (!g_str_has_prefix(f, "http:") &&
609         !g_str_has_prefix(f, "https:") &&
610         !g_str_has_prefix(f, "file:") &&
611         !g_str_has_prefix(f, "about:") &&
612         !g_str_has_prefix(f, "data:"))
613     {
614         g_free(f);
615         fabs = realpath(t, NULL);
616         if (fabs != NULL)
617         {
618             f = g_strdup_printf("file://%s", fabs);
619             free(fabs);
620         }
621         else
622             f = g_strdup_printf("http://%s", t);
623         return f;
624     }
625     else
626         return g_strdup(t);
627 }
628
629 void
630 external_handler_run(GSimpleAction *simple, GVariant *param, gpointer data)
631 {
632     struct Client *c = (struct Client *)data;
633     gchar *argv[] = { "lariza-external-handler", "-u", NULL, NULL };
634     GPid pid;
635     GError *err = NULL;
636
637     (void)simple;
638     (void)param;
639
640     argv[2] = c->external_handler_uri;
641     if (!g_spawn_async(NULL, argv, NULL, G_SPAWN_SEARCH_PATH, NULL, NULL,
642                        &pid, &err))
643     {
644         fprintf(stderr, __NAME__": Could not launch key handler: %s\n",
645                 err->message);
646         g_error_free(err);
647     }
648     else
649         g_spawn_close_pid(pid);
650 }
651
652 void
653 grab_environment_configuration(void)
654 {
655     const gchar *e;
656
657     e = g_getenv(__NAME_UPPERCASE__"_ACCEPTED_LANGUAGE");
658     if (e != NULL)
659         accepted_language[0] = g_strdup(e);
660
661     e = g_getenv(__NAME_UPPERCASE__"_DOWNLOAD_DIR");
662     if (e != NULL)
663         download_dir = g_strdup(e);
664
665     e = g_getenv(__NAME_UPPERCASE__"_ENABLE_CONSOLE_TO_STDOUT");
666     if (e != NULL)
667         enable_console_to_stdout = TRUE;
668
669     e = g_getenv(__NAME_UPPERCASE__"_FIFO_SUFFIX");
670     if (e != NULL)
671         fifo_suffix = g_strdup(e);
672
673     e = g_getenv(__NAME_UPPERCASE__"_HISTORY_FILE");
674     if (e != NULL)
675         history_file = g_strdup(e);
676
677     e = g_getenv(__NAME_UPPERCASE__"_HOME_URI");
678     if (e != NULL)
679         home_uri = g_strdup(e);
680
681     e = g_getenv(__NAME_UPPERCASE__"_TAB_POS");
682     if (e != NULL)
683     {
684         if (strcmp(e, "top") == 0)
685             tab_pos = GTK_POS_TOP;
686         if (strcmp(e, "right") == 0)
687             tab_pos = GTK_POS_RIGHT;
688         if (strcmp(e, "bottom") == 0)
689             tab_pos = GTK_POS_BOTTOM;
690         if (strcmp(e, "left") == 0)
691             tab_pos = GTK_POS_LEFT;
692     }
693
694     e = g_getenv(__NAME_UPPERCASE__"_TAB_WIDTH_CHARS");
695     if (e != NULL)
696         tab_width_chars = atoi(e);
697
698     e = g_getenv(__NAME_UPPERCASE__"_USER_AGENT");
699     if (e != NULL)
700         user_agent = g_strdup(e);
701
702     e = g_getenv(__NAME_UPPERCASE__"_ZOOM");
703     if (e != NULL)
704         global_zoom = atof(e);
705 }
706
707 void
708 grab_feeds_finished(GObject *object, GAsyncResult *result, gpointer data)
709 {
710     struct Client *c = (struct Client *)data;
711     WebKitJavascriptResult *js_result;
712     JSCValue *value;
713     JSCException *exception;
714     GError *err = NULL;
715     gchar *str_value;
716
717     g_free(c->feed_html);
718     c->feed_html = NULL;
719
720     /* This was taken almost verbatim from the example in WebKit's
721      * documentation:
722      *
723      * https://webkitgtk.org/reference/webkit2gtk/stable/WebKitWebView.html#webkit-web-view-run-javascript-finish */
724
725     js_result = webkit_web_view_run_javascript_finish(WEBKIT_WEB_VIEW(object),
726                                                       result, &err);
727     if (!js_result)
728     {
729         fprintf(stderr, __NAME__": Error running javascript: %s\n", err->message);
730         g_error_free(err);
731         return;
732     }
733
734     value = webkit_javascript_result_get_js_value(js_result);
735     if (jsc_value_is_string(value))
736     {
737         str_value = jsc_value_to_string(value);
738         exception = jsc_context_get_exception(jsc_value_get_context(value));
739         if (exception != NULL)
740         {
741             fprintf(stderr, __NAME__": Error running javascript: %s\n",
742                     jsc_exception_get_message(exception));
743         }
744         else
745             c->feed_html = str_value;
746
747         gtk_entry_set_icon_from_icon_name(GTK_ENTRY(c->location),
748                                           GTK_ENTRY_ICON_PRIMARY,
749                                           "application-rss+xml-symbolic");
750         gtk_entry_set_icon_activatable(GTK_ENTRY(c->location),
751                                        GTK_ENTRY_ICON_PRIMARY,
752                                        TRUE);
753     }
754     else
755     {
756         gtk_entry_set_icon_from_icon_name(GTK_ENTRY(c->location),
757                                           GTK_ENTRY_ICON_PRIMARY,
758                                           NULL);
759     }
760
761     webkit_javascript_result_unref(js_result);
762 }
763
764 void
765 hover_web_view(WebKitWebView *web_view, WebKitHitTestResult *ht, guint modifiers,
766                gpointer data)
767 {
768     struct Client *c = (struct Client *)data;
769
770     if (!gtk_widget_is_focus(c->location))
771     {
772         if (webkit_hit_test_result_context_is_link(ht))
773         {
774             gtk_entry_set_text(GTK_ENTRY(c->location),
775                                webkit_hit_test_result_get_link_uri(ht));
776
777             if (c->hover_uri != NULL)
778                 g_free(c->hover_uri);
779             c->hover_uri = g_strdup(webkit_hit_test_result_get_link_uri(ht));
780         }
781         else
782         {
783             gtk_entry_set_text(GTK_ENTRY(c->location),
784                                webkit_web_view_get_uri(WEBKIT_WEB_VIEW(c->web_view)));
785
786             if (c->hover_uri != NULL)
787                 g_free(c->hover_uri);
788             c->hover_uri = NULL;
789         }
790     }
791 }
792
793 void
794 icon_location(GtkEntry *entry, GtkEntryIconPosition icon_pos, GdkEvent *event,
795               gpointer data)
796 {
797     struct Client *c = (struct Client *)data;
798     gchar *d;
799     gchar *data_template =
800         "data:text/html,"
801         "<!DOCTYPE html>"
802         "<html>"
803         "    <head>"
804         "        <meta charset=\"UTF-8\">"
805         "        <title>Feeds</title>"
806         "    </head>"
807         "    <body>"
808         "        <p>Feeds found on this page:</p>"
809         "        <ul>"
810         "        %s"
811         "        </ul>"
812         "    </body>"
813         "</html>";
814
815     if (c->feed_html != NULL)
816     {
817         /* What we're actually trying to do is show a simple HTML page
818          * that lists all the feeds on the current page. The function
819          * webkit_web_view_load_html() looks like the proper way to do
820          * that. Sad thing is, it doesn't create a history entry, but
821          * instead simply replaces the content of the current page. This
822          * is not what we want.
823          *
824          * RFC 2397 [0] defines the data URI scheme [1]. We abuse this
825          * mechanism to show my custom HTML snippet *and* create a
826          * history entry.
827          *
828          * [0]: https://tools.ietf.org/html/rfc2397
829          * [1]: https://en.wikipedia.org/wiki/Data_URI_scheme */
830         d = g_strdup_printf(data_template, c->feed_html);
831         webkit_web_view_load_uri(WEBKIT_WEB_VIEW(c->web_view), d);
832         g_free(d);
833     }
834 }
835
836 gboolean
837 key_common(GtkWidget *widget, GdkEvent *event, gpointer data)
838 {
839     struct Client *c = (struct Client *)data;
840     WebKitWebContext *wc = webkit_web_view_get_context(WEBKIT_WEB_VIEW(c->web_view));
841     gchar *f;
842
843     if (event->type == GDK_KEY_PRESS)
844     {
845         if (((GdkEventKey *)event)->state & GDK_MOD1_MASK)
846         {
847             switch (((GdkEventKey *)event)->keyval)
848             {
849                 case GDK_KEY_q:  /* close window (left hand) */
850                     client_destroy(NULL, c);
851                     return TRUE;
852                 case GDK_KEY_w:  /* home (left hand) */
853                     f = ensure_uri_scheme(home_uri);
854                     webkit_web_view_load_uri(WEBKIT_WEB_VIEW(c->web_view), f);
855                     g_free(f);
856                     return TRUE;
857                 case GDK_KEY_e:  /* new tab (left hand) */
858                     f = ensure_uri_scheme(home_uri);
859                     client_new(f, NULL, TRUE);
860                     g_free(f);
861                     return TRUE;
862                 case GDK_KEY_r:  /* reload (left hand) */
863                     webkit_web_view_reload_bypass_cache(WEBKIT_WEB_VIEW(
864                                                         c->web_view));
865                     return TRUE;
866                 case GDK_KEY_d:  /* download manager (left hand) */
867                     gtk_widget_show_all(dm.win);
868                     return TRUE;
869                 case GDK_KEY_2:  /* search forward (left hand) */
870                 case GDK_KEY_n:  /* search forward (maybe both hands) */
871                     search(c, 1);
872                     return TRUE;
873                 case GDK_KEY_3:  /* search backward (left hand) */
874                     search(c, -1);
875                     return TRUE;
876                 case GDK_KEY_l:  /* location (BOTH hands) */
877                     gtk_widget_grab_focus(c->location);
878                     return TRUE;
879                 case GDK_KEY_k:  /* initiate search (BOTH hands) */
880                     gtk_widget_grab_focus(c->location);
881                     gtk_entry_set_text(GTK_ENTRY(c->location), ":/");
882                     gtk_editable_set_position(GTK_EDITABLE(c->location), -1);
883                     return TRUE;
884                 case GDK_KEY_c:  /* reload trusted certs (left hand) */
885                     trust_user_certs(wc);
886                     return TRUE;
887                 case GDK_KEY_x:  /* launch external handler (left hand) */
888                     if (c->external_handler_uri != NULL)
889                         g_free(c->external_handler_uri);
890                     c->external_handler_uri = g_strdup(
891                         webkit_web_view_get_uri(WEBKIT_WEB_VIEW(c->web_view)));
892                     external_handler_run(NULL, NULL, c);
893                     return TRUE;
894                 case GDK_KEY_a:  /* go one tab to the left (left hand) */
895                     gtk_notebook_prev_page(GTK_NOTEBOOK(mw.notebook));
896                     return TRUE;
897                 case GDK_KEY_s:  /* go one tab to the right (left hand) */
898                     gtk_notebook_next_page(GTK_NOTEBOOK(mw.notebook));
899                     return TRUE;
900             }
901         }
902         /* navigate backward (left hand) */
903         else if (((GdkEventKey *)event)->keyval == GDK_KEY_F2)
904         {
905             webkit_web_view_go_back(WEBKIT_WEB_VIEW(c->web_view));
906             return TRUE;
907         }
908         /* navigate forward (left hand) */
909         else if (((GdkEventKey *)event)->keyval == GDK_KEY_F3)
910         {
911             webkit_web_view_go_forward(WEBKIT_WEB_VIEW(c->web_view));
912             return TRUE;
913         }
914     }
915
916     return FALSE;
917 }
918
919 gboolean
920 key_downloadmanager(GtkWidget *widget, GdkEvent *event, gpointer data)
921 {
922     if (event->type == GDK_KEY_PRESS)
923     {
924         if (((GdkEventKey *)event)->state & GDK_MOD1_MASK)
925         {
926             switch (((GdkEventKey *)event)->keyval)
927             {
928                 case GDK_KEY_d:  /* close window (left hand) */
929                 case GDK_KEY_q:
930                     downloadmanager_delete(dm.win, NULL);
931                     return TRUE;
932             }
933         }
934     }
935
936     return FALSE;
937 }
938
939 gboolean
940 key_location(GtkWidget *widget, GdkEvent *event, gpointer data)
941 {
942     struct Client *c = (struct Client *)data;
943     const gchar *t;
944     gchar *f;
945
946     if (key_common(widget, event, data))
947         return TRUE;
948
949     if (event->type == GDK_KEY_PRESS)
950     {
951         switch (((GdkEventKey *)event)->keyval)
952         {
953             case GDK_KEY_KP_Enter:
954             case GDK_KEY_Return:
955                 gtk_widget_grab_focus(c->web_view);
956                 t = gtk_entry_get_text(GTK_ENTRY(c->location));
957                 if (t != NULL && t[0] == ':' && t[1] == '/')
958                 {
959                     if (search_text != NULL)
960                         g_free(search_text);
961                     search_text = g_strdup(t + 2);
962                     search(c, 0);
963                 }
964                 else if (!keywords_try_search(WEBKIT_WEB_VIEW(c->web_view), t))
965                 {
966                     f = ensure_uri_scheme(t);
967                     webkit_web_view_load_uri(WEBKIT_WEB_VIEW(c->web_view), f);
968                     g_free(f);
969                 }
970                 return TRUE;
971             case GDK_KEY_Escape:
972                 t = webkit_web_view_get_uri(WEBKIT_WEB_VIEW(c->web_view));
973                 gtk_entry_set_text(GTK_ENTRY(c->location),
974                                    (t == NULL ? __NAME__ : t));
975                 return TRUE;
976         }
977     }
978
979     return FALSE;
980 }
981
982 gboolean
983 key_web_view(GtkWidget *widget, GdkEvent *event, gpointer data)
984 {
985     struct Client *c = (struct Client *)data;
986     gdouble dx, dy;
987     gfloat z;
988
989     if (key_common(widget, event, data))
990         return TRUE;
991
992     if (event->type == GDK_KEY_PRESS)
993     {
994         if (((GdkEventKey *)event)->keyval == GDK_KEY_Escape)
995         {
996             webkit_web_view_stop_loading(WEBKIT_WEB_VIEW(c->web_view));
997             gtk_entry_set_progress_fraction(GTK_ENTRY(c->location), 0);
998         }
999     }
1000     else if (event->type == GDK_BUTTON_RELEASE)
1001     {
1002         switch (((GdkEventButton *)event)->button)
1003         {
1004             case 2:
1005                 if (c->hover_uri != NULL)
1006                 {
1007                     client_new(c->hover_uri, NULL, TRUE);
1008                     return TRUE;
1009                 }
1010                 break;
1011             case 8:
1012                 webkit_web_view_go_back(WEBKIT_WEB_VIEW(c->web_view));
1013                 return TRUE;
1014             case 9:
1015                 webkit_web_view_go_forward(WEBKIT_WEB_VIEW(c->web_view));
1016                 return TRUE;
1017         }
1018     }
1019     else if (event->type == GDK_SCROLL)
1020     {
1021         if (((GdkEventScroll *)event)->state & GDK_MOD1_MASK ||
1022             ((GdkEventScroll *)event)->state & GDK_CONTROL_MASK)
1023         {
1024             gdk_event_get_scroll_deltas(event, &dx, &dy);
1025             z = webkit_web_view_get_zoom_level(WEBKIT_WEB_VIEW(c->web_view));
1026             z += -dy * 0.1;
1027             z = dx != 0 ? global_zoom : z;
1028             webkit_web_view_set_zoom_level(WEBKIT_WEB_VIEW(c->web_view), z);
1029             return TRUE;
1030         }
1031     }
1032
1033     return FALSE;
1034 }
1035
1036 void
1037 keywords_load(void)
1038 {
1039     GError *err = NULL;
1040     GIOChannel *channel = NULL;
1041     gchar *path = NULL, *buf = NULL;
1042     gchar **tokens = NULL;
1043
1044     keywords = g_hash_table_new(g_str_hash, g_str_equal);
1045
1046     path = g_build_filename(g_get_user_config_dir(), __NAME__, "keywordsearch",
1047                             NULL);
1048     channel = g_io_channel_new_file(path, "r", &err);
1049     if (channel != NULL)
1050     {
1051         while (g_io_channel_read_line(channel, &buf, NULL, NULL, NULL)
1052                == G_IO_STATUS_NORMAL)
1053         {
1054             g_strstrip(buf);
1055             if (buf[0] != '#')
1056             {
1057                 tokens = g_strsplit(buf, " ", 2);
1058                 if (tokens[0] != NULL && tokens[1] != NULL)
1059                     g_hash_table_insert(keywords, g_strdup(tokens[0]),
1060                                         g_strdup(tokens[1]));
1061                 g_strfreev(tokens);
1062             }
1063             g_free(buf);
1064         }
1065         g_io_channel_shutdown(channel, FALSE, NULL);
1066     }
1067     g_free(path);
1068 }
1069
1070 gboolean
1071 keywords_try_search(WebKitWebView *web_view, const gchar *t)
1072 {
1073     gboolean ret = FALSE;
1074     gchar **tokens = NULL;
1075     gchar *val = NULL, *escaped = NULL, *uri = NULL;
1076
1077     tokens = g_strsplit(t, " ", 2);
1078     if (tokens[0] != NULL && tokens[1] != NULL)
1079     {
1080         val = g_hash_table_lookup(keywords, tokens[0]);
1081         if (val != NULL)
1082         {
1083             escaped = g_uri_escape_string(tokens[1], NULL, TRUE);
1084             uri = g_strdup_printf((gchar *)val, escaped);
1085             webkit_web_view_load_uri(web_view, uri);
1086             g_free(uri);
1087             g_free(escaped);
1088             ret = TRUE;
1089         }
1090     }
1091     g_strfreev(tokens);
1092
1093     return ret;
1094 }
1095
1096 void
1097 mainwindow_setup(void)
1098 {
1099     mw.win = gtk_window_new(GTK_WINDOW_TOPLEVEL);
1100     gtk_window_set_default_size(GTK_WINDOW(mw.win), 800, 600);
1101     g_signal_connect(G_OBJECT(mw.win), "destroy", gtk_main_quit, NULL);
1102     gtk_window_set_title(GTK_WINDOW(mw.win), __NAME__);
1103
1104     mw.notebook = gtk_notebook_new();
1105     gtk_notebook_set_scrollable(GTK_NOTEBOOK(mw.notebook), TRUE);
1106     gtk_notebook_set_tab_pos(GTK_NOTEBOOK(mw.notebook), tab_pos);
1107     gtk_container_add(GTK_CONTAINER(mw.win), mw.notebook);
1108     g_signal_connect(G_OBJECT(mw.notebook), "switch-page",
1109                      G_CALLBACK(mainwindow_title_before), NULL);
1110 }
1111
1112 void
1113 mainwindow_title_before(GtkNotebook *nb, GtkWidget *p, guint idx, gpointer data)
1114 {
1115     mainwindow_title(idx);
1116 }
1117
1118 void
1119 mainwindow_title(gint idx)
1120 {
1121     GtkWidget *child, *evbox, *label;
1122     const gchar *text;
1123
1124     if (idx == -1)
1125     {
1126         idx = gtk_notebook_get_current_page(GTK_NOTEBOOK(mw.notebook));
1127         if (idx == -1)
1128             return;
1129     }
1130
1131     child = gtk_notebook_get_nth_page(GTK_NOTEBOOK(mw.notebook), idx);
1132     if (child == NULL)
1133         return;
1134
1135     evbox = gtk_notebook_get_tab_label(GTK_NOTEBOOK(mw.notebook), child);
1136     label = gtk_bin_get_child(GTK_BIN(evbox));
1137     text = gtk_label_get_text(GTK_LABEL(label));
1138     gtk_window_set_title(GTK_WINDOW(mw.win), text);
1139 }
1140
1141 gboolean
1142 menu_web_view(WebKitWebView *web_view, WebKitContextMenu *menu, GdkEvent *ev,
1143               WebKitHitTestResult *ht, gpointer data)
1144 {
1145     struct Client *c = (struct Client *)data;
1146     GSimpleAction *action = NULL;
1147     WebKitContextMenuItem *mi = NULL;
1148     const gchar *uri = NULL;
1149
1150     (void)ev;
1151
1152     if (webkit_hit_test_result_context_is_link(ht))
1153         uri = webkit_hit_test_result_get_link_uri(ht);
1154     else if (webkit_hit_test_result_context_is_image(ht))
1155         uri = webkit_hit_test_result_get_image_uri(ht);
1156     else if (webkit_hit_test_result_context_is_media(ht))
1157         uri = webkit_hit_test_result_get_media_uri(ht);
1158
1159     if (uri != NULL)
1160     {
1161         webkit_context_menu_append(menu, webkit_context_menu_item_new_separator());
1162
1163         if (c->external_handler_uri != NULL)
1164             g_free(c->external_handler_uri);
1165         c->external_handler_uri = g_strdup(uri);
1166         action = g_simple_action_new("external_handler", NULL);
1167         g_signal_connect(G_OBJECT(action), "activate",
1168                          G_CALLBACK(external_handler_run), data);
1169         mi = webkit_context_menu_item_new_from_gaction(G_ACTION(action),
1170                                                        "Open with external handler",
1171                                                        NULL);
1172         webkit_context_menu_append(menu, mi);
1173         g_object_unref(action);
1174     }
1175
1176     /* FALSE = Show the menu. (TRUE = Don't ever show it.) */
1177     return FALSE;
1178 }
1179
1180 gboolean
1181 quit_if_nothing_active(void)
1182 {
1183     if (clients == 0)
1184     {
1185         if (downloads == 0)
1186         {
1187             gtk_main_quit();
1188             return TRUE;
1189         }
1190         else
1191             gtk_widget_show_all(dm.win);
1192     }
1193
1194     return FALSE;
1195 }
1196
1197 gboolean
1198 remote_msg(GIOChannel *channel, GIOCondition condition, gpointer data)
1199 {
1200     gchar *uri = NULL;
1201
1202     g_io_channel_read_line(channel, &uri, NULL, NULL, NULL);
1203     if (uri)
1204     {
1205         g_strstrip(uri);
1206         client_new(uri, NULL, TRUE);
1207         g_free(uri);
1208     }
1209     return TRUE;
1210 }
1211
1212 void
1213 run_user_scripts(WebKitWebView *web_view)
1214 {
1215     gchar *base = NULL, *path = NULL, *contents = NULL;
1216     const gchar *entry = NULL;
1217     GDir *scriptdir = NULL;
1218
1219     base = g_build_filename(g_get_user_config_dir(), __NAME__, "user-scripts", NULL);
1220     scriptdir = g_dir_open(base, 0, NULL);
1221     if (scriptdir != NULL)
1222     {
1223         while ((entry = g_dir_read_name(scriptdir)) != NULL)
1224         {
1225             path = g_build_filename(base, entry, NULL);
1226             if (g_str_has_suffix(path, ".js"))
1227             {
1228                 if (g_file_get_contents(path, &contents, NULL, NULL))
1229                 {
1230                     webkit_web_view_run_javascript(web_view, contents, NULL, NULL, NULL);
1231                     g_free(contents);
1232                 }
1233             }
1234             g_free(path);
1235         }
1236         g_dir_close(scriptdir);
1237     }
1238
1239     g_free(base);
1240 }
1241
1242 void
1243 search(gpointer data, gint direction)
1244 {
1245     struct Client *c = (struct Client *)data;
1246     WebKitWebView *web_view = WEBKIT_WEB_VIEW(c->web_view);
1247     WebKitFindController *fc = webkit_web_view_get_find_controller(web_view);
1248
1249     if (search_text == NULL)
1250         return;
1251
1252     switch (direction)
1253     {
1254         case 0:
1255             webkit_find_controller_search(fc, search_text,
1256                                           WEBKIT_FIND_OPTIONS_CASE_INSENSITIVE |
1257                                           WEBKIT_FIND_OPTIONS_WRAP_AROUND,
1258                                           G_MAXUINT);
1259             break;
1260         case 1:
1261             webkit_find_controller_search_next(fc);
1262             break;
1263         case -1:
1264             webkit_find_controller_search_previous(fc);
1265             break;
1266     }
1267 }
1268
1269 void
1270 show_web_view(WebKitWebView *web_view, gpointer data)
1271 {
1272     struct Client *c = (struct Client *)data;
1273     gint idx;
1274
1275     (void)web_view;
1276
1277     gtk_widget_show_all(mw.win);
1278
1279     idx = gtk_notebook_page_num(GTK_NOTEBOOK(mw.notebook), c->vbox);
1280     if (idx != -1)
1281         gtk_notebook_set_current_page(GTK_NOTEBOOK(mw.notebook), idx);
1282
1283     gtk_widget_grab_focus(c->web_view);
1284 }
1285
1286 void
1287 trust_user_certs(WebKitWebContext *wc)
1288 {
1289     GTlsCertificate *cert;
1290     const gchar *basedir, *file, *absfile;
1291     GDir *dir;
1292
1293     basedir = g_build_filename(g_get_user_config_dir(), __NAME__, "certs", NULL);
1294     dir = g_dir_open(basedir, 0, NULL);
1295     if (dir != NULL)
1296     {
1297         file = g_dir_read_name(dir);
1298         while (file != NULL)
1299         {
1300             absfile = g_build_filename(g_get_user_config_dir(), __NAME__, "certs",
1301                                        file, NULL);
1302             cert = g_tls_certificate_new_from_file(absfile, NULL);
1303             if (cert == NULL)
1304                 fprintf(stderr, __NAME__": Could not load trusted cert '%s'\n", file);
1305             else
1306                 webkit_web_context_allow_tls_certificate_for_host(wc, cert, file);
1307             file = g_dir_read_name(dir);
1308         }
1309         g_dir_close(dir);
1310     }
1311 }
1312
1313
1314 int
1315 main(int argc, char **argv)
1316 {
1317     gchar *c;
1318     int opt, i;
1319
1320     gtk_init(&argc, &argv);
1321     webkit_web_context_set_process_model(webkit_web_context_get_default(),
1322         WEBKIT_PROCESS_MODEL_MULTIPLE_SECONDARY_PROCESSES);
1323
1324     grab_environment_configuration();
1325
1326     while ((opt = getopt(argc, argv, "C")) != -1)
1327     {
1328         switch (opt)
1329         {
1330             case 'C':
1331                 cooperative_instances = FALSE;
1332                 break;
1333             default:
1334                 fprintf(stderr, "Usage: "__NAME__" [OPTION]... [URI]...\n");
1335                 exit(EXIT_FAILURE);
1336         }
1337     }
1338
1339     keywords_load();
1340     if (cooperative_instances)
1341         cooperation_setup();
1342     downloadmanager_setup();
1343
1344     mainwindow_setup();
1345
1346     if (!cooperative_instances || cooperative_alone)
1347     {
1348         c = g_build_filename(g_get_user_config_dir(), __NAME__, "web_extensions",
1349                              NULL);
1350         webkit_web_context_set_web_extensions_directory(
1351             webkit_web_context_get_default(), c
1352         );
1353     }
1354
1355     if (optind >= argc)
1356         client_new(home_uri, NULL, TRUE);
1357     else
1358     {
1359         for (i = optind; i < argc; i++)
1360             client_new(argv[i], NULL, TRUE);
1361     }
1362
1363     if (!cooperative_instances || cooperative_alone)
1364         gtk_main();
1365     exit(EXIT_SUCCESS);
1366 }