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