]> git.armaanb.net Git - chorizo.git/blob - browser.c
Remove size request for the progress bar
[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), 1);
207
208     c->top_box = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 0);
209     gtk_box_pack_start(GTK_BOX(c->top_box), c->location, TRUE, TRUE, 0);
210     gtk_box_pack_start(GTK_BOX(c->top_box), c->progress, FALSE, FALSE, 0);
211
212     c->vbox = gtk_box_new(GTK_ORIENTATION_VERTICAL, 0);
213     gtk_box_pack_start(GTK_BOX(c->vbox), c->top_box, FALSE, FALSE, 0);
214     gtk_box_pack_start(GTK_BOX(c->vbox), c->web_view, TRUE, TRUE, 0);
215
216     gtk_container_add(GTK_CONTAINER(c->win), c->vbox);
217
218     gtk_widget_grab_focus(c->web_view);
219     gtk_widget_show_all(c->win);
220
221     if (uri != NULL)
222     {
223         f = ensure_uri_scheme(uri);
224         webkit_web_view_load_uri(WEBKIT_WEB_VIEW(c->web_view), f);
225         g_free(f);
226     }
227
228     clients++;
229
230     return WEBKIT_WEB_VIEW(c->web_view);
231 }
232
233 WebKitWebView *
234 client_new_request(WebKitWebView *web_view,
235                    WebKitNavigationAction *navigation_action, gpointer data)
236 {
237     return client_new(NULL);
238 }
239
240 void
241 cooperation_setup(void)
242 {
243     GIOChannel *towatch;
244     gchar *fifofilename, *fifopath;
245
246     fifofilename = g_strdup_printf("%s-%s", __NAME__".fifo", fifo_suffix);
247     fifopath = g_build_filename(g_get_user_runtime_dir(), fifofilename, NULL);
248     g_free(fifofilename);
249
250     if (!g_file_test(fifopath, G_FILE_TEST_EXISTS))
251         mkfifo(fifopath, 0600);
252
253     cooperative_pipe_fp = open(fifopath, O_WRONLY | O_NONBLOCK);
254     if (!cooperative_pipe_fp)
255     {
256         fprintf(stderr, __NAME__": Can't open FIFO at all.\n");
257     }
258     else
259     {
260         if (write(cooperative_pipe_fp, "", 0) == -1)
261         {
262             /* Could not do an empty write to the FIFO which means there's
263              * no one listening. */
264             close(cooperative_pipe_fp);
265             towatch = g_io_channel_new_file(fifopath, "r+", NULL);
266             g_io_add_watch(towatch, G_IO_IN, (GIOFunc)remote_msg, NULL);
267         }
268         else
269             cooperative_alone = FALSE;
270     }
271
272     g_free(fifopath);
273 }
274
275 void
276 changed_download_progress(GObject *obj, GParamSpec *pspec, gpointer data)
277 {
278     WebKitDownload *download = WEBKIT_DOWNLOAD(obj);
279     WebKitURIResponse *resp;
280     GtkToolItem *tb = GTK_TOOL_ITEM(data);
281     gdouble p, size_mb;
282     const gchar *uri;
283     gchar *t, *filename, *base;
284
285     p = webkit_download_get_estimated_progress(download) * 100;
286     resp = webkit_download_get_response(download);
287     size_mb = webkit_uri_response_get_content_length(resp) / 1e6;
288
289     uri = webkit_download_get_destination(download);
290     filename = g_filename_from_uri(uri, NULL, NULL);
291     if (filename == NULL)
292     {
293         /* This really should not happen because WebKit uses that URI to
294          * write to a file... */
295         fprintf(stderr, __NAME__": Could not construct file name from URI!\n");
296         t = g_strdup_printf("%s (%.0f%% of %.1f MB)",
297                             webkit_uri_response_get_uri(resp), p, size_mb);
298     }
299     else
300     {
301         base = g_path_get_basename(filename);
302         t = g_strdup_printf("%s (%.0f%% of %.1f MB)", base, p, size_mb);
303         g_free(filename);
304         g_free(base);
305     }
306     gtk_tool_button_set_label(GTK_TOOL_BUTTON(tb), t);
307     g_free(t);
308 }
309
310 void
311 changed_load_progress(GObject *obj, GParamSpec *pspec, gpointer data)
312 {
313     struct Client *c = (struct Client *)data;
314     gdouble p;
315
316     p = webkit_web_view_get_estimated_load_progress(WEBKIT_WEB_VIEW(c->web_view));
317     gtk_level_bar_set_value(GTK_LEVEL_BAR(c->progress), p);
318 }
319
320 void
321 changed_title(GObject *obj, GParamSpec *pspec, gpointer data)
322 {
323     const gchar *t, *u;
324     struct Client *c = (struct Client *)data;
325
326     u = webkit_web_view_get_uri(WEBKIT_WEB_VIEW(c->web_view));
327     t = webkit_web_view_get_title(WEBKIT_WEB_VIEW(c->web_view));
328
329     u = u == NULL ? __NAME__ : u;
330     u = u[0] == 0 ? __NAME__ : u;
331
332     t = t == NULL ? u : t;
333     t = t[0] == 0 ? u : t;
334
335     gtk_window_set_title(GTK_WINDOW(c->win), t);
336 }
337
338 void
339 changed_uri(GObject *obj, GParamSpec *pspec, gpointer data)
340 {
341     const gchar *t;
342     struct Client *c = (struct Client *)data;
343
344     t = webkit_web_view_get_uri(WEBKIT_WEB_VIEW(c->web_view));
345     gtk_entry_set_text(GTK_ENTRY(c->location), (t == NULL ? __NAME__ : t));
346 }
347
348 gboolean
349 crashed_web_view(WebKitWebView *web_view, gpointer data)
350 {
351     fprintf(stderr, __NAME__": WebView crashed!\n");
352     if (crash_autoreload_delay >= 1)
353     {
354         fprintf(stderr, __NAME__": Reloading WebView in %d seconds.\n",
355                 crash_autoreload_delay);
356         g_timeout_add_seconds(crash_autoreload_delay, crashed_web_view_reload,
357                               web_view);
358     }
359
360     return TRUE;
361 }
362
363 gboolean
364 crashed_web_view_reload(gpointer data)
365 {
366     webkit_web_view_reload_bypass_cache(WEBKIT_WEB_VIEW(data));
367
368     return G_SOURCE_REMOVE;
369 }
370
371 gboolean
372 decide_policy(WebKitWebView *web_view, WebKitPolicyDecision *decision,
373               WebKitPolicyDecisionType type, gpointer data)
374 {
375     WebKitResponsePolicyDecision *r;
376
377     switch (type)
378     {
379         case WEBKIT_POLICY_DECISION_TYPE_RESPONSE:
380             r = WEBKIT_RESPONSE_POLICY_DECISION(decision);
381             if (!webkit_response_policy_decision_is_mime_type_supported(r))
382                 webkit_policy_decision_download(decision);
383             else
384                 webkit_policy_decision_use(decision);
385             break;
386         default:
387             /* Use whatever default there is. */
388             return FALSE;
389     }
390     return TRUE;
391 }
392
393 void
394 download_handle_start(WebKitWebView *web_view, WebKitDownload *download,
395                       gpointer data)
396 {
397     g_signal_connect(G_OBJECT(download), "decide-destination",
398                      G_CALLBACK(download_handle), data);
399 }
400
401 gboolean
402 download_handle(WebKitDownload *download, gchar *suggested_filename, gpointer data)
403 {
404     gchar *sug_clean, *path, *path2 = NULL, *uri;
405     GtkToolItem *tb;
406     int suffix = 1;
407     size_t i;
408
409     sug_clean = g_strdup(suggested_filename);
410     for (i = 0; i < strlen(sug_clean); i++)
411         if (sug_clean[i] == G_DIR_SEPARATOR)
412             sug_clean[i] = '_';
413
414     path = g_build_filename(download_dir, sug_clean, NULL);
415     path2 = g_strdup(path);
416     while (g_file_test(path2, G_FILE_TEST_EXISTS) && suffix < 1000)
417     {
418         g_free(path2);
419
420         path2 = g_strdup_printf("%s.%d", path, suffix);
421         suffix++;
422     }
423
424     if (suffix == 1000)
425     {
426         fprintf(stderr, __NAME__": Suffix reached limit for download.\n");
427         webkit_download_cancel(download);
428     }
429     else
430     {
431         uri = g_filename_to_uri(path2, NULL, NULL);
432         webkit_download_set_destination(download, uri);
433         g_free(uri);
434
435         tb = gtk_tool_button_new(NULL, NULL);
436         gtk_tool_button_set_icon_name(GTK_TOOL_BUTTON(tb), "gtk-delete");
437         gtk_tool_button_set_label(GTK_TOOL_BUTTON(tb), sug_clean);
438         gtk_toolbar_insert(GTK_TOOLBAR(dm.toolbar), tb, 0);
439         gtk_widget_show_all(dm.win);
440
441         g_signal_connect(G_OBJECT(download), "notify::estimated-progress",
442                          G_CALLBACK(changed_download_progress), tb);
443
444         g_object_ref(download);
445         g_signal_connect(G_OBJECT(tb), "clicked",
446                          G_CALLBACK(downloadmanager_cancel), download);
447     }
448
449     g_free(sug_clean);
450     g_free(path);
451     g_free(path2);
452
453     /* Propagate -- to whom it may concern. */
454     return FALSE;
455 }
456
457 void
458 downloadmanager_cancel(GtkToolButton *tb, gpointer data)
459 {
460     WebKitDownload *download = WEBKIT_DOWNLOAD(data);
461
462     webkit_download_cancel(download);
463     g_object_unref(download);
464
465     gtk_widget_destroy(GTK_WIDGET(tb));
466 }
467
468 void
469 downloadmanager_setup(void)
470 {
471     dm.win = gtk_window_new(GTK_WINDOW_TOPLEVEL);
472     gtk_window_set_type_hint(GTK_WINDOW(dm.win), GDK_WINDOW_TYPE_HINT_DIALOG);
473     gtk_window_set_default_size(GTK_WINDOW(dm.win), 500, 250);
474     gtk_window_set_title(GTK_WINDOW(dm.win), __NAME__" - Download Manager");
475     g_signal_connect(G_OBJECT(dm.win), "delete-event",
476                      G_CALLBACK(gtk_widget_hide_on_delete), NULL);
477     g_signal_connect(G_OBJECT(dm.win), "key-press-event",
478                      G_CALLBACK(key_downloadmanager), NULL);
479
480     dm.toolbar = gtk_toolbar_new();
481     gtk_orientable_set_orientation(GTK_ORIENTABLE(dm.toolbar),
482                                    GTK_ORIENTATION_VERTICAL);
483     gtk_toolbar_set_style(GTK_TOOLBAR(dm.toolbar), GTK_TOOLBAR_BOTH_HORIZ);
484     gtk_toolbar_set_show_arrow(GTK_TOOLBAR(dm.toolbar), FALSE);
485
486     dm.scroll = gtk_scrolled_window_new(NULL, NULL);
487     gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(dm.scroll),
488                                    GTK_POLICY_AUTOMATIC, GTK_POLICY_AUTOMATIC);
489     gtk_container_add(GTK_CONTAINER(dm.scroll), dm.toolbar);
490
491     gtk_container_add(GTK_CONTAINER(dm.win), dm.scroll);
492 }
493
494 gchar *
495 ensure_uri_scheme(const gchar *t)
496 {
497     gchar *f;
498
499     f = g_ascii_strdown(t, -1);
500     if (!g_str_has_prefix(f, "http:") &&
501         !g_str_has_prefix(f, "https:") &&
502         !g_str_has_prefix(f, "file:") &&
503         !g_str_has_prefix(f, "about:"))
504     {
505         g_free(f);
506         f = g_strdup_printf("http://%s", t);
507         return f;
508     }
509     else
510         return g_strdup(t);
511 }
512
513 void
514 grab_environment_configuration(void)
515 {
516     const gchar *e;
517
518     e = g_getenv(__NAME_UPPERCASE__"_ACCEPTED_LANGUAGE");
519     if (e != NULL)
520         accepted_language[0] = g_strdup(e);
521
522     e = g_getenv(__NAME_UPPERCASE__"_CRASH_AUTORELOAD_DELAY");
523     if (e != NULL)
524         crash_autoreload_delay = atoi(e);
525
526     e = g_getenv(__NAME_UPPERCASE__"_DOWNLOAD_DIR");
527     if (e != NULL)
528         download_dir = g_strdup(e);
529
530     e = g_getenv(__NAME_UPPERCASE__"_FIFO_SUFFIX");
531     if (e != NULL)
532         fifo_suffix = g_strdup(e);
533
534     e = g_getenv(__NAME_UPPERCASE__"_HOME_URI");
535     if (e != NULL)
536         home_uri = g_strdup(e);
537
538     e = g_getenv(__NAME_UPPERCASE__"_USER_AGENT");
539     if (e != NULL)
540         user_agent = g_strdup(e);
541
542     e = g_getenv(__NAME_UPPERCASE__"_ZOOM");
543     if (e != NULL)
544         global_zoom = atof(e);
545 }
546
547 void
548 hover_web_view(WebKitWebView *web_view, WebKitHitTestResult *ht, guint modifiers,
549                gpointer data)
550 {
551     struct Client *c = (struct Client *)data;
552
553     if (!gtk_widget_is_focus(c->location))
554     {
555         if (webkit_hit_test_result_context_is_link(ht))
556         {
557             gtk_entry_set_text(GTK_ENTRY(c->location),
558                                webkit_hit_test_result_get_link_uri(ht));
559
560             if (c->hover_uri != NULL)
561                 g_free(c->hover_uri);
562             c->hover_uri = g_strdup(webkit_hit_test_result_get_link_uri(ht));
563         }
564         else
565         {
566             gtk_entry_set_text(GTK_ENTRY(c->location),
567                                webkit_web_view_get_uri(WEBKIT_WEB_VIEW(c->web_view)));
568
569             if (c->hover_uri != NULL)
570                 g_free(c->hover_uri);
571             c->hover_uri = NULL;
572         }
573     }
574 }
575
576 gboolean
577 key_downloadmanager(GtkWidget *widget, GdkEvent *event, gpointer data)
578 {
579     if (event->type == GDK_KEY_PRESS)
580     {
581         if (((GdkEventKey *)event)->state & GDK_MOD1_MASK)
582         {
583             switch (((GdkEventKey *)event)->keyval)
584             {
585                 case GDK_KEY_d:  /* close window (left hand) */
586                     gtk_widget_hide(dm.win);
587                     return TRUE;
588             }
589         }
590     }
591
592     return FALSE;
593 }
594
595 gboolean
596 key_location(GtkWidget *widget, GdkEvent *event, gpointer data)
597 {
598     struct Client *c = (struct Client *)data;
599     const gchar *t;
600     gchar *f;
601     WebKitWebContext *wc = webkit_web_view_get_context(WEBKIT_WEB_VIEW(c->web_view));
602
603     if (event->type == GDK_KEY_PRESS)
604     {
605         if (((GdkEventKey *)event)->state & GDK_MOD1_MASK)
606         {
607             switch (((GdkEventKey *)event)->keyval)
608             {
609                 case GDK_KEY_q:  /* close window (left hand) */
610                     gtk_widget_destroy(c->win);
611                     return TRUE;
612                 case GDK_KEY_d:  /* download manager (left hand) */
613                     gtk_widget_show_all(dm.win);
614                     return TRUE;
615                 case GDK_KEY_r:  /* reload (left hand) */
616                     webkit_web_view_reload_bypass_cache(WEBKIT_WEB_VIEW(
617                                                         c->web_view));
618                     return TRUE;
619                 case GDK_KEY_k:  /* initiate search (BOTH hands) */
620                     gtk_entry_set_text(GTK_ENTRY(c->location), "/");
621                     gtk_editable_set_position(GTK_EDITABLE(c->location), -1);
622                     return TRUE;
623                 case GDK_KEY_c:  /* reload trusted certs (left hand) */
624                     trust_user_certs(wc);
625                     return TRUE;
626             }
627         }
628         else
629         {
630             switch (((GdkEventKey *)event)->keyval)
631             {
632                 case GDK_KEY_KP_Enter:
633                 case GDK_KEY_Return:
634                     gtk_widget_grab_focus(c->web_view);
635                     t = gtk_entry_get_text(GTK_ENTRY(c->location));
636                     if (t != NULL && t[0] == '/')
637                     {
638                         if (search_text != NULL)
639                             g_free(search_text);
640                         search_text = g_strdup(t + 1);  /* XXX whacky */
641                         search(c, 0);
642                     }
643                     else if (!keywords_try_search(WEBKIT_WEB_VIEW(c->web_view), t))
644                     {
645                         f = ensure_uri_scheme(t);
646                         webkit_web_view_load_uri(WEBKIT_WEB_VIEW(c->web_view), f);
647                         g_free(f);
648                     }
649                     return TRUE;
650                 case GDK_KEY_Escape:
651                     t = webkit_web_view_get_uri(WEBKIT_WEB_VIEW(c->web_view));
652                     gtk_entry_set_text(GTK_ENTRY(c->location),
653                                        (t == NULL ? __NAME__ : t));
654                     return TRUE;
655             }
656         }
657     }
658
659     return FALSE;
660 }
661
662 gboolean
663 key_web_view(GtkWidget *widget, GdkEvent *event, gpointer data)
664 {
665     struct Client *c = (struct Client *)data;
666     gdouble dx, dy;
667     gchar *f;
668     gfloat z;
669     WebKitWebContext *wc = webkit_web_view_get_context(WEBKIT_WEB_VIEW(c->web_view));
670
671     if (event->type == GDK_KEY_PRESS)
672     {
673         if (((GdkEventKey *)event)->state & GDK_MOD1_MASK)
674         {
675             switch (((GdkEventKey *)event)->keyval)
676             {
677                 case GDK_KEY_q:  /* close window (left hand) */
678                     gtk_widget_destroy(c->win);
679                     return TRUE;
680                 case GDK_KEY_w:  /* home (left hand) */
681                     f = ensure_uri_scheme(home_uri);
682                     webkit_web_view_load_uri(WEBKIT_WEB_VIEW(c->web_view), f);
683                     g_free(f);
684                     return TRUE;
685                 case GDK_KEY_e:  /* new tab (left hand) */
686                     f = ensure_uri_scheme(home_uri);
687                     client_new(f);
688                     g_free(f);
689                     return TRUE;
690                 case GDK_KEY_r:  /* reload (left hand) */
691                     webkit_web_view_reload_bypass_cache(WEBKIT_WEB_VIEW(
692                                                         c->web_view));
693                     return TRUE;
694                 case GDK_KEY_d:  /* download manager (left hand) */
695                     gtk_widget_show_all(dm.win);
696                     return TRUE;
697                 case GDK_KEY_2:  /* search forward (left hand) */
698                 case GDK_KEY_n:  /* search forward (maybe both hands) */
699                     search(c, 1);
700                     return TRUE;
701                 case GDK_KEY_3:  /* search backward (left hand) */
702                     search(c, -1);
703                     return TRUE;
704                 case GDK_KEY_l:  /* location (BOTH hands) */
705                     gtk_widget_grab_focus(c->location);
706                     return TRUE;
707                 case GDK_KEY_k:  /* initiate search (BOTH hands) */
708                     gtk_widget_grab_focus(c->location);
709                     gtk_entry_set_text(GTK_ENTRY(c->location), "/");
710                     gtk_editable_set_position(GTK_EDITABLE(c->location), -1);
711                     return TRUE;
712                 case GDK_KEY_c:  /* reload trusted certs (left hand) */
713                     trust_user_certs(wc);
714                     return TRUE;
715             }
716         }
717         /* navigate backward (left hand) */
718         else if (((GdkEventKey *)event)->keyval == GDK_KEY_F2)
719         {
720             webkit_web_view_go_back(WEBKIT_WEB_VIEW(c->web_view));
721             return TRUE;
722         }
723         /* navigate forward (left hand) */
724         else if (((GdkEventKey *)event)->keyval == GDK_KEY_F3)
725         {
726             webkit_web_view_go_forward(WEBKIT_WEB_VIEW(c->web_view));
727             return TRUE;
728         }
729         else if (((GdkEventKey *)event)->keyval == GDK_KEY_Escape)
730         {
731             webkit_web_view_stop_loading(WEBKIT_WEB_VIEW(c->web_view));
732             gtk_level_bar_set_value(GTK_LEVEL_BAR(c->progress), 0);
733         }
734     }
735     else if (event->type == GDK_BUTTON_PRESS)
736     {
737         switch (((GdkEventButton *)event)->button)
738         {
739             case 2:
740                 if (c->hover_uri != NULL)
741                 {
742                     client_new(c->hover_uri);
743                     return TRUE;
744                 }
745                 break;
746             case 8:
747                 webkit_web_view_go_back(WEBKIT_WEB_VIEW(c->web_view));
748                 return TRUE;
749             case 9:
750                 webkit_web_view_go_forward(WEBKIT_WEB_VIEW(c->web_view));
751                 return TRUE;
752         }
753     }
754     else if (event->type == GDK_SCROLL)
755     {
756         if (((GdkEventScroll *)event)->state & GDK_MOD1_MASK ||
757             ((GdkEventScroll *)event)->state & GDK_CONTROL_MASK)
758         {
759             gdk_event_get_scroll_deltas(event, &dx, &dy);
760             z = webkit_web_view_get_zoom_level(WEBKIT_WEB_VIEW(c->web_view));
761             z += -dy * 0.1;
762             z = dx != 0 ? global_zoom : z;
763             webkit_web_view_set_zoom_level(WEBKIT_WEB_VIEW(c->web_view), z);
764             return TRUE;
765         }
766     }
767
768     return FALSE;
769 }
770
771 void
772 keywords_load(void)
773 {
774     GError *err = NULL;
775     GIOChannel *channel = NULL;
776     gchar *path = NULL, *buf = NULL;
777     gchar **tokens = NULL;
778
779     keywords = g_hash_table_new(g_str_hash, g_str_equal);
780
781     path = g_build_filename(g_get_user_config_dir(), __NAME__, "keywordsearch",
782                             NULL);
783     channel = g_io_channel_new_file(path, "r", &err);
784     if (channel != NULL)
785     {
786         while (g_io_channel_read_line(channel, &buf, NULL, NULL, NULL)
787                == G_IO_STATUS_NORMAL)
788         {
789             g_strstrip(buf);
790             if (buf[0] != '#')
791             {
792                 tokens = g_strsplit(buf, " ", 2);
793                 if (tokens[0] != NULL && tokens[1] != NULL)
794                     g_hash_table_insert(keywords, g_strdup(tokens[0]),
795                                         g_strdup(tokens[1]));
796                 g_strfreev(tokens);
797             }
798             g_free(buf);
799         }
800         g_io_channel_shutdown(channel, FALSE, NULL);
801     }
802     g_free(path);
803 }
804
805 gboolean
806 keywords_try_search(WebKitWebView *web_view, const gchar *t)
807 {
808     gboolean ret = FALSE;
809     gchar **tokens = NULL;
810     gchar *val = NULL, *uri = NULL;
811
812     tokens = g_strsplit(t, " ", 2);
813     if (tokens[0] != NULL && tokens[1] != NULL)
814     {
815         val = g_hash_table_lookup(keywords, tokens[0]);
816         if (val != NULL)
817         {
818             uri = g_strdup_printf((gchar *)val, tokens[1]);
819             webkit_web_view_load_uri(web_view, uri);
820             g_free(uri);
821             ret = TRUE;
822         }
823     }
824     g_strfreev(tokens);
825
826     return ret;
827 }
828
829 gboolean
830 remote_msg(GIOChannel *channel, GIOCondition condition, gpointer data)
831 {
832     gchar *uri = NULL;
833
834     g_io_channel_read_line(channel, &uri, NULL, NULL, NULL);
835     if (uri)
836     {
837         g_strstrip(uri);
838         client_new(uri);
839         g_free(uri);
840     }
841     return TRUE;
842 }
843
844 void
845 search(gpointer data, gint direction)
846 {
847     struct Client *c = (struct Client *)data;
848     WebKitWebView *web_view = WEBKIT_WEB_VIEW(c->web_view);
849     WebKitFindController *fc = webkit_web_view_get_find_controller(web_view);
850
851     if (search_text == NULL)
852         return;
853
854     switch (direction)
855     {
856         case 0:
857             webkit_find_controller_search(fc, search_text,
858                                           WEBKIT_FIND_OPTIONS_CASE_INSENSITIVE |
859                                           WEBKIT_FIND_OPTIONS_WRAP_AROUND,
860                                           G_MAXUINT);
861             break;
862         case 1:
863             webkit_find_controller_search_next(fc);
864             break;
865         case -1:
866             webkit_find_controller_search_previous(fc);
867             break;
868     }
869 }
870
871 Window
872 tabbed_launch(void)
873 {
874     gint tabbed_stdout;
875     GIOChannel *tabbed_stdout_channel;
876     GError *err = NULL;
877     gchar *output = NULL;
878     char *argv[] = { "tabbed", "-c", "-d", "-p", "s1", "-n", __NAME__, NULL };
879     Window plug_into;
880
881     if (!g_spawn_async_with_pipes(NULL, argv, NULL, G_SPAWN_SEARCH_PATH, NULL,
882                                   NULL, NULL, NULL, &tabbed_stdout, NULL,
883                                   &err))
884     {
885         fprintf(stderr, __NAME__": Could not launch tabbed: %s\n", err->message);
886         g_error_free(err);
887         return 0;
888     }
889
890     tabbed_stdout_channel = g_io_channel_unix_new(tabbed_stdout);
891     if (tabbed_stdout_channel == NULL)
892     {
893         fprintf(stderr, __NAME__": Could open tabbed's stdout\n");
894         return 0;
895     }
896     g_io_channel_read_line(tabbed_stdout_channel, &output, NULL, NULL, NULL);
897     g_io_channel_shutdown(tabbed_stdout_channel, FALSE, NULL);
898     if (output == NULL)
899     {
900         fprintf(stderr, __NAME__": Could not read XID from tabbed\n");
901         return 0;
902     }
903     g_strstrip(output);
904     plug_into = strtol(output, NULL, 16);
905     g_free(output);
906     if (plug_into == 0)
907         fprintf(stderr, __NAME__": The XID from tabbed is 0\n");
908     return plug_into;
909 }
910
911 void
912 trust_user_certs(WebKitWebContext *wc)
913 {
914     GTlsCertificate *cert;
915     const gchar *basedir, *file, *absfile;
916     GDir *dir;
917
918     basedir = g_build_filename(g_get_user_config_dir(), __NAME__, "certs", NULL);
919     dir = g_dir_open(basedir, 0, NULL);
920     if (dir != NULL)
921     {
922         file = g_dir_read_name(dir);
923         while (file != NULL)
924         {
925             absfile = g_build_filename(g_get_user_config_dir(), __NAME__, "certs",
926                                        file, NULL);
927             cert = g_tls_certificate_new_from_file(absfile, NULL);
928             if (cert == NULL)
929                 fprintf(stderr, __NAME__": Could not load trusted cert '%s'\n", file);
930             else
931                 webkit_web_context_allow_tls_certificate_for_host(wc, cert, file);
932             file = g_dir_read_name(dir);
933         }
934         g_dir_close(dir);
935     }
936 }
937
938
939 int
940 main(int argc, char **argv)
941 {
942     gchar *c;
943     int opt, i;
944
945     gtk_init(&argc, &argv);
946
947     grab_environment_configuration();
948
949     while ((opt = getopt(argc, argv, "e:CT")) != -1)
950     {
951         switch (opt)
952         {
953             case 'e':
954                 embed = atol(optarg);
955                 tabbed_automagic = FALSE;
956                 break;
957             case 'C':
958                 cooperative_instances = FALSE;
959                 break;
960             case 'T':
961                 tabbed_automagic = FALSE;
962                 break;
963             default:
964                 fprintf(stderr, "Usage: "__NAME__" [OPTION]... [URI]...\n");
965                 exit(EXIT_FAILURE);
966         }
967     }
968
969     keywords_load();
970     if (cooperative_instances)
971         cooperation_setup();
972     downloadmanager_setup();
973
974     if (tabbed_automagic && !(cooperative_instances && !cooperative_alone))
975         embed = tabbed_launch();
976
977     if (!cooperative_instances || cooperative_alone)
978     {
979         c = g_build_filename(g_get_user_data_dir(), __NAME__, "web_extensions",
980                              NULL);
981         webkit_web_context_set_web_extensions_directory(
982             webkit_web_context_get_default(), c
983         );
984     }
985
986     if (optind >= argc)
987         client_new(home_uri);
988     else
989     {
990         for (i = optind; i < argc; i++)
991             client_new(argv[i]);
992     }
993
994     if (!cooperative_instances || cooperative_alone)
995         gtk_main();
996     exit(EXIT_SUCCESS);
997 }