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);
792 g_object_unref(cert);
798 getstyle(const char *uri)
805 for (i = 0; i < LENGTH(styles); ++i) {
806 if (styles[i].regex &&
807 !regexec(&(styles[i].re), uri, 0, NULL, 0))
808 return styles[i].file;
815 setstyle(Client *c, const char *file)
819 if (!g_file_get_contents(file, &style, NULL, NULL)) {
820 fprintf(stderr, "Could not read style file: %s\n", file);
824 webkit_user_content_manager_add_style_sheet(
825 webkit_web_view_get_user_content_manager(c->view),
826 webkit_user_style_sheet_new(style,
827 WEBKIT_USER_CONTENT_INJECT_ALL_FRAMES,
828 WEBKIT_USER_STYLE_LEVEL_USER,
840 if (g_file_get_contents(scriptfile, &script, &l, NULL) && l)
841 evalscript(c, script);
846 evalscript(Client *c, const char *jsstr, ...)
852 script = g_strdup_vprintf(jsstr, ap);
855 webkit_web_view_run_javascript(c->view, script, NULL, NULL, NULL);
860 updatewinid(Client *c)
862 snprintf(winid, LENGTH(winid), "%lu", c->xid);
866 handleplumb(Client *c, const char *uri)
868 Arg a = (Arg)PLUMB(uri);
873 newwindow(Client *c, const Arg *a, int noembed)
877 const char *cmd[28], *uri;
878 const Arg arg = { .v = cmd };
882 cmd[i++] = curconfig[CookiePolicies].val.v;
883 cmd[i++] = curconfig[ScrollBars].val.b ? "-B" : "-b";
884 if (cookiefile && g_strcmp0(cookiefile, "")) {
886 cmd[i++] = cookiefile;
888 if (stylefile && g_strcmp0(stylefile, "")) {
890 cmd[i++] = stylefile;
892 cmd[i++] = curconfig[DiskCache].val.b ? "-D" : "-d";
893 if (embed && !noembed) {
895 snprintf(tmp, LENGTH(tmp), "%lu", embed);
898 cmd[i++] = curconfig[RunInFullscreen].val.b ? "-F" : "-f" ;
899 cmd[i++] = curconfig[Geolocation].val.b ? "-G" : "-g" ;
900 cmd[i++] = curconfig[LoadImages].val.b ? "-I" : "-i" ;
901 cmd[i++] = curconfig[KioskMode].val.b ? "-K" : "-k" ;
902 cmd[i++] = curconfig[Style].val.b ? "-M" : "-m" ;
903 cmd[i++] = curconfig[Inspector].val.b ? "-N" : "-n" ;
904 cmd[i++] = curconfig[Plugins].val.b ? "-P" : "-p" ;
905 if (scriptfile && g_strcmp0(scriptfile, "")) {
907 cmd[i++] = scriptfile;
909 cmd[i++] = curconfig[JavaScript].val.b ? "-S" : "-s";
910 cmd[i++] = curconfig[StrictTLS].val.b ? "-T" : "-t";
911 if (fulluseragent && g_strcmp0(fulluseragent, "")) {
913 cmd[i++] = fulluseragent;
917 /* do not keep zoom level */
927 spawn(Client *c, const Arg *a)
931 close(ConnectionNumber(dpy));
933 execvp(((char **)a->v)[0], (char **)a->v);
934 fprintf(stderr, "%s: execvp %s", argv0, ((char **)a->v)[0]);
941 destroyclient(Client *c)
945 webkit_web_view_stop_loading(c->view);
946 /* Not needed, has already been called
947 gtk_widget_destroy(c->win);
950 for (p = clients; p && p->next != c; p = p->next)
963 destroyclient(clients);
972 newview(Client *c, WebKitWebView *rv)
975 WebKitSettings *settings;
976 WebKitUserContentManager *contentmanager;
977 WebKitWebContext *context;
982 webkit_web_view_new_with_related_view(rv));
984 settings = webkit_settings_new_with_settings(
985 "auto-load-images", curconfig[LoadImages].val.b,
986 "default-font-size", curconfig[FontSize].val.i,
987 "enable-caret-browsing", curconfig[CaretBrowsing].val.b,
988 "enable-developer-extras", curconfig[Inspector].val.b,
989 "enable-dns-prefetching", curconfig[DNSPrefetch].val.b,
990 "enable-frame-flattening", curconfig[FrameFlattening].val.b,
991 "enable-html5-database", curconfig[DiskCache].val.b,
992 "enable-html5-local-storage", curconfig[DiskCache].val.b,
993 "enable-javascript", curconfig[JavaScript].val.b,
994 "enable-plugins", curconfig[Plugins].val.b,
995 "enable-accelerated-2d-canvas", curconfig[AcceleratedCanvas].val.b,
996 "enable-site-specific-quirks", curconfig[SiteQuirks].val.b,
997 "media-playback-requires-user-gesture", curconfig[MediaManualPlay].val.b,
999 /* For mor interesting settings, have a look at
1000 * http://webkitgtk.org/reference/webkit2gtk/stable/WebKitSettings.html */
1002 if (strcmp(fulluseragent, "")) {
1003 webkit_settings_set_user_agent(settings, fulluseragent);
1004 } else if (surfuseragent) {
1005 webkit_settings_set_user_agent_with_application_details(
1006 settings, "Surf", VERSION);
1008 useragent = webkit_settings_get_user_agent(settings);
1010 contentmanager = webkit_user_content_manager_new();
1012 context = webkit_web_context_new_with_website_data_manager(
1013 webkit_website_data_manager_new(
1014 "base-cache-directory", cachedir,
1015 "base-data-directory", cachedir,
1018 /* rendering process model, can be a shared unique one
1019 * or one for each view */
1020 webkit_web_context_set_process_model(context,
1021 WEBKIT_PROCESS_MODEL_MULTIPLE_SECONDARY_PROCESSES);
1023 webkit_web_context_set_tls_errors_policy(context,
1024 curconfig[StrictTLS].val.b ? WEBKIT_TLS_ERRORS_POLICY_FAIL :
1025 WEBKIT_TLS_ERRORS_POLICY_IGNORE);
1027 webkit_web_context_set_cache_model(context,
1028 curconfig[DiskCache].val.b ? WEBKIT_CACHE_MODEL_WEB_BROWSER :
1029 WEBKIT_CACHE_MODEL_DOCUMENT_VIEWER);
1031 /* Currently only works with text file to be compatible with curl */
1032 webkit_cookie_manager_set_persistent_storage(
1033 webkit_web_context_get_cookie_manager(context), cookiefile,
1034 WEBKIT_COOKIE_PERSISTENT_STORAGE_TEXT);
1036 webkit_cookie_manager_set_accept_policy(
1037 webkit_web_context_get_cookie_manager(context),
1038 cookiepolicy_get());
1040 webkit_web_context_set_preferred_languages(context,
1041 curconfig[PreferredLanguages].val.v);
1042 webkit_web_context_set_spell_checking_languages(context,
1043 curconfig[SpellLanguages].val.v);
1044 webkit_web_context_set_spell_checking_enabled(context,
1045 curconfig[SpellChecking].val.b);
1047 g_signal_connect(G_OBJECT(context), "download-started",
1048 G_CALLBACK(downloadstarted), c);
1049 g_signal_connect(G_OBJECT(context), "initialize-web-extensions",
1050 G_CALLBACK(initwebextensions), c);
1052 v = g_object_new(WEBKIT_TYPE_WEB_VIEW,
1053 "settings", settings,
1054 "user-content-manager", contentmanager,
1055 "web-context", context,
1059 g_signal_connect(G_OBJECT(v), "notify::estimated-load-progress",
1060 G_CALLBACK(progresschanged), c);
1061 g_signal_connect(G_OBJECT(v), "notify::title",
1062 G_CALLBACK(titlechanged), c);
1063 g_signal_connect(G_OBJECT(v), "button-release-event",
1064 G_CALLBACK(buttonreleased), c);
1065 g_signal_connect(G_OBJECT(v), "close",
1066 G_CALLBACK(closeview), c);
1067 g_signal_connect(G_OBJECT(v), "create",
1068 G_CALLBACK(createview), c);
1069 g_signal_connect(G_OBJECT(v), "decide-policy",
1070 G_CALLBACK(decidepolicy), c);
1071 g_signal_connect(G_OBJECT(v), "insecure-content-detected",
1072 G_CALLBACK(insecurecontent), c);
1073 g_signal_connect(G_OBJECT(v), "load-changed",
1074 G_CALLBACK(loadchanged), c);
1075 g_signal_connect(G_OBJECT(v), "mouse-target-changed",
1076 G_CALLBACK(mousetargetchanged), c);
1077 g_signal_connect(G_OBJECT(v), "permission-request",
1078 G_CALLBACK(permissionrequested), c);
1079 g_signal_connect(G_OBJECT(v), "ready-to-show",
1080 G_CALLBACK(showview), c);
1086 initwebextensions(WebKitWebContext *wc, Client *c)
1088 webkit_web_context_set_web_extensions_directory(wc, WEBEXTDIR);
1092 createview(WebKitWebView *v, WebKitNavigationAction *a, Client *c)
1096 switch (webkit_navigation_action_get_navigation_type(a)) {
1097 case WEBKIT_NAVIGATION_TYPE_OTHER: /* fallthrough */
1099 * popup windows of type “other” are almost always triggered
1100 * by user gesture, so inverse the logic here
1102 /* instead of this, compare destination uri to mouse-over uri for validating window */
1103 if (webkit_navigation_action_is_user_gesture(a))
1105 case WEBKIT_NAVIGATION_TYPE_LINK_CLICKED: /* fallthrough */
1106 case WEBKIT_NAVIGATION_TYPE_FORM_SUBMITTED: /* fallthrough */
1107 case WEBKIT_NAVIGATION_TYPE_BACK_FORWARD: /* fallthrough */
1108 case WEBKIT_NAVIGATION_TYPE_RELOAD: /* fallthrough */
1109 case WEBKIT_NAVIGATION_TYPE_FORM_RESUBMITTED:
1116 return GTK_WIDGET(n->view);
1120 buttonreleased(GtkWidget *w, GdkEvent *e, Client *c)
1122 WebKitHitTestResultContext element;
1125 element = webkit_hit_test_result_get_context(c->mousepos);
1127 for (i = 0; i < LENGTH(buttons); ++i) {
1128 if (element & buttons[i].target &&
1129 e->button.button == buttons[i].button &&
1130 CLEANMASK(e->button.state) == CLEANMASK(buttons[i].mask) &&
1132 buttons[i].func(c, &buttons[i].arg, c->mousepos);
1133 return buttons[i].stopevent;
1141 processx(GdkXEvent *e, GdkEvent *event, gpointer d)
1143 Client *c = (Client *)d;
1147 if (((XEvent *)e)->type == PropertyNotify) {
1148 ev = &((XEvent *)e)->xproperty;
1149 if (ev->state == PropertyNewValue) {
1150 if (ev->atom == atoms[AtomFind]) {
1153 return GDK_FILTER_REMOVE;
1154 } else if (ev->atom == atoms[AtomGo]) {
1155 a.v = getatom(c, AtomGo);
1158 return GDK_FILTER_REMOVE;
1162 return GDK_FILTER_CONTINUE;
1166 winevent(GtkWidget *w, GdkEvent *e, Client *c)
1171 case GDK_ENTER_NOTIFY:
1172 c->overtitle = c->targeturi;
1176 if (!curconfig[KioskMode].val.b) {
1177 for (i = 0; i < LENGTH(keys); ++i) {
1178 if (gdk_keyval_to_lower(e->key.keyval) ==
1180 CLEANMASK(e->key.state) == keys[i].mod &&
1183 keys[i].func(c, &(keys[i].arg));
1188 case GDK_LEAVE_NOTIFY:
1189 c->overtitle = NULL;
1192 case GDK_WINDOW_STATE:
1193 if (e->window_state.changed_mask ==
1194 GDK_WINDOW_STATE_FULLSCREEN)
1195 c->fullscreen = e->window_state.new_window_state &
1196 GDK_WINDOW_STATE_FULLSCREEN;
1206 showview(WebKitWebView *v, Client *c)
1208 GdkRGBA bgcolor = { 0 };
1211 c->finder = webkit_web_view_get_find_controller(c->view);
1212 c->inspector = webkit_web_view_get_inspector(c->view);
1214 c->win = createwindow(c);
1216 gtk_container_add(GTK_CONTAINER(c->win), GTK_WIDGET(c->view));
1217 gtk_widget_show_all(c->win);
1218 gtk_widget_grab_focus(GTK_WIDGET(c->view));
1220 gwin = gtk_widget_get_window(GTK_WIDGET(c->win));
1221 c->xid = gdk_x11_window_get_xid(gwin);
1224 gdk_display_sync(gtk_widget_get_display(c->win));
1228 if (curconfig[HideBackground].val.b)
1229 webkit_web_view_set_background_color(c->view, &bgcolor);
1231 if (!curconfig[KioskMode].val.b) {
1232 gdk_window_set_events(gwin, GDK_ALL_EVENTS_MASK);
1233 gdk_window_add_filter(gwin, processx, c);
1236 if (curconfig[RunInFullscreen].val.b)
1237 togglefullscreen(c, NULL);
1239 if (curconfig[ZoomLevel].val.f != 1.0)
1240 webkit_web_view_set_zoom_level(c->view,
1241 curconfig[ZoomLevel].val.f);
1243 setatom(c, AtomFind, "");
1244 setatom(c, AtomUri, "about:blank");
1248 createwindow(Client *c)
1254 w = gtk_plug_new(embed);
1256 w = gtk_window_new(GTK_WINDOW_TOPLEVEL);
1258 wmstr = g_path_get_basename(argv0);
1259 gtk_window_set_wmclass(GTK_WINDOW(w), wmstr, "Surf");
1262 wmstr = g_strdup_printf("%s[%lu]", "Surf",
1263 webkit_web_view_get_page_id(c->view));
1264 gtk_window_set_role(GTK_WINDOW(w), wmstr);
1267 gtk_window_set_default_size(GTK_WINDOW(w), winsize[0], winsize[1]);
1270 g_signal_connect(G_OBJECT(w), "destroy",
1271 G_CALLBACK(destroywin), c);
1272 g_signal_connect(G_OBJECT(w), "enter-notify-event",
1273 G_CALLBACK(winevent), c);
1274 g_signal_connect(G_OBJECT(w), "key-press-event",
1275 G_CALLBACK(winevent), c);
1276 g_signal_connect(G_OBJECT(w), "leave-notify-event",
1277 G_CALLBACK(winevent), c);
1278 g_signal_connect(G_OBJECT(w), "window-state-event",
1279 G_CALLBACK(winevent), c);
1285 loadchanged(WebKitWebView *v, WebKitLoadEvent e, Client *c)
1287 const char *title = geturi(c);
1290 case WEBKIT_LOAD_STARTED:
1291 curconfig = defconfig;
1292 setatom(c, AtomUri, title);
1294 c->https = c->insecure = 0;
1295 seturiparameters(c, geturi(c));
1297 case WEBKIT_LOAD_REDIRECTED:
1298 setatom(c, AtomUri, title);
1300 seturiparameters(c, geturi(c));
1302 case WEBKIT_LOAD_COMMITTED:
1303 c->https = webkit_web_view_get_tls_info(c->view, NULL,
1306 case WEBKIT_LOAD_FINISHED:
1307 /* Disabled until we write some WebKitWebExtension for
1308 * manipulating the DOM directly.
1309 evalscript(c, "document.documentElement.style.overflow = '%s'",
1310 enablescrollbars ? "auto" : "hidden");
1319 progresschanged(WebKitWebView *v, GParamSpec *ps, Client *c)
1321 c->progress = webkit_web_view_get_estimated_load_progress(c->view) *
1327 titlechanged(WebKitWebView *view, GParamSpec *ps, Client *c)
1329 c->title = webkit_web_view_get_title(c->view);
1334 mousetargetchanged(WebKitWebView *v, WebKitHitTestResult *h, guint modifiers,
1337 WebKitHitTestResultContext hc = webkit_hit_test_result_get_context(h);
1339 /* Keep the hit test to know where is the pointer on the next click */
1343 c->targeturi = webkit_hit_test_result_get_link_uri(h);
1344 else if (hc & OnImg)
1345 c->targeturi = webkit_hit_test_result_get_image_uri(h);
1346 else if (hc & OnMedia)
1347 c->targeturi = webkit_hit_test_result_get_media_uri(h);
1349 c->targeturi = NULL;
1351 c->overtitle = c->targeturi;
1356 permissionrequested(WebKitWebView *v, WebKitPermissionRequest *r, Client *c)
1358 if (WEBKIT_IS_GEOLOCATION_PERMISSION_REQUEST(r)) {
1359 if (curconfig[Geolocation].val.b)
1360 webkit_permission_request_allow(r);
1362 webkit_permission_request_deny(r);
1370 decidepolicy(WebKitWebView *v, WebKitPolicyDecision *d,
1371 WebKitPolicyDecisionType dt, Client *c)
1374 case WEBKIT_POLICY_DECISION_TYPE_NAVIGATION_ACTION:
1375 decidenavigation(d, c);
1377 case WEBKIT_POLICY_DECISION_TYPE_NEW_WINDOW_ACTION:
1378 decidenewwindow(d, c);
1380 case WEBKIT_POLICY_DECISION_TYPE_RESPONSE:
1381 decideresource(d, c);
1384 webkit_policy_decision_ignore(d);
1391 decidenavigation(WebKitPolicyDecision *d, Client *c)
1393 WebKitNavigationAction *a =
1394 webkit_navigation_policy_decision_get_navigation_action(
1395 WEBKIT_NAVIGATION_POLICY_DECISION(d));
1397 switch (webkit_navigation_action_get_navigation_type(a)) {
1398 case WEBKIT_NAVIGATION_TYPE_LINK_CLICKED: /* fallthrough */
1399 case WEBKIT_NAVIGATION_TYPE_FORM_SUBMITTED: /* fallthrough */
1400 case WEBKIT_NAVIGATION_TYPE_BACK_FORWARD: /* fallthrough */
1401 case WEBKIT_NAVIGATION_TYPE_RELOAD: /* fallthrough */
1402 case WEBKIT_NAVIGATION_TYPE_FORM_RESUBMITTED: /* fallthrough */
1403 case WEBKIT_NAVIGATION_TYPE_OTHER: /* fallthrough */
1405 /* Do not navigate to links with a "_blank" target (popup) */
1406 if (webkit_navigation_policy_decision_get_frame_name(
1407 WEBKIT_NAVIGATION_POLICY_DECISION(d))) {
1408 webkit_policy_decision_ignore(d);
1410 /* Filter out navigation to different domain ? */
1411 /* get action→urirequest, copy and load in new window+view
1412 * on Ctrl+Click ? */
1413 webkit_policy_decision_use(d);
1420 decidenewwindow(WebKitPolicyDecision *d, Client *c)
1423 WebKitNavigationAction *a =
1424 webkit_navigation_policy_decision_get_navigation_action(
1425 WEBKIT_NAVIGATION_POLICY_DECISION(d));
1428 switch (webkit_navigation_action_get_navigation_type(a)) {
1429 case WEBKIT_NAVIGATION_TYPE_LINK_CLICKED: /* fallthrough */
1430 case WEBKIT_NAVIGATION_TYPE_FORM_SUBMITTED: /* fallthrough */
1431 case WEBKIT_NAVIGATION_TYPE_BACK_FORWARD: /* fallthrough */
1432 case WEBKIT_NAVIGATION_TYPE_RELOAD: /* fallthrough */
1433 case WEBKIT_NAVIGATION_TYPE_FORM_RESUBMITTED:
1434 /* Filter domains here */
1435 /* If the value of “mouse-button” is not 0, then the navigation was triggered by a mouse event.
1436 * test for link clicked but no button ? */
1437 arg.v = webkit_uri_request_get_uri(
1438 webkit_navigation_action_get_request(a));
1439 newwindow(c, &arg, 0);
1441 case WEBKIT_NAVIGATION_TYPE_OTHER: /* fallthrough */
1446 webkit_policy_decision_ignore(d);
1450 decideresource(WebKitPolicyDecision *d, Client *c)
1453 WebKitResponsePolicyDecision *r = WEBKIT_RESPONSE_POLICY_DECISION(d);
1454 WebKitURIResponse *res =
1455 webkit_response_policy_decision_get_response(r);
1456 const gchar *uri = webkit_uri_response_get_uri(res);
1458 if (g_str_has_suffix(uri, "/favicon.ico")) {
1459 webkit_policy_decision_ignore(d);
1463 if (!g_str_has_prefix(uri, "http://")
1464 && !g_str_has_prefix(uri, "https://")
1465 && !g_str_has_prefix(uri, "about:")
1466 && !g_str_has_prefix(uri, "file://")
1467 && !g_str_has_prefix(uri, "data:")
1468 && !g_str_has_prefix(uri, "blob:")
1469 && strlen(uri) > 0) {
1470 for (i = 0; i < strlen(uri); i++) {
1471 if (!g_ascii_isprint(uri[i])) {
1477 handleplumb(c, uri);
1478 webkit_policy_decision_ignore(d);
1483 if (webkit_response_policy_decision_is_mime_type_supported(r)) {
1484 webkit_policy_decision_use(d);
1486 webkit_policy_decision_ignore(d);
1492 insecurecontent(WebKitWebView *v, WebKitInsecureContentEvent e, Client *c)
1498 downloadstarted(WebKitWebContext *wc, WebKitDownload *d, Client *c)
1500 g_signal_connect(G_OBJECT(d), "notify::response",
1501 G_CALLBACK(responsereceived), c);
1505 responsereceived(WebKitDownload *d, GParamSpec *ps, Client *c)
1507 download(c, webkit_download_get_response(d));
1508 webkit_download_cancel(d);
1512 download(Client *c, WebKitURIResponse *r)
1514 Arg a = (Arg)DOWNLOAD(webkit_uri_response_get_uri(r), geturi(c));
1519 closeview(WebKitWebView *v, Client *c)
1521 gtk_widget_destroy(c->win);
1525 destroywin(GtkWidget* w, Client *c)
1533 pasteuri(GtkClipboard *clipboard, const char *text, gpointer d)
1535 Arg a = {.v = text };
1537 loaduri((Client *) d, &a);
1541 reload(Client *c, const Arg *a)
1544 webkit_web_view_reload_bypass_cache(c->view);
1546 webkit_web_view_reload(c->view);
1550 print(Client *c, const Arg *a)
1552 webkit_print_operation_run_dialog(webkit_print_operation_new(c->view),
1553 GTK_WINDOW(c->win));
1557 clipboard(Client *c, const Arg *a)
1559 if (a->b) { /* load clipboard uri */
1560 gtk_clipboard_request_text(gtk_clipboard_get(
1561 GDK_SELECTION_PRIMARY),
1563 } else { /* copy uri */
1564 gtk_clipboard_set_text(gtk_clipboard_get(
1565 GDK_SELECTION_PRIMARY), c->targeturi
1566 ? c->targeturi : geturi(c), -1);
1571 zoom(Client *c, const Arg *a)
1574 webkit_web_view_set_zoom_level(c->view,
1575 curconfig[ZoomLevel].val.f + 0.1);
1577 webkit_web_view_set_zoom_level(c->view,
1578 curconfig[ZoomLevel].val.f - 0.1);
1580 webkit_web_view_set_zoom_level(c->view, 1.0);
1582 curconfig[ZoomLevel].val.f = webkit_web_view_get_zoom_level(c->view);
1586 scroll(Client *c, const Arg *a)
1588 GdkEvent *ev = gdk_event_new(GDK_KEY_PRESS);
1590 gdk_event_set_device(ev, gdkkb);
1591 ev->key.window = gtk_widget_get_window(GTK_WIDGET(c->win));
1592 ev->key.state = GDK_CONTROL_MASK;
1593 ev->key.time = GDK_CURRENT_TIME;
1597 ev->key.keyval = GDK_KEY_Down;
1600 ev->key.keyval = GDK_KEY_Page_Down;
1603 ev->key.keyval = GDK_KEY_Left;
1606 ev->key.keyval = GDK_KEY_Right;
1609 ev->key.keyval = GDK_KEY_Page_Up;
1612 ev->key.keyval = GDK_KEY_Up;
1620 navigate(Client *c, const Arg *a)
1623 webkit_web_view_go_back(c->view);
1625 webkit_web_view_go_forward(c->view);
1629 stop(Client *c, const Arg *a)
1631 webkit_web_view_stop_loading(c->view);
1635 toggle(Client *c, const Arg *a)
1637 curconfig[a->i].val.b ^= 1;
1638 setparameter(c, 1, (ParamName)a->i, &curconfig[a->i].val);
1642 togglefullscreen(Client *c, const Arg *a)
1644 /* toggling value is handled in winevent() */
1646 gtk_window_unfullscreen(GTK_WINDOW(c->win));
1648 gtk_window_fullscreen(GTK_WINDOW(c->win));
1652 togglecookiepolicy(Client *c, const Arg *a)
1655 cookiepolicy %= strlen(curconfig[CookiePolicies].val.v);
1657 setparameter(c, 0, CookiePolicies, NULL);
1661 toggleinspector(Client *c, const Arg *a)
1663 if (webkit_web_inspector_is_attached(c->inspector))
1664 webkit_web_inspector_close(c->inspector);
1665 else if (curconfig[Inspector].val.b)
1666 webkit_web_inspector_show(c->inspector);
1670 find(Client *c, const Arg *a)
1676 webkit_find_controller_search_next(c->finder);
1678 webkit_find_controller_search_previous(c->finder);
1680 s = getatom(c, AtomFind);
1681 f = webkit_find_controller_get_search_text(c->finder);
1683 if (g_strcmp0(f, s) == 0) /* reset search */
1684 webkit_find_controller_search(c->finder, "", findopts,
1687 webkit_find_controller_search(c->finder, s, findopts,
1690 if (strcmp(s, "") == 0)
1691 webkit_find_controller_search_finish(c->finder);
1696 clicknavigate(Client *c, const Arg *a, WebKitHitTestResult *h)
1702 clicknewwindow(Client *c, const Arg *a, WebKitHitTestResult *h)
1706 arg.v = webkit_hit_test_result_get_link_uri(h);
1707 newwindow(c, &arg, a->b);
1711 clickexternplayer(Client *c, const Arg *a, WebKitHitTestResult *h)
1715 arg = (Arg)VIDEOPLAY(webkit_hit_test_result_get_media_uri(h));
1720 main(int argc, char *argv[])
1725 memset(&arg, 0, sizeof(arg));
1727 /* command line args */
1730 defconfig CSETV(CookiePolicies, EARGF(usage()));
1733 defconfig CSETB(ScrollBars, 0);
1736 defconfig CSETB(ScrollBars, 1);
1739 cookiefile = EARGF(usage());
1742 stylefile = EARGF(usage());
1745 defconfig CSETB(DiskCache, 0);
1748 defconfig CSETB(DiskCache, 1);
1751 embed = strtol(EARGF(usage()), NULL, 0);
1754 defconfig CSETB(RunInFullscreen, 0);
1757 defconfig CSETB(RunInFullscreen, 1);
1760 defconfig CSETB(Geolocation, 0);
1763 defconfig CSETB(Geolocation, 1);
1766 defconfig CSETB(LoadImages, 0);
1769 defconfig CSETB(LoadImages, 1);
1772 defconfig CSETB(KioskMode, 0);
1775 defconfig CSETB(KioskMode, 1);
1778 defconfig CSETB(Style, 0);
1781 defconfig CSETB(Style, 1);
1784 defconfig CSETB(Inspector, 0);
1787 defconfig CSETB(Inspector, 1);
1790 defconfig CSETB(Plugins, 0);
1793 defconfig CSETB(Plugins, 1);
1796 scriptfile = EARGF(usage());
1799 defconfig CSETB(JavaScript, 0);
1802 defconfig CSETB(JavaScript, 1);
1805 defconfig CSETB(StrictTLS, 0);
1808 defconfig CSETB(StrictTLS, 1);
1811 fulluseragent = EARGF(usage());
1814 die("surf-"VERSION", ©2009-2017 surf engineers, "
1815 "see LICENSE for details\n");
1820 defconfig CSETF(ZoomLevel, strtof(EARGF(usage()), NULL));
1828 arg.v = "about:blank";
1831 c = newclient(NULL);