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