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,
101 typedef struct Client {
104 WebKitWebInspector *inspector;
105 WebKitFindController *finder;
106 WebKitHitTestResult *mousepos;
107 GTlsCertificateFlags tlsflags;
109 int progress, fullscreen;
110 const char *title, *overtitle, *targeturi;
118 void (*func)(Client *c, const Arg *a);
126 void (*func)(Client *c, const Arg *a, WebKitHitTestResult *h);
128 unsigned int stopevent;
133 Parameter config[ParameterLast];
144 static void usage(void);
145 static void die(const char *errstr, ...);
146 static void setup(void);
147 static void sigchld(int unused);
148 static void sighup(int unused);
149 static char *buildfile(const char *path);
150 static char *buildpath(const char *path);
151 static const char *getuserhomedir(const char *user);
152 static const char *getcurrentuserhomedir(void);
153 static Client *newclient(Client *c);
154 static void loaduri(Client *c, const Arg *a);
155 static const char *geturi(Client *c);
156 static void setatom(Client *c, int a, const char *v);
157 static const char *getatom(Client *c, int a);
158 static void updatetitle(Client *c);
159 static void gettogglestats(Client *c);
160 static void getpagestats(Client *c);
161 static WebKitCookieAcceptPolicy cookiepolicy_get(void);
162 static char cookiepolicy_set(const WebKitCookieAcceptPolicy p);
163 static void seturiparameters(Client *c, const char *uri);
164 static void setparameter(Client *c, int refresh, ParamName p, const Arg *a);
165 static const char *getstyle(const char *uri);
166 static void setstyle(Client *c, const char *stylefile);
167 static void runscript(Client *c);
168 static void evalscript(Client *c, const char *jsstr, ...);
169 static void updatewinid(Client *c);
170 static void handleplumb(Client *c, const char *uri);
171 static void newwindow(Client *c, const Arg *a, int noembed);
172 static void spawn(Client *c, const Arg *a);
173 static void destroyclient(Client *c);
174 static void cleanup(void);
177 static WebKitWebView *newview(Client *c, WebKitWebView *rv);
178 static void initwebextensions(WebKitWebContext *wc, Client *c);
179 static GtkWidget *createview(WebKitWebView *v, WebKitNavigationAction *a,
181 static gboolean buttonreleased(GtkWidget *w, GdkEvent *e, Client *c);
182 static GdkFilterReturn processx(GdkXEvent *xevent, GdkEvent *event,
184 static gboolean winevent(GtkWidget *w, GdkEvent *e, Client *c);
185 static void showview(WebKitWebView *v, Client *c);
186 static GtkWidget *createwindow(Client *c);
187 static void loadchanged(WebKitWebView *v, WebKitLoadEvent e, Client *c);
188 static void progresschanged(WebKitWebView *v, GParamSpec *ps, Client *c);
189 static void titlechanged(WebKitWebView *view, GParamSpec *ps, Client *c);
190 static void mousetargetchanged(WebKitWebView *v, WebKitHitTestResult *h,
191 guint modifiers, Client *c);
192 static gboolean permissionrequested(WebKitWebView *v,
193 WebKitPermissionRequest *r, Client *c);
194 static gboolean decidepolicy(WebKitWebView *v, WebKitPolicyDecision *d,
195 WebKitPolicyDecisionType dt, Client *c);
196 static void decidenavigation(WebKitPolicyDecision *d, Client *c);
197 static void decidenewwindow(WebKitPolicyDecision *d, Client *c);
198 static void decideresource(WebKitPolicyDecision *d, Client *c);
199 static void downloadstarted(WebKitWebContext *wc, WebKitDownload *d,
201 static void responsereceived(WebKitDownload *d, GParamSpec *ps, Client *c);
202 static void download(Client *c, WebKitURIResponse *r);
203 static void closeview(WebKitWebView *v, Client *c);
204 static void destroywin(GtkWidget* w, Client *c);
207 static void pasteuri(GtkClipboard *clipboard, const char *text, gpointer d);
208 static void reload(Client *c, const Arg *a);
209 static void print(Client *c, const Arg *a);
210 static void clipboard(Client *c, const Arg *a);
211 static void zoom(Client *c, const Arg *a);
212 static void scroll(Client *c, const Arg *a);
213 static void navigate(Client *c, const Arg *a);
214 static void stop(Client *c, const Arg *a);
215 static void toggle(Client *c, const Arg *a);
216 static void togglefullscreen(Client *c, const Arg *a);
217 static void togglecookiepolicy(Client *c, const Arg *a);
218 static void toggleinspector(Client *c, const Arg *a);
219 static void find(Client *c, const Arg *a);
222 static void clicknavigate(Client *c, const Arg *a, WebKitHitTestResult *h);
223 static void clicknewwindow(Client *c, const Arg *a, WebKitHitTestResult *h);
224 static void clickexternplayer(Client *c, const Arg *a, WebKitHitTestResult *h);
226 static char winid[64];
227 static char togglestats[10];
228 static char pagestats[2];
229 static Atom atoms[AtomLast];
232 static int cookiepolicy;
234 static Client *clients;
235 static GdkDevice *gdkkb;
236 static char *stylefile;
237 static const char *useragent;
238 static Parameter *curconfig;
241 /* configuration, allows nested code to access above variables */
247 die("usage: %s [-bBdDfFgGiIkKmMnNpPsSvx] [-a cookiepolicies ] "
248 "[-c cookiefile] [-e xid] [-r scriptfile] [-t stylefile] "
249 "[-u useragent] [-z zoomlevel] [uri]\n", basename(argv0));
253 die(const char *errstr, ...)
257 va_start(ap, errstr);
258 vfprintf(stderr, errstr, ap);
269 /* clean up any zombies immediately */
271 if (signal(SIGHUP, sighup) == SIG_ERR)
272 die("Can't install SIGHUP handler");
274 if (!(dpy = XOpenDisplay(NULL)))
275 die("Can't open default display");
278 atoms[AtomFind] = XInternAtom(dpy, "_SURF_FIND", False);
279 atoms[AtomGo] = XInternAtom(dpy, "_SURF_GO", False);
280 atoms[AtomUri] = XInternAtom(dpy, "_SURF_URI", False);
282 gtk_init(NULL, NULL);
284 gdpy = gdk_display_get_default();
286 curconfig = defconfig;
289 cookiefile = buildfile(cookiefile);
290 scriptfile = buildfile(scriptfile);
291 cachedir = buildpath(cachedir);
293 gdkkb = gdk_seat_get_keyboard(gdk_display_get_default_seat(gdpy));
296 styledir = buildpath(styledir);
297 for (i = 0; i < LENGTH(styles); ++i) {
298 if (regcomp(&(styles[i].re), styles[i].regex,
301 "Could not compile regex: %s\n",
303 styles[i].regex = NULL;
305 styles[i].style = g_strconcat(styledir, "/",
306 styles[i].style, NULL);
310 stylefile = buildfile(stylefile);
313 for (i = 0; i < LENGTH(uriparams); ++i) {
314 if (!regcomp(&(uriparams[i].re), uriparams[i].uri,
316 /* copy default parameters if they are not already set
317 * or if they are forced */
318 for (j = 0; j < ParameterLast; ++j) {
319 if (!uriparams[i].config[j].force ||
321 uriparams[i].config[j] = defconfig[j];
325 "Could not compile regex: %s\n",
327 uriparams[i].uri = NULL;
335 if (signal(SIGCHLD, sigchld) == SIG_ERR)
336 die("Can't install SIGCHLD handler");
337 while (waitpid(-1, NULL, WNOHANG) > 0)
347 for (c = clients; c; c = c->next)
352 buildfile(const char *path)
354 char *dname, *bname, *bpath, *fpath;
357 dname = g_path_get_dirname(path);
358 bname = g_path_get_basename(path);
360 bpath = buildpath(dname);
363 fpath = g_build_filename(bpath, bname, NULL);
367 if (!(f = fopen(fpath, "a")))
368 die("Could not open file: %s\n", fpath);
370 g_chmod(fpath, 0600); /* always */
377 getuserhomedir(const char *user)
379 struct passwd *pw = getpwnam(user);
382 die("Can't get user %s login information.\n", user);
388 getcurrentuserhomedir(void)
394 homedir = getenv("HOME");
398 user = getenv("USER");
400 return getuserhomedir(user);
402 pw = getpwuid(getuid());
404 die("Can't get current user home directory\n");
410 buildpath(const char *path)
412 char *apath, *name, *p, *fpath;
415 if (path[0] == '~') {
416 if (path[1] == '/' || path[1] == '\0') {
417 p = (char *)&path[1];
418 homedir = getcurrentuserhomedir();
420 if ((p = strchr(path, '/')))
421 name = g_strndup(&path[1], --p - path);
423 name = g_strdup(&path[1]);
425 homedir = getuserhomedir(name);
428 apath = g_build_filename(homedir, p, NULL);
430 apath = g_strdup(path);
433 /* creating directory */
434 if (g_mkdir_with_parents(apath, 0700) < 0)
435 die("Could not access directory: %s\n", apath);
437 fpath = realpath(apath, NULL);
444 newclient(Client *rc)
448 if (!(c = calloc(1, sizeof(Client))))
449 die("Cannot malloc!\n");
455 c->tlsflags = G_TLS_CERTIFICATE_VALIDATE_ALL + 1;
456 c->view = newview(c, rc ? rc->view : NULL);
462 loaduri(Client *c, const Arg *a)
466 const char *uri = a->v;
468 if (g_strcmp0(uri, "") == 0)
471 if (g_str_has_prefix(uri, "http://") ||
472 g_str_has_prefix(uri, "https://") ||
473 g_str_has_prefix(uri, "file://") ||
474 g_str_has_prefix(uri, "about:")) {
476 } else if (!stat(uri, &st) && (path = realpath(uri, NULL))) {
477 url = g_strdup_printf("file://%s", path);
480 url = g_strdup_printf("http://%s", uri);
483 setatom(c, AtomUri, url);
485 if (strcmp(url, geturi(c)) == 0) {
488 webkit_web_view_load_uri(c->view, url);
500 if (!(uri = webkit_web_view_get_uri(c->view)))
506 setatom(Client *c, int a, const char *v)
509 XChangeProperty(dpy, c->xid,
510 atoms[a], XA_STRING, 8, PropModeReplace,
511 (unsigned char *)v, strlen(v) + 1);
515 getatom(Client *c, int a)
517 static char buf[BUFSIZ];
520 unsigned long ldummy;
521 unsigned char *p = NULL;
523 XGetWindowProperty(dpy, c->xid, atoms[a], 0L, BUFSIZ, False, XA_STRING,
524 &adummy, &idummy, &ldummy, &ldummy, &p);
526 strncpy(buf, (char *)p, LENGTH(buf) - 1);
535 updatetitle(Client *c)
538 const char *name = c->overtitle ? c->overtitle :
539 c->title ? c->title : "";
541 if (curconfig[ShowIndicators].val.b) {
545 if (c->progress != 100)
546 title = g_strdup_printf("[%i%%] %s:%s | %s",
547 c->progress, togglestats, pagestats, name);
549 title = g_strdup_printf("%s:%s | %s",
550 togglestats, pagestats, name);
552 gtk_window_set_title(GTK_WINDOW(c->win), title);
555 gtk_window_set_title(GTK_WINDOW(c->win), name);
560 gettogglestats(Client *c)
562 togglestats[0] = cookiepolicy_set(cookiepolicy_get());
563 togglestats[1] = curconfig[CaretBrowsing].val.b ? 'C' : 'c';
564 togglestats[2] = curconfig[Geolocation].val.b ? 'G' : 'g';
565 togglestats[3] = curconfig[DiskCache].val.b ? 'D' : 'd';
566 togglestats[4] = curconfig[LoadImages].val.b ? 'I' : 'i';
567 togglestats[5] = curconfig[JavaScript].val.b ? 'S' : 's';
568 togglestats[6] = curconfig[Plugins].val.b ? 'V' : 'v';
569 togglestats[7] = curconfig[Style].val.b ? 'M' : 'm';
570 togglestats[8] = curconfig[FrameFlattening].val.b ? 'F' : 'f';
571 togglestats[9] = '\0';
575 getpagestats(Client *c)
577 pagestats[0] = c->tlsflags > G_TLS_CERTIFICATE_VALIDATE_ALL ? '-' :
578 c->tlsflags > 0 ? 'U' : 'T';
582 WebKitCookieAcceptPolicy
583 cookiepolicy_get(void)
585 switch (((char *)curconfig[CookiePolicies].val.v)[cookiepolicy]) {
587 return WEBKIT_COOKIE_POLICY_ACCEPT_NEVER;
589 return WEBKIT_COOKIE_POLICY_ACCEPT_NO_THIRD_PARTY;
590 default: /* fallthrough */
592 return WEBKIT_COOKIE_POLICY_ACCEPT_ALWAYS;
597 cookiepolicy_set(const WebKitCookieAcceptPolicy p)
600 case WEBKIT_COOKIE_POLICY_ACCEPT_NEVER:
602 case WEBKIT_COOKIE_POLICY_ACCEPT_NO_THIRD_PARTY:
604 default: /* fallthrough */
605 case WEBKIT_COOKIE_POLICY_ACCEPT_ALWAYS:
611 seturiparameters(Client *c, const char *uri)
615 for (i = 0; i < LENGTH(uriparams); ++i) {
616 if (uriparams[i].uri &&
617 !regexec(&(uriparams[i].re), uri, 0, NULL, 0)) {
618 curconfig = uriparams[i].config;
623 for (i = 0; i < ParameterLast; ++i)
624 setparameter(c, 0, i, &curconfig[i].val);
628 setparameter(Client *c, int refresh, ParamName p, const Arg *a)
630 GdkRGBA bgcolor = { 0 };
631 WebKitSettings *s = webkit_web_view_get_settings(c->view);
634 case AcceleratedCanvas:
635 webkit_settings_set_enable_accelerated_2d_canvas(s, a->b);
638 webkit_settings_set_enable_caret_browsing(s, a->b);
642 webkit_cookie_manager_set_accept_policy(
643 webkit_web_context_get_cookie_manager(
644 webkit_web_view_get_context(c->view)),
649 webkit_web_context_set_cache_model(
650 webkit_web_view_get_context(c->view), a->b ?
651 WEBKIT_CACHE_MODEL_WEB_BROWSER :
652 WEBKIT_CACHE_MODEL_DOCUMENT_VIEWER);
653 return; /* do not update */
655 webkit_settings_set_enable_dns_prefetching(s, a->b);
656 return; /* do not update */
658 webkit_settings_set_default_font_size(s, a->i);
659 return; /* do not update */
660 case FrameFlattening:
661 webkit_settings_set_enable_frame_flattening(s, a->b);
668 webkit_web_view_set_background_color(c->view, &bgcolor);
669 return; /* do not update */
671 webkit_settings_set_enable_developer_extras(s, a->b);
672 return; /* do not update */
674 webkit_settings_set_enable_javascript(s, a->b);
677 return; /* do nothing */
679 webkit_settings_set_auto_load_images(s, a->b);
681 case MediaManualPlay:
682 webkit_settings_set_media_playback_requires_user_gesture(s, a->b);
685 webkit_settings_set_enable_plugins(s, a->b);
687 case PreferredLanguages:
688 return; /* do nothing */
689 case RunInFullscreen:
690 return; /* do nothing */
692 /* Disabled until we write some WebKitWebExtension for
693 * manipulating the DOM directly.
694 enablescrollbars = !enablescrollbars;
695 evalscript(c, "document.documentElement.style.overflow = '%s'",
696 enablescrollbars ? "auto" : "hidden");
698 return; /* do not update */
702 webkit_settings_set_enable_site_specific_quirks(s, a->b);
705 webkit_web_context_set_spell_checking_enabled(
706 webkit_web_view_get_context(c->view), a->b);
707 return; /* do not update */
709 return; /* do nothing */
711 webkit_web_context_set_tls_errors_policy(
712 webkit_web_view_get_context(c->view), a->b ?
713 WEBKIT_TLS_ERRORS_POLICY_FAIL :
714 WEBKIT_TLS_ERRORS_POLICY_IGNORE);
715 return; /* do not update */
718 setstyle(c, getstyle(geturi(c)));
720 webkit_user_content_manager_remove_all_style_sheets(
721 webkit_web_view_get_user_content_manager(c->view));
725 webkit_web_view_set_zoom_level(c->view, a->f);
726 return; /* do not update */
728 return; /* do nothing */
737 getstyle(const char *uri)
744 for (i = 0; i < LENGTH(styles); ++i) {
745 if (styles[i].regex &&
746 !regexec(&(styles[i].re), uri, 0, NULL, 0))
747 return styles[i].style;
754 setstyle(Client *c, const char *stylefile)
758 if (!g_file_get_contents(stylefile, &style, NULL, NULL)) {
759 fprintf(stderr, "Could not read style file: %s\n", stylefile);
763 webkit_user_content_manager_add_style_sheet(
764 webkit_web_view_get_user_content_manager(c->view),
765 webkit_user_style_sheet_new(style,
766 WEBKIT_USER_CONTENT_INJECT_ALL_FRAMES,
767 WEBKIT_USER_STYLE_LEVEL_USER,
779 if (g_file_get_contents(scriptfile, &script, &l, NULL) && l)
780 evalscript(c, script);
785 evalscript(Client *c, const char *jsstr, ...)
791 script = g_strdup_vprintf(jsstr, ap);
794 webkit_web_view_run_javascript(c->view, script, NULL, NULL, NULL);
799 updatewinid(Client *c)
801 snprintf(winid, LENGTH(winid), "%lu", c->xid);
805 handleplumb(Client *c, const char *uri)
807 Arg a = (Arg)PLUMB(uri);
812 newwindow(Client *c, const Arg *a, int noembed)
816 const char *cmd[26], *uri;
817 const Arg arg = { .v = cmd };
821 cmd[i++] = curconfig[CookiePolicies].val.v;
822 cmd[i++] = curconfig[ScrollBars].val.b ? "-B" : "-b";
823 if (cookiefile && g_strcmp0(cookiefile, "")) {
825 cmd[i++] = cookiefile;
827 cmd[i++] = curconfig[DiskCache].val.b ? "-D" : "-d";
828 if (embed && !noembed) {
830 snprintf(tmp, LENGTH(tmp), "%lu", embed);
833 cmd[i++] = curconfig[RunInFullscreen].val.b ? "-F" : "-f" ;
834 cmd[i++] = curconfig[Geolocation].val.b ? "-G" : "-g" ;
835 cmd[i++] = curconfig[LoadImages].val.b ? "-I" : "-i" ;
836 cmd[i++] = curconfig[KioskMode].val.b ? "-K" : "-k" ;
837 cmd[i++] = curconfig[Style].val.b ? "-M" : "-m" ;
838 cmd[i++] = curconfig[Inspector].val.b ? "-N" : "-n" ;
839 cmd[i++] = curconfig[Plugins].val.b ? "-P" : "-p" ;
840 if (scriptfile && g_strcmp0(scriptfile, "")) {
842 cmd[i++] = scriptfile;
844 cmd[i++] = curconfig[JavaScript].val.b ? "-S" : "-s";
845 if (stylefile && g_strcmp0(stylefile, "")) {
847 cmd[i++] = stylefile;
849 if (fulluseragent && g_strcmp0(fulluseragent, "")) {
851 cmd[i++] = fulluseragent;
855 /* do not keep zoom level */
865 spawn(Client *c, const Arg *a)
869 close(ConnectionNumber(dpy));
871 execvp(((char **)a->v)[0], (char **)a->v);
872 fprintf(stderr, "%s: execvp %s", argv0, ((char **)a->v)[0]);
879 destroyclient(Client *c)
883 webkit_web_view_stop_loading(c->view);
884 /* Not needed, has already been called
885 gtk_widget_destroy(c->win);
888 for (p = clients; p && p->next != c; p = p->next)
901 destroyclient(clients);
910 newview(Client *c, WebKitWebView *rv)
913 WebKitSettings *settings;
914 WebKitUserContentManager *contentmanager;
915 WebKitWebContext *context;
920 webkit_web_view_new_with_related_view(rv));
922 settings = webkit_settings_new_with_settings(
923 "auto-load-images", curconfig[LoadImages].val.b,
924 "default-font-size", curconfig[FontSize].val.i,
925 "enable-caret-browsing", curconfig[CaretBrowsing].val.b,
926 "enable-developer-extras", curconfig[Inspector].val.b,
927 "enable-dns-prefetching", curconfig[DNSPrefetch].val.b,
928 "enable-frame-flattening", curconfig[FrameFlattening].val.b,
929 "enable-html5-database", curconfig[DiskCache].val.b,
930 "enable-html5-local-storage", curconfig[DiskCache].val.b,
931 "enable-javascript", curconfig[JavaScript].val.b,
932 "enable-plugins", curconfig[Plugins].val.b,
933 "enable-accelerated-2d-canvas", curconfig[AcceleratedCanvas].val.b,
934 "enable-site-specific-quirks", curconfig[SiteQuirks].val.b,
935 "media-playback-requires-user-gesture", curconfig[MediaManualPlay].val.b,
937 /* For mor interesting settings, have a look at
938 * http://webkitgtk.org/reference/webkit2gtk/stable/WebKitSettings.html */
940 if (strcmp(fulluseragent, "")) {
941 webkit_settings_set_user_agent(settings, fulluseragent);
942 } else if (surfuseragent) {
943 webkit_settings_set_user_agent_with_application_details(
944 settings, "Surf", VERSION);
946 useragent = webkit_settings_get_user_agent(settings);
948 contentmanager = webkit_user_content_manager_new();
950 context = webkit_web_context_new_with_website_data_manager(
951 webkit_website_data_manager_new(
952 "base-cache-directory", cachedir,
953 "base-data-directory", cachedir,
956 /* rendering process model, can be a shared unique one
957 * or one for each view */
958 webkit_web_context_set_process_model(context,
959 WEBKIT_PROCESS_MODEL_MULTIPLE_SECONDARY_PROCESSES);
961 webkit_web_context_set_tls_errors_policy(context,
962 curconfig[StrictSSL].val.b ? WEBKIT_TLS_ERRORS_POLICY_FAIL :
963 WEBKIT_TLS_ERRORS_POLICY_IGNORE);
965 webkit_web_context_set_cache_model(context,
966 curconfig[DiskCache].val.b ? WEBKIT_CACHE_MODEL_WEB_BROWSER :
967 WEBKIT_CACHE_MODEL_DOCUMENT_VIEWER);
969 /* Currently only works with text file to be compatible with curl */
970 webkit_cookie_manager_set_persistent_storage(
971 webkit_web_context_get_cookie_manager(context), cookiefile,
972 WEBKIT_COOKIE_PERSISTENT_STORAGE_TEXT);
974 webkit_cookie_manager_set_accept_policy(
975 webkit_web_context_get_cookie_manager(context),
978 webkit_web_context_set_preferred_languages(context,
979 curconfig[PreferredLanguages].val.v);
980 webkit_web_context_set_spell_checking_languages(context,
981 curconfig[SpellLanguages].val.v);
982 webkit_web_context_set_spell_checking_enabled(context,
983 curconfig[SpellChecking].val.b);
985 g_signal_connect(G_OBJECT(context), "download-started",
986 G_CALLBACK(downloadstarted), c);
987 g_signal_connect(G_OBJECT(context), "initialize-web-extensions",
988 G_CALLBACK(initwebextensions), c);
990 v = g_object_new(WEBKIT_TYPE_WEB_VIEW,
991 "settings", settings,
992 "user-content-manager", contentmanager,
993 "web-context", context,
997 g_signal_connect(G_OBJECT(v), "notify::estimated-load-progress",
998 G_CALLBACK(progresschanged), c);
999 g_signal_connect(G_OBJECT(v), "notify::title",
1000 G_CALLBACK(titlechanged), c);
1001 g_signal_connect(G_OBJECT(v), "button-release-event",
1002 G_CALLBACK(buttonreleased), c);
1003 g_signal_connect(G_OBJECT(v), "close",
1004 G_CALLBACK(closeview), c);
1005 g_signal_connect(G_OBJECT(v), "create",
1006 G_CALLBACK(createview), c);
1007 g_signal_connect(G_OBJECT(v), "decide-policy",
1008 G_CALLBACK(decidepolicy), c);
1009 g_signal_connect(G_OBJECT(v), "load-changed",
1010 G_CALLBACK(loadchanged), c);
1011 g_signal_connect(G_OBJECT(v), "mouse-target-changed",
1012 G_CALLBACK(mousetargetchanged), c);
1013 g_signal_connect(G_OBJECT(v), "permission-request",
1014 G_CALLBACK(permissionrequested), c);
1015 g_signal_connect(G_OBJECT(v), "ready-to-show",
1016 G_CALLBACK(showview), c);
1022 initwebextensions(WebKitWebContext *wc, Client *c)
1024 webkit_web_context_set_web_extensions_directory(wc, WEBEXTDIR);
1028 createview(WebKitWebView *v, WebKitNavigationAction *a, Client *c)
1032 switch (webkit_navigation_action_get_navigation_type(a)) {
1033 case WEBKIT_NAVIGATION_TYPE_OTHER: /* fallthrough */
1035 * popup windows of type “other” are almost always triggered
1036 * by user gesture, so inverse the logic here
1038 /* instead of this, compare destination uri to mouse-over uri for validating window */
1039 if (webkit_navigation_action_is_user_gesture(a))
1041 case WEBKIT_NAVIGATION_TYPE_LINK_CLICKED: /* fallthrough */
1042 case WEBKIT_NAVIGATION_TYPE_FORM_SUBMITTED: /* fallthrough */
1043 case WEBKIT_NAVIGATION_TYPE_BACK_FORWARD: /* fallthrough */
1044 case WEBKIT_NAVIGATION_TYPE_RELOAD: /* fallthrough */
1045 case WEBKIT_NAVIGATION_TYPE_FORM_RESUBMITTED:
1052 return GTK_WIDGET(n->view);
1056 buttonreleased(GtkWidget *w, GdkEvent *e, Client *c)
1058 WebKitHitTestResultContext element;
1061 element = webkit_hit_test_result_get_context(c->mousepos);
1063 for (i = 0; i < LENGTH(buttons); ++i) {
1064 if (element & buttons[i].target &&
1065 e->button.button == buttons[i].button &&
1066 CLEANMASK(e->button.state) == CLEANMASK(buttons[i].mask) &&
1068 buttons[i].func(c, &buttons[i].arg, c->mousepos);
1069 return buttons[i].stopevent;
1077 processx(GdkXEvent *e, GdkEvent *event, gpointer d)
1079 Client *c = (Client *)d;
1083 if (((XEvent *)e)->type == PropertyNotify) {
1084 ev = &((XEvent *)e)->xproperty;
1085 if (ev->state == PropertyNewValue) {
1086 if (ev->atom == atoms[AtomFind]) {
1089 return GDK_FILTER_REMOVE;
1090 } else if (ev->atom == atoms[AtomGo]) {
1091 a.v = getatom(c, AtomGo);
1094 return GDK_FILTER_REMOVE;
1098 return GDK_FILTER_CONTINUE;
1102 winevent(GtkWidget *w, GdkEvent *e, Client *c)
1107 case GDK_ENTER_NOTIFY:
1108 c->overtitle = c->targeturi;
1112 if (!curconfig[KioskMode].val.b) {
1113 for (i = 0; i < LENGTH(keys); ++i) {
1114 if (gdk_keyval_to_lower(e->key.keyval) ==
1116 CLEANMASK(e->key.state) == keys[i].mod &&
1119 keys[i].func(c, &(keys[i].arg));
1124 case GDK_LEAVE_NOTIFY:
1125 c->overtitle = NULL;
1128 case GDK_WINDOW_STATE:
1129 if (e->window_state.changed_mask ==
1130 GDK_WINDOW_STATE_FULLSCREEN)
1131 c->fullscreen = e->window_state.new_window_state &
1132 GDK_WINDOW_STATE_FULLSCREEN;
1142 showview(WebKitWebView *v, Client *c)
1144 GdkRGBA bgcolor = { 0 };
1147 c->finder = webkit_web_view_get_find_controller(c->view);
1148 c->inspector = webkit_web_view_get_inspector(c->view);
1150 c->win = createwindow(c);
1152 gtk_container_add(GTK_CONTAINER(c->win), GTK_WIDGET(c->view));
1153 gtk_widget_show_all(c->win);
1154 gtk_widget_grab_focus(GTK_WIDGET(c->view));
1156 gwin = gtk_widget_get_window(GTK_WIDGET(c->win));
1157 c->xid = gdk_x11_window_get_xid(gwin);
1160 gdk_display_sync(gtk_widget_get_display(c->win));
1164 if (curconfig[HideBackground].val.b)
1165 webkit_web_view_set_background_color(c->view, &bgcolor);
1167 if (!curconfig[KioskMode].val.b) {
1168 gdk_window_set_events(gwin, GDK_ALL_EVENTS_MASK);
1169 gdk_window_add_filter(gwin, processx, c);
1172 if (curconfig[RunInFullscreen].val.b)
1173 togglefullscreen(c, NULL);
1175 if (curconfig[ZoomLevel].val.f != 1.0)
1176 webkit_web_view_set_zoom_level(c->view,
1177 curconfig[ZoomLevel].val.f);
1179 setatom(c, AtomFind, "");
1180 setatom(c, AtomUri, "about:blank");
1184 createwindow(Client *c)
1190 w = gtk_plug_new(embed);
1192 w = gtk_window_new(GTK_WINDOW_TOPLEVEL);
1194 wmstr = g_path_get_basename(argv0);
1195 gtk_window_set_wmclass(GTK_WINDOW(w), wmstr, "Surf");
1198 wmstr = g_strdup_printf("%s[%lu]", "Surf",
1199 webkit_web_view_get_page_id(c->view));
1200 gtk_window_set_role(GTK_WINDOW(w), wmstr);
1203 gtk_window_set_default_size(GTK_WINDOW(w), winsize[0], winsize[1]);
1206 g_signal_connect(G_OBJECT(w), "destroy",
1207 G_CALLBACK(destroywin), c);
1208 g_signal_connect(G_OBJECT(w), "enter-notify-event",
1209 G_CALLBACK(winevent), c);
1210 g_signal_connect(G_OBJECT(w), "key-press-event",
1211 G_CALLBACK(winevent), c);
1212 g_signal_connect(G_OBJECT(w), "leave-notify-event",
1213 G_CALLBACK(winevent), c);
1214 g_signal_connect(G_OBJECT(w), "window-state-event",
1215 G_CALLBACK(winevent), c);
1221 loadchanged(WebKitWebView *v, WebKitLoadEvent e, Client *c)
1223 const char *title = geturi(c);
1226 case WEBKIT_LOAD_STARTED:
1227 curconfig = defconfig;
1228 setatom(c, AtomUri, title);
1230 c->tlsflags = G_TLS_CERTIFICATE_VALIDATE_ALL + 1;
1231 seturiparameters(c, geturi(c));
1233 case WEBKIT_LOAD_REDIRECTED:
1234 setatom(c, AtomUri, title);
1236 seturiparameters(c, geturi(c));
1238 case WEBKIT_LOAD_COMMITTED:
1239 if (!webkit_web_view_get_tls_info(c->view, NULL,
1241 c->tlsflags = G_TLS_CERTIFICATE_VALIDATE_ALL + 1;
1244 case WEBKIT_LOAD_FINISHED:
1245 /* Disabled until we write some WebKitWebExtension for
1246 * manipulating the DOM directly.
1247 evalscript(c, "document.documentElement.style.overflow = '%s'",
1248 enablescrollbars ? "auto" : "hidden");
1257 progresschanged(WebKitWebView *v, GParamSpec *ps, Client *c)
1259 c->progress = webkit_web_view_get_estimated_load_progress(c->view) *
1265 titlechanged(WebKitWebView *view, GParamSpec *ps, Client *c)
1267 c->title = webkit_web_view_get_title(c->view);
1272 mousetargetchanged(WebKitWebView *v, WebKitHitTestResult *h, guint modifiers,
1275 WebKitHitTestResultContext hc = webkit_hit_test_result_get_context(h);
1277 /* Keep the hit test to know where is the pointer on the next click */
1281 c->targeturi = webkit_hit_test_result_get_link_uri(h);
1282 else if (hc & OnImg)
1283 c->targeturi = webkit_hit_test_result_get_image_uri(h);
1284 else if (hc & OnMedia)
1285 c->targeturi = webkit_hit_test_result_get_media_uri(h);
1287 c->targeturi = NULL;
1289 c->overtitle = c->targeturi;
1294 permissionrequested(WebKitWebView *v, WebKitPermissionRequest *r, Client *c)
1296 if (WEBKIT_IS_GEOLOCATION_PERMISSION_REQUEST(r)) {
1297 if (curconfig[Geolocation].val.b)
1298 webkit_permission_request_allow(r);
1300 webkit_permission_request_deny(r);
1308 decidepolicy(WebKitWebView *v, WebKitPolicyDecision *d,
1309 WebKitPolicyDecisionType dt, Client *c)
1312 case WEBKIT_POLICY_DECISION_TYPE_NAVIGATION_ACTION:
1313 decidenavigation(d, c);
1315 case WEBKIT_POLICY_DECISION_TYPE_NEW_WINDOW_ACTION:
1316 decidenewwindow(d, c);
1318 case WEBKIT_POLICY_DECISION_TYPE_RESPONSE:
1319 decideresource(d, c);
1322 webkit_policy_decision_ignore(d);
1329 decidenavigation(WebKitPolicyDecision *d, Client *c)
1331 WebKitNavigationAction *a =
1332 webkit_navigation_policy_decision_get_navigation_action(
1333 WEBKIT_NAVIGATION_POLICY_DECISION(d));
1335 switch (webkit_navigation_action_get_navigation_type(a)) {
1336 case WEBKIT_NAVIGATION_TYPE_LINK_CLICKED: /* fallthrough */
1337 case WEBKIT_NAVIGATION_TYPE_FORM_SUBMITTED: /* fallthrough */
1338 case WEBKIT_NAVIGATION_TYPE_BACK_FORWARD: /* fallthrough */
1339 case WEBKIT_NAVIGATION_TYPE_RELOAD: /* fallthrough */
1340 case WEBKIT_NAVIGATION_TYPE_FORM_RESUBMITTED: /* fallthrough */
1341 case WEBKIT_NAVIGATION_TYPE_OTHER: /* fallthrough */
1343 /* Do not navigate to links with a "_blank" target (popup) */
1344 if (webkit_navigation_policy_decision_get_frame_name(
1345 WEBKIT_NAVIGATION_POLICY_DECISION(d))) {
1346 webkit_policy_decision_ignore(d);
1348 /* Filter out navigation to different domain ? */
1349 /* get action→urirequest, copy and load in new window+view
1350 * on Ctrl+Click ? */
1351 webkit_policy_decision_use(d);
1358 decidenewwindow(WebKitPolicyDecision *d, Client *c)
1361 WebKitNavigationAction *a =
1362 webkit_navigation_policy_decision_get_navigation_action(
1363 WEBKIT_NAVIGATION_POLICY_DECISION(d));
1366 switch (webkit_navigation_action_get_navigation_type(a)) {
1367 case WEBKIT_NAVIGATION_TYPE_LINK_CLICKED: /* fallthrough */
1368 case WEBKIT_NAVIGATION_TYPE_FORM_SUBMITTED: /* fallthrough */
1369 case WEBKIT_NAVIGATION_TYPE_BACK_FORWARD: /* fallthrough */
1370 case WEBKIT_NAVIGATION_TYPE_RELOAD: /* fallthrough */
1371 case WEBKIT_NAVIGATION_TYPE_FORM_RESUBMITTED:
1372 /* Filter domains here */
1373 /* If the value of “mouse-button” is not 0, then the navigation was triggered by a mouse event.
1374 * test for link clicked but no button ? */
1375 arg.v = webkit_uri_request_get_uri(
1376 webkit_navigation_action_get_request(a));
1377 newwindow(c, &arg, 0);
1379 case WEBKIT_NAVIGATION_TYPE_OTHER: /* fallthrough */
1384 webkit_policy_decision_ignore(d);
1388 decideresource(WebKitPolicyDecision *d, Client *c)
1391 WebKitResponsePolicyDecision *r = WEBKIT_RESPONSE_POLICY_DECISION(d);
1392 WebKitURIResponse *res =
1393 webkit_response_policy_decision_get_response(r);
1394 const gchar *uri = webkit_uri_response_get_uri(res);
1396 if (g_str_has_suffix(uri, "/favicon.ico")) {
1397 webkit_policy_decision_ignore(d);
1401 if (!g_str_has_prefix(uri, "http://")
1402 && !g_str_has_prefix(uri, "https://")
1403 && !g_str_has_prefix(uri, "about:")
1404 && !g_str_has_prefix(uri, "file://")
1405 && !g_str_has_prefix(uri, "data:")
1406 && !g_str_has_prefix(uri, "blob:")
1407 && strlen(uri) > 0) {
1408 for (i = 0; i < strlen(uri); i++) {
1409 if (!g_ascii_isprint(uri[i])) {
1415 handleplumb(c, uri);
1416 webkit_policy_decision_ignore(d);
1421 if (webkit_response_policy_decision_is_mime_type_supported(r)) {
1422 webkit_policy_decision_use(d);
1424 webkit_policy_decision_ignore(d);
1430 downloadstarted(WebKitWebContext *wc, WebKitDownload *d, Client *c)
1432 g_signal_connect(G_OBJECT(d), "notify::response",
1433 G_CALLBACK(responsereceived), c);
1437 responsereceived(WebKitDownload *d, GParamSpec *ps, Client *c)
1439 download(c, webkit_download_get_response(d));
1440 webkit_download_cancel(d);
1444 download(Client *c, WebKitURIResponse *r)
1446 Arg a = (Arg)DOWNLOAD(webkit_uri_response_get_uri(r), geturi(c));
1451 closeview(WebKitWebView *v, Client *c)
1453 gtk_widget_destroy(c->win);
1457 destroywin(GtkWidget* w, Client *c)
1465 pasteuri(GtkClipboard *clipboard, const char *text, gpointer d)
1467 Arg a = {.v = text };
1469 loaduri((Client *) d, &a);
1473 reload(Client *c, const Arg *a)
1476 webkit_web_view_reload_bypass_cache(c->view);
1478 webkit_web_view_reload(c->view);
1482 print(Client *c, const Arg *a)
1484 webkit_print_operation_run_dialog(webkit_print_operation_new(c->view),
1485 GTK_WINDOW(c->win));
1489 clipboard(Client *c, const Arg *a)
1491 if (a->b) { /* load clipboard uri */
1492 gtk_clipboard_request_text(gtk_clipboard_get(
1493 GDK_SELECTION_PRIMARY),
1495 } else { /* copy uri */
1496 gtk_clipboard_set_text(gtk_clipboard_get(
1497 GDK_SELECTION_PRIMARY), c->targeturi
1498 ? c->targeturi : geturi(c), -1);
1503 zoom(Client *c, const Arg *a)
1506 webkit_web_view_set_zoom_level(c->view,
1507 curconfig[ZoomLevel].val.f + 0.1);
1509 webkit_web_view_set_zoom_level(c->view,
1510 curconfig[ZoomLevel].val.f - 0.1);
1512 webkit_web_view_set_zoom_level(c->view, 1.0);
1514 curconfig[ZoomLevel].val.f = webkit_web_view_get_zoom_level(c->view);
1518 scroll(Client *c, const Arg *a)
1520 GdkEvent *ev = gdk_event_new(GDK_KEY_PRESS);
1522 gdk_event_set_device(ev, gdkkb);
1523 ev->key.window = gtk_widget_get_window(GTK_WIDGET(c->win));
1524 ev->key.state = GDK_CONTROL_MASK;
1525 ev->key.time = GDK_CURRENT_TIME;
1529 ev->key.keyval = GDK_KEY_Down;
1532 ev->key.keyval = GDK_KEY_Page_Down;
1535 ev->key.keyval = GDK_KEY_Left;
1538 ev->key.keyval = GDK_KEY_Right;
1541 ev->key.keyval = GDK_KEY_Page_Up;
1544 ev->key.keyval = GDK_KEY_Up;
1552 navigate(Client *c, const Arg *a)
1555 webkit_web_view_go_back(c->view);
1557 webkit_web_view_go_forward(c->view);
1561 stop(Client *c, const Arg *a)
1563 webkit_web_view_stop_loading(c->view);
1567 toggle(Client *c, const Arg *a)
1569 curconfig[a->i].val.b ^= 1;
1570 setparameter(c, 1, (ParamName)a->i, &curconfig[a->i].val);
1574 togglefullscreen(Client *c, const Arg *a)
1576 /* toggling value is handled in winevent() */
1578 gtk_window_unfullscreen(GTK_WINDOW(c->win));
1580 gtk_window_fullscreen(GTK_WINDOW(c->win));
1584 togglecookiepolicy(Client *c, const Arg *a)
1587 cookiepolicy %= strlen(curconfig[CookiePolicies].val.v);
1589 setparameter(c, 0, CookiePolicies, NULL);
1593 toggleinspector(Client *c, const Arg *a)
1595 if (webkit_web_inspector_is_attached(c->inspector))
1596 webkit_web_inspector_close(c->inspector);
1597 else if (curconfig[Inspector].val.b)
1598 webkit_web_inspector_show(c->inspector);
1602 find(Client *c, const Arg *a)
1608 webkit_find_controller_search_next(c->finder);
1610 webkit_find_controller_search_previous(c->finder);
1612 s = getatom(c, AtomFind);
1613 f = webkit_find_controller_get_search_text(c->finder);
1615 if (g_strcmp0(f, s) == 0) /* reset search */
1616 webkit_find_controller_search(c->finder, "", findopts,
1619 webkit_find_controller_search(c->finder, s, findopts,
1622 if (strcmp(s, "") == 0)
1623 webkit_find_controller_search_finish(c->finder);
1628 clicknavigate(Client *c, const Arg *a, WebKitHitTestResult *h)
1634 clicknewwindow(Client *c, const Arg *a, WebKitHitTestResult *h)
1638 arg.v = webkit_hit_test_result_get_link_uri(h);
1639 newwindow(c, &arg, a->b);
1643 clickexternplayer(Client *c, const Arg *a, WebKitHitTestResult *h)
1647 arg = (Arg)VIDEOPLAY(webkit_hit_test_result_get_media_uri(h));
1652 main(int argc, char *argv[])
1657 memset(&arg, 0, sizeof(arg));
1659 /* command line args */
1662 defconfig CSETV(CookiePolicies, EARGF(usage()));
1665 defconfig CSETB(ScrollBars, 0);
1668 defconfig CSETB(ScrollBars, 1);
1671 cookiefile = EARGF(usage());
1674 defconfig CSETB(DiskCache, 0);
1677 defconfig CSETB(DiskCache, 1);
1680 embed = strtol(EARGF(usage()), NULL, 0);
1683 defconfig CSETB(RunInFullscreen, 0);
1686 defconfig CSETB(RunInFullscreen, 1);
1689 defconfig CSETB(Geolocation, 0);
1692 defconfig CSETB(Geolocation, 1);
1695 defconfig CSETB(LoadImages, 0);
1698 defconfig CSETB(LoadImages, 1);
1701 defconfig CSETB(KioskMode, 0);
1704 defconfig CSETB(KioskMode, 1);
1707 defconfig CSETB(Style, 0);
1710 defconfig CSETB(Style, 1);
1713 defconfig CSETB(Inspector, 0);
1716 defconfig CSETB(Inspector, 1);
1719 defconfig CSETB(Plugins, 0);
1722 defconfig CSETB(Plugins, 1);
1725 scriptfile = EARGF(usage());
1728 defconfig CSETB(JavaScript, 0);
1731 defconfig CSETB(JavaScript, 1);
1734 stylefile = EARGF(usage());
1737 fulluseragent = EARGF(usage());
1740 die("surf-"VERSION", ©2009-2015 surf engineers, "
1741 "see LICENSE for details\n");
1746 defconfig CSETF(ZoomLevel, strtof(EARGF(usage()), NULL));
1754 arg.v = "about:blank";
1757 c = newclient(NULL);