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