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