1 /* See LICENSE file for copyright and license details.
3 * To understand surf, start reading main().
20 #include <gdk/gdkkeysyms.h>
22 #include <glib/gstdio.h>
25 #include <JavaScriptCore/JavaScript.h>
26 #include <webkit2/webkit2.h>
28 #include <X11/Xatom.h>
32 #define LENGTH(x) (sizeof(x) / sizeof(x[0]))
33 #define CLEANMASK(mask) (mask & (MODKEY|GDK_SHIFT_MASK))
35 enum { AtomFind, AtomGo, AtomUri, AtomLast };
48 OnDoc = WEBKIT_HIT_TEST_RESULT_CONTEXT_DOCUMENT,
49 OnLink = WEBKIT_HIT_TEST_RESULT_CONTEXT_LINK,
50 OnImg = WEBKIT_HIT_TEST_RESULT_CONTEXT_IMAGE,
51 OnMedia = WEBKIT_HIT_TEST_RESULT_CONTEXT_MEDIA,
52 OnEdit = WEBKIT_HIT_TEST_RESULT_CONTEXT_EDITABLE,
53 OnBar = WEBKIT_HIT_TEST_RESULT_CONTEXT_SCROLLBAR,
54 OnSel = WEBKIT_HIT_TEST_RESULT_CONTEXT_SELECTION,
55 OnAny = OnDoc | OnLink | OnImg | OnMedia | OnEdit | OnBar | OnSel,
64 typedef struct Client {
67 WebKitWebInspector *inspector;
68 WebKitFindController *finder;
69 WebKitHitTestResult *mousepos;
70 GTlsCertificateFlags tlsflags;
74 const char *title, *targeturi;
82 void (*func)(Client *c, const Arg *a);
90 void (*func)(Client *c, const Arg *a, WebKitHitTestResult *h);
92 unsigned int stopevent;
102 static void usage(void);
103 static void die(const char *errstr, ...);
104 static void setup(void);
105 static void sigchld(int unused);
106 static char *buildfile(const char *path);
107 static char *buildpath(const char *path);
108 static Client *newclient(Client *c);
109 static void addaccelgroup(Client *c);
110 static void loaduri(Client *c, const Arg *a);
111 static char *geturi(Client *c);
112 static void setatom(Client *c, int a, const char *v);
113 static const char *getatom(Client *c, int a);
114 static void updatetitle(Client *c);
115 static void gettogglestats(Client *c);
116 static void getpagestats(Client *c);
117 static WebKitCookieAcceptPolicy cookiepolicy_get(void);
118 static char cookiepolicy_set(const WebKitCookieAcceptPolicy p);
119 static const gchar *getstyle(const char *uri);
120 static void setstyle(Client *c, const char *stylefile);
121 static void runscript(Client *c);
122 static void evalscript(Client *c, const char *jsstr, ...);
123 static void updatewinid(Client *c);
124 static void handleplumb(Client *c, const gchar *uri);
125 static void newwindow(Client *c, const Arg *arg, gboolean noembed);
126 static void spawn(Client *c, const Arg *a);
127 static void destroyclient(Client *c);
128 static void cleanup(void);
131 static WebKitWebView *newview(Client *c, WebKitWebView *rv);
132 static GtkWidget *createview(WebKitWebView *v, WebKitNavigationAction *a,
134 static gboolean buttonreleased(GtkWidget *w, GdkEventKey *e, Client *c);
135 static gboolean keypress(GtkAccelGroup *group, GObject *obj, guint key,
136 GdkModifierType mods, Client *c);
137 static GdkFilterReturn processx(GdkXEvent *xevent, GdkEvent *event,
139 static gboolean winevent(GtkWidget *w, GdkEvent *e, Client *c);
140 static void showview(WebKitWebView *v, Client *c);
141 static GtkWidget *createwindow(Client *c);
142 static void loadchanged(WebKitWebView *v, WebKitLoadEvent e, Client *c);
143 static void progresschanged(WebKitWebView *v, GParamSpec *ps, Client *c);
144 static void titlechanged(WebKitWebView *view, GParamSpec *ps, Client *c);
145 static void mousetargetchanged(WebKitWebView *v, WebKitHitTestResult *h,
146 guint modifiers, Client *c);
147 static gboolean permissionrequested(WebKitWebView *v,
148 WebKitPermissionRequest *r, Client *c);
149 static gboolean decidepolicy(WebKitWebView *v, WebKitPolicyDecision *d,
150 WebKitPolicyDecisionType dt, Client *c);
151 static void decidenavigation(WebKitPolicyDecision *d, Client *c);
152 static void decidenewwindow(WebKitPolicyDecision *d, Client *c);
153 static void decideresource(WebKitPolicyDecision *d, Client *c);
154 static void downloadstarted(WebKitWebContext *wc, WebKitDownload *d,
156 static void responsereceived(WebKitDownload *d, GParamSpec *ps, Client *c);
157 static void download(Client *c, WebKitURIResponse *r);
158 static void closeview(WebKitWebView *v, Client *c);
159 static void destroywin(GtkWidget* w, Client *c);
162 static void pasteuri(GtkClipboard *clipboard, const char *text, gpointer d);
163 static void reload(Client *c, const Arg *arg);
164 static void print(Client *c, const Arg *a);
165 static void clipboard(Client *c, const Arg *a);
166 static void zoom(Client *c, const Arg *a);
167 static void scroll_v(Client *c, const Arg *a);
168 static void scroll_h(Client *c, const Arg *a);
169 static void navigate(Client *c, const Arg *a);
170 static void stop(Client *c, const Arg *arg);
171 static void toggle(Client *c, const Arg *a);
172 static void togglefullscreen(Client *c, const Arg *a);
173 static void togglecookiepolicy(Client *c, const Arg *arg);
174 static void togglestyle(Client *c, const Arg *arg);
175 static void toggleinspector(Client *c, const Arg *a);
176 static void find(Client *c, const Arg *a);
179 static void clicknavigate(Client *c, const Arg *a, WebKitHitTestResult *h);
180 static void clicknewwindow(Client *c, const Arg *a, WebKitHitTestResult *h);
182 static char winid[64];
183 static char togglestats[10];
184 static char pagestats[2];
185 static Atom atoms[AtomLast];
187 static gboolean showxid = FALSE;
188 static int cookiepolicy;
190 static Client *clients;
191 static char *stylefile;
192 static const char *useragent;
195 /* configuration, allows nested code to access above variables */
201 die("usage: %s [-bBdDfFgGiIkKmMnNpPsSvx] [-a cookiepolicies ] "
202 "[-c cookiefile] [-e xid] [-r scriptfile] [-t stylefile] "
203 "[-u useragent] [-z zoomlevel] [uri]\n", basename(argv0));
207 die(const char *errstr, ...)
211 va_start(ap, errstr);
212 vfprintf(stderr, errstr, ap);
222 /* clean up any zombies immediately */
224 gtk_init(NULL, NULL);
226 dpy = GDK_DISPLAY_XDISPLAY(gdk_display_get_default());
229 atoms[AtomFind] = XInternAtom(dpy, "_SURF_FIND", False);
230 atoms[AtomGo] = XInternAtom(dpy, "_SURF_GO", False);
231 atoms[AtomUri] = XInternAtom(dpy, "_SURF_URI", False);
234 cookiefile = buildfile(cookiefile);
235 scriptfile = buildfile(scriptfile);
236 cachedir = buildpath(cachedir);
238 if (stylefile == NULL) {
239 styledir = buildpath(styledir);
240 for (i = 0; i < LENGTH(styles); i++) {
241 if (regcomp(&(styles[i].re), styles[i].regex,
244 "Could not compile regex: %s\n",
246 styles[i].regex = NULL;
248 styles[i].style = g_strconcat(styledir, "/",
249 styles[i].style, NULL);
253 stylefile = buildfile(stylefile);
260 if (signal(SIGCHLD, sigchld) == SIG_ERR)
261 die("Can't install SIGCHLD handler");
262 while (0 < waitpid(-1, NULL, WNOHANG));
266 buildfile(const char *path)
268 char *dname, *bname, *bpath, *fpath;
271 dname = g_path_get_dirname(path);
272 bname = g_path_get_basename(path);
274 bpath = buildpath(dname);
277 fpath = g_build_filename(bpath, bname, NULL);
281 if (!(f = fopen(fpath, "a")))
282 die("Could not open file: %s\n", fpath);
284 g_chmod(fpath, 0600); /* always */
291 buildpath(const char *path)
294 char *apath, *name, *p, *fpath;
296 if (path[0] == '~') {
297 if (path[1] == '/' || path[1] == '\0') {
298 p = (char *)&path[1];
299 pw = getpwuid(getuid());
301 if ((p = strchr(path, '/')))
302 name = g_strndup(&path[1], --p - path);
304 name = g_strdup(&path[1]);
306 if (!(pw = getpwnam(name))) {
307 die("Can't get user %s home directory: %s.\n",
312 apath = g_build_filename(pw->pw_dir, p, NULL);
314 apath = g_strdup(path);
317 /* creating directory */
318 if (g_mkdir_with_parents(apath, 0700) < 0)
319 die("Could not access directory: %s\n", apath);
321 fpath = realpath(apath, NULL);
328 newclient(Client *rc)
332 if (!(c = calloc(1, sizeof(Client))))
333 die("Cannot malloc!\n");
341 c->view = newview(c, rc ? rc->view : NULL);
342 c->tlsflags = G_TLS_CERTIFICATE_VALIDATE_ALL + 1;
348 addaccelgroup(Client *c)
351 GtkAccelGroup *group = gtk_accel_group_new();
354 for (i = 0; i < LENGTH(keys); i++) {
355 closure = g_cclosure_new(G_CALLBACK(keypress), c, NULL);
356 gtk_accel_group_connect(group, keys[i].keyval, keys[i].mod, 0,
359 gtk_window_add_accel_group(GTK_WINDOW(c->win), group);
363 loaduri(Client *c, const Arg *a)
367 const char *uri = (char *)a->v;
369 if (g_strcmp0(uri, "") == 0)
372 if (g_strrstr(uri, "://") || g_str_has_prefix(uri, "about:")) {
374 } else if (!stat(uri, &st) && (path = realpath(uri, NULL))) {
375 url = g_strdup_printf("file://%s", path);
378 url = g_strdup_printf("http://%s", uri);
381 setatom(c, AtomUri, url);
383 if (strcmp(url, geturi(c)) == 0) {
386 webkit_web_view_load_uri(c->view, url);
387 c->title = geturi(c);
399 if (!(uri = (char *)webkit_web_view_get_uri(c->view)))
405 setatom(Client *c, int a, const char *v)
408 XChangeProperty(dpy, c->xid,
409 atoms[a], XA_STRING, 8, PropModeReplace,
410 (unsigned char *)v, strlen(v) + 1);
414 getatom(Client *c, int a)
416 static char buf[BUFSIZ];
419 unsigned long ldummy;
420 unsigned char *p = NULL;
422 XGetWindowProperty(dpy, c->xid,
423 atoms[a], 0L, BUFSIZ, False, XA_STRING,
424 &adummy, &idummy, &ldummy, &ldummy, &p);
426 strncpy(buf, (char *)p, LENGTH(buf)-1);
435 updatetitle(Client *c)
439 if (showindicators) {
443 if (c->progress != 100) {
444 title = g_strdup_printf("[%i%%] %s:%s | %s",
445 c->progress, togglestats, pagestats,
446 c->targeturi ? c->targeturi : c->title);
448 title = g_strdup_printf("%s:%s | %s",
449 togglestats, pagestats,
450 c->targeturi ? c->targeturi : c->title);
453 gtk_window_set_title(GTK_WINDOW(c->win), title);
456 gtk_window_set_title(GTK_WINDOW(c->win), c->title ?
462 gettogglestats(Client *c)
464 togglestats[0] = cookiepolicy_set(cookiepolicy_get());
465 togglestats[1] = enablecaretbrowsing ? 'C' : 'c';
466 togglestats[2] = allowgeolocation ? 'G' : 'g';
467 togglestats[3] = enablecache ? 'D' : 'd';
468 togglestats[4] = loadimages ? 'I' : 'i';
469 togglestats[5] = enablescripts ? 'S': 's';
470 togglestats[6] = enableplugins ? 'V' : 'v';
471 togglestats[7] = enablestyle ? 'M' : 'm';
472 togglestats[8] = enableframeflattening ? 'F' : 'f';
473 togglestats[9] = '\0';
477 getpagestats(Client *c)
479 pagestats[0] = c->tlsflags > G_TLS_CERTIFICATE_VALIDATE_ALL ? '-' :
480 c->tlsflags > 0 ? 'U' : 'T';
484 WebKitCookieAcceptPolicy
485 cookiepolicy_get(void)
487 switch (cookiepolicies[cookiepolicy]) {
489 return WEBKIT_COOKIE_POLICY_ACCEPT_NEVER;
491 return WEBKIT_COOKIE_POLICY_ACCEPT_NO_THIRD_PARTY;
497 return WEBKIT_COOKIE_POLICY_ACCEPT_ALWAYS;
501 cookiepolicy_set(const WebKitCookieAcceptPolicy ep)
504 case WEBKIT_COOKIE_POLICY_ACCEPT_NEVER:
506 case WEBKIT_COOKIE_POLICY_ACCEPT_NO_THIRD_PARTY:
508 case WEBKIT_COOKIE_POLICY_ACCEPT_ALWAYS:
517 getstyle(const char *uri)
521 if (stylefile != NULL)
524 for (i = 0; i < LENGTH(styles); i++) {
525 if (styles[i].regex && !regexec(&(styles[i].re), uri, 0,
527 return styles[i].style;
534 setstyle(Client *c, const char *stylefile)
538 if (!g_file_get_contents(stylefile, &style, NULL, NULL)) {
539 fprintf(stderr, "Could not read style file: %s\n", stylefile);
543 webkit_user_content_manager_add_style_sheet(
544 webkit_web_view_get_user_content_manager(c->view),
545 webkit_user_style_sheet_new(style,
546 WEBKIT_USER_CONTENT_INJECT_ALL_FRAMES,
547 WEBKIT_USER_STYLE_LEVEL_USER,
559 if (g_file_get_contents(scriptfile, &script, &l, NULL) && l)
560 evalscript(c, script);
565 evalscript(Client *c, const char *jsstr, ...)
571 script = g_strdup_vprintf(jsstr, ap);
574 webkit_web_view_run_javascript(c->view, script, NULL, NULL, NULL);
579 updatewinid(Client *c)
581 snprintf(winid, LENGTH(winid), "%lu", c->xid);
585 handleplumb(Client *c, const gchar *uri)
589 arg = (Arg)PLUMB(uri);
594 newwindow(Client *c, const Arg *a, int noembed)
598 const char *cmd[26], *uri;
599 const Arg arg = { .v = cmd };
603 cmd[i++] = cookiepolicies;
604 cmd[i++] = enablescrollbars ? "-B" : "-b";
605 if (cookiefile && g_strcmp0(cookiefile, "")) {
607 cmd[i++] = cookiefile;
609 cmd[i++] = enablecache ? "-D" : "-d";
610 if (embed && !noembed) {
612 snprintf(tmp, LENGTH(tmp), "%lu", embed);
615 cmd[i++] = runinfullscreen ? "-F" : "-f";
616 cmd[i++] = allowgeolocation ? "-G" : "-g";
617 cmd[i++] = loadimages ? "-I" : "-i";
618 cmd[i++] = kioskmode ? "-K" : "-k";
619 cmd[i++] = enablestyle ? "-M" : "-m";
620 cmd[i++] = enableinspector ? "-N" : "-n";
621 cmd[i++] = enableplugins ? "-P" : "-p";
622 if (scriptfile && g_strcmp0(scriptfile, "")) {
624 cmd[i++] = scriptfile;
626 cmd[i++] = enablescripts ? "-S" : "-s";
627 if (stylefile && g_strcmp0(stylefile, "")) {
629 cmd[i++] = stylefile;
631 if (fulluseragent && g_strcmp0(fulluseragent, "")) {
633 cmd[i++] = fulluseragent;
637 /* do not keep zoom level */
647 spawn(Client *c, const Arg *arg)
651 close(ConnectionNumber(dpy));
653 execvp(((char **)arg->v)[0], (char **)arg->v);
654 fprintf(stderr, "surf: execvp %s", ((char **)arg->v)[0]);
661 destroyclient(Client *c)
665 webkit_web_view_stop_loading(c->view);
666 /* Not needed, has already been called
667 gtk_widget_destroy(c->win);
670 for (p = clients; p && p->next != c; p = p->next)
683 destroyclient(clients);
691 newview(Client *c, WebKitWebView *rv)
694 WebKitSettings *settings;
695 WebKitUserContentManager *contentmanager;
696 WebKitWebContext *context;
701 webkit_web_view_new_with_related_view(rv));
703 settings = webkit_settings_new_with_settings(
704 "auto-load-images", loadimages,
705 "default-font-size", defaultfontsize,
706 "enable-caret-browsing", enablecaretbrowsing,
707 "enable-developer-extras", enableinspector,
708 "enable-dns-prefetching", enablednsprefetching,
709 "enable-frame-flattening", enableframeflattening,
710 "enable-html5-database", enablecache,
711 "enable-html5-local-storage", enablecache,
712 "enable-javascript", enablescripts,
713 "enable-plugins", enableplugins,
715 /* Have a look at http://webkitgtk.org/reference/webkit2gtk/stable/WebKitSettings.html
716 * for more interesting settings */
718 if (strcmp(fulluseragent, "")) {
719 webkit_settings_set_user_agent(settings, fulluseragent);
720 } else if (surfuseragent) {
721 webkit_settings_set_user_agent_with_application_details(
722 settings, "Surf", VERSION);
724 useragent = webkit_settings_get_user_agent(settings);
726 contentmanager = webkit_user_content_manager_new();
728 context = webkit_web_context_new_with_website_data_manager(
729 webkit_website_data_manager_new(
730 "base-cache-directory", cachedir,
731 "base-data-directory", cachedir,
734 /* rendering process model, can be a shared unique one or one for each
736 webkit_web_context_set_process_model(context,
737 WEBKIT_PROCESS_MODEL_MULTIPLE_SECONDARY_PROCESSES);
739 webkit_web_context_set_tls_errors_policy(context, strictssl ?
740 WEBKIT_TLS_ERRORS_POLICY_FAIL : WEBKIT_TLS_ERRORS_POLICY_IGNORE);
742 webkit_web_context_set_cache_model(context, enablecache ?
743 WEBKIT_CACHE_MODEL_WEB_BROWSER : WEBKIT_CACHE_MODEL_DOCUMENT_VIEWER);
745 /* Currently only works with text file to be compatible with curl */
746 webkit_cookie_manager_set_persistent_storage(
747 webkit_web_context_get_cookie_manager(context), cookiefile,
748 WEBKIT_COOKIE_PERSISTENT_STORAGE_TEXT);
750 webkit_cookie_manager_set_accept_policy(
751 webkit_web_context_get_cookie_manager(context),
754 g_signal_connect(G_OBJECT(context), "download-started",
755 G_CALLBACK(downloadstarted), c);
757 v = g_object_new(WEBKIT_TYPE_WEB_VIEW,
758 "settings", settings,
759 "user-content-manager", contentmanager,
760 "web-context", context,
764 g_signal_connect(G_OBJECT(v),
766 G_CALLBACK(titlechanged), c);
767 g_signal_connect(G_OBJECT(v),
768 "mouse-target-changed",
769 G_CALLBACK(mousetargetchanged), c);
770 g_signal_connect(G_OBJECT(v),
771 "permission-request",
772 G_CALLBACK(permissionrequested), c);
773 g_signal_connect(G_OBJECT(v),
775 G_CALLBACK(createview), c);
776 g_signal_connect(G_OBJECT(v), "ready-to-show",
777 G_CALLBACK(showview), c);
778 g_signal_connect(G_OBJECT(v),
780 G_CALLBACK(decidepolicy), c);
781 g_signal_connect(G_OBJECT(v),
783 G_CALLBACK(loadchanged), c);
784 g_signal_connect(G_OBJECT(v),
785 "notify::estimated-load-progress",
786 G_CALLBACK(progresschanged), c);
787 g_signal_connect(G_OBJECT(v),
788 "button-release-event",
789 G_CALLBACK(buttonreleased), c);
790 g_signal_connect(G_OBJECT(v), "close",
791 G_CALLBACK(closeview), c);
797 createview(WebKitWebView *v, WebKitNavigationAction *a, Client *c)
801 switch (webkit_navigation_action_get_navigation_type(a)) {
802 case WEBKIT_NAVIGATION_TYPE_OTHER: /* fallthrough */
804 * popup windows of type “other” are almost always triggered
805 * by user gesture, so inverse the logic here
807 /* instead of this, compare destination uri to mouse-over uri for validating window */
808 if (webkit_navigation_action_is_user_gesture(a)) {
812 case WEBKIT_NAVIGATION_TYPE_LINK_CLICKED: /* fallthrough */
813 case WEBKIT_NAVIGATION_TYPE_FORM_SUBMITTED: /* fallthrough */
814 case WEBKIT_NAVIGATION_TYPE_BACK_FORWARD: /* fallthrough */
815 case WEBKIT_NAVIGATION_TYPE_RELOAD: /* fallthrough */
816 case WEBKIT_NAVIGATION_TYPE_FORM_RESUBMITTED:
824 return GTK_WIDGET(n->view);
828 buttonreleased(GtkWidget *w, GdkEventKey *e, Client *c)
830 WebKitHitTestResultContext element;
831 GdkEventButton *eb = (GdkEventButton*)e;
834 element = webkit_hit_test_result_get_context(c->mousepos);
836 for (i = 0; i < LENGTH(buttons); ++i) {
837 if (element & buttons[i].target &&
838 eb->button == buttons[i].button &&
839 CLEANMASK(eb->state) == CLEANMASK(buttons[i].mask) &&
841 buttons[i].func(c, &buttons[i].arg, c->mousepos);
842 return buttons[i].stopevent;
850 keypress(GtkAccelGroup *group, GObject *obj, guint key, GdkModifierType mods,
854 gboolean processed = FALSE;
856 mods = CLEANMASK(mods);
857 key = gdk_keyval_to_lower(key);
859 for (i = 0; i < LENGTH(keys); i++) {
860 if (key == keys[i].keyval
861 && mods == keys[i].mod
863 keys[i].func(c, &(keys[i].arg));
872 processx(GdkXEvent *e, GdkEvent *event, gpointer d)
874 Client *c = (Client *)d;
878 if (((XEvent *)e)->type == PropertyNotify) {
879 ev = &((XEvent *)e)->xproperty;
880 if (ev->state == PropertyNewValue) {
881 if (ev->atom == atoms[AtomFind]) {
884 return GDK_FILTER_REMOVE;
885 } else if (ev->atom == atoms[AtomGo]) {
886 arg.v = getatom(c, AtomGo);
889 return GDK_FILTER_REMOVE;
893 return GDK_FILTER_CONTINUE;
897 winevent(GtkWidget *w, GdkEvent *e, Client *c)
900 case GDK_LEAVE_NOTIFY:
904 case GDK_WINDOW_STATE: /* fallthrough */
905 if (e->window_state.changed_mask ==
906 GDK_WINDOW_STATE_FULLSCREEN) {
907 c->fullscreen = e->window_state.new_window_state &
908 GDK_WINDOW_STATE_FULLSCREEN;
919 showview(WebKitWebView *v, Client *c)
921 GdkGeometry hints = { 1, 1 };
922 GdkRGBA bgcolor = { 0 };
925 c->win = createwindow(c);
928 c->inspector = webkit_web_view_get_inspector(c->view);
930 c->finder = webkit_web_view_get_find_controller(c->view);
936 gtk_container_add(GTK_CONTAINER(c->win), GTK_WIDGET(c->view));
939 gtk_widget_grab_focus(GTK_WIDGET(c->view));
940 gtk_widget_show(GTK_WIDGET(c->view));
941 gtk_widget_show(c->win);
942 gwin = gtk_widget_get_window(GTK_WIDGET(c->win));
943 c->xid = gdk_x11_window_get_xid(gwin);
944 gtk_window_set_geometry_hints(GTK_WINDOW(c->win), NULL, &hints,
946 gdk_window_set_events(gwin, GDK_ALL_EVENTS_MASK);
947 gdk_window_add_filter(gwin, processx, c);
949 if (zoomlevel != 1.0)
950 webkit_web_view_set_zoom_level(c->view, zoomlevel);
953 togglefullscreen(c, NULL);
955 setatom(c, AtomFind, "");
956 setatom(c, AtomUri, "about:blank");
958 webkit_web_view_set_background_color(c->view, &bgcolor);
961 gdk_display_sync(gtk_widget_get_display(c->win));
962 printf("%lu\n", c->xid);
964 if (fclose(stdout) != 0) {
965 die("Error closing stdout");
971 createwindow(Client *c)
976 w = gtk_plug_new(embed);
978 w = gtk_window_new(GTK_WINDOW_TOPLEVEL);
980 /* TA: 20091214: Despite what the GNOME docs say, the ICCCM
981 * is always correct, so we should still call this function.
982 * But when doing so, we *must* differentiate between a
983 * WM_CLASS and a resource on the window. By convention, the
984 * window class (WM_CLASS) is capped, while the resource is in
985 * lowercase. Both these values come as a pair.
987 gtk_window_set_wmclass(GTK_WINDOW(w), "surf", "Surf");
989 /* TA: 20091214: And set the role here as well -- so that
990 * sessions can pick this up.
992 gtk_window_set_role(GTK_WINDOW(w), "Surf");
994 gtk_window_set_default_size(GTK_WINDOW(w), 800, 600);
997 g_signal_connect(G_OBJECT(w), "destroy",
998 G_CALLBACK(destroywin), c);
999 g_signal_connect(G_OBJECT(w), "leave-notify-event",
1000 G_CALLBACK(winevent), c);
1001 g_signal_connect(G_OBJECT(w), "window-state-event",
1002 G_CALLBACK(winevent), c);
1008 loadchanged(WebKitWebView *v, WebKitLoadEvent e, Client *c)
1011 case WEBKIT_LOAD_STARTED:
1012 c->tlsflags = G_TLS_CERTIFICATE_VALIDATE_ALL + 1;
1014 case WEBKIT_LOAD_REDIRECTED:
1015 setatom(c, AtomUri, geturi(c));
1017 case WEBKIT_LOAD_COMMITTED:
1018 if (!webkit_web_view_get_tls_info(c->view, NULL, &(c->tlsflags)))
1019 c->tlsflags = G_TLS_CERTIFICATE_VALIDATE_ALL + 1;
1021 setatom(c, AtomUri, geturi(c));
1024 setstyle(c, getstyle(geturi(c)));
1026 case WEBKIT_LOAD_FINISHED:
1027 /* Disabled until we write some WebKitWebExtension for
1028 * manipulating the DOM directly.
1029 evalscript(c, "document.documentElement.style.overflow = '%s'",
1030 enablescrollbars ? "auto" : "hidden");
1039 progresschanged(WebKitWebView *v, GParamSpec *ps, Client *c)
1041 c->progress = webkit_web_view_get_estimated_load_progress(c->view) *
1047 titlechanged(WebKitWebView *view, GParamSpec *ps, Client *c)
1049 c->title = webkit_web_view_get_title(c->view);
1054 mousetargetchanged(WebKitWebView *v, WebKitHitTestResult *h, guint modifiers,
1057 WebKitHitTestResultContext hc;
1059 /* Keep the hit test to know where is the pointer on the next click */
1062 hc = webkit_hit_test_result_get_context(h);
1065 c->targeturi = webkit_hit_test_result_get_link_uri(h);
1066 else if (hc & OnImg)
1067 c->targeturi = webkit_hit_test_result_get_image_uri(h);
1068 else if (hc & OnMedia)
1069 c->targeturi = webkit_hit_test_result_get_media_uri(h);
1071 c->targeturi = NULL;
1076 permissionrequested(WebKitWebView *v, WebKitPermissionRequest *r, Client *c)
1078 if (WEBKIT_IS_GEOLOCATION_PERMISSION_REQUEST(r)) {
1079 if (allowgeolocation)
1080 webkit_permission_request_allow(r);
1082 webkit_permission_request_deny(r);
1090 decidepolicy(WebKitWebView *v, WebKitPolicyDecision *d,
1091 WebKitPolicyDecisionType dt, Client *c)
1094 case WEBKIT_POLICY_DECISION_TYPE_NAVIGATION_ACTION:
1095 decidenavigation(d, c);
1097 case WEBKIT_POLICY_DECISION_TYPE_NEW_WINDOW_ACTION:
1098 decidenewwindow(d, c);
1100 case WEBKIT_POLICY_DECISION_TYPE_RESPONSE:
1101 decideresource(d, c);
1104 webkit_policy_decision_ignore(d);
1111 decidenavigation(WebKitPolicyDecision *d, Client *c)
1113 WebKitNavigationAction *a;
1115 a = webkit_navigation_policy_decision_get_navigation_action(
1116 WEBKIT_NAVIGATION_POLICY_DECISION(d));
1118 switch (webkit_navigation_action_get_navigation_type(a)) {
1119 case WEBKIT_NAVIGATION_TYPE_LINK_CLICKED: /* fallthrough */
1120 case WEBKIT_NAVIGATION_TYPE_FORM_SUBMITTED: /* fallthrough */
1121 case WEBKIT_NAVIGATION_TYPE_BACK_FORWARD: /* fallthrough */
1122 case WEBKIT_NAVIGATION_TYPE_RELOAD: /* fallthrough */
1123 case WEBKIT_NAVIGATION_TYPE_FORM_RESUBMITTED:
1124 case WEBKIT_NAVIGATION_TYPE_OTHER: /* fallthrough */
1126 /* Do not navigate to links with a "_blank" target (popup) */
1127 if (webkit_navigation_policy_decision_get_frame_name(
1128 WEBKIT_NAVIGATION_POLICY_DECISION(d))) {
1129 webkit_policy_decision_ignore(d);
1131 /* Filter out navigation to different domain ? */
1132 /* get action→urirequest, copy and load in new window+view
1133 * on Ctrl+Click ? */
1134 webkit_policy_decision_use(d);
1141 decidenewwindow(WebKitPolicyDecision *d, Client *c)
1143 WebKitNavigationAction *a;
1146 a = webkit_navigation_policy_decision_get_navigation_action(
1147 WEBKIT_NAVIGATION_POLICY_DECISION(d));
1149 switch (webkit_navigation_action_get_navigation_type(a)) {
1150 case WEBKIT_NAVIGATION_TYPE_LINK_CLICKED: /* fallthrough */
1151 case WEBKIT_NAVIGATION_TYPE_FORM_SUBMITTED: /* fallthrough */
1152 case WEBKIT_NAVIGATION_TYPE_BACK_FORWARD: /* fallthrough */
1153 case WEBKIT_NAVIGATION_TYPE_RELOAD: /* fallthrough */
1154 case WEBKIT_NAVIGATION_TYPE_FORM_RESUBMITTED:
1155 /* Filter domains here */
1156 /* If the value of “mouse-button” is not 0, then the navigation was triggered by a mouse event.
1157 * test for link clicked but no button ? */
1158 arg.v = webkit_uri_request_get_uri(
1159 webkit_navigation_action_get_request(a));
1160 newwindow(c, &arg, 0);
1162 case WEBKIT_NAVIGATION_TYPE_OTHER: /* fallthrough */
1167 webkit_policy_decision_ignore(d);
1171 decideresource(WebKitPolicyDecision *d, Client *c)
1175 WebKitResponsePolicyDecision *r = WEBKIT_RESPONSE_POLICY_DECISION(d);
1176 WebKitURIResponse *res;
1178 res = webkit_response_policy_decision_get_response(r);
1179 uri = webkit_uri_response_get_uri(res);
1181 if (g_str_has_suffix(uri, "/favicon.ico"))
1182 webkit_uri_request_set_uri(
1183 webkit_response_policy_decision_get_request(r),
1186 if (!g_str_has_prefix(uri, "http://")
1187 && !g_str_has_prefix(uri, "https://")
1188 && !g_str_has_prefix(uri, "about:")
1189 && !g_str_has_prefix(uri, "file://")
1190 && !g_str_has_prefix(uri, "data:")
1191 && !g_str_has_prefix(uri, "blob:")
1192 && strlen(uri) > 0) {
1193 for (i = 0; i < strlen(uri); i++) {
1194 if (!g_ascii_isprint(uri[i])) {
1200 handleplumb(c, uri);
1201 webkit_policy_decision_ignore(d);
1205 if (webkit_response_policy_decision_is_mime_type_supported(r)) {
1206 webkit_policy_decision_use(d);
1208 webkit_policy_decision_ignore(d);
1214 downloadstarted(WebKitWebContext *wc, WebKitDownload *d, Client *c)
1216 g_signal_connect(G_OBJECT(d), "notify::response",
1217 G_CALLBACK(responsereceived), c);
1221 responsereceived(WebKitDownload *d, GParamSpec *ps, Client *c)
1223 download(c, webkit_download_get_response(d));
1224 webkit_download_cancel(d);
1228 download(Client *c, WebKitURIResponse *r)
1232 a = (Arg)DOWNLOAD(webkit_uri_response_get_uri(r), geturi(c));
1237 closeview(WebKitWebView *v, Client *c)
1239 gtk_widget_destroy(c->win);
1243 destroywin(GtkWidget* w, Client *c)
1246 if (clients == NULL)
1251 pasteuri(GtkClipboard *clipboard, const char *text, gpointer d)
1253 Arg arg = {.v = text };
1255 loaduri((Client *) d, &arg);
1259 reload(Client *c, const Arg *arg)
1261 gboolean nocache = *(gboolean *)arg;
1263 webkit_web_view_reload_bypass_cache(c->view);
1265 webkit_web_view_reload(c->view);
1269 print(Client *c, const Arg *a)
1271 webkit_print_operation_run_dialog(webkit_print_operation_new(c->view),
1272 GTK_WINDOW(c->win));
1276 clipboard(Client *c, const Arg *a)
1278 if (a->b) { /* load clipboard uri */
1279 gtk_clipboard_request_text(gtk_clipboard_get(
1280 GDK_SELECTION_PRIMARY),
1282 } else { /* copy uri */
1283 gtk_clipboard_set_text(gtk_clipboard_get(
1284 GDK_SELECTION_PRIMARY), c->targeturi
1285 ? c->targeturi : geturi(c), -1);
1290 zoom(Client *c, const Arg *a)
1293 webkit_web_view_set_zoom_level(c->view, zoomlevel + 0.1);
1295 webkit_web_view_set_zoom_level(c->view, zoomlevel - 0.1);
1297 webkit_web_view_set_zoom_level(c->view, 1.0);
1299 zoomlevel = webkit_web_view_get_zoom_level(c->view);
1303 scroll_v(Client *c, const Arg *a)
1305 evalscript(c, "window.scrollBy(0, %d * (window.innerHeight / 100))",
1310 scroll_h(Client *c, const Arg *a)
1312 evalscript(c, "window.scrollBy(%d * (window.innerWidth / 100), 0)",
1317 navigate(Client *c, const Arg *a)
1320 webkit_web_view_go_back(c->view);
1322 webkit_web_view_go_forward(c->view);
1326 stop(Client *c, const Arg *arg)
1328 webkit_web_view_stop_loading(c->view);
1332 toggle(Client *c, const Arg *a)
1336 s = webkit_web_view_get_settings(c->view);
1338 switch ((unsigned int)a->i) {
1340 enablecaretbrowsing = !enablecaretbrowsing;
1341 webkit_settings_set_enable_caret_browsing(s,
1342 enablecaretbrowsing);
1344 return; /* do not reload */
1346 case FrameFlattening:
1347 enableframeflattening = !enableframeflattening;
1348 webkit_settings_set_enable_frame_flattening(s,
1349 enableframeflattening);
1352 allowgeolocation = !allowgeolocation;
1355 enablescripts = !enablescripts;
1356 webkit_settings_set_enable_javascript(s, enablescripts);
1359 loadimages = !loadimages;
1360 webkit_settings_set_auto_load_images(s, loadimages);
1363 enableplugins = !enableplugins;
1364 webkit_settings_set_enable_plugins(s, enableplugins);
1367 /* Disabled until we write some WebKitWebExtension for
1368 * manipulating the DOM directly.
1369 enablescrollbars = !enablescrollbars;
1370 evalscript(c, "document.documentElement.style.overflow = '%s'",
1371 enablescrollbars ? "auto" : "hidden");
1373 return; /* do not reload */
1382 togglefullscreen(Client *c, const Arg *a)
1384 /* toggling value is handled in winevent() */
1386 gtk_window_unfullscreen(GTK_WINDOW(c->win));
1388 gtk_window_fullscreen(GTK_WINDOW(c->win));
1392 togglecookiepolicy(Client *c, const Arg *arg)
1395 cookiepolicy %= strlen(cookiepolicies);
1397 webkit_cookie_manager_set_accept_policy(
1398 webkit_web_context_get_cookie_manager(
1399 webkit_web_view_get_context(c->view)),
1400 cookiepolicy_get());
1403 /* Do not reload. */
1407 togglestyle(Client *c, const Arg *arg)
1409 enablestyle = !enablestyle;
1410 setstyle(c, enablestyle ? getstyle(geturi(c)) : "");
1416 toggleinspector(Client *c, const Arg *a)
1418 if (enableinspector) {
1419 if (webkit_web_inspector_is_attached(c->inspector))
1420 webkit_web_inspector_close(c->inspector);
1422 webkit_web_inspector_show(c->inspector);
1427 find(Client *c, const Arg *a)
1433 webkit_find_controller_search_next(c->finder);
1435 webkit_find_controller_search_previous(c->finder);
1437 s = getatom(c, AtomFind);
1438 f = webkit_find_controller_get_search_text(c->finder);
1440 if (g_strcmp0(f, s) == 0) /* reset search */
1441 webkit_find_controller_search(c->finder, "", findopts, G_MAXUINT);
1443 webkit_find_controller_search(c->finder, s, findopts, G_MAXUINT);
1445 if (strcmp(s, "") == 0)
1446 webkit_find_controller_search_finish(c->finder);
1451 clicknavigate(Client *c, const Arg *a, WebKitHitTestResult *h)
1457 clicknewwindow(Client *c, const Arg *a, WebKitHitTestResult *h)
1461 arg.v = webkit_hit_test_result_get_link_uri(h);
1462 newwindow(c, &arg, a->b);
1466 main(int argc, char *argv[])
1471 memset(&arg, 0, sizeof(arg));
1473 /* command line args */
1476 cookiepolicies = EARGF(usage());
1479 enablescrollbars = 0;
1482 enablescrollbars = 1;
1485 cookiefile = EARGF(usage());
1494 embed = strtol(EARGF(usage()), NULL, 0);
1497 runinfullscreen = 0;
1500 runinfullscreen = 1;
1503 allowgeolocation = 0;
1506 allowgeolocation = 1;
1527 enableinspector = 0;
1530 enableinspector = 1;
1539 scriptfile = EARGF(usage());
1548 stylefile = EARGF(usage());
1551 useragent = EARGF(usage());
1554 die("surf-"VERSION", ©2009-2015 surf engineers, "
1555 "see LICENSE for details\n");
1560 zoomlevel = strtof(EARGF(usage()), NULL);
1569 c = newclient(NULL);
1572 loaduri(clients, &arg);
1579 return EXIT_SUCCESS;