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 gtk_init(NULL, NULL);
276 gdpy = gdk_display_get_default();
277 dpy = GDK_DISPLAY_XDISPLAY(gdpy);
279 curconfig = defconfig;
282 atoms[AtomFind] = XInternAtom(dpy, "_SURF_FIND", False);
283 atoms[AtomGo] = XInternAtom(dpy, "_SURF_GO", False);
284 atoms[AtomUri] = XInternAtom(dpy, "_SURF_URI", False);
287 cookiefile = buildfile(cookiefile);
288 scriptfile = buildfile(scriptfile);
289 cachedir = buildpath(cachedir);
291 gdkkb = gdk_seat_get_keyboard(gdk_display_get_default_seat(gdpy));
294 styledir = buildpath(styledir);
295 for (i = 0; i < LENGTH(styles); ++i) {
296 if (regcomp(&(styles[i].re), styles[i].regex,
299 "Could not compile regex: %s\n",
301 styles[i].regex = NULL;
303 styles[i].style = g_strconcat(styledir, "/",
304 styles[i].style, NULL);
308 stylefile = buildfile(stylefile);
311 for (i = 0; i < LENGTH(uriparams); ++i) {
312 if (!regcomp(&(uriparams[i].re), uriparams[i].uri,
314 /* copy default parameters if they are not already set
315 * or if they are forced */
316 for (j = 0; j < ParameterLast; ++j) {
317 if (!uriparams[i].config[j].force ||
319 uriparams[i].config[j] = defconfig[j];
323 "Could not compile regex: %s\n",
325 uriparams[i].uri = NULL;
333 if (signal(SIGCHLD, sigchld) == SIG_ERR)
334 die("Can't install SIGCHLD handler");
335 while (waitpid(-1, NULL, WNOHANG) > 0)
345 for (c = clients; c; c = c->next)
350 buildfile(const char *path)
352 char *dname, *bname, *bpath, *fpath;
355 dname = g_path_get_dirname(path);
356 bname = g_path_get_basename(path);
358 bpath = buildpath(dname);
361 fpath = g_build_filename(bpath, bname, NULL);
365 if (!(f = fopen(fpath, "a")))
366 die("Could not open file: %s\n", fpath);
368 g_chmod(fpath, 0600); /* always */
375 getuserhomedir(const char *user)
377 struct passwd *pw = getpwnam(user);
380 die("Can't get user %s login information.\n", user);
386 getcurrentuserhomedir(void)
392 homedir = getenv("HOME");
396 user = getenv("USER");
398 return getuserhomedir(user);
400 pw = getpwuid(getuid());
402 die("Can't get current user home directory\n");
408 buildpath(const char *path)
410 char *apath, *name, *p, *fpath;
413 if (path[0] == '~') {
414 if (path[1] == '/' || path[1] == '\0') {
415 p = (char *)&path[1];
416 homedir = getcurrentuserhomedir();
418 if ((p = strchr(path, '/')))
419 name = g_strndup(&path[1], --p - path);
421 name = g_strdup(&path[1]);
423 homedir = getuserhomedir(name);
426 apath = g_build_filename(homedir, p, NULL);
428 apath = g_strdup(path);
431 /* creating directory */
432 if (g_mkdir_with_parents(apath, 0700) < 0)
433 die("Could not access directory: %s\n", apath);
435 fpath = realpath(apath, NULL);
442 newclient(Client *rc)
446 if (!(c = calloc(1, sizeof(Client))))
447 die("Cannot malloc!\n");
453 c->tlsflags = G_TLS_CERTIFICATE_VALIDATE_ALL + 1;
454 c->view = newview(c, rc ? rc->view : NULL);
460 loaduri(Client *c, const Arg *a)
464 const char *uri = a->v;
466 if (g_strcmp0(uri, "") == 0)
469 if (g_str_has_prefix(uri, "http://") ||
470 g_str_has_prefix(uri, "https://") ||
471 g_str_has_prefix(uri, "file://") ||
472 g_str_has_prefix(uri, "about:")) {
474 } else if (!stat(uri, &st) && (path = realpath(uri, NULL))) {
475 url = g_strdup_printf("file://%s", path);
478 url = g_strdup_printf("http://%s", uri);
481 setatom(c, AtomUri, url);
483 if (strcmp(url, geturi(c)) == 0) {
486 webkit_web_view_load_uri(c->view, url);
498 if (!(uri = webkit_web_view_get_uri(c->view)))
504 setatom(Client *c, int a, const char *v)
507 XChangeProperty(dpy, c->xid,
508 atoms[a], XA_STRING, 8, PropModeReplace,
509 (unsigned char *)v, strlen(v) + 1);
513 getatom(Client *c, int a)
515 static char buf[BUFSIZ];
518 unsigned long ldummy;
519 unsigned char *p = NULL;
521 XGetWindowProperty(dpy, c->xid, atoms[a], 0L, BUFSIZ, False, XA_STRING,
522 &adummy, &idummy, &ldummy, &ldummy, &p);
524 strncpy(buf, (char *)p, LENGTH(buf) - 1);
533 updatetitle(Client *c)
536 const char *name = c->overtitle ? c->overtitle :
537 c->title ? c->title : "";
539 if (curconfig[ShowIndicators].val.b) {
543 if (c->progress != 100)
544 title = g_strdup_printf("[%i%%] %s:%s | %s",
545 c->progress, togglestats, pagestats, name);
547 title = g_strdup_printf("%s:%s | %s",
548 togglestats, pagestats, name);
550 gtk_window_set_title(GTK_WINDOW(c->win), title);
553 gtk_window_set_title(GTK_WINDOW(c->win), name);
558 gettogglestats(Client *c)
560 togglestats[0] = cookiepolicy_set(cookiepolicy_get());
561 togglestats[1] = curconfig[CaretBrowsing].val.b ? 'C' : 'c';
562 togglestats[2] = curconfig[Geolocation].val.b ? 'G' : 'g';
563 togglestats[3] = curconfig[DiskCache].val.b ? 'D' : 'd';
564 togglestats[4] = curconfig[LoadImages].val.b ? 'I' : 'i';
565 togglestats[5] = curconfig[JavaScript].val.b ? 'S' : 's';
566 togglestats[6] = curconfig[Plugins].val.b ? 'V' : 'v';
567 togglestats[7] = curconfig[Style].val.b ? 'M' : 'm';
568 togglestats[8] = curconfig[FrameFlattening].val.b ? 'F' : 'f';
569 togglestats[9] = '\0';
573 getpagestats(Client *c)
575 pagestats[0] = c->tlsflags > G_TLS_CERTIFICATE_VALIDATE_ALL ? '-' :
576 c->tlsflags > 0 ? 'U' : 'T';
580 WebKitCookieAcceptPolicy
581 cookiepolicy_get(void)
583 switch (((char *)curconfig[CookiePolicies].val.v)[cookiepolicy]) {
585 return WEBKIT_COOKIE_POLICY_ACCEPT_NEVER;
587 return WEBKIT_COOKIE_POLICY_ACCEPT_NO_THIRD_PARTY;
588 default: /* fallthrough */
590 return WEBKIT_COOKIE_POLICY_ACCEPT_ALWAYS;
595 cookiepolicy_set(const WebKitCookieAcceptPolicy p)
598 case WEBKIT_COOKIE_POLICY_ACCEPT_NEVER:
600 case WEBKIT_COOKIE_POLICY_ACCEPT_NO_THIRD_PARTY:
602 default: /* fallthrough */
603 case WEBKIT_COOKIE_POLICY_ACCEPT_ALWAYS:
609 seturiparameters(Client *c, const char *uri)
613 for (i = 0; i < LENGTH(uriparams); ++i) {
614 if (uriparams[i].uri &&
615 !regexec(&(uriparams[i].re), uri, 0, NULL, 0)) {
616 curconfig = uriparams[i].config;
621 for (i = 0; i < ParameterLast; ++i)
622 setparameter(c, 0, i, &curconfig[i].val);
626 setparameter(Client *c, int refresh, ParamName p, const Arg *a)
628 GdkRGBA bgcolor = { 0 };
629 WebKitSettings *s = webkit_web_view_get_settings(c->view);
632 case AcceleratedCanvas:
633 webkit_settings_set_enable_accelerated_2d_canvas(s, a->b);
636 webkit_settings_set_enable_caret_browsing(s, a->b);
640 webkit_cookie_manager_set_accept_policy(
641 webkit_web_context_get_cookie_manager(
642 webkit_web_view_get_context(c->view)),
647 webkit_web_context_set_cache_model(
648 webkit_web_view_get_context(c->view), a->b ?
649 WEBKIT_CACHE_MODEL_WEB_BROWSER :
650 WEBKIT_CACHE_MODEL_DOCUMENT_VIEWER);
651 return; /* do not update */
653 webkit_settings_set_enable_dns_prefetching(s, a->b);
654 return; /* do not update */
656 webkit_settings_set_default_font_size(s, a->i);
657 return; /* do not update */
658 case FrameFlattening:
659 webkit_settings_set_enable_frame_flattening(s, a->b);
666 webkit_web_view_set_background_color(c->view, &bgcolor);
667 return; /* do not update */
669 webkit_settings_set_enable_developer_extras(s, a->b);
670 return; /* do not update */
672 webkit_settings_set_enable_javascript(s, a->b);
675 return; /* do nothing */
677 webkit_settings_set_auto_load_images(s, a->b);
679 case MediaManualPlay:
680 webkit_settings_set_media_playback_requires_user_gesture(s, a->b);
683 webkit_settings_set_enable_plugins(s, a->b);
685 case PreferredLanguages:
686 return; /* do nothing */
687 case RunInFullscreen:
688 return; /* do nothing */
690 /* Disabled until we write some WebKitWebExtension for
691 * manipulating the DOM directly.
692 enablescrollbars = !enablescrollbars;
693 evalscript(c, "document.documentElement.style.overflow = '%s'",
694 enablescrollbars ? "auto" : "hidden");
696 return; /* do not update */
700 webkit_settings_set_enable_site_specific_quirks(s, a->b);
703 webkit_web_context_set_spell_checking_enabled(
704 webkit_web_view_get_context(c->view), a->b);
705 return; /* do not update */
707 return; /* do nothing */
709 webkit_web_context_set_tls_errors_policy(
710 webkit_web_view_get_context(c->view), a->b ?
711 WEBKIT_TLS_ERRORS_POLICY_FAIL :
712 WEBKIT_TLS_ERRORS_POLICY_IGNORE);
713 return; /* do not update */
716 setstyle(c, getstyle(geturi(c)));
718 webkit_user_content_manager_remove_all_style_sheets(
719 webkit_web_view_get_user_content_manager(c->view));
723 webkit_web_view_set_zoom_level(c->view, a->f);
724 return; /* do not update */
726 return; /* do nothing */
735 getstyle(const char *uri)
742 for (i = 0; i < LENGTH(styles); ++i) {
743 if (styles[i].regex &&
744 !regexec(&(styles[i].re), uri, 0, NULL, 0))
745 return styles[i].style;
752 setstyle(Client *c, const char *stylefile)
756 if (!g_file_get_contents(stylefile, &style, NULL, NULL)) {
757 fprintf(stderr, "Could not read style file: %s\n", stylefile);
761 webkit_user_content_manager_add_style_sheet(
762 webkit_web_view_get_user_content_manager(c->view),
763 webkit_user_style_sheet_new(style,
764 WEBKIT_USER_CONTENT_INJECT_ALL_FRAMES,
765 WEBKIT_USER_STYLE_LEVEL_USER,
777 if (g_file_get_contents(scriptfile, &script, &l, NULL) && l)
778 evalscript(c, script);
783 evalscript(Client *c, const char *jsstr, ...)
789 script = g_strdup_vprintf(jsstr, ap);
792 webkit_web_view_run_javascript(c->view, script, NULL, NULL, NULL);
797 updatewinid(Client *c)
799 snprintf(winid, LENGTH(winid), "%lu", c->xid);
803 handleplumb(Client *c, const char *uri)
805 Arg a = (Arg)PLUMB(uri);
810 newwindow(Client *c, const Arg *a, int noembed)
814 const char *cmd[26], *uri;
815 const Arg arg = { .v = cmd };
819 cmd[i++] = curconfig[CookiePolicies].val.v;
820 cmd[i++] = curconfig[ScrollBars].val.b ? "-B" : "-b";
821 if (cookiefile && g_strcmp0(cookiefile, "")) {
823 cmd[i++] = cookiefile;
825 cmd[i++] = curconfig[DiskCache].val.b ? "-D" : "-d";
826 if (embed && !noembed) {
828 snprintf(tmp, LENGTH(tmp), "%lu", embed);
831 cmd[i++] = curconfig[RunInFullscreen].val.b ? "-F" : "-f" ;
832 cmd[i++] = curconfig[Geolocation].val.b ? "-G" : "-g" ;
833 cmd[i++] = curconfig[LoadImages].val.b ? "-I" : "-i" ;
834 cmd[i++] = curconfig[KioskMode].val.b ? "-K" : "-k" ;
835 cmd[i++] = curconfig[Style].val.b ? "-M" : "-m" ;
836 cmd[i++] = curconfig[Inspector].val.b ? "-N" : "-n" ;
837 cmd[i++] = curconfig[Plugins].val.b ? "-P" : "-p" ;
838 if (scriptfile && g_strcmp0(scriptfile, "")) {
840 cmd[i++] = scriptfile;
842 cmd[i++] = curconfig[JavaScript].val.b ? "-S" : "-s";
843 if (stylefile && g_strcmp0(stylefile, "")) {
845 cmd[i++] = stylefile;
847 if (fulluseragent && g_strcmp0(fulluseragent, "")) {
849 cmd[i++] = fulluseragent;
853 /* do not keep zoom level */
863 spawn(Client *c, const Arg *a)
867 close(ConnectionNumber(dpy));
869 execvp(((char **)a->v)[0], (char **)a->v);
870 fprintf(stderr, "%s: execvp %s", argv0, ((char **)a->v)[0]);
877 destroyclient(Client *c)
881 webkit_web_view_stop_loading(c->view);
882 /* Not needed, has already been called
883 gtk_widget_destroy(c->win);
886 for (p = clients; p && p->next != c; p = p->next)
899 destroyclient(clients);
907 newview(Client *c, WebKitWebView *rv)
910 WebKitSettings *settings;
911 WebKitUserContentManager *contentmanager;
912 WebKitWebContext *context;
917 webkit_web_view_new_with_related_view(rv));
919 settings = webkit_settings_new_with_settings(
920 "auto-load-images", curconfig[LoadImages].val.b,
921 "default-font-size", curconfig[FontSize].val.f,
922 "enable-caret-browsing", curconfig[CaretBrowsing].val.b,
923 "enable-developer-extras", curconfig[Inspector].val.b,
924 "enable-dns-prefetching", curconfig[DNSPrefetch].val.b,
925 "enable-frame-flattening", curconfig[FrameFlattening].val.b,
926 "enable-html5-database", curconfig[DiskCache].val.b,
927 "enable-html5-local-storage", curconfig[DiskCache].val.b,
928 "enable-javascript", curconfig[JavaScript].val.b,
929 "enable-plugins", curconfig[Plugins].val.b,
930 "enable-accelerated-2d-canvas", curconfig[AcceleratedCanvas].val.b,
931 "enable-site-specific-quirks", curconfig[SiteQuirks].val.b,
932 "media-playback-requires-user-gesture", curconfig[MediaManualPlay].val.b,
934 /* For mor interesting settings, have a look at
935 * http://webkitgtk.org/reference/webkit2gtk/stable/WebKitSettings.html */
937 if (strcmp(fulluseragent, "")) {
938 webkit_settings_set_user_agent(settings, fulluseragent);
939 } else if (surfuseragent) {
940 webkit_settings_set_user_agent_with_application_details(
941 settings, "Surf", VERSION);
943 useragent = webkit_settings_get_user_agent(settings);
945 contentmanager = webkit_user_content_manager_new();
947 context = webkit_web_context_new_with_website_data_manager(
948 webkit_website_data_manager_new(
949 "base-cache-directory", cachedir,
950 "base-data-directory", cachedir,
953 /* rendering process model, can be a shared unique one
954 * or one for each view */
955 webkit_web_context_set_process_model(context,
956 WEBKIT_PROCESS_MODEL_MULTIPLE_SECONDARY_PROCESSES);
958 webkit_web_context_set_tls_errors_policy(context,
959 curconfig[StrictSSL].val.b ? WEBKIT_TLS_ERRORS_POLICY_FAIL :
960 WEBKIT_TLS_ERRORS_POLICY_IGNORE);
962 webkit_web_context_set_cache_model(context,
963 curconfig[DiskCache].val.b ? WEBKIT_CACHE_MODEL_WEB_BROWSER :
964 WEBKIT_CACHE_MODEL_DOCUMENT_VIEWER);
966 /* Currently only works with text file to be compatible with curl */
967 webkit_cookie_manager_set_persistent_storage(
968 webkit_web_context_get_cookie_manager(context), cookiefile,
969 WEBKIT_COOKIE_PERSISTENT_STORAGE_TEXT);
971 webkit_cookie_manager_set_accept_policy(
972 webkit_web_context_get_cookie_manager(context),
975 webkit_web_context_set_preferred_languages(context,
976 curconfig[PreferredLanguages].val.v);
977 webkit_web_context_set_spell_checking_languages(context,
978 curconfig[SpellLanguages].val.v);
979 webkit_web_context_set_spell_checking_enabled(context,
980 curconfig[SpellChecking].val.b);
982 g_signal_connect(G_OBJECT(context), "download-started",
983 G_CALLBACK(downloadstarted), c);
984 g_signal_connect(G_OBJECT(context), "initialize-web-extensions",
985 G_CALLBACK(initwebextensions), c);
987 v = g_object_new(WEBKIT_TYPE_WEB_VIEW,
988 "settings", settings,
989 "user-content-manager", contentmanager,
990 "web-context", context,
994 g_signal_connect(G_OBJECT(v), "notify::estimated-load-progress",
995 G_CALLBACK(progresschanged), c);
996 g_signal_connect(G_OBJECT(v), "notify::title",
997 G_CALLBACK(titlechanged), c);
998 g_signal_connect(G_OBJECT(v), "button-release-event",
999 G_CALLBACK(buttonreleased), c);
1000 g_signal_connect(G_OBJECT(v), "close",
1001 G_CALLBACK(closeview), c);
1002 g_signal_connect(G_OBJECT(v), "create",
1003 G_CALLBACK(createview), c);
1004 g_signal_connect(G_OBJECT(v), "decide-policy",
1005 G_CALLBACK(decidepolicy), c);
1006 g_signal_connect(G_OBJECT(v), "load-changed",
1007 G_CALLBACK(loadchanged), c);
1008 g_signal_connect(G_OBJECT(v), "mouse-target-changed",
1009 G_CALLBACK(mousetargetchanged), c);
1010 g_signal_connect(G_OBJECT(v), "permission-request",
1011 G_CALLBACK(permissionrequested), c);
1012 g_signal_connect(G_OBJECT(v), "ready-to-show",
1013 G_CALLBACK(showview), c);
1019 initwebextensions(WebKitWebContext *wc, Client *c)
1021 webkit_web_context_set_web_extensions_directory(wc, WEBEXTDIR);
1025 createview(WebKitWebView *v, WebKitNavigationAction *a, Client *c)
1029 switch (webkit_navigation_action_get_navigation_type(a)) {
1030 case WEBKIT_NAVIGATION_TYPE_OTHER: /* fallthrough */
1032 * popup windows of type “other” are almost always triggered
1033 * by user gesture, so inverse the logic here
1035 /* instead of this, compare destination uri to mouse-over uri for validating window */
1036 if (webkit_navigation_action_is_user_gesture(a))
1038 case WEBKIT_NAVIGATION_TYPE_LINK_CLICKED: /* fallthrough */
1039 case WEBKIT_NAVIGATION_TYPE_FORM_SUBMITTED: /* fallthrough */
1040 case WEBKIT_NAVIGATION_TYPE_BACK_FORWARD: /* fallthrough */
1041 case WEBKIT_NAVIGATION_TYPE_RELOAD: /* fallthrough */
1042 case WEBKIT_NAVIGATION_TYPE_FORM_RESUBMITTED:
1049 return GTK_WIDGET(n->view);
1053 buttonreleased(GtkWidget *w, GdkEvent *e, Client *c)
1055 WebKitHitTestResultContext element;
1058 element = webkit_hit_test_result_get_context(c->mousepos);
1060 for (i = 0; i < LENGTH(buttons); ++i) {
1061 if (element & buttons[i].target &&
1062 e->button.button == buttons[i].button &&
1063 CLEANMASK(e->button.state) == CLEANMASK(buttons[i].mask) &&
1065 buttons[i].func(c, &buttons[i].arg, c->mousepos);
1066 return buttons[i].stopevent;
1074 processx(GdkXEvent *e, GdkEvent *event, gpointer d)
1076 Client *c = (Client *)d;
1080 if (((XEvent *)e)->type == PropertyNotify) {
1081 ev = &((XEvent *)e)->xproperty;
1082 if (ev->state == PropertyNewValue) {
1083 if (ev->atom == atoms[AtomFind]) {
1086 return GDK_FILTER_REMOVE;
1087 } else if (ev->atom == atoms[AtomGo]) {
1088 a.v = getatom(c, AtomGo);
1091 return GDK_FILTER_REMOVE;
1095 return GDK_FILTER_CONTINUE;
1099 winevent(GtkWidget *w, GdkEvent *e, Client *c)
1104 case GDK_ENTER_NOTIFY:
1105 c->overtitle = c->targeturi;
1109 if (!curconfig[KioskMode].val.b) {
1110 for (i = 0; i < LENGTH(keys); ++i) {
1111 if (gdk_keyval_to_lower(e->key.keyval) ==
1113 CLEANMASK(e->key.state) == keys[i].mod &&
1116 keys[i].func(c, &(keys[i].arg));
1121 case GDK_LEAVE_NOTIFY:
1122 c->overtitle = NULL;
1125 case GDK_WINDOW_STATE:
1126 if (e->window_state.changed_mask ==
1127 GDK_WINDOW_STATE_FULLSCREEN)
1128 c->fullscreen = e->window_state.new_window_state &
1129 GDK_WINDOW_STATE_FULLSCREEN;
1139 showview(WebKitWebView *v, Client *c)
1141 GdkRGBA bgcolor = { 0 };
1144 c->finder = webkit_web_view_get_find_controller(c->view);
1145 c->inspector = webkit_web_view_get_inspector(c->view);
1147 c->win = createwindow(c);
1149 gtk_container_add(GTK_CONTAINER(c->win), GTK_WIDGET(c->view));
1150 gtk_widget_show_all(c->win);
1151 gtk_widget_grab_focus(GTK_WIDGET(c->view));
1153 gwin = gtk_widget_get_window(GTK_WIDGET(c->win));
1154 c->xid = gdk_x11_window_get_xid(gwin);
1157 gdk_display_sync(gtk_widget_get_display(c->win));
1161 if (curconfig[HideBackground].val.b)
1162 webkit_web_view_set_background_color(c->view, &bgcolor);
1164 if (!curconfig[KioskMode].val.b) {
1165 gdk_window_set_events(gwin, GDK_ALL_EVENTS_MASK);
1166 gdk_window_add_filter(gwin, processx, c);
1169 if (curconfig[RunInFullscreen].val.b)
1170 togglefullscreen(c, NULL);
1172 if (curconfig[ZoomLevel].val.f != 1.0)
1173 webkit_web_view_set_zoom_level(c->view,
1174 curconfig[ZoomLevel].val.f);
1176 setatom(c, AtomFind, "");
1177 setatom(c, AtomUri, "about:blank");
1181 createwindow(Client *c)
1187 w = gtk_plug_new(embed);
1189 w = gtk_window_new(GTK_WINDOW_TOPLEVEL);
1191 wmstr = g_path_get_basename(argv0);
1192 gtk_window_set_wmclass(GTK_WINDOW(w), wmstr, "Surf");
1195 wmstr = g_strdup_printf("%s[%lu]", "Surf",
1196 webkit_web_view_get_page_id(c->view));
1197 gtk_window_set_role(GTK_WINDOW(w), wmstr);
1200 gtk_window_set_default_size(GTK_WINDOW(w), 800, 600);
1203 g_signal_connect(G_OBJECT(w), "destroy",
1204 G_CALLBACK(destroywin), c);
1205 g_signal_connect(G_OBJECT(w), "enter-notify-event",
1206 G_CALLBACK(winevent), c);
1207 g_signal_connect(G_OBJECT(w), "key-press-event",
1208 G_CALLBACK(winevent), c);
1209 g_signal_connect(G_OBJECT(w), "leave-notify-event",
1210 G_CALLBACK(winevent), c);
1211 g_signal_connect(G_OBJECT(w), "window-state-event",
1212 G_CALLBACK(winevent), c);
1218 loadchanged(WebKitWebView *v, WebKitLoadEvent e, Client *c)
1220 const char *title = geturi(c);
1223 case WEBKIT_LOAD_STARTED:
1224 curconfig = defconfig;
1225 setatom(c, AtomUri, title);
1227 c->tlsflags = G_TLS_CERTIFICATE_VALIDATE_ALL + 1;
1228 seturiparameters(c, geturi(c));
1230 case WEBKIT_LOAD_REDIRECTED:
1231 setatom(c, AtomUri, title);
1233 seturiparameters(c, geturi(c));
1235 case WEBKIT_LOAD_COMMITTED:
1236 if (!webkit_web_view_get_tls_info(c->view, NULL,
1238 c->tlsflags = G_TLS_CERTIFICATE_VALIDATE_ALL + 1;
1241 case WEBKIT_LOAD_FINISHED:
1242 /* Disabled until we write some WebKitWebExtension for
1243 * manipulating the DOM directly.
1244 evalscript(c, "document.documentElement.style.overflow = '%s'",
1245 enablescrollbars ? "auto" : "hidden");
1254 progresschanged(WebKitWebView *v, GParamSpec *ps, Client *c)
1256 c->progress = webkit_web_view_get_estimated_load_progress(c->view) *
1262 titlechanged(WebKitWebView *view, GParamSpec *ps, Client *c)
1264 c->title = webkit_web_view_get_title(c->view);
1269 mousetargetchanged(WebKitWebView *v, WebKitHitTestResult *h, guint modifiers,
1272 WebKitHitTestResultContext hc = webkit_hit_test_result_get_context(h);
1274 /* Keep the hit test to know where is the pointer on the next click */
1278 c->targeturi = webkit_hit_test_result_get_link_uri(h);
1279 else if (hc & OnImg)
1280 c->targeturi = webkit_hit_test_result_get_image_uri(h);
1281 else if (hc & OnMedia)
1282 c->targeturi = webkit_hit_test_result_get_media_uri(h);
1284 c->targeturi = NULL;
1286 c->overtitle = c->targeturi;
1291 permissionrequested(WebKitWebView *v, WebKitPermissionRequest *r, Client *c)
1293 if (WEBKIT_IS_GEOLOCATION_PERMISSION_REQUEST(r)) {
1294 if (curconfig[Geolocation].val.b)
1295 webkit_permission_request_allow(r);
1297 webkit_permission_request_deny(r);
1305 decidepolicy(WebKitWebView *v, WebKitPolicyDecision *d,
1306 WebKitPolicyDecisionType dt, Client *c)
1309 case WEBKIT_POLICY_DECISION_TYPE_NAVIGATION_ACTION:
1310 decidenavigation(d, c);
1312 case WEBKIT_POLICY_DECISION_TYPE_NEW_WINDOW_ACTION:
1313 decidenewwindow(d, c);
1315 case WEBKIT_POLICY_DECISION_TYPE_RESPONSE:
1316 decideresource(d, c);
1319 webkit_policy_decision_ignore(d);
1326 decidenavigation(WebKitPolicyDecision *d, Client *c)
1328 WebKitNavigationAction *a =
1329 webkit_navigation_policy_decision_get_navigation_action(
1330 WEBKIT_NAVIGATION_POLICY_DECISION(d));
1332 switch (webkit_navigation_action_get_navigation_type(a)) {
1333 case WEBKIT_NAVIGATION_TYPE_LINK_CLICKED: /* fallthrough */
1334 case WEBKIT_NAVIGATION_TYPE_FORM_SUBMITTED: /* fallthrough */
1335 case WEBKIT_NAVIGATION_TYPE_BACK_FORWARD: /* fallthrough */
1336 case WEBKIT_NAVIGATION_TYPE_RELOAD: /* fallthrough */
1337 case WEBKIT_NAVIGATION_TYPE_FORM_RESUBMITTED: /* fallthrough */
1338 case WEBKIT_NAVIGATION_TYPE_OTHER: /* fallthrough */
1340 /* Do not navigate to links with a "_blank" target (popup) */
1341 if (webkit_navigation_policy_decision_get_frame_name(
1342 WEBKIT_NAVIGATION_POLICY_DECISION(d))) {
1343 webkit_policy_decision_ignore(d);
1345 /* Filter out navigation to different domain ? */
1346 /* get action→urirequest, copy and load in new window+view
1347 * on Ctrl+Click ? */
1348 webkit_policy_decision_use(d);
1355 decidenewwindow(WebKitPolicyDecision *d, Client *c)
1358 WebKitNavigationAction *a =
1359 webkit_navigation_policy_decision_get_navigation_action(
1360 WEBKIT_NAVIGATION_POLICY_DECISION(d));
1363 switch (webkit_navigation_action_get_navigation_type(a)) {
1364 case WEBKIT_NAVIGATION_TYPE_LINK_CLICKED: /* fallthrough */
1365 case WEBKIT_NAVIGATION_TYPE_FORM_SUBMITTED: /* fallthrough */
1366 case WEBKIT_NAVIGATION_TYPE_BACK_FORWARD: /* fallthrough */
1367 case WEBKIT_NAVIGATION_TYPE_RELOAD: /* fallthrough */
1368 case WEBKIT_NAVIGATION_TYPE_FORM_RESUBMITTED:
1369 /* Filter domains here */
1370 /* If the value of “mouse-button” is not 0, then the navigation was triggered by a mouse event.
1371 * test for link clicked but no button ? */
1372 arg.v = webkit_uri_request_get_uri(
1373 webkit_navigation_action_get_request(a));
1374 newwindow(c, &arg, 0);
1376 case WEBKIT_NAVIGATION_TYPE_OTHER: /* fallthrough */
1381 webkit_policy_decision_ignore(d);
1385 decideresource(WebKitPolicyDecision *d, Client *c)
1388 WebKitResponsePolicyDecision *r = WEBKIT_RESPONSE_POLICY_DECISION(d);
1389 WebKitURIResponse *res =
1390 webkit_response_policy_decision_get_response(r);
1391 const gchar *uri = webkit_uri_response_get_uri(res);
1393 if (g_str_has_suffix(uri, "/favicon.ico")) {
1394 webkit_policy_decision_ignore(d);
1398 if (!g_str_has_prefix(uri, "http://")
1399 && !g_str_has_prefix(uri, "https://")
1400 && !g_str_has_prefix(uri, "about:")
1401 && !g_str_has_prefix(uri, "file://")
1402 && !g_str_has_prefix(uri, "data:")
1403 && !g_str_has_prefix(uri, "blob:")
1404 && strlen(uri) > 0) {
1405 for (i = 0; i < strlen(uri); i++) {
1406 if (!g_ascii_isprint(uri[i])) {
1412 handleplumb(c, uri);
1413 webkit_policy_decision_ignore(d);
1418 if (webkit_response_policy_decision_is_mime_type_supported(r)) {
1419 webkit_policy_decision_use(d);
1421 webkit_policy_decision_ignore(d);
1427 downloadstarted(WebKitWebContext *wc, WebKitDownload *d, Client *c)
1429 g_signal_connect(G_OBJECT(d), "notify::response",
1430 G_CALLBACK(responsereceived), c);
1434 responsereceived(WebKitDownload *d, GParamSpec *ps, Client *c)
1436 download(c, webkit_download_get_response(d));
1437 webkit_download_cancel(d);
1441 download(Client *c, WebKitURIResponse *r)
1443 Arg a = (Arg)DOWNLOAD(webkit_uri_response_get_uri(r), geturi(c));
1448 closeview(WebKitWebView *v, Client *c)
1450 gtk_widget_destroy(c->win);
1454 destroywin(GtkWidget* w, Client *c)
1462 pasteuri(GtkClipboard *clipboard, const char *text, gpointer d)
1464 Arg a = {.v = text };
1466 loaduri((Client *) d, &a);
1470 reload(Client *c, const Arg *a)
1473 webkit_web_view_reload_bypass_cache(c->view);
1475 webkit_web_view_reload(c->view);
1479 print(Client *c, const Arg *a)
1481 webkit_print_operation_run_dialog(webkit_print_operation_new(c->view),
1482 GTK_WINDOW(c->win));
1486 clipboard(Client *c, const Arg *a)
1488 if (a->b) { /* load clipboard uri */
1489 gtk_clipboard_request_text(gtk_clipboard_get(
1490 GDK_SELECTION_PRIMARY),
1492 } else { /* copy uri */
1493 gtk_clipboard_set_text(gtk_clipboard_get(
1494 GDK_SELECTION_PRIMARY), c->targeturi
1495 ? c->targeturi : geturi(c), -1);
1500 zoom(Client *c, const Arg *a)
1503 webkit_web_view_set_zoom_level(c->view,
1504 curconfig[ZoomLevel].val.f + 0.1);
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, 1.0);
1511 curconfig[ZoomLevel].val.f = webkit_web_view_get_zoom_level(c->view);
1515 scroll(Client *c, const Arg *a)
1517 GdkEvent *ev = gdk_event_new(GDK_KEY_PRESS);
1519 gdk_event_set_device(ev, gdkkb);
1520 ev->key.window = gtk_widget_get_window(GTK_WIDGET(c->win));
1521 ev->key.state = GDK_CONTROL_MASK;
1522 ev->key.time = GDK_CURRENT_TIME;
1526 ev->key.keyval = GDK_KEY_Down;
1529 ev->key.keyval = GDK_KEY_Page_Down;
1532 ev->key.keyval = GDK_KEY_Left;
1535 ev->key.keyval = GDK_KEY_Right;
1538 ev->key.keyval = GDK_KEY_Page_Up;
1541 ev->key.keyval = GDK_KEY_Up;
1549 navigate(Client *c, const Arg *a)
1552 webkit_web_view_go_back(c->view);
1554 webkit_web_view_go_forward(c->view);
1558 stop(Client *c, const Arg *a)
1560 webkit_web_view_stop_loading(c->view);
1564 toggle(Client *c, const Arg *a)
1566 curconfig[a->i].val.b ^= 1;
1567 setparameter(c, 1, (ParamName)a->i, &curconfig[a->i].val);
1571 togglefullscreen(Client *c, const Arg *a)
1573 /* toggling value is handled in winevent() */
1575 gtk_window_unfullscreen(GTK_WINDOW(c->win));
1577 gtk_window_fullscreen(GTK_WINDOW(c->win));
1581 togglecookiepolicy(Client *c, const Arg *a)
1584 cookiepolicy %= strlen(curconfig[CookiePolicies].val.v);
1586 setparameter(c, 0, CookiePolicies, NULL);
1590 toggleinspector(Client *c, const Arg *a)
1592 if (webkit_web_inspector_is_attached(c->inspector))
1593 webkit_web_inspector_close(c->inspector);
1594 else if (curconfig[Inspector].val.b)
1595 webkit_web_inspector_show(c->inspector);
1599 find(Client *c, const Arg *a)
1605 webkit_find_controller_search_next(c->finder);
1607 webkit_find_controller_search_previous(c->finder);
1609 s = getatom(c, AtomFind);
1610 f = webkit_find_controller_get_search_text(c->finder);
1612 if (g_strcmp0(f, s) == 0) /* reset search */
1613 webkit_find_controller_search(c->finder, "", findopts,
1616 webkit_find_controller_search(c->finder, s, findopts,
1619 if (strcmp(s, "") == 0)
1620 webkit_find_controller_search_finish(c->finder);
1625 clicknavigate(Client *c, const Arg *a, WebKitHitTestResult *h)
1631 clicknewwindow(Client *c, const Arg *a, WebKitHitTestResult *h)
1635 arg.v = webkit_hit_test_result_get_link_uri(h);
1636 newwindow(c, &arg, a->b);
1640 clickexternplayer(Client *c, const Arg *a, WebKitHitTestResult *h)
1644 arg = (Arg)VIDEOPLAY(webkit_hit_test_result_get_media_uri(h));
1649 main(int argc, char *argv[])
1654 memset(&arg, 0, sizeof(arg));
1656 /* command line args */
1659 defconfig CSETV(CookiePolicies, EARGF(usage()));
1662 defconfig CSETB(ScrollBars, 0);
1665 defconfig CSETB(ScrollBars, 1);
1668 cookiefile = EARGF(usage());
1671 defconfig CSETB(DiskCache, 0);
1674 defconfig CSETB(DiskCache, 1);
1677 embed = strtol(EARGF(usage()), NULL, 0);
1680 defconfig CSETB(RunInFullscreen, 0);
1683 defconfig CSETB(RunInFullscreen, 1);
1686 defconfig CSETB(Geolocation, 0);
1689 defconfig CSETB(Geolocation, 1);
1692 defconfig CSETB(LoadImages, 0);
1695 defconfig CSETB(LoadImages, 1);
1698 defconfig CSETB(KioskMode, 0);
1701 defconfig CSETB(KioskMode, 1);
1704 defconfig CSETB(Style, 0);
1707 defconfig CSETB(Style, 1);
1710 defconfig CSETB(Inspector, 0);
1713 defconfig CSETB(Inspector, 1);
1716 defconfig CSETB(Plugins, 0);
1719 defconfig CSETB(Plugins, 1);
1722 scriptfile = EARGF(usage());
1725 defconfig CSETB(JavaScript, 0);
1728 defconfig CSETB(JavaScript, 1);
1731 stylefile = EARGF(usage());
1734 fulluseragent = EARGF(usage());
1737 die("surf-"VERSION", ©2009-2015 surf engineers, "
1738 "see LICENSE for details\n");
1743 defconfig CSETF(ZoomLevel, strtof(EARGF(usage()), NULL));
1751 arg.v = "about:blank";
1754 c = newclient(NULL);