]> git.armaanb.net Git - chorizo.git/blob - browser.c
Shorten some code
[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 <gdk/gdkx.h>
10 #include <gdk/gdkkeysyms.h>
11 #include <gio/gio.h>
12 #include <webkit/webkit.h>
13
14
15 static void adblock(WebKitWebView *, WebKitWebFrame *, WebKitWebResource *,
16                     WebKitNetworkRequest *, WebKitNetworkResponse *, gpointer);
17 static void adblock_load(void);
18 static void client_destroy(GtkWidget *obj, gpointer data);
19 static gboolean client_destroy_request(WebKitWebView *, gpointer);
20 static WebKitWebView *client_new(const gchar *uri);
21 static WebKitWebView *client_new_request(WebKitWebView *, WebKitWebFrame *,
22                                          gpointer);
23 static void cooperation_setup(void);
24 static void changed_load_progress(GObject *obj, GParamSpec *pspec,
25                                   gpointer data);
26 static void changed_title(GObject *, GParamSpec *, gpointer);
27 static void changed_uri(GObject *, GParamSpec *, gpointer);
28 static gboolean download_handle(WebKitWebView *, WebKitDownload *, gpointer);
29 static gboolean download_reset_indicator(gpointer);
30 static gboolean download_request(WebKitWebView *, WebKitWebFrame *,
31                                  WebKitNetworkRequest *, gchar *,
32                                  WebKitWebPolicyDecision *, gpointer);
33 static void downloadmanager_cancel(GtkToolButton *, gpointer data);
34 static void downloadmanager_progress(GObject *obj, GParamSpec *pspec,
35                                      gpointer data);
36 static void downloadmanager_setup(void);
37 static gchar *ensure_url_scheme(const gchar *);
38 static void grab_environment_configuration(void);
39 static void hover_web_view(WebKitWebView *, gchar *, gchar *, gpointer);
40 static gboolean key_downloadmanager(GtkWidget *, GdkEvent *, gpointer);
41 static gboolean key_location(GtkWidget *, GdkEvent *, gpointer);
42 static gboolean key_web_view(GtkWidget *, GdkEvent *, gpointer);
43 static void keywords_load(void);
44 static gboolean keywords_try_search(WebKitWebView *, const gchar *);
45 static gboolean remote_msg(GIOChannel *, GIOCondition, gpointer);
46 static void search(gpointer, gint);
47 static Window tabbed_launch(void);
48 static void usage(void);
49
50
51 struct Client
52 {
53         GtkWidget *location;
54         GtkWidget *progress;
55         GtkWidget *scroll;
56         GtkWidget *status;
57         GtkWidget *top_box;
58         GtkWidget *vbox;
59         GtkWidget *web_view;
60         GtkWidget *win;
61 };
62
63 struct DownloadManager
64 {
65         GtkWidget *scroll;
66         GtkWidget *toolbar;
67         GtkWidget *win;
68 } dm;
69
70
71 static gchar *accepted_language = "en-US";
72 static GSList *adblock_patterns = NULL;
73 static gint clients = 0;
74 static gboolean cooperative_alone = TRUE;
75 static gboolean cooperative_instances = TRUE;
76 static int cooperative_pipe_fp = 0;
77 static gchar *download_dir = "/tmp";
78 static gint downloads_indicated = 0;
79 static Window embed = 0;
80 static gchar *first_uri = NULL;
81 static gdouble global_zoom = 1.0;
82 static GHashTable *keywords = NULL;
83 static gboolean language_is_set = FALSE;
84 static gchar *search_text = NULL;
85 static gboolean show_all_requests = FALSE;
86 static gboolean tabbed_automagic = TRUE;
87
88
89 void
90 adblock(WebKitWebView *web_view, WebKitWebFrame *frame,
91         WebKitWebResource *resource, WebKitNetworkRequest *request,
92         WebKitNetworkResponse *response, gpointer data)
93 {
94         GSList *it = adblock_patterns;
95         const gchar *uri;
96
97         (void)web_view;
98         (void)frame;
99         (void)resource;
100         (void)response;
101         (void)data;
102
103         uri = webkit_network_request_get_uri(request);
104         if (show_all_requests)
105                 fprintf(stderr, "   -> %s\n", uri);
106
107         while (it)
108         {
109                 if (g_regex_match((GRegex *)(it->data), uri, 0, NULL))
110                 {
111                         webkit_network_request_set_uri(request, "about:blank");
112                         if (show_all_requests)
113                                 fprintf(stderr, "            BLOCKED!\n");
114                         return;
115                 }
116                 it = g_slist_next(it);
117         }
118 }
119
120 void
121 adblock_load(void)
122 {
123         GRegex *re = NULL;
124         GError *err = NULL;
125         GIOChannel *channel = NULL;
126         gchar *path = NULL, *buf = NULL;
127
128         path = g_build_filename(g_get_user_config_dir(), __NAME__, "adblock.black",
129                                 NULL);
130         channel = g_io_channel_new_file(path, "r", &err);
131         if (channel != NULL)
132         {
133                 while (g_io_channel_read_line(channel, &buf, NULL, NULL, NULL)
134                        == G_IO_STATUS_NORMAL)
135                 {
136                         g_strstrip(buf);
137                         re = g_regex_new(buf,
138                                          G_REGEX_CASELESS | G_REGEX_OPTIMIZE,
139                                          G_REGEX_MATCH_PARTIAL, &err);
140                         if (err != NULL)
141                         {
142                                 fprintf(stderr, __NAME__": Could not compile regex: %s\n", buf);
143                                 g_error_free(err);
144                                 err = NULL;
145                         }
146                         adblock_patterns = g_slist_append(adblock_patterns, re);
147
148                         g_free(buf);
149                 }
150         }
151         g_io_channel_shutdown(channel, FALSE, NULL);
152         g_free(path);
153 }
154
155 void
156 client_destroy(GtkWidget *obj, gpointer data)
157 {
158         struct Client *c = (struct Client *)data;
159
160         (void)obj;
161         (void)data;
162
163         free(c);
164         clients--;
165
166         if (clients == 0)
167                 gtk_main_quit();
168 }
169
170 gboolean
171 client_destroy_request(WebKitWebView *web_view, gpointer data)
172 {
173         struct Client *c = (struct Client *)data;
174
175         (void)web_view;
176
177         gtk_widget_destroy(c->win);
178
179         return TRUE;
180 }
181
182 WebKitWebView *
183 client_new(const gchar *uri)
184 {
185         struct Client *c;
186         gchar *f;
187
188         if (uri != NULL && cooperative_instances && !cooperative_alone)
189         {
190                 write(cooperative_pipe_fp, uri, strlen(uri));
191                 write(cooperative_pipe_fp, "\n", 1);
192                 return NULL;
193         }
194
195         c = malloc(sizeof(struct Client));
196         if (!c)
197         {
198                 fprintf(stderr, __NAME__": fatal: malloc failed\n");
199                 exit(EXIT_FAILURE);
200         }
201
202         c->win = NULL;
203         if (embed != 0)
204         {
205                 c->win = gtk_plug_new(embed);
206                 if (!gtk_plug_get_embedded(GTK_PLUG(c->win)))
207                 {
208                         fprintf(stderr, __NAME__": Can't plug-in to XID %ld.\n", embed);
209                         gtk_widget_destroy(c->win);
210                         c->win = NULL;
211                         embed = 0;
212                 }
213         }
214
215         if (c->win == NULL)
216         {
217                 c->win = gtk_window_new(GTK_WINDOW_TOPLEVEL);
218                 gtk_window_set_wmclass(GTK_WINDOW(c->win), __NAME__, __NAME_CAPITALIZED__);
219         }
220
221         /* When using Gtk2, it only shows a white area when run in suckless'
222          * tabbed. It appears we need to set a default window size for this
223          * to work. This is not needed when using Gtk3. */
224         gtk_window_set_default_size(GTK_WINDOW(c->win), 1024, 768);
225
226         g_signal_connect(G_OBJECT(c->win), "destroy", G_CALLBACK(client_destroy), c);
227         gtk_window_set_title(GTK_WINDOW(c->win), __NAME__);
228
229         c->web_view = webkit_web_view_new();
230
231         /* XXX I really do want to enable this option. However, I get
232          * reproducable crashes with it enabled. I've seen bug reports from
233          * 2010 about this... WebKit crashes in libpixman, so maybe it's not
234          * a WebKit issue.
235          * Yeah, well. I'll turn it off for now. */
236         /*webkit_web_view_set_full_content_zoom(WEBKIT_WEB_VIEW(c->web_view), TRUE);*/
237
238         webkit_web_view_set_zoom_level(WEBKIT_WEB_VIEW(c->web_view), global_zoom);
239         g_signal_connect(G_OBJECT(c->web_view), "notify::title",
240                          G_CALLBACK(changed_title), c);
241         g_signal_connect(G_OBJECT(c->web_view), "notify::uri",
242                          G_CALLBACK(changed_uri), c);
243         g_signal_connect(G_OBJECT(c->web_view), "notify::progress",
244                          G_CALLBACK(changed_load_progress), c);
245         g_signal_connect(G_OBJECT(c->web_view), "create-web-view",
246                          G_CALLBACK(client_new_request), NULL);
247         g_signal_connect(G_OBJECT(c->web_view), "close-web-view",
248                          G_CALLBACK(client_destroy_request), c);
249         g_signal_connect(G_OBJECT(c->web_view),
250                          "mime-type-policy-decision-requested",
251                          G_CALLBACK(download_request), NULL);
252         g_signal_connect(G_OBJECT(c->web_view), "download-requested",
253                          G_CALLBACK(download_handle), c);
254         g_signal_connect(G_OBJECT(c->web_view), "key-press-event",
255                          G_CALLBACK(key_web_view), c);
256         g_signal_connect(G_OBJECT(c->web_view), "button-press-event",
257                          G_CALLBACK(key_web_view), c);
258         g_signal_connect(G_OBJECT(c->web_view), "scroll-event",
259                          G_CALLBACK(key_web_view), c);
260         g_signal_connect(G_OBJECT(c->web_view), "hovering-over-link",
261                          G_CALLBACK(hover_web_view), c);
262         g_signal_connect(G_OBJECT(c->web_view), "resource-request-starting",
263                          G_CALLBACK(adblock), NULL);
264
265         if (!language_is_set)
266         {
267                 g_object_set(webkit_get_default_session(), "accept-language",
268                              accepted_language, NULL);
269                 language_is_set = TRUE;
270         }
271
272         c->scroll = gtk_scrolled_window_new(NULL, NULL);
273
274         gtk_container_add(GTK_CONTAINER(c->scroll), c->web_view);
275
276         c->location = gtk_entry_new();
277         g_signal_connect(G_OBJECT(c->location), "key-press-event",
278                          G_CALLBACK(key_location), c);
279
280         c->progress = gtk_progress_bar_new();
281         gtk_progress_bar_set_fraction(GTK_PROGRESS_BAR(c->progress), 0);
282
283         c->status = gtk_progress_bar_new();
284         gtk_progress_bar_set_fraction(GTK_PROGRESS_BAR(c->status), 0);
285         gtk_widget_set_size_request(c->status, 20, -1);
286
287         c->top_box = gtk_hbox_new(FALSE, 0);
288         gtk_box_pack_start(GTK_BOX(c->top_box), c->status, FALSE, FALSE, 2);
289         gtk_box_pack_start(GTK_BOX(c->top_box), c->location, TRUE, TRUE, 0);
290         gtk_box_pack_end(GTK_BOX(c->top_box), c->progress, FALSE, TRUE, 2);
291
292         c->vbox = gtk_vbox_new(FALSE, 0);
293         gtk_box_pack_start(GTK_BOX(c->vbox), c->top_box, FALSE, FALSE, 2);
294         gtk_container_add(GTK_CONTAINER(c->vbox), c->scroll);
295
296         gtk_container_add(GTK_CONTAINER(c->win), c->vbox);
297
298         gtk_widget_grab_focus(c->web_view);
299         gtk_widget_show_all(c->win);
300
301         if (uri != NULL)
302         {
303                 f = ensure_url_scheme(uri);
304                 if (show_all_requests)
305                         fprintf(stderr, "====> %s\n", uri);
306                 webkit_web_view_load_uri(WEBKIT_WEB_VIEW(c->web_view), f);
307                 g_free(f);
308         }
309
310         clients++;
311
312         return WEBKIT_WEB_VIEW(c->web_view);
313 }
314
315 WebKitWebView *
316 client_new_request(WebKitWebView *web_view, WebKitWebFrame *frame, gpointer data)
317 {
318         (void)web_view;
319         (void)frame;
320         (void)data;
321
322         return client_new(NULL);
323 }
324
325 void
326 cooperation_setup(void)
327 {
328         GIOChannel *towatch;
329         const gchar *e;
330         gchar *fifofilename, *fifopath;
331
332         e = g_getenv(__NAME_UPPERCASE__"_FIFO_SUFFIX");
333         if (e != NULL)
334                 fifofilename = g_strdup_printf("%s-%s", __NAME__".fifo", e);
335         else
336                 fifofilename = g_strdup(__NAME__".fifo");
337         fifopath = g_build_filename(g_get_user_runtime_dir(), fifofilename, NULL);
338         g_free(fifofilename);
339
340         if (!g_file_test(fifopath, G_FILE_TEST_EXISTS))
341                 mkfifo(fifopath, 0600);
342
343         cooperative_pipe_fp = open(fifopath, O_WRONLY | O_NONBLOCK);
344         if (!cooperative_pipe_fp)
345         {
346                 fprintf(stderr, __NAME__": Can't open FIFO at all.\n");
347         }
348         else
349         {
350                 if (write(cooperative_pipe_fp, "", 0) == -1)
351                 {
352                         /* Could not do an empty write to the FIFO which means there's
353                          * no one listening. */
354                         close(cooperative_pipe_fp);
355                         towatch = g_io_channel_new_file(fifopath, "r+", NULL);
356                         g_io_add_watch(towatch, G_IO_IN, (GIOFunc)remote_msg, NULL);
357                 }
358                 else
359                         cooperative_alone = FALSE;
360         }
361
362         g_free(fifopath);
363 }
364
365 void
366 changed_load_progress(GObject *obj, GParamSpec *pspec, gpointer data)
367 {
368         struct Client *c = (struct Client *)data;
369         gdouble p;
370
371         (void)obj;
372         (void)pspec;
373
374         p = webkit_web_view_get_progress(WEBKIT_WEB_VIEW(c->web_view));
375         gtk_progress_bar_set_fraction(GTK_PROGRESS_BAR(c->progress), p);
376 }
377
378 void
379 changed_title(GObject *obj, GParamSpec *pspec, gpointer data)
380 {
381         const gchar *t;
382         struct Client *c = (struct Client *)data;
383
384         (void)obj;
385         (void)pspec;
386
387         t = webkit_web_view_get_title(WEBKIT_WEB_VIEW(c->web_view));
388         gtk_window_set_title(GTK_WINDOW(c->win), (t == NULL ? __NAME__ : t));
389 }
390
391 void
392 changed_uri(GObject *obj, GParamSpec *pspec, gpointer data)
393 {
394         const gchar *t;
395         struct Client *c = (struct Client *)data;
396
397         (void)obj;
398         (void)pspec;
399
400         t = webkit_web_view_get_uri(WEBKIT_WEB_VIEW(c->web_view));
401         gtk_entry_set_text(GTK_ENTRY(c->location), (t == NULL ? __NAME__ : t));
402 }
403
404 gboolean
405 download_handle(WebKitWebView *web_view, WebKitDownload *download, gpointer data)
406 {
407         struct Client *c = (struct Client *)data;
408         gchar *path, *path2 = NULL, *uri;
409         GtkToolItem *tb;
410         gboolean ret;
411         int suffix = 1;
412
413         (void)web_view;
414         (void)data;
415
416         path = g_build_filename(download_dir,
417                                 webkit_download_get_suggested_filename(download),
418                                 NULL);
419         path2 = g_strdup(path);
420         while (g_file_test(path2, G_FILE_TEST_EXISTS) && suffix < 1000)
421         {
422                 g_free(path2);
423
424                 path2 = g_strdup_printf("%s.%d", path, suffix);
425                 suffix++;
426         }
427
428         if (suffix == 1000)
429         {
430                 fprintf(stderr, __NAME__": Suffix reached limit for download.\n");
431                 ret = FALSE;
432         }
433         else
434         {
435                 uri = g_filename_to_uri(path2, NULL, NULL);
436                 webkit_download_set_destination_uri(download, uri);
437                 ret = TRUE;
438                 g_free(uri);
439
440                 gtk_progress_bar_set_fraction(GTK_PROGRESS_BAR(c->status), 1);
441                 downloads_indicated++;
442                 g_timeout_add(500, download_reset_indicator, c);
443
444                 tb = gtk_tool_button_new_from_stock(GTK_STOCK_DELETE);
445                 gtk_tool_button_set_label(GTK_TOOL_BUTTON(tb),
446                                           webkit_download_get_suggested_filename(download));
447                 gtk_toolbar_insert(GTK_TOOLBAR(dm.toolbar), tb, 0);
448                 gtk_widget_show_all(dm.toolbar);
449
450                 g_signal_connect(G_OBJECT(download), "notify::progress",
451                                  G_CALLBACK(downloadmanager_progress), tb);
452
453                 g_object_ref(download);
454                 g_signal_connect(G_OBJECT(tb), "clicked",
455                                  G_CALLBACK(downloadmanager_cancel), download);
456         }
457
458         g_free(path);
459         g_free(path2);
460
461         return ret;
462 }
463
464 gboolean
465 download_reset_indicator(gpointer data)
466 {
467         struct Client *c = (struct Client *)data;
468
469         downloads_indicated--;
470         if (downloads_indicated == 0)
471                 gtk_progress_bar_set_fraction(GTK_PROGRESS_BAR(c->status), 0);
472
473         return FALSE;
474 }
475
476 gboolean
477 download_request(WebKitWebView *web_view, WebKitWebFrame *frame,
478                  WebKitNetworkRequest *request, gchar *mime_type,
479                  WebKitWebPolicyDecision *policy_decision, gpointer data)
480 {
481         (void)frame;
482         (void)request;
483         (void)data;
484
485         if (!webkit_web_view_can_show_mime_type(web_view, mime_type))
486         {
487                 webkit_web_policy_decision_download(policy_decision);
488                 return TRUE;
489         }
490         return FALSE;
491 }
492
493 void
494 downloadmanager_cancel(GtkToolButton *tb, gpointer data)
495 {
496         WebKitDownload *download = WEBKIT_DOWNLOAD(data);
497
498         webkit_download_cancel(download);
499         g_object_unref(download);
500
501         gtk_widget_destroy(GTK_WIDGET(tb));
502 }
503
504 void
505 downloadmanager_progress(GObject *obj, GParamSpec *pspec, gpointer data)
506 {
507         WebKitDownload *download = WEBKIT_DOWNLOAD(obj);
508         GtkToolItem *tb = GTK_TOOL_ITEM(data);
509         gdouble p;
510         gchar *t;
511
512         (void)pspec;
513
514         p = webkit_download_get_progress(download) * 100;
515         t = g_strdup_printf("%s (%.0f%%)",
516                             webkit_download_get_suggested_filename(download),
517                                                 p);
518         gtk_tool_button_set_label(GTK_TOOL_BUTTON(tb), t);
519         g_free(t);
520 }
521
522 void
523 downloadmanager_setup(void)
524 {
525         dm.win = gtk_window_new(GTK_WINDOW_TOPLEVEL);
526         gtk_window_set_type_hint(GTK_WINDOW(dm.win), GDK_WINDOW_TYPE_HINT_DIALOG);
527         gtk_window_set_default_size(GTK_WINDOW(dm.win), 500, 250);
528         gtk_window_set_title(GTK_WINDOW(dm.win), __NAME__" - Download Manager");
529         g_signal_connect(G_OBJECT(dm.win), "delete-event",
530                          G_CALLBACK(gtk_widget_hide_on_delete), NULL);
531         g_signal_connect(G_OBJECT(dm.win), "key-press-event",
532                          G_CALLBACK(key_downloadmanager), NULL);
533
534         dm.toolbar = gtk_toolbar_new();
535         gtk_orientable_set_orientation(GTK_ORIENTABLE(dm.toolbar),
536                                        GTK_ORIENTATION_VERTICAL);
537         gtk_toolbar_set_style(GTK_TOOLBAR(dm.toolbar), GTK_TOOLBAR_BOTH_HORIZ);
538         gtk_toolbar_set_show_arrow(GTK_TOOLBAR(dm.toolbar), FALSE);
539
540         dm.scroll = gtk_scrolled_window_new(NULL, NULL);
541         gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(dm.scroll),
542                                        GTK_POLICY_AUTOMATIC, GTK_POLICY_AUTOMATIC);
543         gtk_scrolled_window_add_with_viewport(GTK_SCROLLED_WINDOW(dm.scroll),
544                                               dm.toolbar);
545
546         gtk_container_add(GTK_CONTAINER(dm.win), dm.scroll);
547 }
548
549 gchar *
550 ensure_url_scheme(const gchar *t)
551 {
552         gchar *f;
553
554         f = g_ascii_strdown(t, -1);
555         if (!g_str_has_prefix(f, "http:") &&
556             !g_str_has_prefix(f, "https:") &&
557             !g_str_has_prefix(f, "file:") &&
558             !g_str_has_prefix(f, "about:"))
559         {
560                 g_free(f);
561                 f = g_strdup_printf("http://%s", t);
562                 return f;
563         }
564         else
565                 return g_strdup(t);
566 }
567
568 void
569 grab_environment_configuration(void)
570 {
571         const gchar *e;
572
573         e = g_getenv(__NAME_UPPERCASE__"_ACCEPTED_LANGUAGE");
574         if (e != NULL)
575                 accepted_language = g_strdup(e);
576
577         e = g_getenv(__NAME_UPPERCASE__"_DOWNLOAD_DIR");
578         if (e != NULL)
579                 download_dir = g_strdup(e);
580
581         e = g_getenv(__NAME_UPPERCASE__"_ZOOM");
582         if (e != NULL)
583                 global_zoom = atof(e);
584 }
585
586 void
587 hover_web_view(WebKitWebView *web_view, gchar *title, gchar *uri, gpointer data)
588 {
589         struct Client *c = (struct Client *)data;
590
591         (void)web_view;
592         (void)title;
593
594         if (!gtk_widget_is_focus(c->location))
595         {
596                 if (uri == NULL)
597                         gtk_entry_set_text(GTK_ENTRY(c->location),
598                                            webkit_web_view_get_uri(WEBKIT_WEB_VIEW(c->web_view)));
599                 else
600                         gtk_entry_set_text(GTK_ENTRY(c->location), uri);
601         }
602 }
603
604 gboolean
605 key_downloadmanager(GtkWidget *widget, GdkEvent *event, gpointer data)
606 {
607         (void)widget;
608         (void)data;
609
610         if (event->type == GDK_KEY_PRESS)
611         {
612                 if (((GdkEventKey *)event)->state & GDK_MOD1_MASK)
613                 {
614                         switch (((GdkEventKey *)event)->keyval)
615                         {
616                                 case GDK_KEY_q:  /* close window (left hand) */
617                                         gtk_widget_hide(dm.win);
618                                         return TRUE;
619                         }
620                 }
621         }
622
623         return FALSE;
624 }
625
626 gboolean
627 key_location(GtkWidget *widget, GdkEvent *event, gpointer data)
628 {
629         struct Client *c = (struct Client *)data;
630         const gchar *t;
631         gchar *f;
632
633         (void)widget;
634
635         if (event->type == GDK_KEY_PRESS)
636         {
637                 if (((GdkEventKey *)event)->state & GDK_MOD1_MASK)
638                 {
639                         switch (((GdkEventKey *)event)->keyval)
640                         {
641                                 case GDK_KEY_q:  /* close window (left hand) */
642                                         gtk_widget_destroy(c->win);
643                                         return TRUE;
644                                 case GDK_KEY_d:  /* download manager (left hand) */
645                                         gtk_widget_show_all(dm.win);
646                                         return TRUE;
647                                 case GDK_KEY_r:  /* reload (left hand) */
648                                         webkit_web_view_reload_bypass_cache(WEBKIT_WEB_VIEW(
649                                                                             c->web_view));
650                                         return TRUE;
651                                 case GDK_KEY_k:  /* initiate search (BOTH hands) */
652                                         gtk_entry_set_text(GTK_ENTRY(c->location), "/");
653                                         gtk_editable_set_position(GTK_EDITABLE(c->location), -1);
654                                         return TRUE;
655                         }
656                 }
657                 else
658                 {
659                         switch (((GdkEventKey *)event)->keyval)
660                         {
661                                 case GDK_KEY_Return:
662                                         gtk_widget_grab_focus(c->web_view);
663                                         t = gtk_entry_get_text(GTK_ENTRY(c->location));
664                                         if (t != NULL && t[0] == '/')
665                                         {
666                                                 if (search_text != NULL)
667                                                         g_free(search_text);
668                                                 search_text = g_strdup(t + 1);  /* XXX whacky */
669                                                 search(c, 1);
670                                         }
671                                         else if (!keywords_try_search(WEBKIT_WEB_VIEW(c->web_view), t))
672                                         {
673                                                 f = ensure_url_scheme(t);
674                                                 if (show_all_requests)
675                                                         fprintf(stderr, "====> %s\n", f);
676                                                 webkit_web_view_load_uri(WEBKIT_WEB_VIEW(c->web_view), f);
677                                                 g_free(f);
678                                         }
679                                         return TRUE;
680                                 case GDK_KEY_Escape:
681                                         t = webkit_web_view_get_uri(WEBKIT_WEB_VIEW(c->web_view));
682                                         gtk_entry_set_text(GTK_ENTRY(c->location),
683                                                            (t == NULL ? __NAME__ : t));
684                                         return TRUE;
685                         }
686                 }
687         }
688
689         return FALSE;
690 }
691
692 gboolean
693 key_web_view(GtkWidget *widget, GdkEvent *event, gpointer data)
694 {
695         struct Client *c = (struct Client *)data;
696         WebKitHitTestResultContext ht_context;
697         WebKitHitTestResult *ht_result = NULL;
698         gchar *ht_uri = NULL, *f;
699         gfloat z;
700
701         (void)widget;
702
703         if (event->type == GDK_KEY_PRESS)
704         {
705                 if (((GdkEventKey *)event)->state & GDK_MOD1_MASK)
706                 {
707                         switch (((GdkEventKey *)event)->keyval)
708                         {
709                                 case GDK_KEY_q:  /* close window (left hand) */
710                                         gtk_widget_destroy(c->win);
711                                         return TRUE;
712                                 case GDK_KEY_w:  /* home (left hand) */
713                                         f = ensure_url_scheme(first_uri);
714                                         if (show_all_requests)
715                                                 fprintf(stderr, "====> %s\n", f);
716                                         webkit_web_view_load_uri(WEBKIT_WEB_VIEW(c->web_view), f);
717                                         g_free(f);
718                                         return TRUE;
719                                 case GDK_KEY_e:  /* new tab (left hand) */
720                                         f = ensure_url_scheme(first_uri);
721                                         if (show_all_requests)
722                                                 fprintf(stderr, "====> %s\n", f);
723                                         client_new(f);
724                                         g_free(f);
725                                         return TRUE;
726                                 case GDK_KEY_r:  /* reload (left hand) */
727                                         webkit_web_view_reload_bypass_cache(WEBKIT_WEB_VIEW(
728                                                                             c->web_view));
729                                         return TRUE;
730                                 case GDK_KEY_d:  /* download manager (left hand) */
731                                         gtk_widget_show_all(dm.win);
732                                         return TRUE;
733                                 case GDK_KEY_2:  /* search forward (left hand) */
734                                 case GDK_KEY_n:  /* search forward (maybe both hands) */
735                                         search(c, 1);
736                                         return TRUE;
737                                 case GDK_KEY_3:  /* search backward (left hand) */
738                                         search(c, -1);
739                                         return TRUE;
740                                 case GDK_KEY_l:  /* location (BOTH hands) */
741                                         gtk_widget_grab_focus(c->location);
742                                         return TRUE;
743                                 case GDK_KEY_k:  /* initiate search (BOTH hands) */
744                                         gtk_widget_grab_focus(c->location);
745                                         gtk_entry_set_text(GTK_ENTRY(c->location), "/");
746                                         gtk_editable_set_position(GTK_EDITABLE(c->location), -1);
747                                         return TRUE;
748                         }
749                 }
750                 else if (((GdkEventKey *)event)->keyval == GDK_KEY_Escape)
751                 {
752                         webkit_web_view_stop_loading(WEBKIT_WEB_VIEW(c->web_view));
753                         gtk_progress_bar_set_fraction(GTK_PROGRESS_BAR(c->progress), 0);
754                 }
755         }
756         else if (event->type == GDK_BUTTON_PRESS)
757         {
758                 switch (((GdkEventButton *)event)->button)
759                 {
760                         case 2:
761                                 ht_result = webkit_web_view_get_hit_test_result(
762                                                                    WEBKIT_WEB_VIEW(c->web_view),
763                                                                        (GdkEventButton *)event);
764                                 g_object_get(ht_result, "context", &ht_context, NULL);
765                                 if (ht_context & WEBKIT_HIT_TEST_RESULT_CONTEXT_LINK)
766                                 {
767                                         g_object_get(ht_result, "link-uri", &ht_uri, NULL);
768                                         client_new(ht_uri);
769                                         g_object_unref(ht_result);
770                                         return TRUE;
771                                 }
772                                 g_object_unref(ht_result);
773                                 break;
774                         case 8:
775                                 webkit_web_view_go_back(WEBKIT_WEB_VIEW(c->web_view));
776                                 return TRUE;
777                         case 9:
778                                 webkit_web_view_go_forward(WEBKIT_WEB_VIEW(c->web_view));
779                                 return TRUE;
780                 }
781         }
782         else if (event->type == GDK_SCROLL)
783         {
784                 if (((GdkEventScroll *)event)->state & GDK_MOD1_MASK ||
785                     ((GdkEventScroll *)event)->state & GDK_CONTROL_MASK)
786                 {
787                         switch (((GdkEventScroll *)event)->direction)
788                         {
789                                 case GDK_SCROLL_UP:
790                                         z = webkit_web_view_get_zoom_level(WEBKIT_WEB_VIEW(
791                                                                                      c->web_view));
792                                         z += 0.1;
793                                         webkit_web_view_set_zoom_level(WEBKIT_WEB_VIEW(c->web_view),
794                                                                        z);
795                                         return TRUE;
796                                 case GDK_SCROLL_DOWN:
797                                         z = webkit_web_view_get_zoom_level(WEBKIT_WEB_VIEW(
798                                                                                      c->web_view));
799                                         z -= 0.1;
800                                         webkit_web_view_set_zoom_level(WEBKIT_WEB_VIEW(c->web_view),
801                                                                        z);
802                                         return TRUE;
803                                 default:
804                                         break;
805                         }
806                 }
807         }
808
809         return FALSE;
810 }
811
812 void
813 keywords_load(void)
814 {
815         GError *err = NULL;
816         GIOChannel *channel = NULL;
817         gchar *path = NULL, *buf = NULL;
818         gchar **tokens = NULL;
819
820         keywords = g_hash_table_new(g_str_hash, g_str_equal);
821
822         path = g_build_filename(g_get_user_config_dir(), __NAME__, "keywordsearch",
823                                 NULL);
824         channel = g_io_channel_new_file(path, "r", &err);
825         if (channel != NULL)
826         {
827                 while (g_io_channel_read_line(channel, &buf, NULL, NULL, NULL)
828                        == G_IO_STATUS_NORMAL)
829                 {
830                         g_strstrip(buf);
831                         if (buf[0] != '#')
832                         {
833                                 tokens = g_strsplit(buf, " ", 2);
834                                 if (tokens[0] != NULL && tokens[1] != NULL)
835                                         g_hash_table_insert(keywords, tokens[0], tokens[1]);
836                                 else
837                                         g_strfreev(tokens);
838                         }
839                         g_free(buf);
840                 }
841         }
842         g_io_channel_shutdown(channel, FALSE, NULL);
843         g_free(path);
844 }
845
846 gboolean
847 keywords_try_search(WebKitWebView *web_view, const gchar *t)
848 {
849         gboolean ret = FALSE;
850         gchar **tokens = NULL;
851         gchar *val = NULL, *uri = NULL;
852
853         tokens = g_strsplit(t, " ", 2);
854         if (tokens[0] != NULL && tokens[1] != NULL)
855         {
856                 val = g_hash_table_lookup(keywords, tokens[0]);
857                 if (val != NULL)
858                 {
859                         uri = g_strdup_printf((gchar *)val, tokens[1]);
860                         if (show_all_requests)
861                                 fprintf(stderr, "====> %s\n", uri);
862                         webkit_web_view_load_uri(web_view, uri);
863                         g_free(uri);
864                         ret = TRUE;
865                 }
866         }
867         g_strfreev(tokens);
868
869         return ret;
870 }
871
872 gboolean
873 remote_msg(GIOChannel *channel, GIOCondition condition, gpointer data)
874 {
875         gchar *uri = NULL;
876
877         (void)condition;
878         (void)data;
879
880         g_io_channel_read_line(channel, &uri, NULL, NULL, NULL);
881         if (uri)
882         {
883                 g_strstrip(uri);
884                 client_new(uri);
885                 g_free(uri);
886         }
887         return TRUE;
888 }
889
890 void
891 search(gpointer data, gint direction)
892 {
893         struct Client *c = (struct Client *)data;
894
895         if (search_text == NULL)
896                 return;
897
898         webkit_web_view_search_text(WEBKIT_WEB_VIEW(c->web_view), search_text,
899                                     FALSE, direction == 1, TRUE);
900 }
901
902 Window
903 tabbed_launch(void)
904 {
905         gint tabbed_stdout;
906         GIOChannel *tabbed_stdout_channel;
907         GError *err = NULL;
908         gchar *output = NULL;
909         char *argv[] = { "tabbed", "-c", "-d", "-p", "s1", "-n", __NAME__, NULL };
910         Window plug_into;
911
912         if (!g_spawn_async_with_pipes(NULL, argv, NULL, G_SPAWN_SEARCH_PATH, NULL,
913                                       NULL, NULL, NULL, &tabbed_stdout, NULL,
914                                       &err))
915         {
916                 fprintf(stderr, __NAME__": Could not launch tabbed: %s\n", err->message);
917                 g_error_free(err);
918                 return 0;
919         }
920
921         tabbed_stdout_channel = g_io_channel_unix_new(tabbed_stdout);
922         g_io_channel_read_line(tabbed_stdout_channel, &output, NULL, NULL, NULL);
923         if (output == NULL)
924         {
925                 fprintf(stderr, __NAME__": Could not read XID from tabbed\n");
926                 return 0;
927         }
928
929         g_io_channel_shutdown(tabbed_stdout_channel, FALSE, NULL);
930
931         g_strstrip(output);
932         plug_into = strtol(output, NULL, 16);
933         g_free(output);
934         return plug_into;
935 }
936
937 void
938 usage(void)
939 {
940         fprintf(stderr, "Usage: "__NAME__" [OPTION]... <URI>...\n");
941         exit(EXIT_FAILURE);
942 }
943
944
945 int
946 main(int argc, char **argv)
947 {
948         int opt, i;
949
950         gtk_init(&argc, &argv);
951
952         grab_environment_configuration();
953
954         while ((opt = getopt(argc, argv, "e:rCT")) != -1)
955         {
956                 switch (opt)
957                 {
958                         case 'e':
959                                 embed = atol(optarg);
960                                 tabbed_automagic = FALSE;
961                                 break;
962                         case 'r':
963                                 show_all_requests = TRUE;
964                                 break;
965                         case 'C':
966                                 cooperative_instances = FALSE;
967                                 break;
968                         case 'T':
969                                 tabbed_automagic = FALSE;
970                                 break;
971                         default:
972                                 usage();
973                 }
974         }
975
976         if (optind >= argc)
977                 usage();
978
979         adblock_load();
980         keywords_load();
981         cooperation_setup();
982         downloadmanager_setup();
983
984         if (tabbed_automagic && !(cooperative_instances && !cooperative_alone))
985                 embed = tabbed_launch();
986
987         first_uri = g_strdup(argv[optind]);
988         for (i = optind; i < argc; i++)
989                 client_new(argv[i]);
990         if (!cooperative_instances || cooperative_alone)
991                 gtk_main();
992         exit(EXIT_SUCCESS);
993 }