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