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