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