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