]> git.armaanb.net Git - chorizo.git/blob - browser.c
Revamp downloads manager
[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         gtk_label_set_text(GTK_LABEL(c->tablabel), t);
436         gtk_widget_set_tooltip_text(c->tablabel, t);
437         mainwindow_title(gtk_notebook_get_current_page(GTK_NOTEBOOK(mw.notebook)));
438 }
439
440 void
441 changed_uri(GObject *obj, GParamSpec *pspec, gpointer data)
442 {
443         const gchar *t;
444         struct Client *c = (struct Client *)data;
445         FILE *fp;
446
447         t = webkit_web_view_get_uri(WEBKIT_WEB_VIEW(c->web_view));
448
449         /* When a web process crashes, we get a "notify::uri" signal, but we
450          * can no longer read a meaningful URI. It's just an empty string
451          * now. Not updating the location bar in this scenario is important,
452          * because we would override the "WEB PROCESS CRASHED" message. */
453         if (t != NULL && strlen(t) > 0) {
454                 gtk_entry_set_text(GTK_ENTRY(c->location), t);
455
456                 if (cfg.history_file != NULL) {
457                         fp = fopen(cfg.history_file, "a");
458                         if (fp != NULL) {
459                                 fprintf(fp, "%s\n", t);
460                                 fclose(fp);
461                         } else {
462                                 perror(__NAME__": Error opening history file");
463                         }
464                 }
465         }
466 }
467
468 gboolean
469 crashed_web_view(WebKitWebView *web_view, gpointer data)
470 {
471         gchar *t;
472         struct Client *c = (struct Client *)data;
473
474         t = g_strdup_printf("WEB PROCESS CRASHED: %s",
475                                                                                         webkit_web_view_get_uri(WEBKIT_WEB_VIEW(web_view)));
476         gtk_entry_set_text(GTK_ENTRY(c->location), t);
477         g_free(t);
478
479         return TRUE;
480 }
481
482 gboolean
483 decide_policy(WebKitWebView *web_view, WebKitPolicyDecision *decision,
484                                                         WebKitPolicyDecisionType type, gpointer data)
485 {
486         WebKitResponsePolicyDecision *r;
487
488         switch (type) {
489         case WEBKIT_POLICY_DECISION_TYPE_RESPONSE:
490                 r = WEBKIT_RESPONSE_POLICY_DECISION(decision);
491                 if (!webkit_response_policy_decision_is_mime_type_supported(r))
492                         webkit_policy_decision_download(decision);
493                 else
494                         webkit_policy_decision_use(decision);
495                 break;
496         default:
497                 /* Use whatever default there is. */
498                 return FALSE;
499         }
500         return TRUE;
501 }
502
503 void
504 download_finished(WebKitDownload *download, gpointer data)
505 {
506         if (strcmp(gtk_tool_button_get_icon_name(GTK_TOOL_BUTTON(data)),
507                                                  "dialog-error") != 0)
508                 gtk_tool_button_set_icon_name(GTK_TOOL_BUTTON(data), "emblem-downloads");
509         downloads--;
510 }
511
512 void
513 download_start(WebKitWebView *web_view, WebKitDownload *download,
514                                                          gpointer data)
515 {
516         g_signal_connect(G_OBJECT(download), "decide-destination",
517                                                                          G_CALLBACK(download_handle), data);
518 }
519
520 gboolean
521 download_handle(WebKitDownload *download, gchar *suggested_filename,
522                                                                 gpointer data)
523 {
524         gchar *sug_clean, *path, *path2 = NULL, *uri;
525         GtkToolItem *tb;
526         int suffix = 1;
527         size_t i;
528
529         sug_clean = g_strdup(suggested_filename);
530         for (i = 0; i < strlen(sug_clean); i++)
531                 if (sug_clean[i] == G_DIR_SEPARATOR)
532                         sug_clean[i] = '_';
533
534         path = g_build_filename(cfg.download_dir, sug_clean, NULL);
535         path2 = g_strdup(path);
536         while (g_file_test(path2, G_FILE_TEST_EXISTS) && suffix < 1000) {
537                 g_free(path2);
538
539                 path2 = g_strdup_printf("%s.%d", path, suffix);
540                 suffix++;
541         }
542
543         if (suffix == 1000) {
544                 fprintf(stderr, __NAME__": Suffix reached limit for download.\n");
545                 webkit_download_cancel(download);
546         } else {
547                 uri = g_filename_to_uri(path2, NULL, NULL);
548                 webkit_download_set_destination(download, uri);
549                 g_free(uri);
550
551                 tb = gtk_tool_button_new(NULL, NULL);
552                 gtk_tool_button_set_icon_name(GTK_TOOL_BUTTON(tb), "network-receive");
553                 gtk_tool_button_set_label(GTK_TOOL_BUTTON(tb), sug_clean);
554                 gtk_toolbar_insert(GTK_TOOLBAR(dm.toolbar), tb, 0);
555                 gtk_widget_show_all(dm.win);
556
557                 g_signal_connect(G_OBJECT(download), "notify::estimated-progress",
558                                                                                  G_CALLBACK(changed_download_progress), tb);
559
560                 downloads++;
561                 g_signal_connect(G_OBJECT(download), "finished",
562                                                                                  G_CALLBACK(download_finished), tb);
563
564                 g_object_ref(download);
565
566                 struct DownloadItem *payload = malloc(sizeof(*payload));
567                 payload->tb = (GtkToolButton *)tb;
568                 payload->download = download;
569                 g_signal_connect(G_OBJECT(tb), "clicked", G_CALLBACK(download_click),
570                                                                                  payload);
571                 g_signal_connect(G_OBJECT(tb), "failed", G_CALLBACK(download_cancel),
572                                                                                  payload);
573                 g_signal_connect(G_OBJECT(tb), "destroy_event", G_CALLBACK(g_free),
574                                                                                  payload);
575         }
576
577         g_free(sug_clean);
578         g_free(path);
579         g_free(path2);
580
581         /* Propagate -- to whom it may concern. */
582         return FALSE;
583 }
584
585 void
586 download_cancel(GtkMenuItem *tb, gpointer data)
587 {
588         struct DownloadItem *payload = data;
589         gtk_tool_button_set_icon_name(GTK_TOOL_BUTTON(payload->tb), "dialog-error");
590         webkit_download_cancel(payload->download);
591 }
592
593 void
594 download_remove(GtkMenuItem *tb, gpointer data)
595 {
596         struct DownloadItem *payload = data;
597         g_object_unref(payload->download);
598         gtk_widget_destroy(GTK_WIDGET(payload->tb));
599 }
600
601 void
602 download_copy_url(GtkMenuItem *tb, gpointer data)
603 {
604         struct DownloadItem *payload = data;
605         WebKitURIRequest *req = webkit_download_get_request(payload->download);
606         const gchar *uri = webkit_uri_request_get_uri(req);
607         gtk_clipboard_set_text(gtk_clipboard_get(GDK_SELECTION_CLIPBOARD), uri,
608                                                                                                  strlen(uri));
609 }
610
611 void
612 download_copy_path(GtkMenuItem *tb, gpointer data)
613 {
614         struct DownloadItem *payload = data;
615         const gchar *path = webkit_download_get_destination(payload->download);
616         gtk_clipboard_set_text(gtk_clipboard_get(GDK_SELECTION_CLIPBOARD), path + 7,
617                                                                                                  strlen(path) - 7); // Offset by 7 to remove "file://"
618 }
619
620 void
621 download_click(GtkToolButton *tb, gpointer data)
622 {
623   GtkWidget *pmenu = gtk_menu_new();
624         GtkWidget *option;
625
626         if (strcmp(gtk_tool_button_get_icon_name(GTK_TOOL_BUTTON(tb)),
627                                                  "network-receive") == 0) {
628                 option = gtk_menu_item_new_with_label("Cancel download");
629                 g_signal_connect(G_OBJECT(option), "activate",
630                                                                                  G_CALLBACK(download_cancel), data);
631         } else {
632                 option = gtk_menu_item_new_with_label("Remove download");
633                 g_signal_connect(G_OBJECT(option), "activate",
634                                                                                  G_CALLBACK(download_remove), data);
635         }
636         gtk_widget_show(option);
637         gtk_menu_shell_append(GTK_MENU_SHELL(pmenu), option);
638
639         option = gtk_menu_item_new_with_label("Copy download URL");
640         gtk_widget_show(option);
641         gtk_menu_shell_append(GTK_MENU_SHELL(pmenu), option);
642         g_signal_connect(G_OBJECT(option), "activate",
643                                                                          G_CALLBACK(download_copy_url), data);
644
645         option = gtk_menu_item_new_with_label("Copy local path");
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_path), data);
650
651         gtk_menu_popup_at_pointer(GTK_MENU(pmenu), NULL);
652 }
653
654 gboolean
655 downloadmanager_delete(GtkWidget *obj, gpointer data)
656 {
657         if (!quit_if_nothing_active())
658                 gtk_widget_hide(dm.win);
659
660         return TRUE;
661 }
662
663 void
664 downloadmanager_setup(void)
665 {
666         dm.win = gtk_window_new(GTK_WINDOW_TOPLEVEL);
667         gtk_window_set_type_hint(GTK_WINDOW(dm.win), GDK_WINDOW_TYPE_HINT_DIALOG);
668         gtk_window_set_default_size(GTK_WINDOW(dm.win), 500, 250);
669         gtk_window_set_title(GTK_WINDOW(dm.win), __NAME__" - Download Manager");
670         g_signal_connect(G_OBJECT(dm.win), "delete-event",
671                                                                          G_CALLBACK(downloadmanager_delete), NULL);
672         g_signal_connect(G_OBJECT(dm.win), "key-press-event",
673                                                                          G_CALLBACK(key_downloadmanager), NULL);
674
675         dm.toolbar = gtk_toolbar_new();
676         gtk_orientable_set_orientation(GTK_ORIENTABLE(dm.toolbar),
677                                                                                                                                  GTK_ORIENTATION_VERTICAL);
678         gtk_toolbar_set_style(GTK_TOOLBAR(dm.toolbar), GTK_TOOLBAR_BOTH_HORIZ);
679         gtk_toolbar_set_show_arrow(GTK_TOOLBAR(dm.toolbar), FALSE);
680
681         dm.scroll = gtk_scrolled_window_new(NULL, NULL);
682         gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(dm.scroll),
683                                                                                                                                  GTK_POLICY_AUTOMATIC, GTK_POLICY_AUTOMATIC);
684         gtk_container_add(GTK_CONTAINER(dm.scroll), dm.toolbar);
685
686         gtk_container_add(GTK_CONTAINER(dm.win), dm.scroll);
687 }
688
689 gchar *
690 ensure_uri_scheme(const gchar *t)
691 {
692         gchar *f, *fabs;
693
694         f = g_ascii_strdown(t, -1);
695         if (!g_str_has_prefix(f, "http:") &&
696                         !g_str_has_prefix(f, "https:") &&
697                         !g_str_has_prefix(f, "file:") &&
698                         !g_str_has_prefix(f, "about:") &&
699                         !g_str_has_prefix(f, "data:") &&
700                         !g_str_has_prefix(f, "webkit:")) {
701                 g_free(f);
702                 fabs = realpath(t, NULL);
703                 if (fabs != NULL) {
704                         f = g_strdup_printf("file://%s", fabs);
705                         free(fabs);
706                 } else {
707                         f = g_strdup_printf("http://%s", t);
708                 }
709                 return f;
710         } else
711                 return g_strdup(t);
712 }
713
714 void
715 get_config(void)
716 {
717         cfg.accepted_language[0] = NULL;
718         cfg.accepted_language[1] = NULL;
719         cfg.cooperative_alone = TRUE;
720         cfg.cooperative_alone = TRUE;
721         cfg.fifo_suffix = "main";
722
723         const char *e = g_getenv(__NAME_UPPERCASE__"_FIFO_SUFFIX");
724         if (e != NULL)
725                 cfg.fifo_suffix = g_strdup(e);
726
727         char *xdg_down = getenv("XDG_DOWNLOAD_DIR");
728         cfg.download_dir = (xdg_down) ? xdg_down : "/var/tmp";
729
730         config = get_ini();
731         cfg.accepted_language[0] = g_key_file_get_string(config, "browser",
732                                                                                                                                                                                                          "accepted_language", NULL);
733         cfg.history_file = g_key_file_get_string(config, "browser", "history_file",
734                                                                                                                                                                          NULL);
735         cfg.home_uri = g_key_file_get_string(config, "browser", "homepage", NULL);
736         cfg.home_uri = (cfg.home_uri) ? cfg.home_uri : "about:blank";
737         cfg.enable_console_to_stdout = g_key_file_get_boolean(config, "browser",
738                                                                                                                                                                                                                                 "console_to_stdout",
739                                                                                                                                                                                                                                 NULL);
740         cfg.user_agent = g_key_file_get_string(config, "browser", "user_agent", NULL);
741         cfg.javascript_disabled = g_key_file_get_boolean(config, "browser",
742                                                                                                                                                                                                          "javascript_disabled", NULL);
743         char *input_cookie_policy = g_key_file_get_string(config, "browser",
744                                                                                                                                                                                                                 "cookie_policy", NULL);
745         cfg.cookie_policy = WEBKIT_COOKIE_POLICY_ACCEPT_NO_THIRD_PARTY;
746         if (input_cookie_policy) {
747                 if (strcmp(input_cookie_policy, "all") == 0) {
748                         cfg.cookie_policy = WEBKIT_COOKIE_POLICY_ACCEPT_ALWAYS;
749                 } else if (strcmp(input_cookie_policy, "none") == 0) {
750                         cfg.cookie_policy = WEBKIT_COOKIE_POLICY_ACCEPT_NEVER;
751                 }
752         }
753
754         cfg.tab_width_chars = g_key_file_get_integer(config, "ui", "tab_width", NULL);
755         cfg.tab_width_chars = (cfg.tab_width_chars) ? cfg.tab_width_chars : 20;
756         cfg.global_zoom = g_key_file_get_double(config, "ui", "zoom_level", NULL);
757         cfg.global_zoom = (cfg.global_zoom) ? cfg.global_zoom : 1.0;
758         cfg.search_engine = g_key_file_get_string(config, "ui", "search_engine",
759                                                                                                                                                                                 NULL);
760         cfg.search_engine = (cfg.search_engine) ? cfg.search_engine :
761                 "https://duckduckgo.com?q=";
762         cfg.spellcheck_disabled = g_key_file_get_boolean(config, "ui",
763                                                                                                                                                                                                          "spellcheck_disabled", NULL);
764         cfg.spellcheck_language = g_key_file_get_string(config, "ui",
765                                                                                                                                                                                                                                 "spellcheck_language",
766                                                                                                                                                                                                                                 NULL);
767         cfg.spellcheck_language = (cfg.spellcheck_language) ? cfg.spellcheck_language
768                 : "en_US";
769 }
770
771 void
772 grab_feeds_finished(GObject *object, GAsyncResult *result, gpointer data)
773 {
774         struct Client *c = (struct Client *)data;
775         WebKitJavascriptResult *js_result;
776         JSCValue *value;
777         JSCException *exception;
778         GError *err = NULL;
779         gchar *str_value;
780
781         g_free(c->feed_html);
782         c->feed_html = NULL;
783
784         /* This was taken almost verbatim from the example in WebKit's
785          * documentation:
786          *
787          * https://webkitgtk.org/reference/webkit2gtk/stable/WebKitWebView.html#webkit-web-view-run-javascript-finish */
788
789         js_result = webkit_web_view_run_javascript_finish(WEBKIT_WEB_VIEW(object),
790                                                                                                                                                                                                                 result, &err);
791         if (!js_result) {
792                 fprintf(stderr, __NAME__": Error running javascript: %s\n", err->message);
793                 g_error_free(err);
794                 return;
795         }
796
797         value = webkit_javascript_result_get_js_value(js_result);
798         if (jsc_value_is_string(value)) {
799                 str_value = jsc_value_to_string(value);
800                 exception = jsc_context_get_exception(jsc_value_get_context(value));
801                 if (exception != NULL) {
802                         fprintf(stderr, __NAME__": Error running javascript: %s\n",
803                                                         jsc_exception_get_message(exception));
804                 } else {
805                         c->feed_html = str_value;
806                 }
807
808                 gtk_entry_set_icon_from_icon_name(GTK_ENTRY(c->location),
809                                                                                                                                                         GTK_ENTRY_ICON_PRIMARY,
810                                                                                                                                                         "application-rss+xml-symbolic");
811                 gtk_entry_set_icon_activatable(GTK_ENTRY(c->location),
812                                                                                                                                          GTK_ENTRY_ICON_PRIMARY,
813                                                                                                                                          TRUE);
814         } else {
815                 gtk_entry_set_icon_from_icon_name(GTK_ENTRY(c->location),
816                                                                                                                                                         GTK_ENTRY_ICON_PRIMARY,
817                                                                                                                                                         NULL);
818         }
819
820         webkit_javascript_result_unref(js_result);
821 }
822
823 void
824 hover_web_view(WebKitWebView *web_view, WebKitHitTestResult *ht, guint modifiers,
825                                                          gpointer data)
826 {
827         struct Client *c = (struct Client *)data;
828         const char *to_show;
829
830         g_free(c->hover_uri);
831
832         if (webkit_hit_test_result_context_is_link(ht)) {
833                 to_show = webkit_hit_test_result_get_link_uri(ht);
834                 c->hover_uri = g_strdup(to_show);
835         } else {
836                 to_show = webkit_web_view_get_uri(WEBKIT_WEB_VIEW(c->web_view));
837                 c->hover_uri = NULL;
838         }
839
840         if (!gtk_widget_is_focus(c->location))
841                 gtk_entry_set_text(GTK_ENTRY(c->location), to_show);
842 }
843
844 void
845 icon_location(GtkEntry *entry, GtkEntryIconPosition icon_pos, GdkEvent *event,
846                                                         gpointer data)
847 {
848         struct Client *c = (struct Client *)data;
849         gchar *d;
850         gchar *data_template =
851                 "data:text/html,"
852                 "<!DOCTYPE html>"
853                 "<html>"
854                 "    <head>"
855                 "        <meta charset=\"UTF-8\">"
856                 "        <title>Feeds</title>"
857                 "    </head>"
858                 "    <body>"
859                 "        <p>Feeds found on this page:</p>"
860                 "        <ul>"
861                 "        %s"
862                 "        </ul>"
863                 "    </body>"
864                 "</html>";
865
866         if (c->feed_html != NULL)
867                 {
868                         /* What we're actually trying to do is show a simple HTML page
869                          * that lists all the feeds on the current page. The function
870                          * webkit_web_view_load_html() looks like the proper way to do
871                          * that. Sad thing is, it doesn't create a history entry, but
872                          * instead simply replaces the content of the current page. This
873                          * is not what we want.
874                          *
875                          * RFC 2397 [0] defines the data URI scheme [1]. We abuse this
876                          * mechanism to show my custom HTML snippet *and* create a
877                          * history entry.
878                          *
879                          * [0]: https://tools.ietf.org/html/rfc2397
880                          * [1]: https://en.wikipedia.org/wiki/Data_URI_scheme */
881                         d = g_strdup_printf(data_template, c->feed_html);
882                         webkit_web_view_load_uri(WEBKIT_WEB_VIEW(c->web_view), d);
883                         g_free(d);
884                 }
885 }
886
887 void
888 init_default_web_context(void)
889 {
890         gchar *p;
891         WebKitWebContext *wc;
892         WebKitCookieManager *cm;
893
894         wc = webkit_web_context_get_default();
895
896         p = g_build_filename(g_get_user_config_dir(), __NAME__, "adblock", NULL);
897         webkit_web_context_set_sandbox_enabled(wc, TRUE);
898         webkit_web_context_add_path_to_sandbox(wc, p, TRUE);
899         g_free(p);
900
901         webkit_web_context_set_process_model(wc,
902                                                                                                                                                          WEBKIT_PROCESS_MODEL_MULTIPLE_SECONDARY_PROCESSES);
903
904         p = g_build_filename(g_get_user_data_dir(), __NAME__, "web_extensions",
905                                                                                          NULL);
906         webkit_web_context_set_web_extensions_directory(wc, p);
907         g_free(p);
908
909         if (cfg.accepted_language[0] != NULL)
910                 webkit_web_context_set_preferred_languages(wc, cfg.accepted_language);
911
912         g_signal_connect(G_OBJECT(wc), "download-started",
913                                                                          G_CALLBACK(download_start), NULL);
914
915         trust_user_certs(wc);
916
917         cm = webkit_web_context_get_cookie_manager(wc);
918         webkit_cookie_manager_set_accept_policy(cm, cfg.cookie_policy);
919
920         webkit_web_context_set_favicon_database_directory(wc, NULL);
921         webkit_cookie_manager_set_persistent_storage(cm,
922                                                                                                                                                                                          g_build_filename("/",
923                                                                                                                                                                                                                                                                 g_get_user_cache_dir(),
924                                                                                                                                                                                                                                                                 __NAME__,
925                                                                                                                                                                                                                                                                 "cookies.db",
926                                                                                                                                                                                                                                                                 NULL),
927                                                                                                                                                                                          WEBKIT_COOKIE_PERSISTENT_STORAGE_SQLITE);
928
929         const gchar * const languages[2] = {(const gchar *)cfg.spellcheck_language,
930                 NULL};
931         webkit_web_context_set_spell_checking_languages(wc, languages);
932         webkit_web_context_set_spell_checking_enabled(wc, !cfg.spellcheck_disabled);
933 }
934
935 void
936 search(gpointer data, gint direction)
937 {
938         struct Client *c = (struct Client *)data;
939         WebKitWebView *web_view = WEBKIT_WEB_VIEW(c->web_view);
940         WebKitFindController *fc = webkit_web_view_get_find_controller(web_view);
941
942         if (search_text == NULL)
943                 return;
944
945         switch (direction) {
946         case 0:
947                 webkit_find_controller_search(fc, search_text,
948                                                                                                                                         WEBKIT_FIND_OPTIONS_CASE_INSENSITIVE |
949                                                                                                                                         WEBKIT_FIND_OPTIONS_WRAP_AROUND,
950                                                                                                                                         G_MAXUINT);
951                 break;
952         case 1:
953                 webkit_find_controller_search_next(fc);
954                 break;
955         case -1:
956                 webkit_find_controller_search_previous(fc);
957                 break;
958         case 2:
959                 webkit_find_controller_search_finish(fc);
960                 break;
961         }
962 }
963
964 void
965 search_init(struct Client *c, int direction)
966 {
967         gtk_widget_grab_focus(c->location);
968         const gchar *contents = gtk_entry_get_text(GTK_ENTRY(c->location));
969         if (strcspn(contents, "s/")) {
970                 gtk_entry_set_text(GTK_ENTRY(c->location), "s/");
971         }
972         gtk_editable_set_position(GTK_EDITABLE(c->location), -1);
973         search(c, 0);
974         search(c, -1);
975         search(c, direction);
976 }
977
978 int
979 def_key(char *key, unsigned int def)
980 {
981         char *conf = g_key_file_get_string(config, "keybindings", key, NULL);
982         return (conf) ? gdk_keyval_from_name((conf) ? conf : NULL) : def;
983 }
984
985 gboolean
986 key_common(GtkWidget *widget, GdkEvent *event, gpointer data)
987 {
988         struct Client *c = (struct Client *)data;
989         gdouble now;
990         gchar *f;
991
992         if (event->type == GDK_KEY_PRESS) {
993                 if (((GdkEventKey *)event)->state & GDK_CONTROL_MASK) {
994                         WebKitSettings *settings = webkit_web_view_get_settings(WEBKIT_WEB_VIEW(c->web_view));
995                         gboolean js = webkit_settings_get_enable_javascript(settings);
996                         int key = ((GdkEventKey *)event)->keyval;
997                         if (def_key("download_manager", GDK_KEY_y) == key) {
998                                 gtk_widget_show_all(dm.win);
999                                 return TRUE;
1000                         } else if (def_key("history_back", GDK_KEY_h) == key) {
1001                                 webkit_web_view_go_back(WEBKIT_WEB_VIEW(c->web_view));
1002                                 return TRUE;
1003                         } else if (def_key("history_forwards", GDK_KEY_l) == key) {
1004                                 webkit_web_view_go_forward(WEBKIT_WEB_VIEW(c->web_view));
1005                                 return TRUE;
1006                         } else if (def_key("location", GDK_KEY_t) == key) {
1007                                 gtk_widget_grab_focus(c->location);
1008                                 const char *uri = webkit_web_view_get_uri(WEBKIT_WEB_VIEW(c->web_view));
1009                                 const char *goal = (uri) ? uri : "https://";
1010                                 gtk_entry_set_text(GTK_ENTRY(c->location), goal);
1011                                 gtk_editable_set_position(GTK_EDITABLE(c->location), -1);
1012                                 return TRUE;
1013                         } else if (def_key("print", GDK_KEY_Print) == key) {
1014                                 webkit_print_operation_run_dialog(webkit_print_operation_new(WEBKIT_WEB_VIEW(c->web_view)),
1015                                                                                                                                                                         GTK_WINDOW(gtk_widget_get_toplevel(mw.win)));
1016                                 return TRUE;
1017                         } else if (def_key("quit", GDK_KEY_g) == key) {
1018                                 search(c, 2);
1019                                 gtk_widget_grab_focus(c->web_view);
1020                                 gtk_entry_set_text(GTK_ENTRY(c->location),
1021                                                                                                          webkit_web_view_get_uri(WEBKIT_WEB_VIEW(c->web_view)));
1022                                 webkit_web_view_run_javascript(WEBKIT_WEB_VIEW(c->web_view),
1023                                                                                                                                                          "window.getSelection().removeAllRanges();"
1024                                                                                                                                                          "document.activeElement.blur();",
1025                                                                                                                                                          NULL, NULL, c);
1026                                 return TRUE;
1027                         } else if (def_key("reload", GDK_KEY_e) == key) {
1028                                 webkit_web_view_reload_bypass_cache(WEBKIT_WEB_VIEW(c->web_view));
1029                                 return TRUE;
1030                         } else if (def_key("scroll_line_down", GDK_KEY_j) == key) {
1031                                 for (int i = 0; i < 2; i++) {
1032                                         event->key.keyval = GDK_KEY_Down;
1033                                         gdk_event_put(event);
1034                                 }
1035                                 return TRUE;
1036                         } else if (def_key("scroll_line_up", GDK_KEY_k) == key) {
1037                                 event->key.keyval = GDK_KEY_Up;
1038                                 gdk_event_put(event);
1039                                 return TRUE;
1040                         } else if (def_key("scroll_page_down", GDK_KEY_f) == key) {
1041                                 event->key.keyval = GDK_KEY_Page_Down;
1042                                 gdk_event_put(event);
1043                                 return TRUE;
1044                         } else if (def_key("scroll_page_up", GDK_KEY_b) == key) {
1045                                 event->key.keyval = GDK_KEY_Page_Up;
1046                                 gdk_event_put(event);
1047                                 return TRUE;
1048                         } else if (def_key("search_forwards", GDK_KEY_s) == key) {
1049                                 search_init(c, 1);
1050                                 return TRUE;
1051                         } else if (def_key("search_backwards", GDK_KEY_r) == key) {
1052                                 search_init(c, -1);
1053                                 return TRUE;
1054                         } else if (def_key("tab_close", GDK_KEY_q) == key) {
1055                                 client_destroy(NULL, c);
1056                                 return TRUE;
1057                         } else if (def_key("tab_switch_1", GDK_KEY_1) == key) {
1058                                 gtk_notebook_set_current_page(GTK_NOTEBOOK(mw.notebook), 0);
1059                                 return TRUE;
1060                         } else if (def_key("tab_switch_2", GDK_KEY_2) == key) {
1061                                 gtk_notebook_set_current_page(GTK_NOTEBOOK(mw.notebook), 1);
1062                                 return TRUE;
1063                         } else if (def_key("tab_switch_3", GDK_KEY_3) == key) {
1064                                 gtk_notebook_set_current_page(GTK_NOTEBOOK(mw.notebook), 2);
1065                                 return TRUE;
1066                         } else if (def_key("tab_switch_4", GDK_KEY_4) == key) {
1067                                 gtk_notebook_set_current_page(GTK_NOTEBOOK(mw.notebook), 3);
1068                                 return TRUE;
1069                         } else if (def_key("tab_switch_5", GDK_KEY_5) == key) {
1070                                 gtk_notebook_set_current_page(GTK_NOTEBOOK(mw.notebook), 4);
1071                                 return TRUE;
1072                         } else if (def_key("tab_switch_6", GDK_KEY_6) == key) {
1073                                 gtk_notebook_set_current_page(GTK_NOTEBOOK(mw.notebook), 5);
1074                                 return TRUE;
1075                         } else if (def_key("tab_switch_7", GDK_KEY_7) == key) {
1076                                 gtk_notebook_set_current_page(GTK_NOTEBOOK(mw.notebook), 6);
1077                                 return TRUE;
1078                         } else if (def_key("tab_switch_8", GDK_KEY_8) == key) {
1079                                 gtk_notebook_set_current_page(GTK_NOTEBOOK(mw.notebook), 7);
1080                                 return TRUE;
1081                         } else if (def_key("tab_switch_9", GDK_KEY_9) == key) {
1082                                 gtk_notebook_set_current_page(GTK_NOTEBOOK(mw.notebook), 8);
1083                                 return TRUE;
1084                         } else if (def_key("tab_previous", GDK_KEY_u) == key) {
1085                                 gtk_notebook_prev_page(GTK_NOTEBOOK(mw.notebook));
1086                                 return TRUE;
1087                         } else if (def_key("tab_new", GDK_KEY_w) == key) {
1088                                 f = ensure_uri_scheme(cfg.home_uri);
1089                                 client_new(f, NULL, TRUE, TRUE);
1090                                 g_free(f);
1091                                 return TRUE;
1092                         } else if (def_key("tab_next", GDK_KEY_i) == key) {
1093                                 gtk_notebook_next_page(GTK_NOTEBOOK(mw.notebook));
1094                                 return TRUE;
1095                         } else if (def_key("toggle_js", GDK_KEY_o) == key) {
1096                                 webkit_settings_set_enable_javascript(settings, (js) ? FALSE : TRUE);
1097                                 webkit_web_view_set_settings(WEBKIT_WEB_VIEW(c->web_view), settings);
1098                                 return TRUE;
1099                         } else if (def_key("web_search", GDK_KEY_d) == key) {
1100                                 gtk_widget_grab_focus(c->location);
1101                                 gtk_entry_set_text(GTK_ENTRY(c->location), "w/");
1102                                 gtk_editable_set_position(GTK_EDITABLE(c->location), -1);
1103                                 return TRUE;
1104                         } else if (def_key("zoom_in", GDK_KEY_equal) == key) {
1105                                 now = webkit_web_view_get_zoom_level(WEBKIT_WEB_VIEW(c->web_view));
1106                                 webkit_web_view_set_zoom_level(WEBKIT_WEB_VIEW(c->web_view), now + 0.1);
1107                                 return TRUE;
1108                         } else if (def_key("zoom_out", GDK_KEY_minus) == key) {
1109                                 now = webkit_web_view_get_zoom_level(WEBKIT_WEB_VIEW(c->web_view));
1110                                 webkit_web_view_set_zoom_level(WEBKIT_WEB_VIEW(c->web_view), now - 0.1);
1111                                 return TRUE;
1112                         } else if (def_key("zoom_reset", GDK_KEY_0) == key) {
1113                                 webkit_web_view_set_zoom_level(WEBKIT_WEB_VIEW(c->web_view),
1114                                                                                                                                                          cfg.global_zoom);
1115                                 return TRUE;
1116                         }
1117                 }
1118         }
1119         return FALSE;
1120 }
1121
1122 gboolean
1123 key_downloadmanager(GtkWidget *widget, GdkEvent *event, gpointer data)
1124 {
1125         if (event->type == GDK_KEY_PRESS) {
1126                 if (((GdkEventKey *)event)->state & GDK_CONTROL_MASK) {
1127                         int key = ((GdkEventKey *)event)->keyval;
1128                         if ((def_key("close_tab", GDK_KEY_q) == key) ||
1129                                         (def_key("download_manager", GDK_KEY_y) == key)) {
1130                                 downloadmanager_delete(dm.win, NULL);
1131                                 return TRUE;
1132                         }
1133                 }
1134         }
1135
1136         return FALSE;
1137 }
1138
1139 gboolean
1140 key_location(GtkWidget *widget, GdkEvent *event, gpointer data)
1141 {
1142         struct Client *c = (struct Client *)data;
1143         const gchar *t;
1144         gchar *f;
1145
1146         if (key_common(widget, event, data))
1147                 return TRUE;
1148
1149         if (event->type == GDK_KEY_PRESS) {
1150                 int key = ((GdkEventKey *)event)->keyval;
1151                 if ((GDK_KEY_KP_Enter == key) || (GDK_KEY_Return == key)) {
1152                         gtk_widget_grab_focus(c->web_view);
1153                         t = gtk_entry_get_text(GTK_ENTRY(c->location));
1154                         if (t != NULL && t[0] == 's' && t[1] == '/') {
1155                                 if (search_text != NULL)
1156                                         g_free(search_text);
1157                                 search_text = g_strdup(t + 2);
1158                                 search(c, 0);
1159                         } else if (t != NULL && t[0] == 'w' && t[1] == '/') {
1160                                 const char *engine = cfg.search_engine;
1161                                 int len = strlen(engine) + strlen(t) - 2;
1162                                 char *f = (char *) malloc(len);
1163                                 snprintf(f, len + 1, "%s%s", engine, t + 2);
1164                                 webkit_web_view_load_uri(WEBKIT_WEB_VIEW(c->web_view), f);
1165                                 free(f);
1166                         } else {
1167                                 f = ensure_uri_scheme(t);
1168                                 webkit_web_view_load_uri(WEBKIT_WEB_VIEW(c->web_view), f);
1169                                 g_free(f);
1170                         }
1171                         return TRUE;
1172                 } else if ((GDK_KEY_Escape == key) ||
1173                                                          (def_key("quit", GDK_KEY_g) == key)) {
1174                         t = webkit_web_view_get_uri(WEBKIT_WEB_VIEW(c->web_view));
1175                         gtk_entry_set_text(GTK_ENTRY(c->location),
1176                                                                                                  (t == NULL ? __NAME__ : t));
1177                         return TRUE;
1178                 }
1179         }
1180         return FALSE;
1181 }
1182
1183 gboolean
1184 key_tablabel(GtkWidget *widget, GdkEvent *event, gpointer data)
1185 {
1186         GdkScrollDirection direction;
1187
1188         if (event->type == GDK_BUTTON_RELEASE) {
1189                 switch (((GdkEventButton *)event)->button) {
1190                 case 2:
1191                         client_destroy(NULL, data);
1192                         return TRUE;
1193                 }
1194         } else if (event->type == GDK_SCROLL) {
1195                 gdk_event_get_scroll_direction(event, &direction);
1196                 switch (direction) {
1197                 case GDK_SCROLL_UP:
1198                         gtk_notebook_prev_page(GTK_NOTEBOOK(mw.notebook));
1199                         break;
1200                 case GDK_SCROLL_DOWN:
1201                         gtk_notebook_next_page(GTK_NOTEBOOK(mw.notebook));
1202                         break;
1203                 default:
1204                         break;
1205                 }
1206                 return TRUE;
1207         }
1208         return FALSE;
1209 }
1210
1211 gboolean
1212 key_web_view(GtkWidget *widget, GdkEvent *event, gpointer data)
1213 {
1214         struct Client *c = (struct Client *)data;
1215         gdouble dx, dy;
1216         gfloat z;
1217
1218         if (key_common(widget, event, data))
1219                 return TRUE;
1220
1221         if (event->type == GDK_KEY_PRESS) {
1222                 if (((GdkEventKey *)event)->keyval == GDK_KEY_Escape) {
1223                         webkit_web_view_stop_loading(WEBKIT_WEB_VIEW(c->web_view));
1224                         gtk_entry_set_progress_fraction(GTK_ENTRY(c->location), 0);
1225                 }
1226         } else if (event->type == GDK_BUTTON_RELEASE) {
1227                 switch (((GdkEventButton *)event)->button) {
1228                 case 2:
1229                         if (c->hover_uri != NULL) {
1230                                 client_new(c->hover_uri, NULL, TRUE, FALSE);
1231                                 return TRUE;
1232                         }
1233                         break;
1234                 case 8:
1235                         webkit_web_view_go_back(WEBKIT_WEB_VIEW(c->web_view));
1236                         return TRUE;
1237                 case 9:
1238                         webkit_web_view_go_forward(WEBKIT_WEB_VIEW(c->web_view));
1239                         return TRUE;
1240                 }
1241         } else if (event->type == GDK_SCROLL) {
1242                 if (((GdkEventScroll *)event)->state & GDK_CONTROL_MASK ||
1243                                 ((GdkEventScroll *)event)->state & GDK_CONTROL_MASK) {
1244                         gdk_event_get_scroll_deltas(event, &dx, &dy);
1245                         z = webkit_web_view_get_zoom_level(WEBKIT_WEB_VIEW(c->web_view));
1246                         z += -dy * 0.1;
1247                         z = dx != 0 ? cfg.global_zoom : z;
1248                         webkit_web_view_set_zoom_level(WEBKIT_WEB_VIEW(c->web_view), z);
1249                         return TRUE;
1250                 }
1251         }
1252
1253         return FALSE;
1254 }
1255
1256 void
1257 mainwindow_setup(void)
1258 {
1259         mw.win = gtk_window_new(GTK_WINDOW_TOPLEVEL);
1260         gtk_window_set_default_size(GTK_WINDOW(mw.win), 800, 600);
1261         g_signal_connect(G_OBJECT(mw.win), "destroy", gtk_main_quit, NULL);
1262         gtk_window_set_title(GTK_WINDOW(mw.win), __NAME__);
1263
1264         mw.notebook = gtk_notebook_new();
1265         gtk_notebook_set_scrollable(GTK_NOTEBOOK(mw.notebook), TRUE);
1266         gtk_container_add(GTK_CONTAINER(mw.win), mw.notebook);
1267         g_signal_connect(G_OBJECT(mw.notebook), "switch-page",
1268                                                                          G_CALLBACK(notebook_switch_page), NULL);
1269 }
1270
1271 void
1272 mainwindow_title(gint idx)
1273 {
1274         GtkWidget *child, *widg, *tablabel;
1275         const gchar *text;
1276
1277         child = gtk_notebook_get_nth_page(GTK_NOTEBOOK(mw.notebook), idx);
1278         if (child == NULL)
1279                 return;
1280
1281         widg = gtk_notebook_get_tab_label(GTK_NOTEBOOK(mw.notebook), child);
1282         tablabel = (GtkWidget *)g_object_get_data(G_OBJECT(widg), "lariza-tab-label");
1283         text = gtk_label_get_text(GTK_LABEL(tablabel));
1284         gtk_window_set_title(GTK_WINDOW(mw.win), text);
1285 }
1286
1287 void
1288 notebook_switch_page(GtkNotebook *nb, GtkWidget *p, guint idx, gpointer data)
1289 {
1290         mainwindow_title(idx);
1291 }
1292
1293 gboolean
1294 quit_if_nothing_active(void)
1295 {
1296         if (clients == 0) {
1297                 if (downloads == 0) {
1298                         gtk_main_quit();
1299                         return TRUE;
1300                 } else {
1301                         gtk_widget_show_all(dm.win);
1302                 }
1303         }
1304
1305         return FALSE;
1306 }
1307
1308 gboolean
1309 remote_msg(GIOChannel *channel, GIOCondition condition, gpointer data)
1310 {
1311         gchar *uri = NULL;
1312
1313         g_io_channel_read_line(channel, &uri, NULL, NULL, NULL);
1314         if (uri) {
1315                 g_strstrip(uri);
1316                 client_new(uri, NULL, TRUE, TRUE);
1317                 g_free(uri);
1318         }
1319         return TRUE;
1320 }
1321
1322 void
1323 run_user_scripts(WebKitWebView *web_view)
1324 {
1325         gchar *base = NULL, *path = NULL, *contents = NULL;
1326         const gchar *entry = NULL;
1327         GDir *scriptdir = NULL;
1328
1329         base = g_build_filename(g_get_user_data_dir(), __NAME__, "user-scripts",
1330                                                                                                         NULL);
1331         scriptdir = g_dir_open(base, 0, NULL);
1332         if (scriptdir != NULL) {
1333                 while ((entry = g_dir_read_name(scriptdir)) != NULL) {
1334                         path = g_build_filename(base, entry, NULL);
1335                         char *jscmd = malloc(strlen(path) + 36);
1336                         sprintf(jscmd, "console.log(\"Running userscript %s\");", path);
1337                         if (g_str_has_suffix(path, ".js")) {
1338                                 if (g_file_get_contents(path, &contents, NULL, NULL)) {
1339                                         webkit_web_view_run_javascript(web_view, jscmd, NULL, NULL, NULL);
1340                                         webkit_web_view_run_javascript(web_view, contents, NULL, NULL, NULL);
1341                                         g_free(contents);
1342                                         g_free(jscmd);
1343                                 }
1344                         }
1345                         g_free(path);
1346                 }
1347                 g_dir_close(scriptdir);
1348         }
1349
1350         g_free(base);
1351 }
1352
1353 void
1354 show_web_view(WebKitWebView *web_view, gpointer data)
1355 {
1356         struct Client *c = (struct Client *)data;
1357         gint idx;
1358
1359         (void)web_view;
1360
1361         gtk_widget_show_all(mw.win);
1362
1363         if (c->focus_new_tab) {
1364                 idx = gtk_notebook_page_num(GTK_NOTEBOOK(mw.notebook), c->vbox);
1365                 if (idx != -1)
1366                         gtk_notebook_set_current_page(GTK_NOTEBOOK(mw.notebook), idx);
1367
1368                 gtk_widget_grab_focus(c->web_view);
1369         }
1370 }
1371
1372 void
1373 trust_user_certs(WebKitWebContext *wc)
1374 {
1375         GTlsCertificate *cert;
1376         const gchar *basedir, *file, *absfile;
1377         GDir *dir;
1378
1379         basedir = g_build_filename(g_get_user_data_dir(), __NAME__, "certs", NULL);
1380         dir = g_dir_open(basedir, 0, NULL);
1381         if (dir != NULL) {
1382                 file = g_dir_read_name(dir);
1383                 while (file != NULL) {
1384                         absfile = g_build_filename(g_get_user_data_dir(), __NAME__, "certs",
1385
1386                                                                                                                                  file, NULL);
1387                         cert = g_tls_certificate_new_from_file(absfile, NULL);
1388                         if (cert == NULL)
1389                                 fprintf(stderr, __NAME__": Could not load trusted cert '%s'\n", file);
1390                         else
1391                                 webkit_web_context_allow_tls_certificate_for_host(wc, cert, file);
1392                         file = g_dir_read_name(dir);
1393                 }
1394                 g_dir_close(dir);
1395         }
1396 }
1397
1398 GKeyFile *
1399 get_ini(void)
1400 {
1401         GKeyFileFlags flags = G_KEY_FILE_NONE;
1402         g_autoptr(GError) error = NULL;
1403         config = g_key_file_new();
1404
1405         // Load user config
1406         if (!g_key_file_load_from_file(config,
1407                                                                                                                                  g_build_filename(g_get_user_config_dir(),
1408                                                                                                                                                                                                         __NAME__, "lariza.ini",
1409                                                                                                                                                                                                         NULL), flags, &error)) {
1410                 // Load global config
1411                 if (!g_key_file_load_from_file(config, "/etc/lariza.ini", flags,
1412                                                                                                                                          &error)) {
1413                         fprintf(stderr, "Could not load lariza.ini: %s", error->message);
1414                 }
1415         }
1416         return config;
1417 }
1418
1419 int
1420 main(int argc, char **argv)
1421 {
1422         int opt, i;
1423
1424         gtk_init(&argc, &argv);
1425         get_config();
1426
1427         while ((opt = getopt(argc, argv, "C")) != -1) {
1428                 switch (opt) {
1429                 case 'C':
1430                         cfg.cooperative_instances = FALSE;
1431                         break;
1432                 default:
1433                         fprintf(stderr, "Usage: "__NAME__" [OPTION]... [URI]...\n");
1434                         exit(EXIT_FAILURE);
1435                 }
1436         }
1437
1438         if (cfg.cooperative_instances)
1439                 cooperation_setup();
1440
1441         if (!cfg.cooperative_instances || cfg.cooperative_alone)
1442                 init_default_web_context();
1443
1444         downloadmanager_setup();
1445         mainwindow_setup();
1446
1447         if (optind >= argc) {
1448                 client_new(cfg.home_uri, NULL, TRUE, TRUE);
1449         } else {
1450                 for (i = optind; i < argc; i++)
1451                         client_new(argv[i], NULL, TRUE, TRUE);
1452         }
1453
1454         if (!cfg.cooperative_instances || cfg.cooperative_alone)
1455                 gtk_main();
1456
1457         exit(EXIT_SUCCESS);
1458 }