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