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))
34 #define SETB(p, s) [p] = { { .b = s }, }
35 #define SETI(p, s) [p] = { { .i = s }, }
36 #define SETV(p, s) [p] = { { .v = s }, }
37 #define SETF(p, s) [p] = { { .f = s }, }
38 #define FSETB(p, s) [p] = { { .b = s }, 1 }
39 #define FSETI(p, s) [p] = { { .i = s }, 1 }
40 #define FSETV(p, s) [p] = { { .v = s }, 1 }
41 #define FSETF(p, s) [p] = { { .f = s }, 1 }
42 #define CSETB(p, s) [p] = (Parameter){ { .b = s }, 1 }
43 #define CSETI(p, s) [p] = (Parameter){ { .i = s }, 1 }
44 #define CSETV(p, s) [p] = (Parameter){ { .v = s }, 1 }
45 #define CSETF(p, s) [p] = (Parameter){ { .f = s }, 1 }
47 enum { AtomFind, AtomGo, AtomUri, AtomLast };
50 OnDoc = WEBKIT_HIT_TEST_RESULT_CONTEXT_DOCUMENT,
51 OnLink = WEBKIT_HIT_TEST_RESULT_CONTEXT_LINK,
52 OnImg = WEBKIT_HIT_TEST_RESULT_CONTEXT_IMAGE,
53 OnMedia = WEBKIT_HIT_TEST_RESULT_CONTEXT_MEDIA,
54 OnEdit = WEBKIT_HIT_TEST_RESULT_CONTEXT_EDITABLE,
55 OnBar = WEBKIT_HIT_TEST_RESULT_CONTEXT_SCROLLBAR,
56 OnSel = WEBKIT_HIT_TEST_RESULT_CONTEXT_SELECTION,
57 OnAny = OnDoc | OnLink | OnImg | OnMedia | OnEdit | OnBar | OnSel,
102 typedef struct Client {
105 WebKitWebInspector *inspector;
106 WebKitFindController *finder;
107 WebKitHitTestResult *mousepos;
108 GTlsCertificateFlags tlserr;
110 int progress, fullscreen, https, insecure;
111 const char *title, *overtitle, *targeturi;
119 void (*func)(Client *c, const Arg *a);
127 void (*func)(Client *c, const Arg *a, WebKitHitTestResult *h);
129 unsigned int stopevent;
134 Parameter config[ParameterLast];
145 static void usage(void);
146 static void die(const char *errstr, ...);
147 static void setup(void);
148 static void sigchld(int unused);
149 static void sighup(int unused);
150 static char *buildfile(const char *path);
151 static char *buildpath(const char *path);
152 static const char *getuserhomedir(const char *user);
153 static const char *getcurrentuserhomedir(void);
154 static Client *newclient(Client *c);
155 static void loaduri(Client *c, const Arg *a);
156 static const char *geturi(Client *c);
157 static void setatom(Client *c, int a, const char *v);
158 static const char *getatom(Client *c, int a);
159 static void updatetitle(Client *c);
160 static void gettogglestats(Client *c);
161 static void getpagestats(Client *c);
162 static WebKitCookieAcceptPolicy cookiepolicy_get(void);
163 static char cookiepolicy_set(const WebKitCookieAcceptPolicy p);
164 static void seturiparameters(Client *c, const char *uri);
165 static void setparameter(Client *c, int refresh, ParamName p, const Arg *a);
166 static const char *getcert(const char *uri);
167 static void setcert(Client *c, const char *file);
168 static const char *getstyle(const char *uri);
169 static void setstyle(Client *c, const char *file);
170 static void runscript(Client *c);
171 static void evalscript(Client *c, const char *jsstr, ...);
172 static void updatewinid(Client *c);
173 static void handleplumb(Client *c, const char *uri);
174 static void newwindow(Client *c, const Arg *a, int noembed);
175 static void spawn(Client *c, const Arg *a);
176 static void destroyclient(Client *c);
177 static void cleanup(void);
180 static WebKitWebView *newview(Client *c, WebKitWebView *rv);
181 static void initwebextensions(WebKitWebContext *wc, Client *c);
182 static GtkWidget *createview(WebKitWebView *v, WebKitNavigationAction *a,
184 static gboolean buttonreleased(GtkWidget *w, GdkEvent *e, Client *c);
185 static GdkFilterReturn processx(GdkXEvent *xevent, GdkEvent *event,
187 static gboolean winevent(GtkWidget *w, GdkEvent *e, Client *c);
188 static void showview(WebKitWebView *v, Client *c);
189 static GtkWidget *createwindow(Client *c);
190 static void loadchanged(WebKitWebView *v, WebKitLoadEvent e, Client *c);
191 static void progresschanged(WebKitWebView *v, GParamSpec *ps, Client *c);
192 static void titlechanged(WebKitWebView *view, GParamSpec *ps, Client *c);
193 static void mousetargetchanged(WebKitWebView *v, WebKitHitTestResult *h,
194 guint modifiers, Client *c);
195 static gboolean permissionrequested(WebKitWebView *v,
196 WebKitPermissionRequest *r, Client *c);
197 static gboolean decidepolicy(WebKitWebView *v, WebKitPolicyDecision *d,
198 WebKitPolicyDecisionType dt, Client *c);
199 static void decidenavigation(WebKitPolicyDecision *d, Client *c);
200 static void decidenewwindow(WebKitPolicyDecision *d, Client *c);
201 static void decideresource(WebKitPolicyDecision *d, Client *c);
202 static void insecurecontent(WebKitWebView *v, WebKitInsecureContentEvent e,
204 static void downloadstarted(WebKitWebContext *wc, WebKitDownload *d,
206 static void responsereceived(WebKitDownload *d, GParamSpec *ps, Client *c);
207 static void download(Client *c, WebKitURIResponse *r);
208 static void closeview(WebKitWebView *v, Client *c);
209 static void destroywin(GtkWidget* w, Client *c);
212 static void pasteuri(GtkClipboard *clipboard, const char *text, gpointer d);
213 static void reload(Client *c, const Arg *a);
214 static void print(Client *c, const Arg *a);
215 static void clipboard(Client *c, const Arg *a);
216 static void zoom(Client *c, const Arg *a);
217 static void scroll(Client *c, const Arg *a);
218 static void navigate(Client *c, const Arg *a);
219 static void stop(Client *c, const Arg *a);
220 static void toggle(Client *c, const Arg *a);
221 static void togglefullscreen(Client *c, const Arg *a);
222 static void togglecookiepolicy(Client *c, const Arg *a);
223 static void toggleinspector(Client *c, const Arg *a);
224 static void find(Client *c, const Arg *a);
227 static void clicknavigate(Client *c, const Arg *a, WebKitHitTestResult *h);
228 static void clicknewwindow(Client *c, const Arg *a, WebKitHitTestResult *h);
229 static void clickexternplayer(Client *c, const Arg *a, WebKitHitTestResult *h);
231 static char winid[64];
232 static char togglestats[11];
233 static char pagestats[2];
234 static Atom atoms[AtomLast];
237 static int cookiepolicy;
239 static Client *clients;
240 static GdkDevice *gdkkb;
241 static char *stylefile;
242 static const char *useragent;
243 static Parameter *curconfig;
246 /* configuration, allows nested code to access above variables */
252 die("usage: %s [-bBdDfFgGiIkKmMnNpPsStTvx] [-a cookiepolicies ] "
253 "[-c cookiefile] [-C stylefile] [-e xid] [-r scriptfile] "
254 "[-u useragent] [-z zoomlevel] [uri]\n", basename(argv0));
258 die(const char *errstr, ...)
262 va_start(ap, errstr);
263 vfprintf(stderr, errstr, ap);
274 /* clean up any zombies immediately */
276 if (signal(SIGHUP, sighup) == SIG_ERR)
277 die("Can't install SIGHUP handler");
279 if (!(dpy = XOpenDisplay(NULL)))
280 die("Can't open default display");
283 atoms[AtomFind] = XInternAtom(dpy, "_SURF_FIND", False);
284 atoms[AtomGo] = XInternAtom(dpy, "_SURF_GO", False);
285 atoms[AtomUri] = XInternAtom(dpy, "_SURF_URI", False);
287 gtk_init(NULL, NULL);
289 gdpy = gdk_display_get_default();
291 curconfig = defconfig;
294 cookiefile = buildfile(cookiefile);
295 scriptfile = buildfile(scriptfile);
296 cachedir = buildpath(cachedir);
297 certdir = buildpath(certdir);
299 gdkkb = gdk_seat_get_keyboard(gdk_display_get_default_seat(gdpy));
301 for (i = 0; i < LENGTH(certs); ++i) {
302 if (!regcomp(&(certs[i].re), certs[i].regex, REG_EXTENDED)) {
303 certs[i].file = g_strconcat(certdir, "/", certs[i].file,
306 fprintf(stderr, "Could not compile regex: %s\n",
308 certs[i].regex = NULL;
313 styledir = buildpath(styledir);
314 for (i = 0; i < LENGTH(styles); ++i) {
315 if (!regcomp(&(styles[i].re), styles[i].regex,
317 styles[i].file = g_strconcat(styledir, "/",
318 styles[i].file, NULL);
320 fprintf(stderr, "Could not compile regex: %s\n",
322 styles[i].regex = NULL;
327 stylefile = buildfile(stylefile);
330 for (i = 0; i < LENGTH(uriparams); ++i) {
331 if (!regcomp(&(uriparams[i].re), uriparams[i].uri,
333 /* copy default parameters if they are not already set
334 * or if they are forced */
335 for (j = 0; j < ParameterLast; ++j) {
336 if (!uriparams[i].config[j].force ||
338 uriparams[i].config[j] = defconfig[j];
341 fprintf(stderr, "Could not compile regex: %s\n",
343 uriparams[i].uri = NULL;
351 if (signal(SIGCHLD, sigchld) == SIG_ERR)
352 die("Can't install SIGCHLD handler");
353 while (waitpid(-1, NULL, WNOHANG) > 0)
363 for (c = clients; c; c = c->next)
368 buildfile(const char *path)
370 char *dname, *bname, *bpath, *fpath;
373 dname = g_path_get_dirname(path);
374 bname = g_path_get_basename(path);
376 bpath = buildpath(dname);
379 fpath = g_build_filename(bpath, bname, NULL);
383 if (!(f = fopen(fpath, "a")))
384 die("Could not open file: %s\n", fpath);
386 g_chmod(fpath, 0600); /* always */
393 getuserhomedir(const char *user)
395 struct passwd *pw = getpwnam(user);
398 die("Can't get user %s login information.\n", user);
404 getcurrentuserhomedir(void)
410 homedir = getenv("HOME");
414 user = getenv("USER");
416 return getuserhomedir(user);
418 pw = getpwuid(getuid());
420 die("Can't get current user home directory\n");
426 buildpath(const char *path)
428 char *apath, *name, *p, *fpath;
431 if (path[0] == '~') {
432 if (path[1] == '/' || path[1] == '\0') {
433 p = (char *)&path[1];
434 homedir = getcurrentuserhomedir();
436 if ((p = strchr(path, '/')))
437 name = g_strndup(&path[1], --p - path);
439 name = g_strdup(&path[1]);
441 homedir = getuserhomedir(name);
444 apath = g_build_filename(homedir, p, NULL);
446 apath = g_strdup(path);
449 /* creating directory */
450 if (g_mkdir_with_parents(apath, 0700) < 0)
451 die("Could not access directory: %s\n", apath);
453 fpath = realpath(apath, NULL);
460 newclient(Client *rc)
464 if (!(c = calloc(1, sizeof(Client))))
465 die("Cannot malloc!\n");
471 c->view = newview(c, rc ? rc->view : NULL);
477 loaduri(Client *c, const Arg *a)
481 const char *uri = a->v;
483 if (g_strcmp0(uri, "") == 0)
486 if (g_str_has_prefix(uri, "http://") ||
487 g_str_has_prefix(uri, "https://") ||
488 g_str_has_prefix(uri, "file://") ||
489 g_str_has_prefix(uri, "about:")) {
491 } else if (!stat(uri, &st) && (path = realpath(uri, NULL))) {
492 url = g_strdup_printf("file://%s", path);
495 url = g_strdup_printf("http://%s", uri);
498 setatom(c, AtomUri, url);
500 if (strcmp(url, geturi(c)) == 0) {
503 webkit_web_view_load_uri(c->view, url);
515 if (!(uri = webkit_web_view_get_uri(c->view)))
521 setatom(Client *c, int a, const char *v)
524 XChangeProperty(dpy, c->xid,
525 atoms[a], XA_STRING, 8, PropModeReplace,
526 (unsigned char *)v, strlen(v) + 1);
530 getatom(Client *c, int a)
532 static char buf[BUFSIZ];
535 unsigned long ldummy;
536 unsigned char *p = NULL;
538 XGetWindowProperty(dpy, c->xid, atoms[a], 0L, BUFSIZ, False, XA_STRING,
539 &adummy, &idummy, &ldummy, &ldummy, &p);
541 strncpy(buf, (char *)p, LENGTH(buf) - 1);
550 updatetitle(Client *c)
553 const char *name = c->overtitle ? c->overtitle :
554 c->title ? c->title : "";
556 if (curconfig[ShowIndicators].val.b) {
560 if (c->progress != 100)
561 title = g_strdup_printf("[%i%%] %s:%s | %s",
562 c->progress, togglestats, pagestats, name);
564 title = g_strdup_printf("%s:%s | %s",
565 togglestats, pagestats, name);
567 gtk_window_set_title(GTK_WINDOW(c->win), title);
570 gtk_window_set_title(GTK_WINDOW(c->win), name);
575 gettogglestats(Client *c)
577 togglestats[0] = cookiepolicy_set(cookiepolicy_get());
578 togglestats[1] = curconfig[CaretBrowsing].val.b ? 'C' : 'c';
579 togglestats[2] = curconfig[Geolocation].val.b ? 'G' : 'g';
580 togglestats[3] = curconfig[DiskCache].val.b ? 'D' : 'd';
581 togglestats[4] = curconfig[LoadImages].val.b ? 'I' : 'i';
582 togglestats[5] = curconfig[JavaScript].val.b ? 'S' : 's';
583 togglestats[6] = curconfig[Plugins].val.b ? 'V' : 'v';
584 togglestats[7] = curconfig[Style].val.b ? 'M' : 'm';
585 togglestats[8] = curconfig[FrameFlattening].val.b ? 'F' : 'f';
586 togglestats[9] = curconfig[StrictTLS].val.b ? 'T' : 't';
587 togglestats[10] = '\0';
591 getpagestats(Client *c)
594 pagestats[0] = (c->tlserr || c->insecure) ? 'U' : 'T';
600 WebKitCookieAcceptPolicy
601 cookiepolicy_get(void)
603 switch (((char *)curconfig[CookiePolicies].val.v)[cookiepolicy]) {
605 return WEBKIT_COOKIE_POLICY_ACCEPT_NEVER;
607 return WEBKIT_COOKIE_POLICY_ACCEPT_NO_THIRD_PARTY;
608 default: /* fallthrough */
610 return WEBKIT_COOKIE_POLICY_ACCEPT_ALWAYS;
615 cookiepolicy_set(const WebKitCookieAcceptPolicy p)
618 case WEBKIT_COOKIE_POLICY_ACCEPT_NEVER:
620 case WEBKIT_COOKIE_POLICY_ACCEPT_NO_THIRD_PARTY:
622 default: /* fallthrough */
623 case WEBKIT_COOKIE_POLICY_ACCEPT_ALWAYS:
629 seturiparameters(Client *c, const char *uri)
633 for (i = 0; i < LENGTH(uriparams); ++i) {
634 if (uriparams[i].uri &&
635 !regexec(&(uriparams[i].re), uri, 0, NULL, 0)) {
636 curconfig = uriparams[i].config;
641 for (i = 0; i < ParameterLast; ++i)
642 setparameter(c, 0, i, &curconfig[i].val);
646 setparameter(Client *c, int refresh, ParamName p, const Arg *a)
648 GdkRGBA bgcolor = { 0 };
649 WebKitSettings *s = webkit_web_view_get_settings(c->view);
652 case AcceleratedCanvas:
653 webkit_settings_set_enable_accelerated_2d_canvas(s, a->b);
656 webkit_settings_set_enable_caret_browsing(s, a->b);
661 setcert(c, geturi(c));
662 return; /* do not update */
664 webkit_cookie_manager_set_accept_policy(
665 webkit_web_context_get_cookie_manager(
666 webkit_web_view_get_context(c->view)),
671 webkit_web_context_set_cache_model(
672 webkit_web_view_get_context(c->view), a->b ?
673 WEBKIT_CACHE_MODEL_WEB_BROWSER :
674 WEBKIT_CACHE_MODEL_DOCUMENT_VIEWER);
675 return; /* do not update */
677 webkit_settings_set_enable_dns_prefetching(s, a->b);
678 return; /* do not update */
680 webkit_settings_set_default_font_size(s, a->i);
681 return; /* do not update */
682 case FrameFlattening:
683 webkit_settings_set_enable_frame_flattening(s, a->b);
690 webkit_web_view_set_background_color(c->view, &bgcolor);
691 return; /* do not update */
693 webkit_settings_set_enable_developer_extras(s, a->b);
694 return; /* do not update */
696 webkit_settings_set_enable_javascript(s, a->b);
699 return; /* do nothing */
701 webkit_settings_set_auto_load_images(s, a->b);
703 case MediaManualPlay:
704 webkit_settings_set_media_playback_requires_user_gesture(s, a->b);
707 webkit_settings_set_enable_plugins(s, a->b);
709 case PreferredLanguages:
710 return; /* do nothing */
711 case RunInFullscreen:
712 return; /* do nothing */
714 /* Disabled until we write some WebKitWebExtension for
715 * manipulating the DOM directly.
716 enablescrollbars = !enablescrollbars;
717 evalscript(c, "document.documentElement.style.overflow = '%s'",
718 enablescrollbars ? "auto" : "hidden");
720 return; /* do not update */
724 webkit_settings_set_enable_site_specific_quirks(s, a->b);
727 webkit_web_context_set_spell_checking_enabled(
728 webkit_web_view_get_context(c->view), a->b);
729 return; /* do not update */
731 return; /* do nothing */
733 webkit_web_context_set_tls_errors_policy(
734 webkit_web_view_get_context(c->view), a->b ?
735 WEBKIT_TLS_ERRORS_POLICY_FAIL :
736 WEBKIT_TLS_ERRORS_POLICY_IGNORE);
740 setstyle(c, getstyle(geturi(c)));
742 webkit_user_content_manager_remove_all_style_sheets(
743 webkit_web_view_get_user_content_manager(c->view));
747 webkit_web_view_set_zoom_level(c->view, a->f);
748 return; /* do not update */
750 return; /* do nothing */
759 getcert(const char *uri)
763 for (i = 0; i < LENGTH(certs); ++i) {
764 if (certs[i].regex &&
765 !regexec(&(certs[i].re), uri, 0, NULL, 0))
766 return certs[i].file;
773 setcert(Client *c, const char *uri)
775 const char *file = getcert(uri);
777 GTlsCertificate *cert;
782 if (!(cert = g_tls_certificate_new_from_file(file, NULL))) {
783 fprintf(stderr, "Could not read certificate file: %s\n", file);
787 uri = strstr(uri, "://") + sizeof("://") - 1;
788 host = strndup(uri, strstr(uri, "/") - uri);
790 webkit_web_context_allow_tls_certificate_for_host(
791 webkit_web_view_get_context(c->view), cert, host);
797 getstyle(const char *uri)
804 for (i = 0; i < LENGTH(styles); ++i) {
805 if (styles[i].regex &&
806 !regexec(&(styles[i].re), uri, 0, NULL, 0))
807 return styles[i].file;
814 setstyle(Client *c, const char *file)
818 if (!g_file_get_contents(file, &style, NULL, NULL)) {
819 fprintf(stderr, "Could not read style file: %s\n", file);
823 webkit_user_content_manager_add_style_sheet(
824 webkit_web_view_get_user_content_manager(c->view),
825 webkit_user_style_sheet_new(style,
826 WEBKIT_USER_CONTENT_INJECT_ALL_FRAMES,
827 WEBKIT_USER_STYLE_LEVEL_USER,
839 if (g_file_get_contents(scriptfile, &script, &l, NULL) && l)
840 evalscript(c, script);
845 evalscript(Client *c, const char *jsstr, ...)
851 script = g_strdup_vprintf(jsstr, ap);
854 webkit_web_view_run_javascript(c->view, script, NULL, NULL, NULL);
859 updatewinid(Client *c)
861 snprintf(winid, LENGTH(winid), "%lu", c->xid);
865 handleplumb(Client *c, const char *uri)
867 Arg a = (Arg)PLUMB(uri);
872 newwindow(Client *c, const Arg *a, int noembed)
876 const char *cmd[28], *uri;
877 const Arg arg = { .v = cmd };
881 cmd[i++] = curconfig[CookiePolicies].val.v;
882 cmd[i++] = curconfig[ScrollBars].val.b ? "-B" : "-b";
883 if (cookiefile && g_strcmp0(cookiefile, "")) {
885 cmd[i++] = cookiefile;
887 if (stylefile && g_strcmp0(stylefile, "")) {
889 cmd[i++] = stylefile;
891 cmd[i++] = curconfig[DiskCache].val.b ? "-D" : "-d";
892 if (embed && !noembed) {
894 snprintf(tmp, LENGTH(tmp), "%lu", embed);
897 cmd[i++] = curconfig[RunInFullscreen].val.b ? "-F" : "-f" ;
898 cmd[i++] = curconfig[Geolocation].val.b ? "-G" : "-g" ;
899 cmd[i++] = curconfig[LoadImages].val.b ? "-I" : "-i" ;
900 cmd[i++] = curconfig[KioskMode].val.b ? "-K" : "-k" ;
901 cmd[i++] = curconfig[Style].val.b ? "-M" : "-m" ;
902 cmd[i++] = curconfig[Inspector].val.b ? "-N" : "-n" ;
903 cmd[i++] = curconfig[Plugins].val.b ? "-P" : "-p" ;
904 if (scriptfile && g_strcmp0(scriptfile, "")) {
906 cmd[i++] = scriptfile;
908 cmd[i++] = curconfig[JavaScript].val.b ? "-S" : "-s";
909 cmd[i++] = curconfig[StrictTLS].val.b ? "-T" : "-t";
910 if (fulluseragent && g_strcmp0(fulluseragent, "")) {
912 cmd[i++] = fulluseragent;
916 /* do not keep zoom level */
926 spawn(Client *c, const Arg *a)
930 close(ConnectionNumber(dpy));
932 execvp(((char **)a->v)[0], (char **)a->v);
933 fprintf(stderr, "%s: execvp %s", argv0, ((char **)a->v)[0]);
940 destroyclient(Client *c)
944 webkit_web_view_stop_loading(c->view);
945 /* Not needed, has already been called
946 gtk_widget_destroy(c->win);
949 for (p = clients; p && p->next != c; p = p->next)
962 destroyclient(clients);
971 newview(Client *c, WebKitWebView *rv)
974 WebKitSettings *settings;
975 WebKitUserContentManager *contentmanager;
976 WebKitWebContext *context;
981 webkit_web_view_new_with_related_view(rv));
983 settings = webkit_settings_new_with_settings(
984 "auto-load-images", curconfig[LoadImages].val.b,
985 "default-font-size", curconfig[FontSize].val.i,
986 "enable-caret-browsing", curconfig[CaretBrowsing].val.b,
987 "enable-developer-extras", curconfig[Inspector].val.b,
988 "enable-dns-prefetching", curconfig[DNSPrefetch].val.b,
989 "enable-frame-flattening", curconfig[FrameFlattening].val.b,
990 "enable-html5-database", curconfig[DiskCache].val.b,
991 "enable-html5-local-storage", curconfig[DiskCache].val.b,
992 "enable-javascript", curconfig[JavaScript].val.b,
993 "enable-plugins", curconfig[Plugins].val.b,
994 "enable-accelerated-2d-canvas", curconfig[AcceleratedCanvas].val.b,
995 "enable-site-specific-quirks", curconfig[SiteQuirks].val.b,
996 "media-playback-requires-user-gesture", curconfig[MediaManualPlay].val.b,
998 /* For mor interesting settings, have a look at
999 * http://webkitgtk.org/reference/webkit2gtk/stable/WebKitSettings.html */
1001 if (strcmp(fulluseragent, "")) {
1002 webkit_settings_set_user_agent(settings, fulluseragent);
1003 } else if (surfuseragent) {
1004 webkit_settings_set_user_agent_with_application_details(
1005 settings, "Surf", VERSION);
1007 useragent = webkit_settings_get_user_agent(settings);
1009 contentmanager = webkit_user_content_manager_new();
1011 context = webkit_web_context_new_with_website_data_manager(
1012 webkit_website_data_manager_new(
1013 "base-cache-directory", cachedir,
1014 "base-data-directory", cachedir,
1017 /* rendering process model, can be a shared unique one
1018 * or one for each view */
1019 webkit_web_context_set_process_model(context,
1020 WEBKIT_PROCESS_MODEL_MULTIPLE_SECONDARY_PROCESSES);
1022 webkit_web_context_set_tls_errors_policy(context,
1023 curconfig[StrictTLS].val.b ? WEBKIT_TLS_ERRORS_POLICY_FAIL :
1024 WEBKIT_TLS_ERRORS_POLICY_IGNORE);
1026 webkit_web_context_set_cache_model(context,
1027 curconfig[DiskCache].val.b ? WEBKIT_CACHE_MODEL_WEB_BROWSER :
1028 WEBKIT_CACHE_MODEL_DOCUMENT_VIEWER);
1030 /* Currently only works with text file to be compatible with curl */
1031 webkit_cookie_manager_set_persistent_storage(
1032 webkit_web_context_get_cookie_manager(context), cookiefile,
1033 WEBKIT_COOKIE_PERSISTENT_STORAGE_TEXT);
1035 webkit_cookie_manager_set_accept_policy(
1036 webkit_web_context_get_cookie_manager(context),
1037 cookiepolicy_get());
1039 webkit_web_context_set_preferred_languages(context,
1040 curconfig[PreferredLanguages].val.v);
1041 webkit_web_context_set_spell_checking_languages(context,
1042 curconfig[SpellLanguages].val.v);
1043 webkit_web_context_set_spell_checking_enabled(context,
1044 curconfig[SpellChecking].val.b);
1046 g_signal_connect(G_OBJECT(context), "download-started",
1047 G_CALLBACK(downloadstarted), c);
1048 g_signal_connect(G_OBJECT(context), "initialize-web-extensions",
1049 G_CALLBACK(initwebextensions), c);
1051 v = g_object_new(WEBKIT_TYPE_WEB_VIEW,
1052 "settings", settings,
1053 "user-content-manager", contentmanager,
1054 "web-context", context,
1058 g_signal_connect(G_OBJECT(v), "notify::estimated-load-progress",
1059 G_CALLBACK(progresschanged), c);
1060 g_signal_connect(G_OBJECT(v), "notify::title",
1061 G_CALLBACK(titlechanged), c);
1062 g_signal_connect(G_OBJECT(v), "button-release-event",
1063 G_CALLBACK(buttonreleased), c);
1064 g_signal_connect(G_OBJECT(v), "close",
1065 G_CALLBACK(closeview), c);
1066 g_signal_connect(G_OBJECT(v), "create",
1067 G_CALLBACK(createview), c);
1068 g_signal_connect(G_OBJECT(v), "decide-policy",
1069 G_CALLBACK(decidepolicy), c);
1070 g_signal_connect(G_OBJECT(v), "insecure-content-detected",
1071 G_CALLBACK(insecurecontent), c);
1072 g_signal_connect(G_OBJECT(v), "load-changed",
1073 G_CALLBACK(loadchanged), c);
1074 g_signal_connect(G_OBJECT(v), "mouse-target-changed",
1075 G_CALLBACK(mousetargetchanged), c);
1076 g_signal_connect(G_OBJECT(v), "permission-request",
1077 G_CALLBACK(permissionrequested), c);
1078 g_signal_connect(G_OBJECT(v), "ready-to-show",
1079 G_CALLBACK(showview), c);
1085 initwebextensions(WebKitWebContext *wc, Client *c)
1087 webkit_web_context_set_web_extensions_directory(wc, WEBEXTDIR);
1091 createview(WebKitWebView *v, WebKitNavigationAction *a, Client *c)
1095 switch (webkit_navigation_action_get_navigation_type(a)) {
1096 case WEBKIT_NAVIGATION_TYPE_OTHER: /* fallthrough */
1098 * popup windows of type “other” are almost always triggered
1099 * by user gesture, so inverse the logic here
1101 /* instead of this, compare destination uri to mouse-over uri for validating window */
1102 if (webkit_navigation_action_is_user_gesture(a))
1104 case WEBKIT_NAVIGATION_TYPE_LINK_CLICKED: /* fallthrough */
1105 case WEBKIT_NAVIGATION_TYPE_FORM_SUBMITTED: /* fallthrough */
1106 case WEBKIT_NAVIGATION_TYPE_BACK_FORWARD: /* fallthrough */
1107 case WEBKIT_NAVIGATION_TYPE_RELOAD: /* fallthrough */
1108 case WEBKIT_NAVIGATION_TYPE_FORM_RESUBMITTED:
1115 return GTK_WIDGET(n->view);
1119 buttonreleased(GtkWidget *w, GdkEvent *e, Client *c)
1121 WebKitHitTestResultContext element;
1124 element = webkit_hit_test_result_get_context(c->mousepos);
1126 for (i = 0; i < LENGTH(buttons); ++i) {
1127 if (element & buttons[i].target &&
1128 e->button.button == buttons[i].button &&
1129 CLEANMASK(e->button.state) == CLEANMASK(buttons[i].mask) &&
1131 buttons[i].func(c, &buttons[i].arg, c->mousepos);
1132 return buttons[i].stopevent;
1140 processx(GdkXEvent *e, GdkEvent *event, gpointer d)
1142 Client *c = (Client *)d;
1146 if (((XEvent *)e)->type == PropertyNotify) {
1147 ev = &((XEvent *)e)->xproperty;
1148 if (ev->state == PropertyNewValue) {
1149 if (ev->atom == atoms[AtomFind]) {
1152 return GDK_FILTER_REMOVE;
1153 } else if (ev->atom == atoms[AtomGo]) {
1154 a.v = getatom(c, AtomGo);
1157 return GDK_FILTER_REMOVE;
1161 return GDK_FILTER_CONTINUE;
1165 winevent(GtkWidget *w, GdkEvent *e, Client *c)
1170 case GDK_ENTER_NOTIFY:
1171 c->overtitle = c->targeturi;
1175 if (!curconfig[KioskMode].val.b) {
1176 for (i = 0; i < LENGTH(keys); ++i) {
1177 if (gdk_keyval_to_lower(e->key.keyval) ==
1179 CLEANMASK(e->key.state) == keys[i].mod &&
1182 keys[i].func(c, &(keys[i].arg));
1187 case GDK_LEAVE_NOTIFY:
1188 c->overtitle = NULL;
1191 case GDK_WINDOW_STATE:
1192 if (e->window_state.changed_mask ==
1193 GDK_WINDOW_STATE_FULLSCREEN)
1194 c->fullscreen = e->window_state.new_window_state &
1195 GDK_WINDOW_STATE_FULLSCREEN;
1205 showview(WebKitWebView *v, Client *c)
1207 GdkRGBA bgcolor = { 0 };
1210 c->finder = webkit_web_view_get_find_controller(c->view);
1211 c->inspector = webkit_web_view_get_inspector(c->view);
1213 c->win = createwindow(c);
1215 gtk_container_add(GTK_CONTAINER(c->win), GTK_WIDGET(c->view));
1216 gtk_widget_show_all(c->win);
1217 gtk_widget_grab_focus(GTK_WIDGET(c->view));
1219 gwin = gtk_widget_get_window(GTK_WIDGET(c->win));
1220 c->xid = gdk_x11_window_get_xid(gwin);
1223 gdk_display_sync(gtk_widget_get_display(c->win));
1227 if (curconfig[HideBackground].val.b)
1228 webkit_web_view_set_background_color(c->view, &bgcolor);
1230 if (!curconfig[KioskMode].val.b) {
1231 gdk_window_set_events(gwin, GDK_ALL_EVENTS_MASK);
1232 gdk_window_add_filter(gwin, processx, c);
1235 if (curconfig[RunInFullscreen].val.b)
1236 togglefullscreen(c, NULL);
1238 if (curconfig[ZoomLevel].val.f != 1.0)
1239 webkit_web_view_set_zoom_level(c->view,
1240 curconfig[ZoomLevel].val.f);
1242 setatom(c, AtomFind, "");
1243 setatom(c, AtomUri, "about:blank");
1247 createwindow(Client *c)
1253 w = gtk_plug_new(embed);
1255 w = gtk_window_new(GTK_WINDOW_TOPLEVEL);
1257 wmstr = g_path_get_basename(argv0);
1258 gtk_window_set_wmclass(GTK_WINDOW(w), wmstr, "Surf");
1261 wmstr = g_strdup_printf("%s[%lu]", "Surf",
1262 webkit_web_view_get_page_id(c->view));
1263 gtk_window_set_role(GTK_WINDOW(w), wmstr);
1266 gtk_window_set_default_size(GTK_WINDOW(w), winsize[0], winsize[1]);
1269 g_signal_connect(G_OBJECT(w), "destroy",
1270 G_CALLBACK(destroywin), c);
1271 g_signal_connect(G_OBJECT(w), "enter-notify-event",
1272 G_CALLBACK(winevent), c);
1273 g_signal_connect(G_OBJECT(w), "key-press-event",
1274 G_CALLBACK(winevent), c);
1275 g_signal_connect(G_OBJECT(w), "leave-notify-event",
1276 G_CALLBACK(winevent), c);
1277 g_signal_connect(G_OBJECT(w), "window-state-event",
1278 G_CALLBACK(winevent), c);
1284 loadchanged(WebKitWebView *v, WebKitLoadEvent e, Client *c)
1286 const char *title = geturi(c);
1289 case WEBKIT_LOAD_STARTED:
1290 curconfig = defconfig;
1291 setatom(c, AtomUri, title);
1293 c->https = c->insecure = 0;
1294 seturiparameters(c, geturi(c));
1296 case WEBKIT_LOAD_REDIRECTED:
1297 setatom(c, AtomUri, title);
1299 seturiparameters(c, geturi(c));
1301 case WEBKIT_LOAD_COMMITTED:
1302 c->https = webkit_web_view_get_tls_info(c->view, NULL,
1305 case WEBKIT_LOAD_FINISHED:
1306 /* Disabled until we write some WebKitWebExtension for
1307 * manipulating the DOM directly.
1308 evalscript(c, "document.documentElement.style.overflow = '%s'",
1309 enablescrollbars ? "auto" : "hidden");
1318 progresschanged(WebKitWebView *v, GParamSpec *ps, Client *c)
1320 c->progress = webkit_web_view_get_estimated_load_progress(c->view) *
1326 titlechanged(WebKitWebView *view, GParamSpec *ps, Client *c)
1328 c->title = webkit_web_view_get_title(c->view);
1333 mousetargetchanged(WebKitWebView *v, WebKitHitTestResult *h, guint modifiers,
1336 WebKitHitTestResultContext hc = webkit_hit_test_result_get_context(h);
1338 /* Keep the hit test to know where is the pointer on the next click */
1342 c->targeturi = webkit_hit_test_result_get_link_uri(h);
1343 else if (hc & OnImg)
1344 c->targeturi = webkit_hit_test_result_get_image_uri(h);
1345 else if (hc & OnMedia)
1346 c->targeturi = webkit_hit_test_result_get_media_uri(h);
1348 c->targeturi = NULL;
1350 c->overtitle = c->targeturi;
1355 permissionrequested(WebKitWebView *v, WebKitPermissionRequest *r, Client *c)
1357 if (WEBKIT_IS_GEOLOCATION_PERMISSION_REQUEST(r)) {
1358 if (curconfig[Geolocation].val.b)
1359 webkit_permission_request_allow(r);
1361 webkit_permission_request_deny(r);
1369 decidepolicy(WebKitWebView *v, WebKitPolicyDecision *d,
1370 WebKitPolicyDecisionType dt, Client *c)
1373 case WEBKIT_POLICY_DECISION_TYPE_NAVIGATION_ACTION:
1374 decidenavigation(d, c);
1376 case WEBKIT_POLICY_DECISION_TYPE_NEW_WINDOW_ACTION:
1377 decidenewwindow(d, c);
1379 case WEBKIT_POLICY_DECISION_TYPE_RESPONSE:
1380 decideresource(d, c);
1383 webkit_policy_decision_ignore(d);
1390 decidenavigation(WebKitPolicyDecision *d, Client *c)
1392 WebKitNavigationAction *a =
1393 webkit_navigation_policy_decision_get_navigation_action(
1394 WEBKIT_NAVIGATION_POLICY_DECISION(d));
1396 switch (webkit_navigation_action_get_navigation_type(a)) {
1397 case WEBKIT_NAVIGATION_TYPE_LINK_CLICKED: /* fallthrough */
1398 case WEBKIT_NAVIGATION_TYPE_FORM_SUBMITTED: /* fallthrough */
1399 case WEBKIT_NAVIGATION_TYPE_BACK_FORWARD: /* fallthrough */
1400 case WEBKIT_NAVIGATION_TYPE_RELOAD: /* fallthrough */
1401 case WEBKIT_NAVIGATION_TYPE_FORM_RESUBMITTED: /* fallthrough */
1402 case WEBKIT_NAVIGATION_TYPE_OTHER: /* fallthrough */
1404 /* Do not navigate to links with a "_blank" target (popup) */
1405 if (webkit_navigation_policy_decision_get_frame_name(
1406 WEBKIT_NAVIGATION_POLICY_DECISION(d))) {
1407 webkit_policy_decision_ignore(d);
1409 /* Filter out navigation to different domain ? */
1410 /* get action→urirequest, copy and load in new window+view
1411 * on Ctrl+Click ? */
1412 webkit_policy_decision_use(d);
1419 decidenewwindow(WebKitPolicyDecision *d, Client *c)
1422 WebKitNavigationAction *a =
1423 webkit_navigation_policy_decision_get_navigation_action(
1424 WEBKIT_NAVIGATION_POLICY_DECISION(d));
1427 switch (webkit_navigation_action_get_navigation_type(a)) {
1428 case WEBKIT_NAVIGATION_TYPE_LINK_CLICKED: /* fallthrough */
1429 case WEBKIT_NAVIGATION_TYPE_FORM_SUBMITTED: /* fallthrough */
1430 case WEBKIT_NAVIGATION_TYPE_BACK_FORWARD: /* fallthrough */
1431 case WEBKIT_NAVIGATION_TYPE_RELOAD: /* fallthrough */
1432 case WEBKIT_NAVIGATION_TYPE_FORM_RESUBMITTED:
1433 /* Filter domains here */
1434 /* If the value of “mouse-button” is not 0, then the navigation was triggered by a mouse event.
1435 * test for link clicked but no button ? */
1436 arg.v = webkit_uri_request_get_uri(
1437 webkit_navigation_action_get_request(a));
1438 newwindow(c, &arg, 0);
1440 case WEBKIT_NAVIGATION_TYPE_OTHER: /* fallthrough */
1445 webkit_policy_decision_ignore(d);
1449 decideresource(WebKitPolicyDecision *d, Client *c)
1452 WebKitResponsePolicyDecision *r = WEBKIT_RESPONSE_POLICY_DECISION(d);
1453 WebKitURIResponse *res =
1454 webkit_response_policy_decision_get_response(r);
1455 const gchar *uri = webkit_uri_response_get_uri(res);
1457 if (g_str_has_suffix(uri, "/favicon.ico")) {
1458 webkit_policy_decision_ignore(d);
1462 if (!g_str_has_prefix(uri, "http://")
1463 && !g_str_has_prefix(uri, "https://")
1464 && !g_str_has_prefix(uri, "about:")
1465 && !g_str_has_prefix(uri, "file://")
1466 && !g_str_has_prefix(uri, "data:")
1467 && !g_str_has_prefix(uri, "blob:")
1468 && strlen(uri) > 0) {
1469 for (i = 0; i < strlen(uri); i++) {
1470 if (!g_ascii_isprint(uri[i])) {
1476 handleplumb(c, uri);
1477 webkit_policy_decision_ignore(d);
1482 if (webkit_response_policy_decision_is_mime_type_supported(r)) {
1483 webkit_policy_decision_use(d);
1485 webkit_policy_decision_ignore(d);
1491 insecurecontent(WebKitWebView *v, WebKitInsecureContentEvent e, Client *c)
1497 downloadstarted(WebKitWebContext *wc, WebKitDownload *d, Client *c)
1499 g_signal_connect(G_OBJECT(d), "notify::response",
1500 G_CALLBACK(responsereceived), c);
1504 responsereceived(WebKitDownload *d, GParamSpec *ps, Client *c)
1506 download(c, webkit_download_get_response(d));
1507 webkit_download_cancel(d);
1511 download(Client *c, WebKitURIResponse *r)
1513 Arg a = (Arg)DOWNLOAD(webkit_uri_response_get_uri(r), geturi(c));
1518 closeview(WebKitWebView *v, Client *c)
1520 gtk_widget_destroy(c->win);
1524 destroywin(GtkWidget* w, Client *c)
1532 pasteuri(GtkClipboard *clipboard, const char *text, gpointer d)
1534 Arg a = {.v = text };
1536 loaduri((Client *) d, &a);
1540 reload(Client *c, const Arg *a)
1543 webkit_web_view_reload_bypass_cache(c->view);
1545 webkit_web_view_reload(c->view);
1549 print(Client *c, const Arg *a)
1551 webkit_print_operation_run_dialog(webkit_print_operation_new(c->view),
1552 GTK_WINDOW(c->win));
1556 clipboard(Client *c, const Arg *a)
1558 if (a->b) { /* load clipboard uri */
1559 gtk_clipboard_request_text(gtk_clipboard_get(
1560 GDK_SELECTION_PRIMARY),
1562 } else { /* copy uri */
1563 gtk_clipboard_set_text(gtk_clipboard_get(
1564 GDK_SELECTION_PRIMARY), c->targeturi
1565 ? c->targeturi : geturi(c), -1);
1570 zoom(Client *c, const Arg *a)
1573 webkit_web_view_set_zoom_level(c->view,
1574 curconfig[ZoomLevel].val.f + 0.1);
1576 webkit_web_view_set_zoom_level(c->view,
1577 curconfig[ZoomLevel].val.f - 0.1);
1579 webkit_web_view_set_zoom_level(c->view, 1.0);
1581 curconfig[ZoomLevel].val.f = webkit_web_view_get_zoom_level(c->view);
1585 scroll(Client *c, const Arg *a)
1587 GdkEvent *ev = gdk_event_new(GDK_KEY_PRESS);
1589 gdk_event_set_device(ev, gdkkb);
1590 ev->key.window = gtk_widget_get_window(GTK_WIDGET(c->win));
1591 ev->key.state = GDK_CONTROL_MASK;
1592 ev->key.time = GDK_CURRENT_TIME;
1596 ev->key.keyval = GDK_KEY_Down;
1599 ev->key.keyval = GDK_KEY_Page_Down;
1602 ev->key.keyval = GDK_KEY_Left;
1605 ev->key.keyval = GDK_KEY_Right;
1608 ev->key.keyval = GDK_KEY_Page_Up;
1611 ev->key.keyval = GDK_KEY_Up;
1619 navigate(Client *c, const Arg *a)
1622 webkit_web_view_go_back(c->view);
1624 webkit_web_view_go_forward(c->view);
1628 stop(Client *c, const Arg *a)
1630 webkit_web_view_stop_loading(c->view);
1634 toggle(Client *c, const Arg *a)
1636 curconfig[a->i].val.b ^= 1;
1637 setparameter(c, 1, (ParamName)a->i, &curconfig[a->i].val);
1641 togglefullscreen(Client *c, const Arg *a)
1643 /* toggling value is handled in winevent() */
1645 gtk_window_unfullscreen(GTK_WINDOW(c->win));
1647 gtk_window_fullscreen(GTK_WINDOW(c->win));
1651 togglecookiepolicy(Client *c, const Arg *a)
1654 cookiepolicy %= strlen(curconfig[CookiePolicies].val.v);
1656 setparameter(c, 0, CookiePolicies, NULL);
1660 toggleinspector(Client *c, const Arg *a)
1662 if (webkit_web_inspector_is_attached(c->inspector))
1663 webkit_web_inspector_close(c->inspector);
1664 else if (curconfig[Inspector].val.b)
1665 webkit_web_inspector_show(c->inspector);
1669 find(Client *c, const Arg *a)
1675 webkit_find_controller_search_next(c->finder);
1677 webkit_find_controller_search_previous(c->finder);
1679 s = getatom(c, AtomFind);
1680 f = webkit_find_controller_get_search_text(c->finder);
1682 if (g_strcmp0(f, s) == 0) /* reset search */
1683 webkit_find_controller_search(c->finder, "", findopts,
1686 webkit_find_controller_search(c->finder, s, findopts,
1689 if (strcmp(s, "") == 0)
1690 webkit_find_controller_search_finish(c->finder);
1695 clicknavigate(Client *c, const Arg *a, WebKitHitTestResult *h)
1701 clicknewwindow(Client *c, const Arg *a, WebKitHitTestResult *h)
1705 arg.v = webkit_hit_test_result_get_link_uri(h);
1706 newwindow(c, &arg, a->b);
1710 clickexternplayer(Client *c, const Arg *a, WebKitHitTestResult *h)
1714 arg = (Arg)VIDEOPLAY(webkit_hit_test_result_get_media_uri(h));
1719 main(int argc, char *argv[])
1724 memset(&arg, 0, sizeof(arg));
1726 /* command line args */
1729 defconfig CSETV(CookiePolicies, EARGF(usage()));
1732 defconfig CSETB(ScrollBars, 0);
1735 defconfig CSETB(ScrollBars, 1);
1738 cookiefile = EARGF(usage());
1741 stylefile = EARGF(usage());
1744 defconfig CSETB(DiskCache, 0);
1747 defconfig CSETB(DiskCache, 1);
1750 embed = strtol(EARGF(usage()), NULL, 0);
1753 defconfig CSETB(RunInFullscreen, 0);
1756 defconfig CSETB(RunInFullscreen, 1);
1759 defconfig CSETB(Geolocation, 0);
1762 defconfig CSETB(Geolocation, 1);
1765 defconfig CSETB(LoadImages, 0);
1768 defconfig CSETB(LoadImages, 1);
1771 defconfig CSETB(KioskMode, 0);
1774 defconfig CSETB(KioskMode, 1);
1777 defconfig CSETB(Style, 0);
1780 defconfig CSETB(Style, 1);
1783 defconfig CSETB(Inspector, 0);
1786 defconfig CSETB(Inspector, 1);
1789 defconfig CSETB(Plugins, 0);
1792 defconfig CSETB(Plugins, 1);
1795 scriptfile = EARGF(usage());
1798 defconfig CSETB(JavaScript, 0);
1801 defconfig CSETB(JavaScript, 1);
1804 defconfig CSETB(StrictTLS, 0);
1807 defconfig CSETB(StrictTLS, 1);
1810 fulluseragent = EARGF(usage());
1813 die("surf-"VERSION", ©2009-2017 surf engineers, "
1814 "see LICENSE for details\n");
1819 defconfig CSETF(ZoomLevel, strtof(EARGF(usage()), NULL));
1827 arg.v = "about:blank";
1830 c = newclient(NULL);