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);
181 static void clickexternplayer(Client *c, const Arg *a, WebKitHitTestResult *h);
183 static char winid[64];
184 static char togglestats[10];
185 static char pagestats[2];
186 static Atom atoms[AtomLast];
188 static gboolean showxid = FALSE;
189 static int cookiepolicy;
191 static Client *clients;
192 static char *stylefile;
193 static const char *useragent;
196 /* configuration, allows nested code to access above variables */
202 die("usage: %s [-bBdDfFgGiIkKmMnNpPsSvx] [-a cookiepolicies ] "
203 "[-c cookiefile] [-e xid] [-r scriptfile] [-t stylefile] "
204 "[-u useragent] [-z zoomlevel] [uri]\n", basename(argv0));
208 die(const char *errstr, ...)
212 va_start(ap, errstr);
213 vfprintf(stderr, errstr, ap);
223 /* clean up any zombies immediately */
225 gtk_init(NULL, NULL);
227 dpy = GDK_DISPLAY_XDISPLAY(gdk_display_get_default());
230 atoms[AtomFind] = XInternAtom(dpy, "_SURF_FIND", False);
231 atoms[AtomGo] = XInternAtom(dpy, "_SURF_GO", False);
232 atoms[AtomUri] = XInternAtom(dpy, "_SURF_URI", False);
235 cookiefile = buildfile(cookiefile);
236 scriptfile = buildfile(scriptfile);
237 cachedir = buildpath(cachedir);
239 if (stylefile == NULL) {
240 styledir = buildpath(styledir);
241 for (i = 0; i < LENGTH(styles); i++) {
242 if (regcomp(&(styles[i].re), styles[i].regex,
245 "Could not compile regex: %s\n",
247 styles[i].regex = NULL;
249 styles[i].style = g_strconcat(styledir, "/",
250 styles[i].style, NULL);
254 stylefile = buildfile(stylefile);
261 if (signal(SIGCHLD, sigchld) == SIG_ERR)
262 die("Can't install SIGCHLD handler");
263 while (0 < waitpid(-1, NULL, WNOHANG));
267 buildfile(const char *path)
269 char *dname, *bname, *bpath, *fpath;
272 dname = g_path_get_dirname(path);
273 bname = g_path_get_basename(path);
275 bpath = buildpath(dname);
278 fpath = g_build_filename(bpath, bname, NULL);
282 if (!(f = fopen(fpath, "a")))
283 die("Could not open file: %s\n", fpath);
285 g_chmod(fpath, 0600); /* always */
292 buildpath(const char *path)
295 char *apath, *name, *p, *fpath;
297 if (path[0] == '~') {
298 if (path[1] == '/' || path[1] == '\0') {
299 p = (char *)&path[1];
300 pw = getpwuid(getuid());
302 if ((p = strchr(path, '/')))
303 name = g_strndup(&path[1], --p - path);
305 name = g_strdup(&path[1]);
307 if (!(pw = getpwnam(name))) {
308 die("Can't get user %s home directory: %s.\n",
313 apath = g_build_filename(pw->pw_dir, p, NULL);
315 apath = g_strdup(path);
318 /* creating directory */
319 if (g_mkdir_with_parents(apath, 0700) < 0)
320 die("Could not access directory: %s\n", apath);
322 fpath = realpath(apath, NULL);
329 newclient(Client *rc)
333 if (!(c = calloc(1, sizeof(Client))))
334 die("Cannot malloc!\n");
342 c->view = newview(c, rc ? rc->view : NULL);
343 c->tlsflags = G_TLS_CERTIFICATE_VALIDATE_ALL + 1;
349 addaccelgroup(Client *c)
352 GtkAccelGroup *group = gtk_accel_group_new();
355 for (i = 0; i < LENGTH(keys); i++) {
356 closure = g_cclosure_new(G_CALLBACK(keypress), c, NULL);
357 gtk_accel_group_connect(group, keys[i].keyval, keys[i].mod, 0,
360 gtk_window_add_accel_group(GTK_WINDOW(c->win), group);
364 loaduri(Client *c, const Arg *a)
368 const char *uri = (char *)a->v;
370 if (g_strcmp0(uri, "") == 0)
373 if (g_strrstr(uri, "://") || g_str_has_prefix(uri, "about:")) {
375 } else if (!stat(uri, &st) && (path = realpath(uri, NULL))) {
376 url = g_strdup_printf("file://%s", path);
379 url = g_strdup_printf("http://%s", uri);
382 setatom(c, AtomUri, url);
384 if (strcmp(url, geturi(c)) == 0) {
387 webkit_web_view_load_uri(c->view, url);
388 c->title = geturi(c);
400 if (!(uri = (char *)webkit_web_view_get_uri(c->view)))
406 setatom(Client *c, int a, const char *v)
409 XChangeProperty(dpy, c->xid,
410 atoms[a], XA_STRING, 8, PropModeReplace,
411 (unsigned char *)v, strlen(v) + 1);
415 getatom(Client *c, int a)
417 static char buf[BUFSIZ];
420 unsigned long ldummy;
421 unsigned char *p = NULL;
423 XGetWindowProperty(dpy, c->xid,
424 atoms[a], 0L, BUFSIZ, False, XA_STRING,
425 &adummy, &idummy, &ldummy, &ldummy, &p);
427 strncpy(buf, (char *)p, LENGTH(buf)-1);
436 updatetitle(Client *c)
440 if (showindicators) {
444 if (c->progress != 100) {
445 title = g_strdup_printf("[%i%%] %s:%s | %s",
446 c->progress, togglestats, pagestats,
447 c->targeturi ? c->targeturi : c->title);
449 title = g_strdup_printf("%s:%s | %s",
450 togglestats, pagestats,
451 c->targeturi ? c->targeturi : c->title);
454 gtk_window_set_title(GTK_WINDOW(c->win), title);
457 gtk_window_set_title(GTK_WINDOW(c->win), c->title ?
463 gettogglestats(Client *c)
465 togglestats[0] = cookiepolicy_set(cookiepolicy_get());
466 togglestats[1] = enablecaretbrowsing ? 'C' : 'c';
467 togglestats[2] = allowgeolocation ? 'G' : 'g';
468 togglestats[3] = enablecache ? 'D' : 'd';
469 togglestats[4] = loadimages ? 'I' : 'i';
470 togglestats[5] = enablescripts ? 'S': 's';
471 togglestats[6] = enableplugins ? 'V' : 'v';
472 togglestats[7] = enablestyle ? 'M' : 'm';
473 togglestats[8] = enableframeflattening ? 'F' : 'f';
474 togglestats[9] = '\0';
478 getpagestats(Client *c)
480 pagestats[0] = c->tlsflags > G_TLS_CERTIFICATE_VALIDATE_ALL ? '-' :
481 c->tlsflags > 0 ? 'U' : 'T';
485 WebKitCookieAcceptPolicy
486 cookiepolicy_get(void)
488 switch (cookiepolicies[cookiepolicy]) {
490 return WEBKIT_COOKIE_POLICY_ACCEPT_NEVER;
492 return WEBKIT_COOKIE_POLICY_ACCEPT_NO_THIRD_PARTY;
498 return WEBKIT_COOKIE_POLICY_ACCEPT_ALWAYS;
502 cookiepolicy_set(const WebKitCookieAcceptPolicy ep)
505 case WEBKIT_COOKIE_POLICY_ACCEPT_NEVER:
507 case WEBKIT_COOKIE_POLICY_ACCEPT_NO_THIRD_PARTY:
509 case WEBKIT_COOKIE_POLICY_ACCEPT_ALWAYS:
518 getstyle(const char *uri)
522 if (stylefile != NULL)
525 for (i = 0; i < LENGTH(styles); i++) {
526 if (styles[i].regex && !regexec(&(styles[i].re), uri, 0,
528 return styles[i].style;
535 setstyle(Client *c, const char *stylefile)
539 if (!g_file_get_contents(stylefile, &style, NULL, NULL)) {
540 fprintf(stderr, "Could not read style file: %s\n", stylefile);
544 webkit_user_content_manager_add_style_sheet(
545 webkit_web_view_get_user_content_manager(c->view),
546 webkit_user_style_sheet_new(style,
547 WEBKIT_USER_CONTENT_INJECT_ALL_FRAMES,
548 WEBKIT_USER_STYLE_LEVEL_USER,
560 if (g_file_get_contents(scriptfile, &script, &l, NULL) && l)
561 evalscript(c, script);
566 evalscript(Client *c, const char *jsstr, ...)
572 script = g_strdup_vprintf(jsstr, ap);
575 webkit_web_view_run_javascript(c->view, script, NULL, NULL, NULL);
580 updatewinid(Client *c)
582 snprintf(winid, LENGTH(winid), "%lu", c->xid);
586 handleplumb(Client *c, const gchar *uri)
590 arg = (Arg)PLUMB(uri);
595 newwindow(Client *c, const Arg *a, int noembed)
599 const char *cmd[26], *uri;
600 const Arg arg = { .v = cmd };
604 cmd[i++] = cookiepolicies;
605 cmd[i++] = enablescrollbars ? "-B" : "-b";
606 if (cookiefile && g_strcmp0(cookiefile, "")) {
608 cmd[i++] = cookiefile;
610 cmd[i++] = enablecache ? "-D" : "-d";
611 if (embed && !noembed) {
613 snprintf(tmp, LENGTH(tmp), "%lu", embed);
616 cmd[i++] = runinfullscreen ? "-F" : "-f";
617 cmd[i++] = allowgeolocation ? "-G" : "-g";
618 cmd[i++] = loadimages ? "-I" : "-i";
619 cmd[i++] = kioskmode ? "-K" : "-k";
620 cmd[i++] = enablestyle ? "-M" : "-m";
621 cmd[i++] = enableinspector ? "-N" : "-n";
622 cmd[i++] = enableplugins ? "-P" : "-p";
623 if (scriptfile && g_strcmp0(scriptfile, "")) {
625 cmd[i++] = scriptfile;
627 cmd[i++] = enablescripts ? "-S" : "-s";
628 if (stylefile && g_strcmp0(stylefile, "")) {
630 cmd[i++] = stylefile;
632 if (fulluseragent && g_strcmp0(fulluseragent, "")) {
634 cmd[i++] = fulluseragent;
638 /* do not keep zoom level */
648 spawn(Client *c, const Arg *arg)
652 close(ConnectionNumber(dpy));
654 execvp(((char **)arg->v)[0], (char **)arg->v);
655 fprintf(stderr, "surf: execvp %s", ((char **)arg->v)[0]);
662 destroyclient(Client *c)
666 webkit_web_view_stop_loading(c->view);
667 /* Not needed, has already been called
668 gtk_widget_destroy(c->win);
671 for (p = clients; p && p->next != c; p = p->next)
684 destroyclient(clients);
692 newview(Client *c, WebKitWebView *rv)
695 WebKitSettings *settings;
696 WebKitUserContentManager *contentmanager;
697 WebKitWebContext *context;
702 webkit_web_view_new_with_related_view(rv));
704 settings = webkit_settings_new_with_settings(
705 "auto-load-images", loadimages,
706 "default-font-size", defaultfontsize,
707 "enable-caret-browsing", enablecaretbrowsing,
708 "enable-developer-extras", enableinspector,
709 "enable-dns-prefetching", enablednsprefetching,
710 "enable-frame-flattening", enableframeflattening,
711 "enable-html5-database", enablecache,
712 "enable-html5-local-storage", enablecache,
713 "enable-javascript", enablescripts,
714 "enable-plugins", enableplugins,
716 /* Have a look at http://webkitgtk.org/reference/webkit2gtk/stable/WebKitSettings.html
717 * for more interesting settings */
719 if (strcmp(fulluseragent, "")) {
720 webkit_settings_set_user_agent(settings, fulluseragent);
721 } else if (surfuseragent) {
722 webkit_settings_set_user_agent_with_application_details(
723 settings, "Surf", VERSION);
725 useragent = webkit_settings_get_user_agent(settings);
727 contentmanager = webkit_user_content_manager_new();
729 context = webkit_web_context_new_with_website_data_manager(
730 webkit_website_data_manager_new(
731 "base-cache-directory", cachedir,
732 "base-data-directory", cachedir,
735 /* rendering process model, can be a shared unique one or one for each
737 webkit_web_context_set_process_model(context,
738 WEBKIT_PROCESS_MODEL_MULTIPLE_SECONDARY_PROCESSES);
740 webkit_web_context_set_tls_errors_policy(context, strictssl ?
741 WEBKIT_TLS_ERRORS_POLICY_FAIL : WEBKIT_TLS_ERRORS_POLICY_IGNORE);
743 webkit_web_context_set_cache_model(context, enablecache ?
744 WEBKIT_CACHE_MODEL_WEB_BROWSER : WEBKIT_CACHE_MODEL_DOCUMENT_VIEWER);
746 /* Currently only works with text file to be compatible with curl */
747 webkit_cookie_manager_set_persistent_storage(
748 webkit_web_context_get_cookie_manager(context), cookiefile,
749 WEBKIT_COOKIE_PERSISTENT_STORAGE_TEXT);
751 webkit_cookie_manager_set_accept_policy(
752 webkit_web_context_get_cookie_manager(context),
755 g_signal_connect(G_OBJECT(context), "download-started",
756 G_CALLBACK(downloadstarted), c);
758 v = g_object_new(WEBKIT_TYPE_WEB_VIEW,
759 "settings", settings,
760 "user-content-manager", contentmanager,
761 "web-context", context,
765 g_signal_connect(G_OBJECT(v),
767 G_CALLBACK(titlechanged), c);
768 g_signal_connect(G_OBJECT(v),
769 "mouse-target-changed",
770 G_CALLBACK(mousetargetchanged), c);
771 g_signal_connect(G_OBJECT(v),
772 "permission-request",
773 G_CALLBACK(permissionrequested), c);
774 g_signal_connect(G_OBJECT(v),
776 G_CALLBACK(createview), c);
777 g_signal_connect(G_OBJECT(v), "ready-to-show",
778 G_CALLBACK(showview), c);
779 g_signal_connect(G_OBJECT(v),
781 G_CALLBACK(decidepolicy), c);
782 g_signal_connect(G_OBJECT(v),
784 G_CALLBACK(loadchanged), c);
785 g_signal_connect(G_OBJECT(v),
786 "notify::estimated-load-progress",
787 G_CALLBACK(progresschanged), c);
788 g_signal_connect(G_OBJECT(v),
789 "button-release-event",
790 G_CALLBACK(buttonreleased), c);
791 g_signal_connect(G_OBJECT(v), "close",
792 G_CALLBACK(closeview), c);
798 createview(WebKitWebView *v, WebKitNavigationAction *a, Client *c)
802 switch (webkit_navigation_action_get_navigation_type(a)) {
803 case WEBKIT_NAVIGATION_TYPE_OTHER: /* fallthrough */
805 * popup windows of type “other” are almost always triggered
806 * by user gesture, so inverse the logic here
808 /* instead of this, compare destination uri to mouse-over uri for validating window */
809 if (webkit_navigation_action_is_user_gesture(a)) {
813 case WEBKIT_NAVIGATION_TYPE_LINK_CLICKED: /* fallthrough */
814 case WEBKIT_NAVIGATION_TYPE_FORM_SUBMITTED: /* fallthrough */
815 case WEBKIT_NAVIGATION_TYPE_BACK_FORWARD: /* fallthrough */
816 case WEBKIT_NAVIGATION_TYPE_RELOAD: /* fallthrough */
817 case WEBKIT_NAVIGATION_TYPE_FORM_RESUBMITTED:
825 return GTK_WIDGET(n->view);
829 buttonreleased(GtkWidget *w, GdkEventKey *e, Client *c)
831 WebKitHitTestResultContext element;
832 GdkEventButton *eb = (GdkEventButton*)e;
835 element = webkit_hit_test_result_get_context(c->mousepos);
837 for (i = 0; i < LENGTH(buttons); ++i) {
838 if (element & buttons[i].target &&
839 eb->button == buttons[i].button &&
840 CLEANMASK(eb->state) == CLEANMASK(buttons[i].mask) &&
842 buttons[i].func(c, &buttons[i].arg, c->mousepos);
843 return buttons[i].stopevent;
851 keypress(GtkAccelGroup *group, GObject *obj, guint key, GdkModifierType mods,
855 gboolean processed = FALSE;
857 mods = CLEANMASK(mods);
858 key = gdk_keyval_to_lower(key);
860 for (i = 0; i < LENGTH(keys); i++) {
861 if (key == keys[i].keyval
862 && mods == keys[i].mod
864 keys[i].func(c, &(keys[i].arg));
873 processx(GdkXEvent *e, GdkEvent *event, gpointer d)
875 Client *c = (Client *)d;
879 if (((XEvent *)e)->type == PropertyNotify) {
880 ev = &((XEvent *)e)->xproperty;
881 if (ev->state == PropertyNewValue) {
882 if (ev->atom == atoms[AtomFind]) {
885 return GDK_FILTER_REMOVE;
886 } else if (ev->atom == atoms[AtomGo]) {
887 arg.v = getatom(c, AtomGo);
890 return GDK_FILTER_REMOVE;
894 return GDK_FILTER_CONTINUE;
898 winevent(GtkWidget *w, GdkEvent *e, Client *c)
901 case GDK_LEAVE_NOTIFY:
905 case GDK_WINDOW_STATE: /* fallthrough */
906 if (e->window_state.changed_mask ==
907 GDK_WINDOW_STATE_FULLSCREEN) {
908 c->fullscreen = e->window_state.new_window_state &
909 GDK_WINDOW_STATE_FULLSCREEN;
920 showview(WebKitWebView *v, Client *c)
922 GdkGeometry hints = { 1, 1 };
923 GdkRGBA bgcolor = { 0 };
926 c->win = createwindow(c);
929 c->inspector = webkit_web_view_get_inspector(c->view);
931 c->finder = webkit_web_view_get_find_controller(c->view);
937 gtk_container_add(GTK_CONTAINER(c->win), GTK_WIDGET(c->view));
940 gtk_widget_grab_focus(GTK_WIDGET(c->view));
941 gtk_widget_show(GTK_WIDGET(c->view));
942 gtk_widget_show(c->win);
943 gwin = gtk_widget_get_window(GTK_WIDGET(c->win));
944 c->xid = gdk_x11_window_get_xid(gwin);
945 gtk_window_set_geometry_hints(GTK_WINDOW(c->win), NULL, &hints,
947 gdk_window_set_events(gwin, GDK_ALL_EVENTS_MASK);
948 gdk_window_add_filter(gwin, processx, c);
950 if (zoomlevel != 1.0)
951 webkit_web_view_set_zoom_level(c->view, zoomlevel);
954 togglefullscreen(c, NULL);
956 setatom(c, AtomFind, "");
957 setatom(c, AtomUri, "about:blank");
959 webkit_web_view_set_background_color(c->view, &bgcolor);
962 gdk_display_sync(gtk_widget_get_display(c->win));
963 printf("%lu\n", c->xid);
965 if (fclose(stdout) != 0) {
966 die("Error closing stdout");
972 createwindow(Client *c)
977 w = gtk_plug_new(embed);
979 w = gtk_window_new(GTK_WINDOW_TOPLEVEL);
981 /* TA: 20091214: Despite what the GNOME docs say, the ICCCM
982 * is always correct, so we should still call this function.
983 * But when doing so, we *must* differentiate between a
984 * WM_CLASS and a resource on the window. By convention, the
985 * window class (WM_CLASS) is capped, while the resource is in
986 * lowercase. Both these values come as a pair.
988 gtk_window_set_wmclass(GTK_WINDOW(w), "surf", "Surf");
990 /* TA: 20091214: And set the role here as well -- so that
991 * sessions can pick this up.
993 gtk_window_set_role(GTK_WINDOW(w), "Surf");
995 gtk_window_set_default_size(GTK_WINDOW(w), 800, 600);
998 g_signal_connect(G_OBJECT(w), "destroy",
999 G_CALLBACK(destroywin), c);
1000 g_signal_connect(G_OBJECT(w), "leave-notify-event",
1001 G_CALLBACK(winevent), c);
1002 g_signal_connect(G_OBJECT(w), "window-state-event",
1003 G_CALLBACK(winevent), c);
1009 loadchanged(WebKitWebView *v, WebKitLoadEvent e, Client *c)
1012 case WEBKIT_LOAD_STARTED:
1013 c->tlsflags = G_TLS_CERTIFICATE_VALIDATE_ALL + 1;
1015 case WEBKIT_LOAD_REDIRECTED:
1016 setatom(c, AtomUri, geturi(c));
1018 case WEBKIT_LOAD_COMMITTED:
1019 if (!webkit_web_view_get_tls_info(c->view, NULL, &(c->tlsflags)))
1020 c->tlsflags = G_TLS_CERTIFICATE_VALIDATE_ALL + 1;
1022 setatom(c, AtomUri, geturi(c));
1025 setstyle(c, getstyle(geturi(c)));
1027 case WEBKIT_LOAD_FINISHED:
1028 /* Disabled until we write some WebKitWebExtension for
1029 * manipulating the DOM directly.
1030 evalscript(c, "document.documentElement.style.overflow = '%s'",
1031 enablescrollbars ? "auto" : "hidden");
1040 progresschanged(WebKitWebView *v, GParamSpec *ps, Client *c)
1042 c->progress = webkit_web_view_get_estimated_load_progress(c->view) *
1048 titlechanged(WebKitWebView *view, GParamSpec *ps, Client *c)
1050 c->title = webkit_web_view_get_title(c->view);
1055 mousetargetchanged(WebKitWebView *v, WebKitHitTestResult *h, guint modifiers,
1058 WebKitHitTestResultContext hc;
1060 /* Keep the hit test to know where is the pointer on the next click */
1063 hc = webkit_hit_test_result_get_context(h);
1066 c->targeturi = webkit_hit_test_result_get_link_uri(h);
1067 else if (hc & OnImg)
1068 c->targeturi = webkit_hit_test_result_get_image_uri(h);
1069 else if (hc & OnMedia)
1070 c->targeturi = webkit_hit_test_result_get_media_uri(h);
1072 c->targeturi = NULL;
1077 permissionrequested(WebKitWebView *v, WebKitPermissionRequest *r, Client *c)
1079 if (WEBKIT_IS_GEOLOCATION_PERMISSION_REQUEST(r)) {
1080 if (allowgeolocation)
1081 webkit_permission_request_allow(r);
1083 webkit_permission_request_deny(r);
1091 decidepolicy(WebKitWebView *v, WebKitPolicyDecision *d,
1092 WebKitPolicyDecisionType dt, Client *c)
1095 case WEBKIT_POLICY_DECISION_TYPE_NAVIGATION_ACTION:
1096 decidenavigation(d, c);
1098 case WEBKIT_POLICY_DECISION_TYPE_NEW_WINDOW_ACTION:
1099 decidenewwindow(d, c);
1101 case WEBKIT_POLICY_DECISION_TYPE_RESPONSE:
1102 decideresource(d, c);
1105 webkit_policy_decision_ignore(d);
1112 decidenavigation(WebKitPolicyDecision *d, Client *c)
1114 WebKitNavigationAction *a;
1116 a = webkit_navigation_policy_decision_get_navigation_action(
1117 WEBKIT_NAVIGATION_POLICY_DECISION(d));
1119 switch (webkit_navigation_action_get_navigation_type(a)) {
1120 case WEBKIT_NAVIGATION_TYPE_LINK_CLICKED: /* fallthrough */
1121 case WEBKIT_NAVIGATION_TYPE_FORM_SUBMITTED: /* fallthrough */
1122 case WEBKIT_NAVIGATION_TYPE_BACK_FORWARD: /* fallthrough */
1123 case WEBKIT_NAVIGATION_TYPE_RELOAD: /* fallthrough */
1124 case WEBKIT_NAVIGATION_TYPE_FORM_RESUBMITTED:
1125 case WEBKIT_NAVIGATION_TYPE_OTHER: /* fallthrough */
1127 /* Do not navigate to links with a "_blank" target (popup) */
1128 if (webkit_navigation_policy_decision_get_frame_name(
1129 WEBKIT_NAVIGATION_POLICY_DECISION(d))) {
1130 webkit_policy_decision_ignore(d);
1132 /* Filter out navigation to different domain ? */
1133 /* get action→urirequest, copy and load in new window+view
1134 * on Ctrl+Click ? */
1135 webkit_policy_decision_use(d);
1142 decidenewwindow(WebKitPolicyDecision *d, Client *c)
1144 WebKitNavigationAction *a;
1147 a = webkit_navigation_policy_decision_get_navigation_action(
1148 WEBKIT_NAVIGATION_POLICY_DECISION(d));
1150 switch (webkit_navigation_action_get_navigation_type(a)) {
1151 case WEBKIT_NAVIGATION_TYPE_LINK_CLICKED: /* fallthrough */
1152 case WEBKIT_NAVIGATION_TYPE_FORM_SUBMITTED: /* fallthrough */
1153 case WEBKIT_NAVIGATION_TYPE_BACK_FORWARD: /* fallthrough */
1154 case WEBKIT_NAVIGATION_TYPE_RELOAD: /* fallthrough */
1155 case WEBKIT_NAVIGATION_TYPE_FORM_RESUBMITTED:
1156 /* Filter domains here */
1157 /* If the value of “mouse-button” is not 0, then the navigation was triggered by a mouse event.
1158 * test for link clicked but no button ? */
1159 arg.v = webkit_uri_request_get_uri(
1160 webkit_navigation_action_get_request(a));
1161 newwindow(c, &arg, 0);
1163 case WEBKIT_NAVIGATION_TYPE_OTHER: /* fallthrough */
1168 webkit_policy_decision_ignore(d);
1172 decideresource(WebKitPolicyDecision *d, Client *c)
1176 WebKitResponsePolicyDecision *r = WEBKIT_RESPONSE_POLICY_DECISION(d);
1177 WebKitURIResponse *res;
1179 res = webkit_response_policy_decision_get_response(r);
1180 uri = webkit_uri_response_get_uri(res);
1182 if (g_str_has_suffix(uri, "/favicon.ico"))
1183 webkit_uri_request_set_uri(
1184 webkit_response_policy_decision_get_request(r),
1187 if (!g_str_has_prefix(uri, "http://")
1188 && !g_str_has_prefix(uri, "https://")
1189 && !g_str_has_prefix(uri, "about:")
1190 && !g_str_has_prefix(uri, "file://")
1191 && !g_str_has_prefix(uri, "data:")
1192 && !g_str_has_prefix(uri, "blob:")
1193 && strlen(uri) > 0) {
1194 for (i = 0; i < strlen(uri); i++) {
1195 if (!g_ascii_isprint(uri[i])) {
1201 handleplumb(c, uri);
1202 webkit_policy_decision_ignore(d);
1206 if (webkit_response_policy_decision_is_mime_type_supported(r)) {
1207 webkit_policy_decision_use(d);
1209 webkit_policy_decision_ignore(d);
1215 downloadstarted(WebKitWebContext *wc, WebKitDownload *d, Client *c)
1217 g_signal_connect(G_OBJECT(d), "notify::response",
1218 G_CALLBACK(responsereceived), c);
1222 responsereceived(WebKitDownload *d, GParamSpec *ps, Client *c)
1224 download(c, webkit_download_get_response(d));
1225 webkit_download_cancel(d);
1229 download(Client *c, WebKitURIResponse *r)
1233 a = (Arg)DOWNLOAD(webkit_uri_response_get_uri(r), geturi(c));
1238 closeview(WebKitWebView *v, Client *c)
1240 gtk_widget_destroy(c->win);
1244 destroywin(GtkWidget* w, Client *c)
1247 if (clients == NULL)
1252 pasteuri(GtkClipboard *clipboard, const char *text, gpointer d)
1254 Arg arg = {.v = text };
1256 loaduri((Client *) d, &arg);
1260 reload(Client *c, const Arg *arg)
1262 gboolean nocache = *(gboolean *)arg;
1264 webkit_web_view_reload_bypass_cache(c->view);
1266 webkit_web_view_reload(c->view);
1270 print(Client *c, const Arg *a)
1272 webkit_print_operation_run_dialog(webkit_print_operation_new(c->view),
1273 GTK_WINDOW(c->win));
1277 clipboard(Client *c, const Arg *a)
1279 if (a->b) { /* load clipboard uri */
1280 gtk_clipboard_request_text(gtk_clipboard_get(
1281 GDK_SELECTION_PRIMARY),
1283 } else { /* copy uri */
1284 gtk_clipboard_set_text(gtk_clipboard_get(
1285 GDK_SELECTION_PRIMARY), c->targeturi
1286 ? c->targeturi : geturi(c), -1);
1291 zoom(Client *c, const Arg *a)
1294 webkit_web_view_set_zoom_level(c->view, zoomlevel + 0.1);
1296 webkit_web_view_set_zoom_level(c->view, zoomlevel - 0.1);
1298 webkit_web_view_set_zoom_level(c->view, 1.0);
1300 zoomlevel = webkit_web_view_get_zoom_level(c->view);
1304 scroll_v(Client *c, const Arg *a)
1306 evalscript(c, "window.scrollBy(0, %d * (window.innerHeight / 100))",
1311 scroll_h(Client *c, const Arg *a)
1313 evalscript(c, "window.scrollBy(%d * (window.innerWidth / 100), 0)",
1318 navigate(Client *c, const Arg *a)
1321 webkit_web_view_go_back(c->view);
1323 webkit_web_view_go_forward(c->view);
1327 stop(Client *c, const Arg *arg)
1329 webkit_web_view_stop_loading(c->view);
1333 toggle(Client *c, const Arg *a)
1337 s = webkit_web_view_get_settings(c->view);
1339 switch ((unsigned int)a->i) {
1341 enablecaretbrowsing = !enablecaretbrowsing;
1342 webkit_settings_set_enable_caret_browsing(s,
1343 enablecaretbrowsing);
1345 return; /* do not reload */
1347 case FrameFlattening:
1348 enableframeflattening = !enableframeflattening;
1349 webkit_settings_set_enable_frame_flattening(s,
1350 enableframeflattening);
1353 allowgeolocation = !allowgeolocation;
1356 enablescripts = !enablescripts;
1357 webkit_settings_set_enable_javascript(s, enablescripts);
1360 loadimages = !loadimages;
1361 webkit_settings_set_auto_load_images(s, loadimages);
1364 enableplugins = !enableplugins;
1365 webkit_settings_set_enable_plugins(s, enableplugins);
1368 /* Disabled until we write some WebKitWebExtension for
1369 * manipulating the DOM directly.
1370 enablescrollbars = !enablescrollbars;
1371 evalscript(c, "document.documentElement.style.overflow = '%s'",
1372 enablescrollbars ? "auto" : "hidden");
1374 return; /* do not reload */
1383 togglefullscreen(Client *c, const Arg *a)
1385 /* toggling value is handled in winevent() */
1387 gtk_window_unfullscreen(GTK_WINDOW(c->win));
1389 gtk_window_fullscreen(GTK_WINDOW(c->win));
1393 togglecookiepolicy(Client *c, const Arg *arg)
1396 cookiepolicy %= strlen(cookiepolicies);
1398 webkit_cookie_manager_set_accept_policy(
1399 webkit_web_context_get_cookie_manager(
1400 webkit_web_view_get_context(c->view)),
1401 cookiepolicy_get());
1404 /* Do not reload. */
1408 togglestyle(Client *c, const Arg *arg)
1410 enablestyle = !enablestyle;
1411 setstyle(c, enablestyle ? getstyle(geturi(c)) : "");
1417 toggleinspector(Client *c, const Arg *a)
1419 if (enableinspector) {
1420 if (webkit_web_inspector_is_attached(c->inspector))
1421 webkit_web_inspector_close(c->inspector);
1423 webkit_web_inspector_show(c->inspector);
1428 find(Client *c, const Arg *a)
1434 webkit_find_controller_search_next(c->finder);
1436 webkit_find_controller_search_previous(c->finder);
1438 s = getatom(c, AtomFind);
1439 f = webkit_find_controller_get_search_text(c->finder);
1441 if (g_strcmp0(f, s) == 0) /* reset search */
1442 webkit_find_controller_search(c->finder, "", findopts, G_MAXUINT);
1444 webkit_find_controller_search(c->finder, s, findopts, G_MAXUINT);
1446 if (strcmp(s, "") == 0)
1447 webkit_find_controller_search_finish(c->finder);
1452 clicknavigate(Client *c, const Arg *a, WebKitHitTestResult *h)
1458 clicknewwindow(Client *c, const Arg *a, WebKitHitTestResult *h)
1462 arg.v = webkit_hit_test_result_get_link_uri(h);
1463 newwindow(c, &arg, a->b);
1467 clickexternplayer(Client *c, const Arg *a, WebKitHitTestResult *h)
1471 if (webkit_hit_test_result_get_context(h) & OnMedia) {
1472 arg = (Arg)VIDEOPLAY(webkit_hit_test_result_get_media_uri(h));
1478 main(int argc, char *argv[])
1483 memset(&arg, 0, sizeof(arg));
1485 /* command line args */
1488 cookiepolicies = EARGF(usage());
1491 enablescrollbars = 0;
1494 enablescrollbars = 1;
1497 cookiefile = EARGF(usage());
1506 embed = strtol(EARGF(usage()), NULL, 0);
1509 runinfullscreen = 0;
1512 runinfullscreen = 1;
1515 allowgeolocation = 0;
1518 allowgeolocation = 1;
1539 enableinspector = 0;
1542 enableinspector = 1;
1551 scriptfile = EARGF(usage());
1560 stylefile = EARGF(usage());
1563 useragent = EARGF(usage());
1566 die("surf-"VERSION", ©2009-2015 surf engineers, "
1567 "see LICENSE for details\n");
1572 zoomlevel = strtof(EARGF(usage()), NULL);
1581 c = newclient(NULL);
1584 loaduri(clients, &arg);
1591 return EXIT_SUCCESS;