]> git.armaanb.net Git - chorizo.git/blob - browser.c
Remove $LARIZA_WEB_EXTENSIONS_DIR
[chorizo.git] / browser.c
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <sys/types.h>
4 #include <sys/stat.h>
5 #include <fcntl.h>
6 #include <string.h>
7
8 #include <gtk/gtk.h>
9 #include <gtk/gtkx.h>
10 #include <gdk/gdkkeysyms.h>
11 #include <gio/gio.h>
12 #include <webkit2/webkit2.h>
13
14
15 static void client_destroy(GtkWidget *, gpointer);
16 static gboolean client_destroy_request(WebKitWebView *, gpointer);
17 static WebKitWebView *client_new(const gchar *);
18 static WebKitWebView *client_new_request(WebKitWebView *, WebKitNavigationAction *,
19                                          gpointer);
20 static void cooperation_setup(void);
21 static void changed_download_progress(GObject *, GParamSpec *, gpointer);
22 static void changed_load_progress(GObject *, GParamSpec *, gpointer);
23 static void changed_title(GObject *, GParamSpec *, gpointer);
24 static void changed_uri(GObject *, GParamSpec *, gpointer);
25 static gboolean crashed_web_view(WebKitWebView *, gpointer);
26 static gboolean crashed_web_view_reload(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 void downloadmanager_setup(void);
33 static gchar *ensure_uri_scheme(const gchar *);
34 static void grab_environment_configuration(void);
35 static void hover_web_view(WebKitWebView *, WebKitHitTestResult *, guint, gpointer);
36 static gboolean key_downloadmanager(GtkWidget *, GdkEvent *, gpointer);
37 static gboolean key_location(GtkWidget *, GdkEvent *, gpointer);
38 static gboolean key_web_view(GtkWidget *, GdkEvent *, gpointer);
39 static void keywords_load(void);
40 static gboolean keywords_try_search(WebKitWebView *, const gchar *);
41 static gboolean remote_msg(GIOChannel *, GIOCondition, gpointer);
42 static void search(gpointer, gint);
43 static Window tabbed_launch(void);
44 static void trust_user_certs(WebKitWebContext *);
45
46
47 struct Client
48 {
49     gchar *hover_uri;
50     GtkWidget *location;
51     GtkWidget *progress;
52     GtkWidget *top_box;
53     GtkWidget *vbox;
54     GtkWidget *web_view;
55     GtkWidget *win;
56 };
57
58 struct DownloadManager
59 {
60     GtkWidget *scroll;
61     GtkWidget *toolbar;
62     GtkWidget *win;
63 } dm;
64
65
66 static const gchar *accepted_language[2] = { NULL, NULL };
67 static gint clients = 0;
68 static gboolean cooperative_alone = TRUE;
69 static gboolean cooperative_instances = TRUE;
70 static int cooperative_pipe_fp = 0;
71 static int crash_autoreload_delay = 2;
72 static gchar *download_dir = "/var/tmp";
73 static Window embed = 0;
74 static gchar *fifo_suffix = "main";
75 static gdouble global_zoom = 1.0;
76 static gchar *home_uri = "about:blank";
77 static gboolean initial_wc_setup_done = FALSE;
78 static GHashTable *keywords = NULL;
79 static gchar *search_text = NULL;
80 static gboolean tabbed_automagic = TRUE;
81 static gchar *user_agent = NULL;
82
83
84 void
85 client_destroy(GtkWidget *obj, gpointer data)
86 {
87     struct Client *c = (struct Client *)data;
88
89     g_signal_handlers_disconnect_by_func(G_OBJECT(c->web_view),
90                                          changed_load_progress, c);
91
92     free(c);
93     clients--;
94
95     if (clients == 0)
96         gtk_main_quit();
97 }
98
99 gboolean
100 client_destroy_request(WebKitWebView *web_view, gpointer data)
101 {
102     struct Client *c = (struct Client *)data;
103
104     gtk_widget_destroy(c->win);
105
106     return TRUE;
107 }
108
109 WebKitWebView *
110 client_new(const gchar *uri)
111 {
112     struct Client *c;
113     WebKitWebContext *wc;
114     gchar *f;
115
116     if (uri != NULL && cooperative_instances && !cooperative_alone)
117     {
118         write(cooperative_pipe_fp, uri, strlen(uri));
119         write(cooperative_pipe_fp, "\n", 1);
120         return NULL;
121     }
122
123     c = malloc(sizeof(struct Client));
124     if (!c)
125     {
126         fprintf(stderr, __NAME__": fatal: malloc failed\n");
127         exit(EXIT_FAILURE);
128     }
129
130     c->hover_uri = NULL;
131     c->win = NULL;
132     if (embed != 0)
133     {
134         c->win = gtk_plug_new(embed);
135         if (!gtk_plug_get_embedded(GTK_PLUG(c->win)))
136         {
137             fprintf(stderr, __NAME__": Can't plug-in to XID %ld.\n", embed);
138             gtk_widget_destroy(c->win);
139             c->win = NULL;
140             embed = 0;
141         }
142     }
143
144     if (c->win == NULL)
145     {
146         c->win = gtk_window_new(GTK_WINDOW_TOPLEVEL);
147         gtk_window_set_wmclass(GTK_WINDOW(c->win), __NAME__, __NAME_CAPITALIZED__);
148     }
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), "close",
168                      G_CALLBACK(client_destroy_request), c);
169     g_signal_connect(G_OBJECT(c->web_view), "decide-policy",
170                      G_CALLBACK(decide_policy), NULL);
171     g_signal_connect(G_OBJECT(c->web_view), "key-press-event",
172                      G_CALLBACK(key_web_view), c);
173     g_signal_connect(G_OBJECT(c->web_view), "button-press-event",
174                      G_CALLBACK(key_web_view), c);
175     g_signal_connect(G_OBJECT(c->web_view), "scroll-event",
176                      G_CALLBACK(key_web_view), c);
177     g_signal_connect(G_OBJECT(c->web_view), "mouse-target-changed",
178                      G_CALLBACK(hover_web_view), c);
179     g_signal_connect(G_OBJECT(c->web_view), "web-process-crashed",
180                      G_CALLBACK(crashed_web_view), c);
181
182     if (!initial_wc_setup_done)
183     {
184         if (accepted_language[0] != NULL)
185             webkit_web_context_set_preferred_languages(wc, accepted_language);
186
187         g_signal_connect(G_OBJECT(wc), "download-started",
188                          G_CALLBACK(download_handle_start), NULL);
189
190         trust_user_certs(wc);
191
192         initial_wc_setup_done = TRUE;
193     }
194
195     if (user_agent != NULL)
196         g_object_set(G_OBJECT(webkit_web_view_get_settings(WEBKIT_WEB_VIEW(c->web_view))),
197                      "user-agent", user_agent, NULL);
198
199     c->location = gtk_entry_new();
200     g_signal_connect(G_OBJECT(c->location), "key-press-event",
201                      G_CALLBACK(key_location), c);
202
203     /* XXX Progress bars don't work/look as intended anymore. Level bars
204      * are a dirty workaround (kind of). */
205     c->progress = gtk_level_bar_new();
206     gtk_level_bar_set_value(GTK_LEVEL_BAR(c->progress), 0);
207     gtk_widget_set_size_request(c->progress, 100, -1);
208
209     c->top_box = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 0);
210     gtk_box_pack_start(GTK_BOX(c->top_box), c->location, TRUE, TRUE, 0);
211     gtk_box_pack_start(GTK_BOX(c->top_box), c->progress, FALSE, FALSE, 0);
212
213     c->vbox = gtk_box_new(GTK_ORIENTATION_VERTICAL, 0);
214     gtk_box_pack_start(GTK_BOX(c->vbox), c->top_box, FALSE, FALSE, 0);
215     gtk_box_pack_start(GTK_BOX(c->vbox), c->web_view, TRUE, TRUE, 0);
216
217     gtk_container_add(GTK_CONTAINER(c->win), c->vbox);
218
219     gtk_widget_grab_focus(c->web_view);
220     gtk_widget_show_all(c->win);
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);
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) * 100;
287     resp = webkit_download_get_response(download);
288     size_mb = webkit_uri_response_get_content_length(resp) / 1e6;
289
290     uri = webkit_download_get_destination(download);
291     filename = g_filename_from_uri(uri, NULL, NULL);
292     if (filename == NULL)
293     {
294         /* This really should not happen because WebKit uses that URI to
295          * write to a file... */
296         fprintf(stderr, __NAME__": Could not construct file name from URI!\n");
297         t = g_strdup_printf("%s (%.0f%% of %.1f MB)",
298                             webkit_uri_response_get_uri(resp), p, size_mb);
299     }
300     else
301     {
302         base = g_path_get_basename(filename);
303         t = g_strdup_printf("%s (%.0f%% of %.1f MB)", base, p, size_mb);
304         g_free(filename);
305         g_free(base);
306     }
307     gtk_tool_button_set_label(GTK_TOOL_BUTTON(tb), t);
308     g_free(t);
309 }
310
311 void
312 changed_load_progress(GObject *obj, GParamSpec *pspec, gpointer data)
313 {
314     struct Client *c = (struct Client *)data;
315     gdouble p;
316
317     p = webkit_web_view_get_estimated_load_progress(WEBKIT_WEB_VIEW(c->web_view));
318     gtk_level_bar_set_value(GTK_LEVEL_BAR(c->progress), p);
319 }
320
321 void
322 changed_title(GObject *obj, GParamSpec *pspec, gpointer data)
323 {
324     const gchar *t;
325     struct Client *c = (struct Client *)data;
326
327     t = webkit_web_view_get_title(WEBKIT_WEB_VIEW(c->web_view));
328     gtk_window_set_title(GTK_WINDOW(c->win), (t == NULL ? __NAME__ : t));
329 }
330
331 void
332 changed_uri(GObject *obj, GParamSpec *pspec, gpointer data)
333 {
334     const gchar *t;
335     struct Client *c = (struct Client *)data;
336
337     t = webkit_web_view_get_uri(WEBKIT_WEB_VIEW(c->web_view));
338     gtk_entry_set_text(GTK_ENTRY(c->location), (t == NULL ? __NAME__ : t));
339 }
340
341 gboolean
342 crashed_web_view(WebKitWebView *web_view, gpointer data)
343 {
344     fprintf(stderr, __NAME__": WebView crashed!\n");
345     if (crash_autoreload_delay >= 1)
346     {
347         fprintf(stderr, __NAME__": Reloading WebView in %d seconds.\n",
348                 crash_autoreload_delay);
349         g_timeout_add_seconds(crash_autoreload_delay, crashed_web_view_reload,
350                               web_view);
351     }
352
353     return TRUE;
354 }
355
356 gboolean
357 crashed_web_view_reload(gpointer data)
358 {
359     webkit_web_view_reload_bypass_cache(WEBKIT_WEB_VIEW(data));
360
361     return G_SOURCE_REMOVE;
362 }
363
364 gboolean
365 decide_policy(WebKitWebView *web_view, WebKitPolicyDecision *decision,
366               WebKitPolicyDecisionType type, gpointer data)
367 {
368     WebKitResponsePolicyDecision *r;
369
370     switch (type)
371     {
372         case WEBKIT_POLICY_DECISION_TYPE_RESPONSE:
373             r = WEBKIT_RESPONSE_POLICY_DECISION(decision);
374             if (!webkit_response_policy_decision_is_mime_type_supported(r))
375                 webkit_policy_decision_download(decision);
376             else
377                 webkit_policy_decision_use(decision);
378             break;
379         default:
380             /* Use whatever default there is. */
381             return FALSE;
382     }
383     return TRUE;
384 }
385
386 void
387 download_handle_start(WebKitWebView *web_view, WebKitDownload *download,
388                       gpointer data)
389 {
390     g_signal_connect(G_OBJECT(download), "decide-destination",
391                      G_CALLBACK(download_handle), data);
392 }
393
394 gboolean
395 download_handle(WebKitDownload *download, gchar *suggested_filename, gpointer data)
396 {
397     gchar *path, *path2 = NULL, *uri;
398     GtkToolItem *tb;
399     int suffix = 1;
400
401     path = g_build_filename(download_dir, suggested_filename, NULL);
402     path2 = g_strdup(path);
403     while (g_file_test(path2, G_FILE_TEST_EXISTS) && suffix < 1000)
404     {
405         g_free(path2);
406
407         path2 = g_strdup_printf("%s.%d", path, suffix);
408         suffix++;
409     }
410
411     if (suffix == 1000)
412     {
413         fprintf(stderr, __NAME__": Suffix reached limit for download.\n");
414         webkit_download_cancel(download);
415     }
416     else
417     {
418         uri = g_filename_to_uri(path2, NULL, NULL);
419         webkit_download_set_destination(download, uri);
420         g_free(uri);
421
422         tb = gtk_tool_button_new(NULL, NULL);
423         gtk_tool_button_set_icon_name(GTK_TOOL_BUTTON(tb), "gtk-delete");
424         gtk_tool_button_set_label(GTK_TOOL_BUTTON(tb), suggested_filename);
425         gtk_toolbar_insert(GTK_TOOLBAR(dm.toolbar), tb, 0);
426         gtk_widget_show_all(dm.win);
427
428         g_signal_connect(G_OBJECT(download), "notify::estimated-progress",
429                          G_CALLBACK(changed_download_progress), tb);
430
431         g_object_ref(download);
432         g_signal_connect(G_OBJECT(tb), "clicked",
433                          G_CALLBACK(downloadmanager_cancel), download);
434     }
435
436     g_free(path);
437     g_free(path2);
438
439     /* Propagate -- to whom it may concern. */
440     return FALSE;
441 }
442
443 void
444 downloadmanager_cancel(GtkToolButton *tb, gpointer data)
445 {
446     WebKitDownload *download = WEBKIT_DOWNLOAD(data);
447
448     webkit_download_cancel(download);
449     g_object_unref(download);
450
451     gtk_widget_destroy(GTK_WIDGET(tb));
452 }
453
454 void
455 downloadmanager_setup(void)
456 {
457     dm.win = gtk_window_new(GTK_WINDOW_TOPLEVEL);
458     gtk_window_set_type_hint(GTK_WINDOW(dm.win), GDK_WINDOW_TYPE_HINT_DIALOG);
459     gtk_window_set_default_size(GTK_WINDOW(dm.win), 500, 250);
460     gtk_window_set_title(GTK_WINDOW(dm.win), __NAME__" - Download Manager");
461     g_signal_connect(G_OBJECT(dm.win), "delete-event",
462                      G_CALLBACK(gtk_widget_hide_on_delete), NULL);
463     g_signal_connect(G_OBJECT(dm.win), "key-press-event",
464                      G_CALLBACK(key_downloadmanager), NULL);
465
466     dm.toolbar = gtk_toolbar_new();
467     gtk_orientable_set_orientation(GTK_ORIENTABLE(dm.toolbar),
468                                    GTK_ORIENTATION_VERTICAL);
469     gtk_toolbar_set_style(GTK_TOOLBAR(dm.toolbar), GTK_TOOLBAR_BOTH_HORIZ);
470     gtk_toolbar_set_show_arrow(GTK_TOOLBAR(dm.toolbar), FALSE);
471
472     dm.scroll = gtk_scrolled_window_new(NULL, NULL);
473     gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(dm.scroll),
474                                    GTK_POLICY_AUTOMATIC, GTK_POLICY_AUTOMATIC);
475     gtk_container_add(GTK_CONTAINER(dm.scroll), dm.toolbar);
476
477     gtk_container_add(GTK_CONTAINER(dm.win), dm.scroll);
478 }
479
480 gchar *
481 ensure_uri_scheme(const gchar *t)
482 {
483     gchar *f;
484
485     f = g_ascii_strdown(t, -1);
486     if (!g_str_has_prefix(f, "http:") &&
487         !g_str_has_prefix(f, "https:") &&
488         !g_str_has_prefix(f, "file:") &&
489         !g_str_has_prefix(f, "about:"))
490     {
491         g_free(f);
492         f = g_strdup_printf("http://%s", t);
493         return f;
494     }
495     else
496         return g_strdup(t);
497 }
498
499 void
500 grab_environment_configuration(void)
501 {
502     const gchar *e;
503
504     e = g_getenv(__NAME_UPPERCASE__"_ACCEPTED_LANGUAGE");
505     if (e != NULL)
506         accepted_language[0] = g_strdup(e);
507
508     e = g_getenv(__NAME_UPPERCASE__"_CRASH_AUTORELOAD_DELAY");
509     if (e != NULL)
510         crash_autoreload_delay = atoi(e);
511
512     e = g_getenv(__NAME_UPPERCASE__"_DOWNLOAD_DIR");
513     if (e != NULL)
514         download_dir = g_strdup(e);
515
516     e = g_getenv(__NAME_UPPERCASE__"_FIFO_SUFFIX");
517     if (e != NULL)
518         fifo_suffix = g_strdup(e);
519
520     e = g_getenv(__NAME_UPPERCASE__"_HOME_URI");
521     if (e != NULL)
522         home_uri = g_strdup(e);
523
524     e = g_getenv(__NAME_UPPERCASE__"_USER_AGENT");
525     if (e != NULL)
526         user_agent = g_strdup(e);
527
528     e = g_getenv(__NAME_UPPERCASE__"_ZOOM");
529     if (e != NULL)
530         global_zoom = atof(e);
531 }
532
533 void
534 hover_web_view(WebKitWebView *web_view, WebKitHitTestResult *ht, guint modifiers,
535                gpointer data)
536 {
537     struct Client *c = (struct Client *)data;
538
539     if (!gtk_widget_is_focus(c->location))
540     {
541         if (webkit_hit_test_result_context_is_link(ht))
542         {
543             gtk_entry_set_text(GTK_ENTRY(c->location),
544                                webkit_hit_test_result_get_link_uri(ht));
545
546             if (c->hover_uri != NULL)
547                 g_free(c->hover_uri);
548             c->hover_uri = g_strdup(webkit_hit_test_result_get_link_uri(ht));
549         }
550         else
551         {
552             gtk_entry_set_text(GTK_ENTRY(c->location),
553                                webkit_web_view_get_uri(WEBKIT_WEB_VIEW(c->web_view)));
554
555             if (c->hover_uri != NULL)
556                 g_free(c->hover_uri);
557             c->hover_uri = NULL;
558         }
559     }
560 }
561
562 gboolean
563 key_downloadmanager(GtkWidget *widget, GdkEvent *event, gpointer data)
564 {
565     if (event->type == GDK_KEY_PRESS)
566     {
567         if (((GdkEventKey *)event)->state & GDK_MOD1_MASK)
568         {
569             switch (((GdkEventKey *)event)->keyval)
570             {
571                 case GDK_KEY_d:  /* close window (left hand) */
572                     gtk_widget_hide(dm.win);
573                     return TRUE;
574             }
575         }
576     }
577
578     return FALSE;
579 }
580
581 gboolean
582 key_location(GtkWidget *widget, GdkEvent *event, gpointer data)
583 {
584     struct Client *c = (struct Client *)data;
585     const gchar *t;
586     gchar *f;
587     WebKitWebContext *wc = webkit_web_view_get_context(WEBKIT_WEB_VIEW(c->web_view));
588
589     if (event->type == GDK_KEY_PRESS)
590     {
591         if (((GdkEventKey *)event)->state & GDK_MOD1_MASK)
592         {
593             switch (((GdkEventKey *)event)->keyval)
594             {
595                 case GDK_KEY_q:  /* close window (left hand) */
596                     gtk_widget_destroy(c->win);
597                     return TRUE;
598                 case GDK_KEY_d:  /* download manager (left hand) */
599                     gtk_widget_show_all(dm.win);
600                     return TRUE;
601                 case GDK_KEY_r:  /* reload (left hand) */
602                     webkit_web_view_reload_bypass_cache(WEBKIT_WEB_VIEW(
603                                                         c->web_view));
604                     return TRUE;
605                 case GDK_KEY_k:  /* initiate search (BOTH hands) */
606                     gtk_entry_set_text(GTK_ENTRY(c->location), "/");
607                     gtk_editable_set_position(GTK_EDITABLE(c->location), -1);
608                     return TRUE;
609                 case GDK_KEY_c:  /* reload trusted certs (left hand) */
610                     trust_user_certs(wc);
611                     return TRUE;
612             }
613         }
614         else
615         {
616             switch (((GdkEventKey *)event)->keyval)
617             {
618                 case GDK_KEY_Return:
619                     gtk_widget_grab_focus(c->web_view);
620                     t = gtk_entry_get_text(GTK_ENTRY(c->location));
621                     if (t != NULL && t[0] == '/')
622                     {
623                         if (search_text != NULL)
624                             g_free(search_text);
625                         search_text = g_strdup(t + 1);  /* XXX whacky */
626                         search(c, 0);
627                     }
628                     else if (!keywords_try_search(WEBKIT_WEB_VIEW(c->web_view), t))
629                     {
630                         f = ensure_uri_scheme(t);
631                         webkit_web_view_load_uri(WEBKIT_WEB_VIEW(c->web_view), f);
632                         g_free(f);
633                     }
634                     return TRUE;
635                 case GDK_KEY_Escape:
636                     t = webkit_web_view_get_uri(WEBKIT_WEB_VIEW(c->web_view));
637                     gtk_entry_set_text(GTK_ENTRY(c->location),
638                                        (t == NULL ? __NAME__ : t));
639                     return TRUE;
640             }
641         }
642     }
643
644     return FALSE;
645 }
646
647 gboolean
648 key_web_view(GtkWidget *widget, GdkEvent *event, gpointer data)
649 {
650     struct Client *c = (struct Client *)data;
651     gdouble dx, dy;
652     gchar *f;
653     gfloat z;
654     WebKitWebContext *wc = webkit_web_view_get_context(WEBKIT_WEB_VIEW(c->web_view));
655
656     if (event->type == GDK_KEY_PRESS)
657     {
658         if (((GdkEventKey *)event)->state & GDK_MOD1_MASK)
659         {
660             switch (((GdkEventKey *)event)->keyval)
661             {
662                 case GDK_KEY_q:  /* close window (left hand) */
663                     gtk_widget_destroy(c->win);
664                     return TRUE;
665                 case GDK_KEY_w:  /* home (left hand) */
666                     f = ensure_uri_scheme(home_uri);
667                     webkit_web_view_load_uri(WEBKIT_WEB_VIEW(c->web_view), f);
668                     g_free(f);
669                     return TRUE;
670                 case GDK_KEY_e:  /* new tab (left hand) */
671                     f = ensure_uri_scheme(home_uri);
672                     client_new(f);
673                     g_free(f);
674                     return TRUE;
675                 case GDK_KEY_r:  /* reload (left hand) */
676                     webkit_web_view_reload_bypass_cache(WEBKIT_WEB_VIEW(
677                                                         c->web_view));
678                     return TRUE;
679                 case GDK_KEY_d:  /* download manager (left hand) */
680                     gtk_widget_show_all(dm.win);
681                     return TRUE;
682                 case GDK_KEY_2:  /* search forward (left hand) */
683                 case GDK_KEY_n:  /* search forward (maybe both hands) */
684                     search(c, 1);
685                     return TRUE;
686                 case GDK_KEY_3:  /* search backward (left hand) */
687                     search(c, -1);
688                     return TRUE;
689                 case GDK_KEY_l:  /* location (BOTH hands) */
690                     gtk_widget_grab_focus(c->location);
691                     return TRUE;
692                 case GDK_KEY_k:  /* initiate search (BOTH hands) */
693                     gtk_widget_grab_focus(c->location);
694                     gtk_entry_set_text(GTK_ENTRY(c->location), "/");
695                     gtk_editable_set_position(GTK_EDITABLE(c->location), -1);
696                     return TRUE;
697                 case GDK_KEY_c:  /* reload trusted certs (left hand) */
698                     trust_user_certs(wc);
699                     return TRUE;
700             }
701         }
702         else if (((GdkEventKey *)event)->keyval == GDK_KEY_Escape)
703         {
704             webkit_web_view_stop_loading(WEBKIT_WEB_VIEW(c->web_view));
705             gtk_level_bar_set_value(GTK_LEVEL_BAR(c->progress), 0);
706         }
707     }
708     else if (event->type == GDK_BUTTON_PRESS)
709     {
710         switch (((GdkEventButton *)event)->button)
711         {
712             case 2:
713                 if (c->hover_uri != NULL)
714                 {
715                     client_new(c->hover_uri);
716                     return TRUE;
717                 }
718                 break;
719             case 8:
720                 webkit_web_view_go_back(WEBKIT_WEB_VIEW(c->web_view));
721                 return TRUE;
722             case 9:
723                 webkit_web_view_go_forward(WEBKIT_WEB_VIEW(c->web_view));
724                 return TRUE;
725         }
726     }
727     else if (event->type == GDK_SCROLL)
728     {
729         if (((GdkEventScroll *)event)->state & GDK_MOD1_MASK ||
730             ((GdkEventScroll *)event)->state & GDK_CONTROL_MASK)
731         {
732             gdk_event_get_scroll_deltas(event, &dx, &dy);
733             z = webkit_web_view_get_zoom_level(WEBKIT_WEB_VIEW(c->web_view));
734             z += -dy * 0.1;
735             z = dx != 0 ? global_zoom : z;
736             webkit_web_view_set_zoom_level(WEBKIT_WEB_VIEW(c->web_view), z);
737             return TRUE;
738         }
739     }
740
741     return FALSE;
742 }
743
744 void
745 keywords_load(void)
746 {
747     GError *err = NULL;
748     GIOChannel *channel = NULL;
749     gchar *path = NULL, *buf = NULL;
750     gchar **tokens = NULL;
751
752     keywords = g_hash_table_new(g_str_hash, g_str_equal);
753
754     path = g_build_filename(g_get_user_config_dir(), __NAME__, "keywordsearch",
755                             NULL);
756     channel = g_io_channel_new_file(path, "r", &err);
757     if (channel != NULL)
758     {
759         while (g_io_channel_read_line(channel, &buf, NULL, NULL, NULL)
760                == G_IO_STATUS_NORMAL)
761         {
762             g_strstrip(buf);
763             if (buf[0] != '#')
764             {
765                 tokens = g_strsplit(buf, " ", 2);
766                 if (tokens[0] != NULL && tokens[1] != NULL)
767                     g_hash_table_insert(keywords, g_strdup(tokens[0]),
768                                         g_strdup(tokens[1]));
769                 g_strfreev(tokens);
770             }
771             g_free(buf);
772         }
773         g_io_channel_shutdown(channel, FALSE, NULL);
774     }
775     g_free(path);
776 }
777
778 gboolean
779 keywords_try_search(WebKitWebView *web_view, const gchar *t)
780 {
781     gboolean ret = FALSE;
782     gchar **tokens = NULL;
783     gchar *val = NULL, *uri = NULL;
784
785     tokens = g_strsplit(t, " ", 2);
786     if (tokens[0] != NULL && tokens[1] != NULL)
787     {
788         val = g_hash_table_lookup(keywords, tokens[0]);
789         if (val != NULL)
790         {
791             uri = g_strdup_printf((gchar *)val, tokens[1]);
792             webkit_web_view_load_uri(web_view, uri);
793             g_free(uri);
794             ret = TRUE;
795         }
796     }
797     g_strfreev(tokens);
798
799     return ret;
800 }
801
802 gboolean
803 remote_msg(GIOChannel *channel, GIOCondition condition, gpointer data)
804 {
805     gchar *uri = NULL;
806
807     g_io_channel_read_line(channel, &uri, NULL, NULL, NULL);
808     if (uri)
809     {
810         g_strstrip(uri);
811         client_new(uri);
812         g_free(uri);
813     }
814     return TRUE;
815 }
816
817 void
818 search(gpointer data, gint direction)
819 {
820     struct Client *c = (struct Client *)data;
821     WebKitWebView *web_view = WEBKIT_WEB_VIEW(c->web_view);
822     WebKitFindController *fc = webkit_web_view_get_find_controller(web_view);
823
824     if (search_text == NULL)
825         return;
826
827     switch (direction)
828     {
829         case 0:
830             webkit_find_controller_search(fc, search_text,
831                                           WEBKIT_FIND_OPTIONS_CASE_INSENSITIVE |
832                                           WEBKIT_FIND_OPTIONS_WRAP_AROUND,
833                                           G_MAXUINT);
834             break;
835         case 1:
836             webkit_find_controller_search_next(fc);
837             break;
838         case -1:
839             webkit_find_controller_search_previous(fc);
840             break;
841     }
842 }
843
844 Window
845 tabbed_launch(void)
846 {
847     gint tabbed_stdout;
848     GIOChannel *tabbed_stdout_channel;
849     GError *err = NULL;
850     gchar *output = NULL;
851     char *argv[] = { "tabbed", "-c", "-d", "-p", "s1", "-n", __NAME__, NULL };
852     Window plug_into;
853
854     if (!g_spawn_async_with_pipes(NULL, argv, NULL, G_SPAWN_SEARCH_PATH, NULL,
855                                   NULL, NULL, NULL, &tabbed_stdout, NULL,
856                                   &err))
857     {
858         fprintf(stderr, __NAME__": Could not launch tabbed: %s\n", err->message);
859         g_error_free(err);
860         return 0;
861     }
862
863     tabbed_stdout_channel = g_io_channel_unix_new(tabbed_stdout);
864     if (tabbed_stdout_channel == NULL)
865     {
866         fprintf(stderr, __NAME__": Could open tabbed's stdout\n");
867         return 0;
868     }
869     g_io_channel_read_line(tabbed_stdout_channel, &output, NULL, NULL, NULL);
870     g_io_channel_shutdown(tabbed_stdout_channel, FALSE, NULL);
871     if (output == NULL)
872     {
873         fprintf(stderr, __NAME__": Could not read XID from tabbed\n");
874         return 0;
875     }
876     g_strstrip(output);
877     plug_into = strtol(output, NULL, 16);
878     g_free(output);
879     if (plug_into == 0)
880         fprintf(stderr, __NAME__": The XID from tabbed is 0\n");
881     return plug_into;
882 }
883
884 void
885 trust_user_certs(WebKitWebContext *wc)
886 {
887     GTlsCertificate *cert;
888     const gchar *basedir, *file, *absfile;
889     GDir *dir;
890
891     basedir = g_build_filename(g_get_user_config_dir(), __NAME__, "certs", NULL);
892     dir = g_dir_open(basedir, 0, NULL);
893     if (dir != NULL)
894     {
895         file = g_dir_read_name(dir);
896         while (file != NULL)
897         {
898             absfile = g_build_filename(g_get_user_config_dir(), __NAME__, "certs",
899                                        file, NULL);
900             cert = g_tls_certificate_new_from_file(absfile, NULL);
901             if (cert == NULL)
902                 fprintf(stderr, __NAME__": Could not load trusted cert '%s'\n", file);
903             else
904                 webkit_web_context_allow_tls_certificate_for_host(wc, cert, file);
905             file = g_dir_read_name(dir);
906         }
907         g_dir_close(dir);
908     }
909 }
910
911
912 int
913 main(int argc, char **argv)
914 {
915     gchar *c;
916     int opt, i;
917
918     gtk_init(&argc, &argv);
919
920     grab_environment_configuration();
921
922     while ((opt = getopt(argc, argv, "e:CT")) != -1)
923     {
924         switch (opt)
925         {
926             case 'e':
927                 embed = atol(optarg);
928                 tabbed_automagic = FALSE;
929                 break;
930             case 'C':
931                 cooperative_instances = FALSE;
932                 break;
933             case 'T':
934                 tabbed_automagic = FALSE;
935                 break;
936             default:
937                 fprintf(stderr, "Usage: "__NAME__" [OPTION]... [URI]...\n");
938                 exit(EXIT_FAILURE);
939         }
940     }
941
942     keywords_load();
943     if (cooperative_instances)
944         cooperation_setup();
945     downloadmanager_setup();
946
947     if (tabbed_automagic && !(cooperative_instances && !cooperative_alone))
948         embed = tabbed_launch();
949
950     if (!cooperative_instances || cooperative_alone)
951     {
952         c = g_build_filename(g_get_user_data_dir(), __NAME__, "web_extensions",
953                              NULL);
954         webkit_web_context_set_web_extensions_directory(
955             webkit_web_context_get_default(), c
956         );
957     }
958
959     if (optind >= argc)
960         client_new(home_uri);
961     else
962     {
963         for (i = optind; i < argc; i++)
964             client_new(argv[i]);
965     }
966
967     if (!cooperative_instances || cooperative_alone)
968         gtk_main();
969     exit(EXIT_SUCCESS);
970 }