]> git.armaanb.net Git - chorizo.git/blob - browser.c
Add hotkeys for switching tabs
[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                 case GDK_KEY_a:  /* go one tab to the left (left hand) */
876                     gtk_notebook_prev_page(GTK_NOTEBOOK(mw.notebook));
877                     return TRUE;
878                 case GDK_KEY_s:  /* go one tab to the right (left hand) */
879                     gtk_notebook_next_page(GTK_NOTEBOOK(mw.notebook));
880                     return TRUE;
881             }
882         }
883         /* navigate backward (left hand) */
884         else if (((GdkEventKey *)event)->keyval == GDK_KEY_F2)
885         {
886             webkit_web_view_go_back(WEBKIT_WEB_VIEW(c->web_view));
887             return TRUE;
888         }
889         /* navigate forward (left hand) */
890         else if (((GdkEventKey *)event)->keyval == GDK_KEY_F3)
891         {
892             webkit_web_view_go_forward(WEBKIT_WEB_VIEW(c->web_view));
893             return TRUE;
894         }
895     }
896
897     return FALSE;
898 }
899
900 gboolean
901 key_downloadmanager(GtkWidget *widget, GdkEvent *event, gpointer data)
902 {
903     if (event->type == GDK_KEY_PRESS)
904     {
905         if (((GdkEventKey *)event)->state & GDK_MOD1_MASK)
906         {
907             switch (((GdkEventKey *)event)->keyval)
908             {
909                 case GDK_KEY_d:  /* close window (left hand) */
910                 case GDK_KEY_q:
911                     downloadmanager_delete(dm.win, NULL);
912                     return TRUE;
913             }
914         }
915     }
916
917     return FALSE;
918 }
919
920 gboolean
921 key_location(GtkWidget *widget, GdkEvent *event, gpointer data)
922 {
923     struct Client *c = (struct Client *)data;
924     const gchar *t;
925     gchar *f;
926
927     if (key_common(widget, event, data))
928         return TRUE;
929
930     if (event->type == GDK_KEY_PRESS)
931     {
932         switch (((GdkEventKey *)event)->keyval)
933         {
934             case GDK_KEY_KP_Enter:
935             case GDK_KEY_Return:
936                 gtk_widget_grab_focus(c->web_view);
937                 t = gtk_entry_get_text(GTK_ENTRY(c->location));
938                 if (t != NULL && t[0] == ':' && t[1] == '/')
939                 {
940                     if (search_text != NULL)
941                         g_free(search_text);
942                     search_text = g_strdup(t + 2);
943                     search(c, 0);
944                 }
945                 else if (!keywords_try_search(WEBKIT_WEB_VIEW(c->web_view), t))
946                 {
947                     f = ensure_uri_scheme(t);
948                     webkit_web_view_load_uri(WEBKIT_WEB_VIEW(c->web_view), f);
949                     g_free(f);
950                 }
951                 return TRUE;
952             case GDK_KEY_Escape:
953                 t = webkit_web_view_get_uri(WEBKIT_WEB_VIEW(c->web_view));
954                 gtk_entry_set_text(GTK_ENTRY(c->location),
955                                    (t == NULL ? __NAME__ : t));
956                 return TRUE;
957         }
958     }
959
960     return FALSE;
961 }
962
963 gboolean
964 key_web_view(GtkWidget *widget, GdkEvent *event, gpointer data)
965 {
966     struct Client *c = (struct Client *)data;
967     gdouble dx, dy;
968     gfloat z;
969
970     if (key_common(widget, event, data))
971         return TRUE;
972
973     if (event->type == GDK_KEY_PRESS)
974     {
975         if (((GdkEventKey *)event)->keyval == GDK_KEY_Escape)
976         {
977             webkit_web_view_stop_loading(WEBKIT_WEB_VIEW(c->web_view));
978             gtk_entry_set_progress_fraction(GTK_ENTRY(c->location), 0);
979         }
980     }
981     else if (event->type == GDK_BUTTON_RELEASE)
982     {
983         switch (((GdkEventButton *)event)->button)
984         {
985             case 2:
986                 if (c->hover_uri != NULL)
987                 {
988                     client_new(c->hover_uri, NULL, TRUE);
989                     return TRUE;
990                 }
991                 break;
992             case 8:
993                 webkit_web_view_go_back(WEBKIT_WEB_VIEW(c->web_view));
994                 return TRUE;
995             case 9:
996                 webkit_web_view_go_forward(WEBKIT_WEB_VIEW(c->web_view));
997                 return TRUE;
998         }
999     }
1000     else if (event->type == GDK_SCROLL)
1001     {
1002         if (((GdkEventScroll *)event)->state & GDK_MOD1_MASK ||
1003             ((GdkEventScroll *)event)->state & GDK_CONTROL_MASK)
1004         {
1005             gdk_event_get_scroll_deltas(event, &dx, &dy);
1006             z = webkit_web_view_get_zoom_level(WEBKIT_WEB_VIEW(c->web_view));
1007             z += -dy * 0.1;
1008             z = dx != 0 ? global_zoom : z;
1009             webkit_web_view_set_zoom_level(WEBKIT_WEB_VIEW(c->web_view), z);
1010             return TRUE;
1011         }
1012     }
1013
1014     return FALSE;
1015 }
1016
1017 void
1018 keywords_load(void)
1019 {
1020     GError *err = NULL;
1021     GIOChannel *channel = NULL;
1022     gchar *path = NULL, *buf = NULL;
1023     gchar **tokens = NULL;
1024
1025     keywords = g_hash_table_new(g_str_hash, g_str_equal);
1026
1027     path = g_build_filename(g_get_user_config_dir(), __NAME__, "keywordsearch",
1028                             NULL);
1029     channel = g_io_channel_new_file(path, "r", &err);
1030     if (channel != NULL)
1031     {
1032         while (g_io_channel_read_line(channel, &buf, NULL, NULL, NULL)
1033                == G_IO_STATUS_NORMAL)
1034         {
1035             g_strstrip(buf);
1036             if (buf[0] != '#')
1037             {
1038                 tokens = g_strsplit(buf, " ", 2);
1039                 if (tokens[0] != NULL && tokens[1] != NULL)
1040                     g_hash_table_insert(keywords, g_strdup(tokens[0]),
1041                                         g_strdup(tokens[1]));
1042                 g_strfreev(tokens);
1043             }
1044             g_free(buf);
1045         }
1046         g_io_channel_shutdown(channel, FALSE, NULL);
1047     }
1048     g_free(path);
1049 }
1050
1051 gboolean
1052 keywords_try_search(WebKitWebView *web_view, const gchar *t)
1053 {
1054     gboolean ret = FALSE;
1055     gchar **tokens = NULL;
1056     gchar *val = NULL, *escaped = NULL, *uri = NULL;
1057
1058     tokens = g_strsplit(t, " ", 2);
1059     if (tokens[0] != NULL && tokens[1] != NULL)
1060     {
1061         val = g_hash_table_lookup(keywords, tokens[0]);
1062         if (val != NULL)
1063         {
1064             escaped = g_uri_escape_string(tokens[1], NULL, TRUE);
1065             uri = g_strdup_printf((gchar *)val, escaped);
1066             webkit_web_view_load_uri(web_view, uri);
1067             g_free(uri);
1068             g_free(escaped);
1069             ret = TRUE;
1070         }
1071     }
1072     g_strfreev(tokens);
1073
1074     return ret;
1075 }
1076
1077 void
1078 mainwindow_setup(void)
1079 {
1080     mw.win = gtk_window_new(GTK_WINDOW_TOPLEVEL);
1081     gtk_window_set_default_size(GTK_WINDOW(mw.win), 800, 600);
1082     g_signal_connect(G_OBJECT(mw.win), "destroy", gtk_main_quit, NULL);
1083     gtk_window_set_title(GTK_WINDOW(mw.win), __NAME__);
1084
1085     mw.notebook = gtk_notebook_new();
1086     gtk_notebook_set_scrollable(GTK_NOTEBOOK(mw.notebook), TRUE);
1087     gtk_container_add(GTK_CONTAINER(mw.win), mw.notebook);
1088     g_signal_connect(G_OBJECT(mw.notebook), "switch-page",
1089                      G_CALLBACK(mainwindow_title_before), NULL);
1090 }
1091
1092 void
1093 mainwindow_title_before(GtkNotebook *nb, GtkWidget *p, guint idx, gpointer data)
1094 {
1095     mainwindow_title(idx);
1096 }
1097
1098 void
1099 mainwindow_title(gint idx)
1100 {
1101     GtkWidget *child, *evbox, *label;
1102     const gchar *text;
1103
1104     if (idx == -1)
1105     {
1106         idx = gtk_notebook_get_current_page(GTK_NOTEBOOK(mw.notebook));
1107         if (idx == -1)
1108             return;
1109     }
1110
1111     child = gtk_notebook_get_nth_page(GTK_NOTEBOOK(mw.notebook), idx);
1112     if (child == NULL)
1113         return;
1114
1115     evbox = gtk_notebook_get_tab_label(GTK_NOTEBOOK(mw.notebook), child);
1116     label = gtk_bin_get_child(GTK_BIN(evbox));
1117     text = gtk_label_get_text(GTK_LABEL(label));
1118     gtk_window_set_title(GTK_WINDOW(mw.win), text);
1119 }
1120
1121 gboolean
1122 menu_web_view(WebKitWebView *web_view, WebKitContextMenu *menu, GdkEvent *ev,
1123               WebKitHitTestResult *ht, gpointer data)
1124 {
1125     struct Client *c = (struct Client *)data;
1126     GSimpleAction *action = NULL;
1127     WebKitContextMenuItem *mi = NULL;
1128     const gchar *uri = NULL;
1129
1130     (void)ev;
1131
1132     if (webkit_hit_test_result_context_is_link(ht))
1133         uri = webkit_hit_test_result_get_link_uri(ht);
1134     else if (webkit_hit_test_result_context_is_image(ht))
1135         uri = webkit_hit_test_result_get_image_uri(ht);
1136     else if (webkit_hit_test_result_context_is_media(ht))
1137         uri = webkit_hit_test_result_get_media_uri(ht);
1138
1139     if (uri != NULL)
1140     {
1141         webkit_context_menu_append(menu, webkit_context_menu_item_new_separator());
1142
1143         if (c->external_handler_uri != NULL)
1144             g_free(c->external_handler_uri);
1145         c->external_handler_uri = g_strdup(uri);
1146         action = g_simple_action_new("external_handler", NULL);
1147         g_signal_connect(G_OBJECT(action), "activate",
1148                          G_CALLBACK(external_handler_run), data);
1149         mi = webkit_context_menu_item_new_from_gaction(G_ACTION(action),
1150                                                        "Open with external handler",
1151                                                        NULL);
1152         webkit_context_menu_append(menu, mi);
1153         g_object_unref(action);
1154     }
1155
1156     /* FALSE = Show the menu. (TRUE = Don't ever show it.) */
1157     return FALSE;
1158 }
1159
1160 gboolean
1161 quit_if_nothing_active(void)
1162 {
1163     if (clients == 0)
1164     {
1165         if (downloads == 0)
1166         {
1167             gtk_main_quit();
1168             return TRUE;
1169         }
1170         else
1171             gtk_widget_show_all(dm.win);
1172     }
1173
1174     return FALSE;
1175 }
1176
1177 gboolean
1178 remote_msg(GIOChannel *channel, GIOCondition condition, gpointer data)
1179 {
1180     gchar *uri = NULL;
1181
1182     g_io_channel_read_line(channel, &uri, NULL, NULL, NULL);
1183     if (uri)
1184     {
1185         g_strstrip(uri);
1186         client_new(uri, NULL, TRUE);
1187         g_free(uri);
1188     }
1189     return TRUE;
1190 }
1191
1192 void
1193 run_user_scripts(WebKitWebView *web_view)
1194 {
1195     gchar *base = NULL, *path = NULL, *contents = NULL;
1196     const gchar *entry = NULL;
1197     GDir *scriptdir = NULL;
1198
1199     base = g_build_filename(g_get_user_config_dir(), __NAME__, "user-scripts", NULL);
1200     scriptdir = g_dir_open(base, 0, NULL);
1201     if (scriptdir != NULL)
1202     {
1203         while ((entry = g_dir_read_name(scriptdir)) != NULL)
1204         {
1205             path = g_build_filename(base, entry, NULL);
1206             if (g_str_has_suffix(path, ".js"))
1207             {
1208                 if (g_file_get_contents(path, &contents, NULL, NULL))
1209                 {
1210                     webkit_web_view_run_javascript(web_view, contents, NULL, NULL, NULL);
1211                     g_free(contents);
1212                 }
1213             }
1214             g_free(path);
1215         }
1216         g_dir_close(scriptdir);
1217     }
1218
1219     g_free(base);
1220 }
1221
1222 void
1223 search(gpointer data, gint direction)
1224 {
1225     struct Client *c = (struct Client *)data;
1226     WebKitWebView *web_view = WEBKIT_WEB_VIEW(c->web_view);
1227     WebKitFindController *fc = webkit_web_view_get_find_controller(web_view);
1228
1229     if (search_text == NULL)
1230         return;
1231
1232     switch (direction)
1233     {
1234         case 0:
1235             webkit_find_controller_search(fc, search_text,
1236                                           WEBKIT_FIND_OPTIONS_CASE_INSENSITIVE |
1237                                           WEBKIT_FIND_OPTIONS_WRAP_AROUND,
1238                                           G_MAXUINT);
1239             break;
1240         case 1:
1241             webkit_find_controller_search_next(fc);
1242             break;
1243         case -1:
1244             webkit_find_controller_search_previous(fc);
1245             break;
1246     }
1247 }
1248
1249 void
1250 show_web_view(WebKitWebView *web_view, gpointer data)
1251 {
1252     struct Client *c = (struct Client *)data;
1253     gint idx;
1254
1255     (void)web_view;
1256
1257     gtk_widget_show_all(mw.win);
1258
1259     idx = gtk_notebook_page_num(GTK_NOTEBOOK(mw.notebook), c->vbox);
1260     if (idx != -1)
1261         gtk_notebook_set_current_page(GTK_NOTEBOOK(mw.notebook), idx);
1262
1263     gtk_widget_grab_focus(c->web_view);
1264 }
1265
1266 void
1267 trust_user_certs(WebKitWebContext *wc)
1268 {
1269     GTlsCertificate *cert;
1270     const gchar *basedir, *file, *absfile;
1271     GDir *dir;
1272
1273     basedir = g_build_filename(g_get_user_config_dir(), __NAME__, "certs", NULL);
1274     dir = g_dir_open(basedir, 0, NULL);
1275     if (dir != NULL)
1276     {
1277         file = g_dir_read_name(dir);
1278         while (file != NULL)
1279         {
1280             absfile = g_build_filename(g_get_user_config_dir(), __NAME__, "certs",
1281                                        file, NULL);
1282             cert = g_tls_certificate_new_from_file(absfile, NULL);
1283             if (cert == NULL)
1284                 fprintf(stderr, __NAME__": Could not load trusted cert '%s'\n", file);
1285             else
1286                 webkit_web_context_allow_tls_certificate_for_host(wc, cert, file);
1287             file = g_dir_read_name(dir);
1288         }
1289         g_dir_close(dir);
1290     }
1291 }
1292
1293
1294 int
1295 main(int argc, char **argv)
1296 {
1297     gchar *c;
1298     int opt, i;
1299
1300     gtk_init(&argc, &argv);
1301     webkit_web_context_set_process_model(webkit_web_context_get_default(),
1302         WEBKIT_PROCESS_MODEL_MULTIPLE_SECONDARY_PROCESSES);
1303
1304     grab_environment_configuration();
1305
1306     while ((opt = getopt(argc, argv, "C")) != -1)
1307     {
1308         switch (opt)
1309         {
1310             case 'C':
1311                 cooperative_instances = FALSE;
1312                 break;
1313             default:
1314                 fprintf(stderr, "Usage: "__NAME__" [OPTION]... [URI]...\n");
1315                 exit(EXIT_FAILURE);
1316         }
1317     }
1318
1319     keywords_load();
1320     if (cooperative_instances)
1321         cooperation_setup();
1322     downloadmanager_setup();
1323
1324     mainwindow_setup();
1325
1326     if (!cooperative_instances || cooperative_alone)
1327     {
1328         c = g_build_filename(g_get_user_config_dir(), __NAME__, "web_extensions",
1329                              NULL);
1330         webkit_web_context_set_web_extensions_directory(
1331             webkit_web_context_get_default(), c
1332         );
1333     }
1334
1335     if (optind >= argc)
1336         client_new(home_uri, NULL, TRUE);
1337     else
1338     {
1339         for (i = optind; i < argc; i++)
1340             client_new(argv[i], NULL, TRUE);
1341     }
1342
1343     if (!cooperative_instances || cooperative_alone)
1344         gtk_main();
1345     exit(EXIT_SUCCESS);
1346 }