]> git.armaanb.net Git - chorizo.git/blob - browser.c
Add mute keybinding
[chorizo.git] / browser.c
1 #include <fcntl.h>
2 #include <limits.h>
3 #include <stdio.h>
4 #include <stdlib.h>
5 #include <string.h>
6 #include <sys/stat.h>
7 #include <sys/types.h>
8
9 #include <JavaScriptCore/JavaScript.h>
10 #include <gdk/gdkkeysyms.h>
11 #include <gio/gio.h>
12 #include <gtk/gtk.h>
13 #include <gtk/gtkx.h>
14 #include <webkit2/webkit2.h>
15
16 void client_destroy(GtkWidget *, gpointer);
17 WebKitWebView *client_new(const gchar *, WebKitWebView *, gboolean,
18                                                                                                         gboolean);
19 WebKitWebView *client_new_request(WebKitWebView *, WebKitNavigationAction *,
20                                                                                                                                         gpointer);
21 void cooperation_setup(void);
22 void changed_download_progress(GObject *, GParamSpec *, gpointer);
23 void changed_load_progress(GObject *, GParamSpec *, gpointer);
24 void changed_favicon(GObject *, GParamSpec *, gpointer);
25 void changed_title(GObject *, GParamSpec *, gpointer);
26 void changed_uri(GObject *, GParamSpec *, gpointer);
27 gboolean crashed_web_view(WebKitWebView *, gpointer);
28 gboolean decide_policy(WebKitWebView *, WebKitPolicyDecision *,
29                                                                                          WebKitPolicyDecisionType, gpointer);
30 gboolean download_handle(WebKitDownload *, gchar *, gpointer);
31 void download_click(GtkToolButton *, gpointer);
32 void download_start(WebKitWebView *, WebKitDownload *, gpointer);
33 void download_cancel(GtkMenuItem *, gpointer);
34 gboolean downloadmanager_delete(GtkWidget *, gpointer);
35 void downloadmanager_setup(void);
36 gchar *ensure_uri_scheme(const gchar *);
37 void grab_environment_configuration(void);
38 void grab_feeds_finished(GObject *, GAsyncResult *, gpointer);
39 void hover_web_view(WebKitWebView *, WebKitHitTestResult *, guint, gpointer);
40 void icon_location(GtkEntry *, GtkEntryIconPosition, GdkEvent *, gpointer);
41 void init_default_web_context(void);
42 gboolean key_common(GtkWidget *, GdkEvent *, gpointer);
43 gboolean key_downloadmanager(GtkWidget *, GdkEvent *, gpointer);
44 gboolean key_location(GtkWidget *, GdkEvent *, gpointer);
45 gboolean key_tablabel(GtkWidget *, GdkEvent *, gpointer);
46 gboolean key_web_view(GtkWidget *, GdkEvent *, gpointer);
47 void mainwindow_setup(void);
48 void mainwindow_title(gint);
49 void notebook_switch_page(GtkNotebook *, GtkWidget *, guint, gpointer);
50 gboolean quit_if_nothing_active(void);
51 gboolean remote_msg(GIOChannel *, GIOCondition, gpointer);
52 void run_user_scripts(WebKitWebView *);
53 void search(gpointer, gint);
54 void show_web_view(WebKitWebView *, gpointer);
55 void trust_user_certs(WebKitWebContext *);
56 GKeyFile *get_ini(void);
57 GKeyFile *config;
58
59 struct Client
60 {
61         gchar *external_handler_uri;
62         gchar *feed_html;
63         gchar *hover_uri;
64         GtkWidget *location;
65         GtkWidget *tabicon;
66         GtkWidget *tablabel;
67         GtkWidget *vbox;
68         GtkWidget *web_view;
69         gboolean focus_new_tab;
70 };
71
72 struct MainWindow
73 {
74         GtkWidget *win;
75         GtkWidget *notebook;
76 } mw;
77
78 struct DownloadManager
79 {
80         GtkWidget *scroll;
81         GtkWidget *toolbar;
82         GtkWidget *win;
83 } dm;
84
85 struct Configuration
86 {
87         WebKitCookieAcceptPolicy cookie_policy;
88         const gchar *accepted_language[2];
89         gboolean cooperative_alone;
90         gboolean cooperative_instances;
91         gboolean enable_console_to_stdout;
92         gboolean javascript_disabled;
93         gboolean spellcheck_disabled;
94         gchar *download_dir;
95         gchar *fifo_suffix;
96         gchar *history_file;
97         gchar *home_uri;
98         gchar *search_engine;
99         gchar *spellcheck_language;
100         gchar *user_agent;
101         gdouble global_zoom;
102         gint tab_width_chars;
103 } cfg;
104
105 struct DownloadItem
106 {
107         GtkToolButton *tb;
108         WebKitDownload *download;
109 };
110
111 gint clients = 0, downloads = 0;
112 int cooperative_pipe_fp = 0;
113 gchar *search_text;
114
115 void
116 client_destroy(GtkWidget *widget, gpointer data)
117 {
118         struct Client *c = (struct Client *)data;
119         gint idx;
120
121         g_signal_handlers_disconnect_by_func(G_OBJECT(c->web_view),
122                                                                                                                                                          changed_load_progress, c);
123
124         idx = gtk_notebook_page_num(GTK_NOTEBOOK(mw.notebook), c->vbox);
125         if (idx == -1)
126                 fprintf(stderr, __NAME__": Tab index was -1, bamboozled\n");
127         else
128                 gtk_notebook_remove_page(GTK_NOTEBOOK(mw.notebook), idx);
129
130         free(c);
131         clients--;
132
133         quit_if_nothing_active();
134 }
135
136 WebKitWebView *
137 client_new(const gchar *uri, WebKitWebView *related_wv, gboolean show,
138                                          gboolean focus_tab)
139 {
140         struct Client *c;
141         gchar *f;
142         GtkWidget *evbox, *tabbox;
143
144         if (uri != NULL && cfg.cooperative_instances && !cfg.cooperative_alone) {
145                 f = ensure_uri_scheme(uri);
146                 write(cooperative_pipe_fp, f, strlen(f));
147                 write(cooperative_pipe_fp, "\n", 1);
148                 g_free(f);
149                 return NULL;
150         }
151
152         c = calloc(1, sizeof(struct Client));
153         if (!c) {
154                 fprintf(stderr, __NAME__": fatal: calloc failed\n");
155                 exit(EXIT_FAILURE);
156         }
157
158         c->focus_new_tab = focus_tab;
159
160         if (related_wv == NULL)
161                 c->web_view = webkit_web_view_new();
162         else
163                 c->web_view = webkit_web_view_new_with_related_view(related_wv);
164
165         webkit_web_view_set_zoom_level(WEBKIT_WEB_VIEW(c->web_view), cfg.global_zoom);
166         WebKitSettings *settings = webkit_web_view_get_settings(WEBKIT_WEB_VIEW(c->web_view));
167         webkit_settings_set_enable_javascript(settings, !cfg.javascript_disabled);
168         g_signal_connect(G_OBJECT(c->web_view), "notify::favicon",
169                                                                          G_CALLBACK(changed_favicon), c);
170         g_signal_connect(G_OBJECT(c->web_view), "notify::title",
171                                                                          G_CALLBACK(changed_title), c);
172         g_signal_connect(G_OBJECT(c->web_view), "notify::uri",
173                                                                          G_CALLBACK(changed_uri), c);
174         g_signal_connect(G_OBJECT(c->web_view), "notify::estimated-load-progress",
175                                                                          G_CALLBACK(changed_load_progress), c);
176         g_signal_connect(G_OBJECT(c->web_view), "create",
177                                                                          G_CALLBACK(client_new_request), NULL);
178         g_signal_connect(G_OBJECT(c->web_view), "close",
179                                                                          G_CALLBACK(client_destroy), c);
180         g_signal_connect(G_OBJECT(c->web_view), "decide-policy",
181                                                                          G_CALLBACK(decide_policy), NULL);
182         g_signal_connect(G_OBJECT(c->web_view), "key-press-event",
183                                                                          G_CALLBACK(key_web_view), c);
184         g_signal_connect(G_OBJECT(c->web_view), "button-release-event",
185                                                                          G_CALLBACK(key_web_view), c);
186         g_signal_connect(G_OBJECT(c->web_view), "scroll-event",
187                                                                          G_CALLBACK(key_web_view), c);
188         g_signal_connect(G_OBJECT(c->web_view), "mouse-target-changed",
189                                                                          G_CALLBACK(hover_web_view), c);
190         g_signal_connect(G_OBJECT(c->web_view), "web-process-crashed",
191                                                                          G_CALLBACK(crashed_web_view), c);
192
193         if (cfg.user_agent != NULL)
194                 g_object_set(G_OBJECT(webkit_web_view_get_settings(WEBKIT_WEB_VIEW(c->web_view))),
195                                                                  "user-agent", cfg.user_agent, NULL);
196
197         if (cfg.enable_console_to_stdout)
198                 webkit_settings_set_enable_write_console_messages_to_stdout(webkit_web_view_get_settings(WEBKIT_WEB_VIEW(c->web_view)), TRUE);
199
200         webkit_settings_set_enable_developer_extras(webkit_web_view_get_settings(WEBKIT_WEB_VIEW(c->web_view)), TRUE);
201
202         c->location = gtk_entry_new();
203         g_signal_connect(G_OBJECT(c->location), "key-press-event",
204                                                                          G_CALLBACK(key_location), c);
205         g_signal_connect(G_OBJECT(c->location), "icon-release",
206                                                                          G_CALLBACK(icon_location), c);
207         /* XXX This is a workaround. Setting this to NULL (which is done in
208          * grab_feeds_finished() if no feed has been detected) adds a little
209          * padding left of the text. Not sure why. The point of this call
210          * right here is to have that padding right from the start. This
211          * avoids a graphical artifact. */
212         gtk_entry_set_icon_from_icon_name(GTK_ENTRY(c->location),
213                                                                                                                                                 GTK_ENTRY_ICON_PRIMARY,
214                                                                                                                                                 NULL);
215
216         c->vbox = gtk_box_new(GTK_ORIENTATION_VERTICAL, 0);
217         gtk_box_pack_start(GTK_BOX(c->vbox), c->location, FALSE, FALSE, 0);
218         gtk_box_pack_start(GTK_BOX(c->vbox), c->web_view, TRUE, TRUE, 0);
219         gtk_container_set_focus_child(GTK_CONTAINER(c->vbox), c->web_view);
220
221         c->tabicon = gtk_image_new_from_icon_name("text-html", GTK_ICON_SIZE_SMALL_TOOLBAR);
222
223         c->tablabel = gtk_label_new(__NAME__);
224         gtk_label_set_ellipsize(GTK_LABEL(c->tablabel), PANGO_ELLIPSIZE_END);
225         gtk_label_set_width_chars(GTK_LABEL(c->tablabel), cfg.tab_width_chars);
226         gtk_widget_set_has_tooltip(c->tablabel, TRUE);
227
228         /* XXX I don't own a HiDPI screen, so I don't know if scale_factor
229          * does the right thing. */
230         tabbox = gtk_box_new(GTK_ORIENTATION_HORIZONTAL,
231                                                                                          5 * gtk_widget_get_scale_factor(mw.win));
232         gtk_box_pack_start(GTK_BOX(tabbox), c->tabicon, FALSE, FALSE, 0);
233         gtk_box_pack_start(GTK_BOX(tabbox), c->tablabel, TRUE, TRUE, 0);
234
235         evbox = gtk_event_box_new();
236         gtk_container_add(GTK_CONTAINER(evbox), tabbox);
237         g_signal_connect(G_OBJECT(evbox), "button-release-event",
238                                                                          G_CALLBACK(key_tablabel), c);
239
240         gtk_widget_add_events(evbox, GDK_SCROLL_MASK);
241         g_signal_connect(G_OBJECT(evbox), "scroll-event",
242                                                                          G_CALLBACK(key_tablabel), c);
243
244         /* For easy access, store a reference to our label. */
245         g_object_set_data(G_OBJECT(evbox), "lariza-tab-label", c->tablabel);
246
247         /* This only shows the event box and the label inside, nothing else.
248          * Needed because the evbox/label is "internal" to the notebook and
249          * not part of the normal "widget tree" (IIUC). */
250         gtk_widget_show_all(evbox);
251
252         gtk_notebook_insert_page(GTK_NOTEBOOK(mw.notebook), c->vbox, evbox,
253                                                                                                          gtk_notebook_get_current_page(GTK_NOTEBOOK(mw.notebook)) + 1);
254         gtk_notebook_set_tab_reorderable(GTK_NOTEBOOK(mw.notebook), c->vbox, TRUE);
255
256         if (show)
257                 show_web_view(NULL, c);
258         else
259                 g_signal_connect(G_OBJECT(c->web_view), "ready-to-show",
260                                                                                  G_CALLBACK(show_web_view), c);
261
262         if (uri != NULL) {
263                 f = ensure_uri_scheme(uri);
264                 webkit_web_view_load_uri(WEBKIT_WEB_VIEW(c->web_view), f);
265                 g_free(f);
266         }
267
268         clients++;
269
270         return WEBKIT_WEB_VIEW(c->web_view);
271 }
272
273 WebKitWebView *
274 client_new_request(WebKitWebView *web_view,
275                                                                          WebKitNavigationAction *navigation_action, gpointer data)
276 {
277         return client_new(NULL, web_view, FALSE, FALSE);
278 }
279
280 void
281 cooperation_setup(void)
282 {
283         GIOChannel *towatch;
284         gchar *fifofilename, *fifopath;
285
286         fifofilename = g_strdup_printf("%s-%s", __NAME__".fifo", cfg.fifo_suffix);
287         fifopath = g_build_filename(g_get_user_runtime_dir(), fifofilename, NULL);
288         g_free(fifofilename);
289
290         if (!g_file_test(fifopath, G_FILE_TEST_EXISTS))
291                 mkfifo(fifopath, 0600);
292
293         cooperative_pipe_fp = open(fifopath, O_WRONLY | O_NONBLOCK);
294         if (!cooperative_pipe_fp) {
295                 fprintf(stderr, __NAME__": Can't open FIFO at all.\n");
296         } else {
297                 if (write(cooperative_pipe_fp, "", 0) == -1) {
298                         /* Could not do an empty write to the FIFO which means there's
299                          * no one listening. */
300                         close(cooperative_pipe_fp);
301                         towatch = g_io_channel_new_file(fifopath, "r+", NULL);
302                         g_io_add_watch(towatch, G_IO_IN, (GIOFunc)remote_msg, NULL);
303                 } else {
304                         cfg.cooperative_alone = FALSE;
305                 }
306         }
307
308         g_free(fifopath);
309 }
310
311 void
312 changed_download_progress(GObject *obj, GParamSpec *pspec, gpointer data)
313 {
314         WebKitDownload *download = WEBKIT_DOWNLOAD(obj);
315         WebKitURIResponse *resp;
316         GtkToolItem *tb = GTK_TOOL_ITEM(data);
317         gdouble p, size_mb;
318         const gchar *uri;
319         gchar *t, *filename, *base;
320
321         p = webkit_download_get_estimated_progress(download);
322         p = p > 1 ? 1 : p;
323         p = p < 0 ? 0 : p;
324         p *= 100;
325         resp = webkit_download_get_response(download);
326         size_mb = webkit_uri_response_get_content_length(resp) / 1e6;
327
328         uri = webkit_download_get_destination(download);
329         filename = g_filename_from_uri(uri, NULL, NULL);
330         if (filename == NULL) {
331                 /* This really should not happen because WebKit uses that URI to
332                  * write to a file... */
333                 fprintf(stderr, __NAME__": Could not construct file name from URI!\n");
334                 t = g_strdup_printf("%s (%.0f%% of %.1f MB)",
335                                                                                                 webkit_uri_response_get_uri(resp), p, size_mb);
336         } else {
337                 base = g_path_get_basename(filename);
338                 t = g_strdup_printf("%s (%.0f%% of %.1f MB)", base, p, size_mb);
339                 g_free(filename);
340                 g_free(base);
341         }
342         gtk_tool_button_set_label(GTK_TOOL_BUTTON(tb), t);
343         g_free(t);
344 }
345
346 void
347 changed_load_progress(GObject *obj, GParamSpec *pspec, gpointer data)
348 {
349         struct Client *c = (struct Client *)data;
350         gdouble p;
351         gchar *grab_feeds =
352                 "a = document.querySelectorAll('"
353                 "    html > head > link[rel=\"alternate\"][href][type=\"application/atom+xml\"],"
354                 "    html > head > link[rel=\"alternate\"][href][type=\"application/rss+xml\"]"
355                 "');"
356                 "if (a.length == 0)"
357                 "    null;"
358                 "else"
359                 "{"
360                 "    out = '';"
361                 "    for (i = 0; i < a.length; i++)"
362                 "    {"
363                 "        url = encodeURIComponent(a[i].href);"
364                 "        if ('title' in a[i] && a[i].title != '')"
365                 "            title = encodeURIComponent(a[i].title);"
366                 "        else"
367                 "            title = url;"
368                 "        out += '<li><a href=\"' + url + '\">' + title + '</a></li>';"
369                 "    }"
370                 "    out;"
371                 "}";
372
373
374         p = webkit_web_view_get_estimated_load_progress(WEBKIT_WEB_VIEW(c->web_view));
375         if (p == 1) {
376                 p = 0;
377
378                 /* The page has loaded fully. We now run the short JavaScript
379                  * snippet above that operates on the DOM. It tries to grab all
380                  * occurences of <link rel="alternate" ...>, i.e. RSS/Atom feed
381                  * references. */
382                 webkit_web_view_run_javascript(WEBKIT_WEB_VIEW(c->web_view),
383                                                                                                                                          grab_feeds, NULL,
384                                                                                                                                          grab_feeds_finished, c);
385
386                 run_user_scripts(WEBKIT_WEB_VIEW(c->web_view));
387         }
388         gtk_entry_set_progress_fraction(GTK_ENTRY(c->location), p);
389 }
390
391 void
392 changed_favicon(GObject *obj, GParamSpec *pspec, gpointer data)
393 {
394         struct Client *c = (struct Client *)data;
395         cairo_surface_t *f;
396         int w, h, w_should, h_should;
397         GdkPixbuf *pb, *pb_scaled;
398
399         f = webkit_web_view_get_favicon(WEBKIT_WEB_VIEW(c->web_view));
400         if (f == NULL) {
401                 gtk_image_set_from_icon_name(GTK_IMAGE(c->tabicon), "text-html",
402                                                                                                                                  GTK_ICON_SIZE_SMALL_TOOLBAR);
403         } else {
404                 w = cairo_image_surface_get_width(f);
405                 h = cairo_image_surface_get_height(f);
406                 pb = gdk_pixbuf_get_from_surface(f, 0, 0, w, h);
407                 if (pb != NULL) {
408                         w_should = 16 * gtk_widget_get_scale_factor(c->tabicon);
409                         h_should = 16 * gtk_widget_get_scale_factor(c->tabicon);
410                         pb_scaled = gdk_pixbuf_scale_simple(pb, w_should, h_should,
411                                                                                                                                                                         GDK_INTERP_BILINEAR);
412                         gtk_image_set_from_pixbuf(GTK_IMAGE(c->tabicon), pb_scaled);
413
414                         g_object_unref(pb_scaled);
415                         g_object_unref(pb);
416                 }
417         }
418 }
419
420 void
421 changed_title(GObject *obj, GParamSpec *pspec, gpointer data)
422 {
423         const gchar *t, *u;
424         struct Client *c = (struct Client *)data;
425
426         u = webkit_web_view_get_uri(WEBKIT_WEB_VIEW(c->web_view));
427         t = webkit_web_view_get_title(WEBKIT_WEB_VIEW(c->web_view));
428
429         u = u == NULL ? __NAME__ : u;
430         u = u[0] == 0 ? __NAME__ : u;
431
432         t = t == NULL ? u : t;
433         t = t[0] == 0 ? u : t;
434
435         gchar *name = malloc(strlen(t) + 4);
436         gchar *muted = (webkit_web_view_get_is_muted(WEBKIT_WEB_VIEW(c->web_view)))
437                 ? "[m] " : "";
438         sprintf(name, "%s%s", muted, t);
439
440         gtk_label_set_text(GTK_LABEL(c->tablabel), name);
441         g_free(name);
442         gtk_widget_set_tooltip_text(c->tablabel, t);
443         mainwindow_title(gtk_notebook_get_current_page(GTK_NOTEBOOK(mw.notebook)));
444 }
445
446 void
447 changed_uri(GObject *obj, GParamSpec *pspec, gpointer data)
448 {
449         const gchar *t;
450         struct Client *c = (struct Client *)data;
451         FILE *fp;
452
453         t = webkit_web_view_get_uri(WEBKIT_WEB_VIEW(c->web_view));
454
455         /* When a web process crashes, we get a "notify::uri" signal, but we
456          * can no longer read a meaningful URI. It's just an empty string
457          * now. Not updating the location bar in this scenario is important,
458          * because we would override the "WEB PROCESS CRASHED" message. */
459         if (t != NULL && strlen(t) > 0) {
460                 gtk_entry_set_text(GTK_ENTRY(c->location), t);
461
462                 if (cfg.history_file != NULL) {
463                         fp = fopen(cfg.history_file, "a");
464                         if (fp != NULL) {
465                                 fprintf(fp, "%s\n", t);
466                                 fclose(fp);
467                         } else {
468                                 perror(__NAME__": Error opening history file");
469                         }
470                 }
471         }
472 }
473
474 gboolean
475 crashed_web_view(WebKitWebView *web_view, gpointer data)
476 {
477         gchar *t;
478         struct Client *c = (struct Client *)data;
479
480         t = g_strdup_printf("WEB PROCESS CRASHED: %s",
481                                                                                         webkit_web_view_get_uri(WEBKIT_WEB_VIEW(web_view)));
482         gtk_entry_set_text(GTK_ENTRY(c->location), t);
483         g_free(t);
484
485         return TRUE;
486 }
487
488 gboolean
489 decide_policy(WebKitWebView *web_view, WebKitPolicyDecision *decision,
490                                                         WebKitPolicyDecisionType type, gpointer data)
491 {
492         WebKitResponsePolicyDecision *r;
493
494         switch (type) {
495         case WEBKIT_POLICY_DECISION_TYPE_RESPONSE:
496                 r = WEBKIT_RESPONSE_POLICY_DECISION(decision);
497                 if (!webkit_response_policy_decision_is_mime_type_supported(r))
498                         webkit_policy_decision_download(decision);
499                 else
500                         webkit_policy_decision_use(decision);
501                 break;
502         default:
503                 /* Use whatever default there is. */
504                 return FALSE;
505         }
506         return TRUE;
507 }
508
509 void
510 download_finished(WebKitDownload *download, gpointer data)
511 {
512         if (strcmp(gtk_tool_button_get_icon_name(GTK_TOOL_BUTTON(data)),
513                                                  "dialog-error") != 0)
514                 gtk_tool_button_set_icon_name(GTK_TOOL_BUTTON(data), "emblem-downloads");
515         downloads--;
516 }
517
518 void
519 download_start(WebKitWebView *web_view, WebKitDownload *download,
520                                                          gpointer data)
521 {
522         g_signal_connect(G_OBJECT(download), "decide-destination",
523                                                                          G_CALLBACK(download_handle), data);
524 }
525
526 gboolean
527 download_handle(WebKitDownload *download, gchar *suggested_filename,
528                                                                 gpointer data)
529 {
530         gchar *sug_clean, *path, *path2 = NULL, *uri;
531         GtkToolItem *tb;
532         int suffix = 1;
533         size_t i;
534
535         sug_clean = g_strdup(suggested_filename);
536         for (i = 0; i < strlen(sug_clean); i++)
537                 if (sug_clean[i] == G_DIR_SEPARATOR)
538                         sug_clean[i] = '_';
539
540         path = g_build_filename(cfg.download_dir, sug_clean, NULL);
541         path2 = g_strdup(path);
542         while (g_file_test(path2, G_FILE_TEST_EXISTS) && suffix < 1000) {
543                 g_free(path2);
544
545                 path2 = g_strdup_printf("%s.%d", path, suffix);
546                 suffix++;
547         }
548
549         if (suffix == 1000) {
550                 fprintf(stderr, __NAME__": Suffix reached limit for download.\n");
551                 webkit_download_cancel(download);
552         } else {
553                 uri = g_filename_to_uri(path2, NULL, NULL);
554                 webkit_download_set_destination(download, uri);
555                 g_free(uri);
556
557                 tb = gtk_tool_button_new(NULL, NULL);
558                 gtk_tool_button_set_icon_name(GTK_TOOL_BUTTON(tb), "network-receive");
559                 gtk_tool_button_set_label(GTK_TOOL_BUTTON(tb), sug_clean);
560                 gtk_toolbar_insert(GTK_TOOLBAR(dm.toolbar), tb, 0);
561                 gtk_widget_show_all(dm.win);
562
563                 g_signal_connect(G_OBJECT(download), "notify::estimated-progress",
564                                                                                  G_CALLBACK(changed_download_progress), tb);
565
566                 downloads++;
567                 g_signal_connect(G_OBJECT(download), "finished",
568                                                                                  G_CALLBACK(download_finished), tb);
569
570                 g_object_ref(download);
571
572                 struct DownloadItem *payload = malloc(sizeof(*payload));
573                 payload->tb = (GtkToolButton *)tb;
574                 payload->download = download;
575                 g_signal_connect(G_OBJECT(tb), "clicked", G_CALLBACK(download_click),
576                                                                                  payload);
577                 g_signal_connect(G_OBJECT(tb), "failed", G_CALLBACK(download_cancel),
578                                                                                  payload);
579                 g_signal_connect(G_OBJECT(tb), "destroy_event", G_CALLBACK(g_free),
580                                                                                  payload);
581         }
582
583         g_free(sug_clean);
584         g_free(path);
585         g_free(path2);
586
587         /* Propagate -- to whom it may concern. */
588         return FALSE;
589 }
590
591 void
592 download_cancel(GtkMenuItem *tb, gpointer data)
593 {
594         struct DownloadItem *payload = data;
595         gtk_tool_button_set_icon_name(GTK_TOOL_BUTTON(payload->tb), "dialog-error");
596         webkit_download_cancel(payload->download);
597 }
598
599 void
600 download_remove(GtkMenuItem *tb, gpointer data)
601 {
602         struct DownloadItem *payload = data;
603         g_object_unref(payload->download);
604         gtk_widget_destroy(GTK_WIDGET(payload->tb));
605 }
606
607 void
608 download_copy_url(GtkMenuItem *tb, gpointer data)
609 {
610         struct DownloadItem *payload = data;
611         WebKitURIRequest *req = webkit_download_get_request(payload->download);
612         const gchar *uri = webkit_uri_request_get_uri(req);
613         gtk_clipboard_set_text(gtk_clipboard_get(GDK_SELECTION_CLIPBOARD), uri,
614                                                                                                  strlen(uri));
615 }
616
617 void
618 download_copy_path(GtkMenuItem *tb, gpointer data)
619 {
620         struct DownloadItem *payload = data;
621         const gchar *path = webkit_download_get_destination(payload->download);
622         gtk_clipboard_set_text(gtk_clipboard_get(GDK_SELECTION_CLIPBOARD), path + 7,
623                                                                                                  strlen(path) - 7); // Offset by 7 to remove "file://"
624 }
625
626 void
627 download_click(GtkToolButton *tb, gpointer data)
628 {
629   GtkWidget *pmenu = gtk_menu_new();
630         GtkWidget *option;
631
632         if (strcmp(gtk_tool_button_get_icon_name(GTK_TOOL_BUTTON(tb)),
633                                                  "network-receive") == 0) {
634                 option = gtk_menu_item_new_with_label("Cancel download");
635                 g_signal_connect(G_OBJECT(option), "activate",
636                                                                                  G_CALLBACK(download_cancel), data);
637         } else {
638                 option = gtk_menu_item_new_with_label("Remove download");
639                 g_signal_connect(G_OBJECT(option), "activate",
640                                                                                  G_CALLBACK(download_remove), data);
641         }
642         gtk_widget_show(option);
643         gtk_menu_shell_append(GTK_MENU_SHELL(pmenu), option);
644
645         option = gtk_menu_item_new_with_label("Copy download URL");
646         gtk_widget_show(option);
647         gtk_menu_shell_append(GTK_MENU_SHELL(pmenu), option);
648         g_signal_connect(G_OBJECT(option), "activate",
649                                                                          G_CALLBACK(download_copy_url), data);
650
651         option = gtk_menu_item_new_with_label("Copy local path");
652         gtk_widget_show(option);
653         gtk_menu_shell_append(GTK_MENU_SHELL(pmenu), option);
654         g_signal_connect(G_OBJECT(option), "activate",
655                                                                          G_CALLBACK(download_copy_path), data);
656
657         gtk_menu_popup_at_pointer(GTK_MENU(pmenu), NULL);
658 }
659
660 gboolean
661 downloadmanager_delete(GtkWidget *obj, gpointer data)
662 {
663         if (!quit_if_nothing_active())
664                 gtk_widget_hide(dm.win);
665
666         return TRUE;
667 }
668
669 void
670 downloadmanager_setup(void)
671 {
672         dm.win = gtk_window_new(GTK_WINDOW_TOPLEVEL);
673         gtk_window_set_type_hint(GTK_WINDOW(dm.win), GDK_WINDOW_TYPE_HINT_DIALOG);
674         gtk_window_set_default_size(GTK_WINDOW(dm.win), 500, 250);
675         gtk_window_set_title(GTK_WINDOW(dm.win), __NAME__" - Download Manager");
676         g_signal_connect(G_OBJECT(dm.win), "delete-event",
677                                                                          G_CALLBACK(downloadmanager_delete), NULL);
678         g_signal_connect(G_OBJECT(dm.win), "key-press-event",
679                                                                          G_CALLBACK(key_downloadmanager), NULL);
680
681         dm.toolbar = gtk_toolbar_new();
682         gtk_orientable_set_orientation(GTK_ORIENTABLE(dm.toolbar),
683                                                                                                                                  GTK_ORIENTATION_VERTICAL);
684         gtk_toolbar_set_style(GTK_TOOLBAR(dm.toolbar), GTK_TOOLBAR_BOTH_HORIZ);
685         gtk_toolbar_set_show_arrow(GTK_TOOLBAR(dm.toolbar), FALSE);
686
687         dm.scroll = gtk_scrolled_window_new(NULL, NULL);
688         gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(dm.scroll),
689                                                                                                                                  GTK_POLICY_AUTOMATIC, GTK_POLICY_AUTOMATIC);
690         gtk_container_add(GTK_CONTAINER(dm.scroll), dm.toolbar);
691
692         gtk_container_add(GTK_CONTAINER(dm.win), dm.scroll);
693 }
694
695 gchar *
696 ensure_uri_scheme(const gchar *t)
697 {
698         gchar *f, *fabs;
699
700         f = g_ascii_strdown(t, -1);
701         if (!g_str_has_prefix(f, "http:") &&
702                         !g_str_has_prefix(f, "https:") &&
703                         !g_str_has_prefix(f, "file:") &&
704                         !g_str_has_prefix(f, "about:") &&
705                         !g_str_has_prefix(f, "data:") &&
706                         !g_str_has_prefix(f, "webkit:")) {
707                 g_free(f);
708                 fabs = realpath(t, NULL);
709                 if (fabs != NULL) {
710                         f = g_strdup_printf("file://%s", fabs);
711                         free(fabs);
712                 } else {
713                         f = g_strdup_printf("http://%s", t);
714                 }
715                 return f;
716         } else
717                 return g_strdup(t);
718 }
719
720 void
721 get_config(void)
722 {
723         cfg.accepted_language[0] = NULL;
724         cfg.accepted_language[1] = NULL;
725         cfg.cooperative_alone = TRUE;
726         cfg.cooperative_alone = TRUE;
727         cfg.fifo_suffix = "main";
728
729         const char *e = g_getenv(__NAME_UPPERCASE__"_FIFO_SUFFIX");
730         if (e != NULL)
731                 cfg.fifo_suffix = g_strdup(e);
732
733         char *xdg_down = getenv("XDG_DOWNLOAD_DIR");
734         cfg.download_dir = (xdg_down) ? xdg_down : "/var/tmp";
735
736         config = get_ini();
737         cfg.accepted_language[0] = g_key_file_get_string(config, "browser",
738                                                                                                                                                                                                          "accepted_language", NULL);
739         cfg.history_file = g_key_file_get_string(config, "browser", "history_file",
740                                                                                                                                                                          NULL);
741         cfg.home_uri = g_key_file_get_string(config, "browser", "homepage", NULL);
742         cfg.home_uri = (cfg.home_uri) ? cfg.home_uri : "about:blank";
743         cfg.enable_console_to_stdout = g_key_file_get_boolean(config, "browser",
744                                                                                                                                                                                                                                 "console_to_stdout",
745                                                                                                                                                                                                                                 NULL);
746         cfg.user_agent = g_key_file_get_string(config, "browser", "user_agent", NULL);
747         cfg.javascript_disabled = g_key_file_get_boolean(config, "browser",
748                                                                                                                                                                                                          "javascript_disabled", NULL);
749         char *input_cookie_policy = g_key_file_get_string(config, "browser",
750                                                                                                                                                                                                                 "cookie_policy", NULL);
751         cfg.cookie_policy = WEBKIT_COOKIE_POLICY_ACCEPT_NO_THIRD_PARTY;
752         if (input_cookie_policy) {
753                 if (strcmp(input_cookie_policy, "all") == 0) {
754                         cfg.cookie_policy = WEBKIT_COOKIE_POLICY_ACCEPT_ALWAYS;
755                 } else if (strcmp(input_cookie_policy, "none") == 0) {
756                         cfg.cookie_policy = WEBKIT_COOKIE_POLICY_ACCEPT_NEVER;
757                 }
758         }
759
760         cfg.tab_width_chars = g_key_file_get_integer(config, "ui", "tab_width", NULL);
761         cfg.tab_width_chars = (cfg.tab_width_chars) ? cfg.tab_width_chars : 20;
762         cfg.global_zoom = g_key_file_get_double(config, "ui", "zoom_level", NULL);
763         cfg.global_zoom = (cfg.global_zoom) ? cfg.global_zoom : 1.0;
764         cfg.search_engine = g_key_file_get_string(config, "ui", "search_engine",
765                                                                                                                                                                                 NULL);
766         cfg.search_engine = (cfg.search_engine) ? cfg.search_engine :
767                 "https://duckduckgo.com?q=";
768         cfg.spellcheck_disabled = g_key_file_get_boolean(config, "ui",
769                                                                                                                                                                                                          "spellcheck_disabled", NULL);
770         cfg.spellcheck_language = g_key_file_get_string(config, "ui",
771                                                                                                                                                                                                                                 "spellcheck_language",
772                                                                                                                                                                                                                                 NULL);
773         cfg.spellcheck_language = (cfg.spellcheck_language) ? cfg.spellcheck_language
774                 : "en_US";
775 }
776
777 void
778 grab_feeds_finished(GObject *object, GAsyncResult *result, gpointer data)
779 {
780         struct Client *c = (struct Client *)data;
781         WebKitJavascriptResult *js_result;
782         JSCValue *value;
783         JSCException *exception;
784         GError *err = NULL;
785         gchar *str_value;
786
787         g_free(c->feed_html);
788         c->feed_html = NULL;
789
790         /* This was taken almost verbatim from the example in WebKit's
791          * documentation:
792          *
793          * https://webkitgtk.org/reference/webkit2gtk/stable/WebKitWebView.html#webkit-web-view-run-javascript-finish */
794
795         js_result = webkit_web_view_run_javascript_finish(WEBKIT_WEB_VIEW(object),
796                                                                                                                                                                                                                 result, &err);
797         if (!js_result) {
798                 fprintf(stderr, __NAME__": Error running javascript: %s\n", err->message);
799                 g_error_free(err);
800                 return;
801         }
802
803         value = webkit_javascript_result_get_js_value(js_result);
804         if (jsc_value_is_string(value)) {
805                 str_value = jsc_value_to_string(value);
806                 exception = jsc_context_get_exception(jsc_value_get_context(value));
807                 if (exception != NULL) {
808                         fprintf(stderr, __NAME__": Error running javascript: %s\n",
809                                                         jsc_exception_get_message(exception));
810                 } else {
811                         c->feed_html = str_value;
812                 }
813
814                 gtk_entry_set_icon_from_icon_name(GTK_ENTRY(c->location),
815                                                                                                                                                         GTK_ENTRY_ICON_PRIMARY,
816                                                                                                                                                         "application-rss+xml-symbolic");
817                 gtk_entry_set_icon_activatable(GTK_ENTRY(c->location),
818                                                                                                                                          GTK_ENTRY_ICON_PRIMARY,
819                                                                                                                                          TRUE);
820         } else {
821                 gtk_entry_set_icon_from_icon_name(GTK_ENTRY(c->location),
822                                                                                                                                                         GTK_ENTRY_ICON_PRIMARY,
823                                                                                                                                                         NULL);
824         }
825
826         webkit_javascript_result_unref(js_result);
827 }
828
829 void
830 hover_web_view(WebKitWebView *web_view, WebKitHitTestResult *ht, guint modifiers,
831                                                          gpointer data)
832 {
833         struct Client *c = (struct Client *)data;
834         const char *to_show;
835
836         g_free(c->hover_uri);
837
838         if (webkit_hit_test_result_context_is_link(ht)) {
839                 to_show = webkit_hit_test_result_get_link_uri(ht);
840                 c->hover_uri = g_strdup(to_show);
841         } else {
842                 to_show = webkit_web_view_get_uri(WEBKIT_WEB_VIEW(c->web_view));
843                 c->hover_uri = NULL;
844         }
845
846         if (!gtk_widget_is_focus(c->location))
847                 gtk_entry_set_text(GTK_ENTRY(c->location), to_show);
848 }
849
850 void
851 icon_location(GtkEntry *entry, GtkEntryIconPosition icon_pos, GdkEvent *event,
852                                                         gpointer data)
853 {
854         struct Client *c = (struct Client *)data;
855         gchar *d;
856         gchar *data_template =
857                 "data:text/html,"
858                 "<!DOCTYPE html>"
859                 "<html>"
860                 "    <head>"
861                 "        <meta charset=\"UTF-8\">"
862                 "        <title>Feeds</title>"
863                 "    </head>"
864                 "    <body>"
865                 "        <p>Feeds found on this page:</p>"
866                 "        <ul>"
867                 "        %s"
868                 "        </ul>"
869                 "    </body>"
870                 "</html>";
871
872         if (c->feed_html != NULL)
873                 {
874                         /* What we're actually trying to do is show a simple HTML page
875                          * that lists all the feeds on the current page. The function
876                          * webkit_web_view_load_html() looks like the proper way to do
877                          * that. Sad thing is, it doesn't create a history entry, but
878                          * instead simply replaces the content of the current page. This
879                          * is not what we want.
880                          *
881                          * RFC 2397 [0] defines the data URI scheme [1]. We abuse this
882                          * mechanism to show my custom HTML snippet *and* create a
883                          * history entry.
884                          *
885                          * [0]: https://tools.ietf.org/html/rfc2397
886                          * [1]: https://en.wikipedia.org/wiki/Data_URI_scheme */
887                         d = g_strdup_printf(data_template, c->feed_html);
888                         webkit_web_view_load_uri(WEBKIT_WEB_VIEW(c->web_view), d);
889                         g_free(d);
890                 }
891 }
892
893 void
894 init_default_web_context(void)
895 {
896         gchar *p;
897         WebKitWebContext *wc;
898         WebKitCookieManager *cm;
899
900         wc = webkit_web_context_get_default();
901
902         p = g_build_filename(g_get_user_config_dir(), __NAME__, "adblock", NULL);
903         webkit_web_context_set_sandbox_enabled(wc, TRUE);
904         webkit_web_context_add_path_to_sandbox(wc, p, TRUE);
905         g_free(p);
906
907         webkit_web_context_set_process_model(wc,
908                                                                                                                                                          WEBKIT_PROCESS_MODEL_MULTIPLE_SECONDARY_PROCESSES);
909
910         p = g_build_filename(g_get_user_data_dir(), __NAME__, "web_extensions",
911                                                                                          NULL);
912         webkit_web_context_set_web_extensions_directory(wc, p);
913         g_free(p);
914
915         if (cfg.accepted_language[0] != NULL)
916                 webkit_web_context_set_preferred_languages(wc, cfg.accepted_language);
917
918         g_signal_connect(G_OBJECT(wc), "download-started",
919                                                                          G_CALLBACK(download_start), NULL);
920
921         trust_user_certs(wc);
922
923         cm = webkit_web_context_get_cookie_manager(wc);
924         webkit_cookie_manager_set_accept_policy(cm, cfg.cookie_policy);
925
926         webkit_web_context_set_favicon_database_directory(wc, NULL);
927         webkit_cookie_manager_set_persistent_storage(cm,
928                                                                                                                                                                                          g_build_filename("/",
929                                                                                                                                                                                                                                                                 g_get_user_cache_dir(),
930                                                                                                                                                                                                                                                                 __NAME__,
931                                                                                                                                                                                                                                                                 "cookies.db",
932                                                                                                                                                                                                                                                                 NULL),
933                                                                                                                                                                                          WEBKIT_COOKIE_PERSISTENT_STORAGE_SQLITE);
934
935         const gchar * const languages[2] = {(const gchar *)cfg.spellcheck_language,
936                 NULL};
937         webkit_web_context_set_spell_checking_languages(wc, languages);
938         webkit_web_context_set_spell_checking_enabled(wc, !cfg.spellcheck_disabled);
939 }
940
941 void
942 search(gpointer data, gint direction)
943 {
944         struct Client *c = (struct Client *)data;
945         WebKitWebView *web_view = WEBKIT_WEB_VIEW(c->web_view);
946         WebKitFindController *fc = webkit_web_view_get_find_controller(web_view);
947
948         if (search_text == NULL)
949                 return;
950
951         switch (direction) {
952         case 0:
953                 webkit_find_controller_search(fc, search_text,
954                                                                                                                                         WEBKIT_FIND_OPTIONS_CASE_INSENSITIVE |
955                                                                                                                                         WEBKIT_FIND_OPTIONS_WRAP_AROUND,
956                                                                                                                                         G_MAXUINT);
957                 break;
958         case 1:
959                 webkit_find_controller_search_next(fc);
960                 break;
961         case -1:
962                 webkit_find_controller_search_previous(fc);
963                 break;
964         case 2:
965                 webkit_find_controller_search_finish(fc);
966                 break;
967         }
968 }
969
970 void
971 search_init(struct Client *c, int direction)
972 {
973         gtk_widget_grab_focus(c->location);
974         const gchar *contents = gtk_entry_get_text(GTK_ENTRY(c->location));
975         if (strcspn(contents, "s/")) {
976                 gtk_entry_set_text(GTK_ENTRY(c->location), "s/");
977         }
978         gtk_editable_set_position(GTK_EDITABLE(c->location), -1);
979         search(c, 0);
980         search(c, -1);
981         search(c, direction);
982 }
983
984 int
985 def_key(char *key, unsigned int def)
986 {
987         char *conf = g_key_file_get_string(config, "keybindings", key, NULL);
988         return (conf) ? gdk_keyval_from_name((conf) ? conf : NULL) : def;
989 }
990
991 gboolean
992 key_common(GtkWidget *widget, GdkEvent *event, gpointer data)
993 {
994         struct Client *c = (struct Client *)data;
995         gdouble now;
996         gchar *f;
997
998         if (event->type == GDK_KEY_PRESS) {
999                 if (((GdkEventKey *)event)->state & GDK_CONTROL_MASK) {
1000                         WebKitSettings *settings = webkit_web_view_get_settings(WEBKIT_WEB_VIEW(c->web_view));
1001                         gboolean js = webkit_settings_get_enable_javascript(settings);
1002                         int key = ((GdkEventKey *)event)->keyval;
1003                         if (def_key("download_manager", GDK_KEY_y) == key) {
1004                                 gtk_widget_show_all(dm.win);
1005                                 return TRUE;
1006                         } else if (def_key("history_back", GDK_KEY_h) == key) {
1007                                 webkit_web_view_go_back(WEBKIT_WEB_VIEW(c->web_view));
1008                                 return TRUE;
1009                         } else if (def_key("history_forwards", GDK_KEY_l) == key) {
1010                                 webkit_web_view_go_forward(WEBKIT_WEB_VIEW(c->web_view));
1011                                 return TRUE;
1012                         } else if (def_key("location", GDK_KEY_t) == key) {
1013                                 gtk_widget_grab_focus(c->location);
1014                                 const char *uri = webkit_web_view_get_uri(WEBKIT_WEB_VIEW(c->web_view));
1015                                 const char *goal = (uri) ? uri : "https://";
1016                                 gtk_entry_set_text(GTK_ENTRY(c->location), goal);
1017                                 gtk_editable_set_position(GTK_EDITABLE(c->location), -1);
1018                                 return TRUE;
1019                         } else if (def_key("print", GDK_KEY_Print) == key) {
1020                                 webkit_print_operation_run_dialog(webkit_print_operation_new(WEBKIT_WEB_VIEW(c->web_view)),
1021                                                                                                                                                                         GTK_WINDOW(gtk_widget_get_toplevel(mw.win)));
1022                                 return TRUE;
1023                         } else if (def_key("quit", GDK_KEY_g) == key) {
1024                                 search(c, 2);
1025                                 gtk_widget_grab_focus(c->web_view);
1026                                 gtk_entry_set_text(GTK_ENTRY(c->location),
1027                                                                                                          webkit_web_view_get_uri(WEBKIT_WEB_VIEW(c->web_view)));
1028                                 webkit_web_view_run_javascript(WEBKIT_WEB_VIEW(c->web_view),
1029                                                                                                                                                          "window.getSelection().removeAllRanges();"
1030                                                                                                                                                          "document.activeElement.blur();",
1031                                                                                                                                                          NULL, NULL, c);
1032                                 return TRUE;
1033                         } else if (def_key("reload", GDK_KEY_e) == key) {
1034                                 webkit_web_view_reload_bypass_cache(WEBKIT_WEB_VIEW(c->web_view));
1035                                 return TRUE;
1036                         } else if (def_key("scroll_line_down", GDK_KEY_j) == key) {
1037                                 for (int i = 0; i < 2; i++) {
1038                                         event->key.keyval = GDK_KEY_Down;
1039                                         gdk_event_put(event);
1040                                 }
1041                                 return TRUE;
1042                         } else if (def_key("scroll_line_up", GDK_KEY_k) == key) {
1043                                 event->key.keyval = GDK_KEY_Up;
1044                                 gdk_event_put(event);
1045                                 return TRUE;
1046                         } else if (def_key("scroll_page_down", GDK_KEY_f) == key) {
1047                                 event->key.keyval = GDK_KEY_Page_Down;
1048                                 gdk_event_put(event);
1049                                 return TRUE;
1050                         } else if (def_key("scroll_page_up", GDK_KEY_b) == key) {
1051                                 event->key.keyval = GDK_KEY_Page_Up;
1052                                 gdk_event_put(event);
1053                                 return TRUE;
1054                         } else if (def_key("search_forwards", GDK_KEY_s) == key) {
1055                                 search_init(c, 1);
1056                                 return TRUE;
1057                         } else if (def_key("search_backwards", GDK_KEY_r) == key) {
1058                                 search_init(c, -1);
1059                                 return TRUE;
1060                         } else if (def_key("tab_close", GDK_KEY_q) == key) {
1061                                 client_destroy(NULL, c);
1062                                 return TRUE;
1063                         } else if (def_key("tab_switch_1", GDK_KEY_1) == key) {
1064                                 gtk_notebook_set_current_page(GTK_NOTEBOOK(mw.notebook), 0);
1065                                 return TRUE;
1066                         } else if (def_key("tab_switch_2", GDK_KEY_2) == key) {
1067                                 gtk_notebook_set_current_page(GTK_NOTEBOOK(mw.notebook), 1);
1068                                 return TRUE;
1069                         } else if (def_key("tab_switch_3", GDK_KEY_3) == key) {
1070                                 gtk_notebook_set_current_page(GTK_NOTEBOOK(mw.notebook), 2);
1071                                 return TRUE;
1072                         } else if (def_key("tab_switch_4", GDK_KEY_4) == key) {
1073                                 gtk_notebook_set_current_page(GTK_NOTEBOOK(mw.notebook), 3);
1074                                 return TRUE;
1075                         } else if (def_key("tab_switch_5", GDK_KEY_5) == key) {
1076                                 gtk_notebook_set_current_page(GTK_NOTEBOOK(mw.notebook), 4);
1077                                 return TRUE;
1078                         } else if (def_key("tab_switch_6", GDK_KEY_6) == key) {
1079                                 gtk_notebook_set_current_page(GTK_NOTEBOOK(mw.notebook), 5);
1080                                 return TRUE;
1081                         } else if (def_key("tab_switch_7", GDK_KEY_7) == key) {
1082                                 gtk_notebook_set_current_page(GTK_NOTEBOOK(mw.notebook), 6);
1083                                 return TRUE;
1084                         } else if (def_key("tab_switch_8", GDK_KEY_8) == key) {
1085                                 gtk_notebook_set_current_page(GTK_NOTEBOOK(mw.notebook), 7);
1086                                 return TRUE;
1087                         } else if (def_key("tab_switch_9", GDK_KEY_9) == key) {
1088                                 gtk_notebook_set_current_page(GTK_NOTEBOOK(mw.notebook), 8);
1089                                 return TRUE;
1090                         } else if (def_key("tab_previous", GDK_KEY_u) == key) {
1091                                 gtk_notebook_prev_page(GTK_NOTEBOOK(mw.notebook));
1092                                 return TRUE;
1093                         } else if (def_key("tab_mute", GDK_KEY_m) == key) {
1094                                 gboolean muted =
1095                                         webkit_web_view_get_is_muted(WEBKIT_WEB_VIEW(c->web_view));
1096                                 webkit_web_view_set_is_muted(WEBKIT_WEB_VIEW(c->web_view), !muted);
1097                                 changed_title(G_OBJECT(c->web_view), NULL, c);
1098                                 return TRUE;
1099                         } else if (def_key("tab_new", GDK_KEY_w) == key) {
1100                                 f = ensure_uri_scheme(cfg.home_uri);
1101                                 client_new(f, NULL, TRUE, TRUE);
1102                                 g_free(f);
1103                                 return TRUE;
1104                         } else if (def_key("tab_next", GDK_KEY_i) == key) {
1105                                 gtk_notebook_next_page(GTK_NOTEBOOK(mw.notebook));
1106                                 return TRUE;
1107                         } else if (def_key("toggle_js", GDK_KEY_o) == key) {
1108                                 webkit_settings_set_enable_javascript(settings, (js) ? FALSE : TRUE);
1109                                 webkit_web_view_set_settings(WEBKIT_WEB_VIEW(c->web_view), settings);
1110                                 return TRUE;
1111                         } else if (def_key("web_search", GDK_KEY_d) == key) {
1112                                 gtk_widget_grab_focus(c->location);
1113                                 gtk_entry_set_text(GTK_ENTRY(c->location), "w/");
1114                                 gtk_editable_set_position(GTK_EDITABLE(c->location), -1);
1115                                 return TRUE;
1116                         } else if (def_key("zoom_in", GDK_KEY_equal) == key) {
1117                                 now = webkit_web_view_get_zoom_level(WEBKIT_WEB_VIEW(c->web_view));
1118                                 webkit_web_view_set_zoom_level(WEBKIT_WEB_VIEW(c->web_view), now + 0.1);
1119                                 return TRUE;
1120                         } else if (def_key("zoom_out", GDK_KEY_minus) == key) {
1121                                 now = webkit_web_view_get_zoom_level(WEBKIT_WEB_VIEW(c->web_view));
1122                                 webkit_web_view_set_zoom_level(WEBKIT_WEB_VIEW(c->web_view), now - 0.1);
1123                                 return TRUE;
1124                         } else if (def_key("zoom_reset", GDK_KEY_0) == key) {
1125                                 webkit_web_view_set_zoom_level(WEBKIT_WEB_VIEW(c->web_view),
1126                                                                                                                                                          cfg.global_zoom);
1127                                 return TRUE;
1128                         }
1129                 }
1130         }
1131         return FALSE;
1132 }
1133
1134 gboolean
1135 key_downloadmanager(GtkWidget *widget, GdkEvent *event, gpointer data)
1136 {
1137         if (event->type == GDK_KEY_PRESS) {
1138                 if (((GdkEventKey *)event)->state & GDK_CONTROL_MASK) {
1139                         int key = ((GdkEventKey *)event)->keyval;
1140                         if ((def_key("close_tab", GDK_KEY_q) == key) ||
1141                                         (def_key("download_manager", GDK_KEY_y) == key)) {
1142                                 downloadmanager_delete(dm.win, NULL);
1143                                 return TRUE;
1144                         }
1145                 }
1146         }
1147
1148         return FALSE;
1149 }
1150
1151 gboolean
1152 key_location(GtkWidget *widget, GdkEvent *event, gpointer data)
1153 {
1154         struct Client *c = (struct Client *)data;
1155         const gchar *t;
1156         gchar *f;
1157
1158         if (key_common(widget, event, data))
1159                 return TRUE;
1160
1161         if (event->type == GDK_KEY_PRESS) {
1162                 int key = ((GdkEventKey *)event)->keyval;
1163                 if ((GDK_KEY_KP_Enter == key) || (GDK_KEY_Return == key)) {
1164                         gtk_widget_grab_focus(c->web_view);
1165                         t = gtk_entry_get_text(GTK_ENTRY(c->location));
1166                         if (t != NULL && t[0] == 's' && t[1] == '/') {
1167                                 if (search_text != NULL)
1168                                         g_free(search_text);
1169                                 search_text = g_strdup(t + 2);
1170                                 search(c, 0);
1171                         } else if (t != NULL && t[0] == 'w' && t[1] == '/') {
1172                                 const char *engine = cfg.search_engine;
1173                                 int len = strlen(engine) + strlen(t) - 2;
1174                                 char *f = (char *) malloc(len);
1175                                 snprintf(f, len + 1, "%s%s", engine, t + 2);
1176                                 webkit_web_view_load_uri(WEBKIT_WEB_VIEW(c->web_view), f);
1177                                 free(f);
1178                         } else {
1179                                 f = ensure_uri_scheme(t);
1180                                 webkit_web_view_load_uri(WEBKIT_WEB_VIEW(c->web_view), f);
1181                                 g_free(f);
1182                         }
1183                         return TRUE;
1184                 } else if ((GDK_KEY_Escape == key) ||
1185                                                          (def_key("quit", GDK_KEY_g) == key)) {
1186                         t = webkit_web_view_get_uri(WEBKIT_WEB_VIEW(c->web_view));
1187                         gtk_entry_set_text(GTK_ENTRY(c->location),
1188                                                                                                  (t == NULL ? __NAME__ : t));
1189                         return TRUE;
1190                 }
1191         }
1192         return FALSE;
1193 }
1194
1195 gboolean
1196 key_tablabel(GtkWidget *widget, GdkEvent *event, gpointer data)
1197 {
1198         GdkScrollDirection direction;
1199
1200         if (event->type == GDK_BUTTON_RELEASE) {
1201                 switch (((GdkEventButton *)event)->button) {
1202                 case 2:
1203                         client_destroy(NULL, data);
1204                         return TRUE;
1205                 }
1206         } else if (event->type == GDK_SCROLL) {
1207                 gdk_event_get_scroll_direction(event, &direction);
1208                 switch (direction) {
1209                 case GDK_SCROLL_UP:
1210                         gtk_notebook_prev_page(GTK_NOTEBOOK(mw.notebook));
1211                         break;
1212                 case GDK_SCROLL_DOWN:
1213                         gtk_notebook_next_page(GTK_NOTEBOOK(mw.notebook));
1214                         break;
1215                 default:
1216                         break;
1217                 }
1218                 return TRUE;
1219         }
1220         return FALSE;
1221 }
1222
1223 gboolean
1224 key_web_view(GtkWidget *widget, GdkEvent *event, gpointer data)
1225 {
1226         struct Client *c = (struct Client *)data;
1227         gdouble dx, dy;
1228         gfloat z;
1229
1230         if (key_common(widget, event, data))
1231                 return TRUE;
1232
1233         if (event->type == GDK_KEY_PRESS) {
1234                 if (((GdkEventKey *)event)->keyval == GDK_KEY_Escape) {
1235                         webkit_web_view_stop_loading(WEBKIT_WEB_VIEW(c->web_view));
1236                         gtk_entry_set_progress_fraction(GTK_ENTRY(c->location), 0);
1237                 }
1238         } else if (event->type == GDK_BUTTON_RELEASE) {
1239                 switch (((GdkEventButton *)event)->button) {
1240                 case 2:
1241                         if (c->hover_uri != NULL) {
1242                                 client_new(c->hover_uri, NULL, TRUE, FALSE);
1243                                 return TRUE;
1244                         }
1245                         break;
1246                 case 8:
1247                         webkit_web_view_go_back(WEBKIT_WEB_VIEW(c->web_view));
1248                         return TRUE;
1249                 case 9:
1250                         webkit_web_view_go_forward(WEBKIT_WEB_VIEW(c->web_view));
1251                         return TRUE;
1252                 }
1253         } else if (event->type == GDK_SCROLL) {
1254                 if (((GdkEventScroll *)event)->state & GDK_CONTROL_MASK ||
1255                                 ((GdkEventScroll *)event)->state & GDK_CONTROL_MASK) {
1256                         gdk_event_get_scroll_deltas(event, &dx, &dy);
1257                         z = webkit_web_view_get_zoom_level(WEBKIT_WEB_VIEW(c->web_view));
1258                         z += -dy * 0.1;
1259                         z = dx != 0 ? cfg.global_zoom : z;
1260                         webkit_web_view_set_zoom_level(WEBKIT_WEB_VIEW(c->web_view), z);
1261                         return TRUE;
1262                 }
1263         }
1264
1265         return FALSE;
1266 }
1267
1268 void
1269 mainwindow_setup(void)
1270 {
1271         mw.win = gtk_window_new(GTK_WINDOW_TOPLEVEL);
1272         gtk_window_set_default_size(GTK_WINDOW(mw.win), 800, 600);
1273         g_signal_connect(G_OBJECT(mw.win), "destroy", gtk_main_quit, NULL);
1274         gtk_window_set_title(GTK_WINDOW(mw.win), __NAME__);
1275
1276         mw.notebook = gtk_notebook_new();
1277         gtk_notebook_set_scrollable(GTK_NOTEBOOK(mw.notebook), TRUE);
1278         gtk_container_add(GTK_CONTAINER(mw.win), mw.notebook);
1279         g_signal_connect(G_OBJECT(mw.notebook), "switch-page",
1280                                                                          G_CALLBACK(notebook_switch_page), NULL);
1281 }
1282
1283 void
1284 mainwindow_title(gint idx)
1285 {
1286         GtkWidget *child, *widg, *tablabel;
1287         const gchar *text;
1288
1289         child = gtk_notebook_get_nth_page(GTK_NOTEBOOK(mw.notebook), idx);
1290         if (child == NULL)
1291                 return;
1292
1293         widg = gtk_notebook_get_tab_label(GTK_NOTEBOOK(mw.notebook), child);
1294         tablabel = (GtkWidget *)g_object_get_data(G_OBJECT(widg), "lariza-tab-label");
1295         text = gtk_label_get_text(GTK_LABEL(tablabel));
1296         gtk_window_set_title(GTK_WINDOW(mw.win), text);
1297 }
1298
1299 void
1300 notebook_switch_page(GtkNotebook *nb, GtkWidget *p, guint idx, gpointer data)
1301 {
1302         mainwindow_title(idx);
1303 }
1304
1305 gboolean
1306 quit_if_nothing_active(void)
1307 {
1308         if (clients == 0) {
1309                 if (downloads == 0) {
1310                         gtk_main_quit();
1311                         return TRUE;
1312                 } else {
1313                         gtk_widget_show_all(dm.win);
1314                 }
1315         }
1316
1317         return FALSE;
1318 }
1319
1320 gboolean
1321 remote_msg(GIOChannel *channel, GIOCondition condition, gpointer data)
1322 {
1323         gchar *uri = NULL;
1324
1325         g_io_channel_read_line(channel, &uri, NULL, NULL, NULL);
1326         if (uri) {
1327                 g_strstrip(uri);
1328                 client_new(uri, NULL, TRUE, TRUE);
1329                 g_free(uri);
1330         }
1331         return TRUE;
1332 }
1333
1334 void
1335 run_user_scripts(WebKitWebView *web_view)
1336 {
1337         gchar *base = NULL, *path = NULL, *contents = NULL;
1338         const gchar *entry = NULL;
1339         GDir *scriptdir = NULL;
1340
1341         base = g_build_filename(g_get_user_data_dir(), __NAME__, "user-scripts",
1342                                                                                                         NULL);
1343         scriptdir = g_dir_open(base, 0, NULL);
1344         if (scriptdir != NULL) {
1345                 while ((entry = g_dir_read_name(scriptdir)) != NULL) {
1346                         path = g_build_filename(base, entry, NULL);
1347                         char *jscmd = malloc(strlen(path) + 36);
1348                         sprintf(jscmd, "console.log(\"Running userscript %s\");", path);
1349                         if (g_str_has_suffix(path, ".js")) {
1350                                 if (g_file_get_contents(path, &contents, NULL, NULL)) {
1351                                         webkit_web_view_run_javascript(web_view, jscmd, NULL, NULL, NULL);
1352                                         webkit_web_view_run_javascript(web_view, contents, NULL, NULL, NULL);
1353                                         g_free(contents);
1354                                         g_free(jscmd);
1355                                 }
1356                         }
1357                         g_free(path);
1358                 }
1359                 g_dir_close(scriptdir);
1360         }
1361
1362         g_free(base);
1363 }
1364
1365 void
1366 show_web_view(WebKitWebView *web_view, gpointer data)
1367 {
1368         struct Client *c = (struct Client *)data;
1369         gint idx;
1370
1371         (void)web_view;
1372
1373         gtk_widget_show_all(mw.win);
1374
1375         if (c->focus_new_tab) {
1376                 idx = gtk_notebook_page_num(GTK_NOTEBOOK(mw.notebook), c->vbox);
1377                 if (idx != -1)
1378                         gtk_notebook_set_current_page(GTK_NOTEBOOK(mw.notebook), idx);
1379
1380                 gtk_widget_grab_focus(c->web_view);
1381         }
1382 }
1383
1384 void
1385 trust_user_certs(WebKitWebContext *wc)
1386 {
1387         GTlsCertificate *cert;
1388         const gchar *basedir, *file, *absfile;
1389         GDir *dir;
1390
1391         basedir = g_build_filename(g_get_user_data_dir(), __NAME__, "certs", NULL);
1392         dir = g_dir_open(basedir, 0, NULL);
1393         if (dir != NULL) {
1394                 file = g_dir_read_name(dir);
1395                 while (file != NULL) {
1396                         absfile = g_build_filename(g_get_user_data_dir(), __NAME__, "certs",
1397
1398                                                                                                                                  file, NULL);
1399                         cert = g_tls_certificate_new_from_file(absfile, NULL);
1400                         if (cert == NULL)
1401                                 fprintf(stderr, __NAME__": Could not load trusted cert '%s'\n", file);
1402                         else
1403                                 webkit_web_context_allow_tls_certificate_for_host(wc, cert, file);
1404                         file = g_dir_read_name(dir);
1405                 }
1406                 g_dir_close(dir);
1407         }
1408 }
1409
1410 GKeyFile *
1411 get_ini(void)
1412 {
1413         GKeyFileFlags flags = G_KEY_FILE_NONE;
1414         g_autoptr(GError) error = NULL;
1415         config = g_key_file_new();
1416
1417         // Load user config
1418         if (!g_key_file_load_from_file(config,
1419                                                                                                                                  g_build_filename(g_get_user_config_dir(),
1420                                                                                                                                                                                                         __NAME__, "lariza.ini",
1421                                                                                                                                                                                                         NULL), flags, &error)) {
1422                 // Load global config
1423                 if (!g_key_file_load_from_file(config, "/etc/lariza.ini", flags,
1424                                                                                                                                          &error)) {
1425                         fprintf(stderr, "Could not load lariza.ini: %s", error->message);
1426                 }
1427         }
1428         return config;
1429 }
1430
1431 int
1432 main(int argc, char **argv)
1433 {
1434         int opt, i;
1435
1436         gtk_init(&argc, &argv);
1437         get_config();
1438
1439         while ((opt = getopt(argc, argv, "C")) != -1) {
1440                 switch (opt) {
1441                 case 'C':
1442                         cfg.cooperative_instances = FALSE;
1443                         break;
1444                 default:
1445                         fprintf(stderr, "Usage: "__NAME__" [OPTION]... [URI]...\n");
1446                         exit(EXIT_FAILURE);
1447                 }
1448         }
1449
1450         if (cfg.cooperative_instances)
1451                 cooperation_setup();
1452
1453         if (!cfg.cooperative_instances || cfg.cooperative_alone)
1454                 init_default_web_context();
1455
1456         downloadmanager_setup();
1457         mainwindow_setup();
1458
1459         if (optind >= argc) {
1460                 client_new(cfg.home_uri, NULL, TRUE, TRUE);
1461         } else {
1462                 for (i = optind; i < argc; i++)
1463                         client_new(argv[i], NULL, TRUE, TRUE);
1464         }
1465
1466         if (!cfg.cooperative_instances || cfg.cooperative_alone)
1467                 gtk_main();
1468
1469         exit(EXIT_SUCCESS);
1470 }