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