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