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 GtkWidget *createview(WebKitWebView *v, WebKitNavigationAction *a,
180 static gboolean buttonreleased(GtkWidget *w, GdkEvent *e, Client *c);
181 static GdkFilterReturn processx(GdkXEvent *xevent, GdkEvent *event,
183 static gboolean winevent(GtkWidget *w, GdkEvent *e, Client *c);
184 static void showview(WebKitWebView *v, Client *c);
185 static GtkWidget *createwindow(Client *c);
186 static void loadchanged(WebKitWebView *v, WebKitLoadEvent e, Client *c);
187 static void progresschanged(WebKitWebView *v, GParamSpec *ps, Client *c);
188 static void titlechanged(WebKitWebView *view, GParamSpec *ps, Client *c);
189 static void mousetargetchanged(WebKitWebView *v, WebKitHitTestResult *h,
190 guint modifiers, Client *c);
191 static gboolean permissionrequested(WebKitWebView *v,
192 WebKitPermissionRequest *r, Client *c);
193 static gboolean decidepolicy(WebKitWebView *v, WebKitPolicyDecision *d,
194 WebKitPolicyDecisionType dt, Client *c);
195 static void decidenavigation(WebKitPolicyDecision *d, Client *c);
196 static void decidenewwindow(WebKitPolicyDecision *d, Client *c);
197 static void decideresource(WebKitPolicyDecision *d, Client *c);
198 static void downloadstarted(WebKitWebContext *wc, WebKitDownload *d,
200 static void responsereceived(WebKitDownload *d, GParamSpec *ps, Client *c);
201 static void download(Client *c, WebKitURIResponse *r);
202 static void closeview(WebKitWebView *v, Client *c);
203 static void destroywin(GtkWidget* w, Client *c);
206 static void pasteuri(GtkClipboard *clipboard, const char *text, gpointer d);
207 static void reload(Client *c, const Arg *a);
208 static void print(Client *c, const Arg *a);
209 static void clipboard(Client *c, const Arg *a);
210 static void zoom(Client *c, const Arg *a);
211 static void scroll(Client *c, const Arg *a);
212 static void navigate(Client *c, const Arg *a);
213 static void stop(Client *c, const Arg *a);
214 static void toggle(Client *c, const Arg *a);
215 static void togglefullscreen(Client *c, const Arg *a);
216 static void togglecookiepolicy(Client *c, const Arg *a);
217 static void toggleinspector(Client *c, const Arg *a);
218 static void find(Client *c, const Arg *a);
221 static void clicknavigate(Client *c, const Arg *a, WebKitHitTestResult *h);
222 static void clicknewwindow(Client *c, const Arg *a, WebKitHitTestResult *h);
223 static void clickexternplayer(Client *c, const Arg *a, WebKitHitTestResult *h);
225 static char winid[64];
226 static char togglestats[10];
227 static char pagestats[2];
228 static Atom atoms[AtomLast];
231 static int cookiepolicy;
233 static Client *clients;
234 static GdkDevice *gdkkb;
235 static char *stylefile;
236 static const char *useragent;
237 static Parameter *curconfig;
240 /* configuration, allows nested code to access above variables */
246 die("usage: %s [-bBdDfFgGiIkKmMnNpPsSvx] [-a cookiepolicies ] "
247 "[-c cookiefile] [-e xid] [-r scriptfile] [-t stylefile] "
248 "[-u useragent] [-z zoomlevel] [uri]\n", basename(argv0));
252 die(const char *errstr, ...)
256 va_start(ap, errstr);
257 vfprintf(stderr, errstr, ap);
268 /* clean up any zombies immediately */
270 if (signal(SIGHUP, sighup) == SIG_ERR)
271 die("Can't install SIGHUP handler");
273 gtk_init(NULL, NULL);
275 gdpy = gdk_display_get_default();
276 dpy = GDK_DISPLAY_XDISPLAY(gdpy);
278 curconfig = defconfig;
281 atoms[AtomFind] = XInternAtom(dpy, "_SURF_FIND", False);
282 atoms[AtomGo] = XInternAtom(dpy, "_SURF_GO", False);
283 atoms[AtomUri] = XInternAtom(dpy, "_SURF_URI", False);
286 cookiefile = buildfile(cookiefile);
287 scriptfile = buildfile(scriptfile);
288 cachedir = buildpath(cachedir);
290 gdkkb = gdk_seat_get_keyboard(gdk_display_get_default_seat(gdpy));
293 styledir = buildpath(styledir);
294 for (i = 0; i < LENGTH(styles); ++i) {
295 if (regcomp(&(styles[i].re), styles[i].regex,
298 "Could not compile regex: %s\n",
300 styles[i].regex = NULL;
302 styles[i].style = g_strconcat(styledir, "/",
303 styles[i].style, NULL);
307 stylefile = buildfile(stylefile);
310 for (i = 0; i < LENGTH(uriparams); ++i) {
311 if (!regcomp(&(uriparams[i].re), uriparams[i].uri,
313 /* copy default parameters if they are not already set
314 * or if they are forced */
315 for (j = 0; j < ParameterLast; ++j) {
316 if (!uriparams[i].config[j].force ||
318 uriparams[i].config[j] = defconfig[j];
322 "Could not compile regex: %s\n",
324 uriparams[i].uri = NULL;
332 if (signal(SIGCHLD, sigchld) == SIG_ERR)
333 die("Can't install SIGCHLD handler");
334 while (waitpid(-1, NULL, WNOHANG) > 0)
344 for (c = clients; c; c = c->next)
349 buildfile(const char *path)
351 char *dname, *bname, *bpath, *fpath;
354 dname = g_path_get_dirname(path);
355 bname = g_path_get_basename(path);
357 bpath = buildpath(dname);
360 fpath = g_build_filename(bpath, bname, NULL);
364 if (!(f = fopen(fpath, "a")))
365 die("Could not open file: %s\n", fpath);
367 g_chmod(fpath, 0600); /* always */
374 getuserhomedir(const char *user)
376 struct passwd *pw = getpwnam(user);
379 die("Can't get user %s login information.\n", user);
385 getcurrentuserhomedir(void)
391 homedir = getenv("HOME");
395 user = getenv("USER");
397 return getuserhomedir(user);
399 pw = getpwuid(getuid());
401 die("Can't get current user home directory\n");
407 buildpath(const char *path)
409 char *apath, *name, *p, *fpath;
412 if (path[0] == '~') {
413 if (path[1] == '/' || path[1] == '\0') {
414 p = (char *)&path[1];
415 homedir = getcurrentuserhomedir();
417 if ((p = strchr(path, '/')))
418 name = g_strndup(&path[1], --p - path);
420 name = g_strdup(&path[1]);
422 homedir = getuserhomedir(name);
425 apath = g_build_filename(homedir, p, NULL);
427 apath = g_strdup(path);
430 /* creating directory */
431 if (g_mkdir_with_parents(apath, 0700) < 0)
432 die("Could not access directory: %s\n", apath);
434 fpath = realpath(apath, NULL);
441 newclient(Client *rc)
445 if (!(c = calloc(1, sizeof(Client))))
446 die("Cannot malloc!\n");
452 c->tlsflags = G_TLS_CERTIFICATE_VALIDATE_ALL + 1;
453 c->view = newview(c, rc ? rc->view : NULL);
459 loaduri(Client *c, const Arg *a)
463 const char *uri = a->v;
465 if (g_strcmp0(uri, "") == 0)
468 if (g_str_has_prefix(uri, "http://") ||
469 g_str_has_prefix(uri, "https://") ||
470 g_str_has_prefix(uri, "file://") ||
471 g_str_has_prefix(uri, "about:")) {
473 } else if (!stat(uri, &st) && (path = realpath(uri, NULL))) {
474 url = g_strdup_printf("file://%s", path);
477 url = g_strdup_printf("http://%s", uri);
480 setatom(c, AtomUri, url);
482 if (strcmp(url, geturi(c)) == 0) {
485 webkit_web_view_load_uri(c->view, url);
497 if (!(uri = webkit_web_view_get_uri(c->view)))
503 setatom(Client *c, int a, const char *v)
506 XChangeProperty(dpy, c->xid,
507 atoms[a], XA_STRING, 8, PropModeReplace,
508 (unsigned char *)v, strlen(v) + 1);
512 getatom(Client *c, int a)
514 static char buf[BUFSIZ];
517 unsigned long ldummy;
518 unsigned char *p = NULL;
520 XGetWindowProperty(dpy, c->xid, atoms[a], 0L, BUFSIZ, False, XA_STRING,
521 &adummy, &idummy, &ldummy, &ldummy, &p);
523 strncpy(buf, (char *)p, LENGTH(buf) - 1);
532 updatetitle(Client *c)
535 const char *name = c->overtitle ? c->overtitle :
536 c->title ? c->title : "";
538 if (curconfig[ShowIndicators].val.b) {
542 if (c->progress != 100)
543 title = g_strdup_printf("[%i%%] %s:%s | %s",
544 c->progress, togglestats, pagestats, name);
546 title = g_strdup_printf("%s:%s | %s",
547 togglestats, pagestats, name);
549 gtk_window_set_title(GTK_WINDOW(c->win), title);
552 gtk_window_set_title(GTK_WINDOW(c->win), name);
557 gettogglestats(Client *c)
559 togglestats[0] = cookiepolicy_set(cookiepolicy_get());
560 togglestats[1] = curconfig[CaretBrowsing].val.b ? 'C' : 'c';
561 togglestats[2] = curconfig[Geolocation].val.b ? 'G' : 'g';
562 togglestats[3] = curconfig[DiskCache].val.b ? 'D' : 'd';
563 togglestats[4] = curconfig[LoadImages].val.b ? 'I' : 'i';
564 togglestats[5] = curconfig[JavaScript].val.b ? 'S' : 's';
565 togglestats[6] = curconfig[Plugins].val.b ? 'V' : 'v';
566 togglestats[7] = curconfig[Style].val.b ? 'M' : 'm';
567 togglestats[8] = curconfig[FrameFlattening].val.b ? 'F' : 'f';
568 togglestats[9] = '\0';
572 getpagestats(Client *c)
574 pagestats[0] = c->tlsflags > G_TLS_CERTIFICATE_VALIDATE_ALL ? '-' :
575 c->tlsflags > 0 ? 'U' : 'T';
579 WebKitCookieAcceptPolicy
580 cookiepolicy_get(void)
582 switch (((char *)curconfig[CookiePolicies].val.v)[cookiepolicy]) {
584 return WEBKIT_COOKIE_POLICY_ACCEPT_NEVER;
586 return WEBKIT_COOKIE_POLICY_ACCEPT_NO_THIRD_PARTY;
587 default: /* fallthrough */
589 return WEBKIT_COOKIE_POLICY_ACCEPT_ALWAYS;
594 cookiepolicy_set(const WebKitCookieAcceptPolicy p)
597 case WEBKIT_COOKIE_POLICY_ACCEPT_NEVER:
599 case WEBKIT_COOKIE_POLICY_ACCEPT_NO_THIRD_PARTY:
601 default: /* fallthrough */
602 case WEBKIT_COOKIE_POLICY_ACCEPT_ALWAYS:
608 seturiparameters(Client *c, const char *uri)
612 for (i = 0; i < LENGTH(uriparams); ++i) {
613 if (uriparams[i].uri &&
614 !regexec(&(uriparams[i].re), uri, 0, NULL, 0)) {
615 curconfig = uriparams[i].config;
620 for (i = 0; i < ParameterLast; ++i)
621 setparameter(c, 0, i, &curconfig[i].val);
625 setparameter(Client *c, int refresh, ParamName p, const Arg *a)
627 GdkRGBA bgcolor = { 0 };
628 WebKitSettings *s = webkit_web_view_get_settings(c->view);
631 case AcceleratedCanvas:
632 webkit_settings_set_enable_accelerated_2d_canvas(s, a->b);
635 webkit_settings_set_enable_caret_browsing(s, a->b);
639 webkit_cookie_manager_set_accept_policy(
640 webkit_web_context_get_cookie_manager(
641 webkit_web_view_get_context(c->view)),
646 webkit_web_context_set_cache_model(
647 webkit_web_view_get_context(c->view), a->b ?
648 WEBKIT_CACHE_MODEL_WEB_BROWSER :
649 WEBKIT_CACHE_MODEL_DOCUMENT_VIEWER);
650 return; /* do not update */
652 webkit_settings_set_enable_dns_prefetching(s, a->b);
653 return; /* do not update */
655 webkit_settings_set_default_font_size(s, a->i);
656 return; /* do not update */
657 case FrameFlattening:
658 webkit_settings_set_enable_frame_flattening(s, a->b);
665 webkit_web_view_set_background_color(c->view, &bgcolor);
666 return; /* do not update */
668 webkit_settings_set_enable_developer_extras(s, a->b);
669 return; /* do not update */
671 webkit_settings_set_enable_javascript(s, a->b);
674 return; /* do nothing */
676 webkit_settings_set_auto_load_images(s, a->b);
678 case MediaManualPlay:
679 webkit_settings_set_media_playback_requires_user_gesture(s, a->b);
682 webkit_settings_set_enable_plugins(s, a->b);
684 case PreferredLanguages:
685 return; /* do nothing */
686 case RunInFullscreen:
687 return; /* do nothing */
689 /* Disabled until we write some WebKitWebExtension for
690 * manipulating the DOM directly.
691 enablescrollbars = !enablescrollbars;
692 evalscript(c, "document.documentElement.style.overflow = '%s'",
693 enablescrollbars ? "auto" : "hidden");
695 return; /* do not update */
699 webkit_settings_set_enable_site_specific_quirks(s, a->b);
702 webkit_web_context_set_spell_checking_enabled(
703 webkit_web_view_get_context(c->view), a->b);
704 return; /* do not update */
706 return; /* do nothing */
708 webkit_web_context_set_tls_errors_policy(
709 webkit_web_view_get_context(c->view), a->b ?
710 WEBKIT_TLS_ERRORS_POLICY_FAIL :
711 WEBKIT_TLS_ERRORS_POLICY_IGNORE);
712 return; /* do not update */
715 setstyle(c, getstyle(geturi(c)));
717 webkit_user_content_manager_remove_all_style_sheets(
718 webkit_web_view_get_user_content_manager(c->view));
722 webkit_web_view_set_zoom_level(c->view, a->f);
723 return; /* do not update */
725 return; /* do nothing */
734 getstyle(const char *uri)
741 for (i = 0; i < LENGTH(styles); ++i) {
742 if (styles[i].regex &&
743 !regexec(&(styles[i].re), uri, 0, NULL, 0))
744 return styles[i].style;
751 setstyle(Client *c, const char *stylefile)
755 if (!g_file_get_contents(stylefile, &style, NULL, NULL)) {
756 fprintf(stderr, "Could not read style file: %s\n", stylefile);
760 webkit_user_content_manager_add_style_sheet(
761 webkit_web_view_get_user_content_manager(c->view),
762 webkit_user_style_sheet_new(style,
763 WEBKIT_USER_CONTENT_INJECT_ALL_FRAMES,
764 WEBKIT_USER_STYLE_LEVEL_USER,
776 if (g_file_get_contents(scriptfile, &script, &l, NULL) && l)
777 evalscript(c, script);
782 evalscript(Client *c, const char *jsstr, ...)
788 script = g_strdup_vprintf(jsstr, ap);
791 webkit_web_view_run_javascript(c->view, script, NULL, NULL, NULL);
796 updatewinid(Client *c)
798 snprintf(winid, LENGTH(winid), "%lu", c->xid);
802 handleplumb(Client *c, const char *uri)
804 Arg a = (Arg)PLUMB(uri);
809 newwindow(Client *c, const Arg *a, int noembed)
813 const char *cmd[26], *uri;
814 const Arg arg = { .v = cmd };
818 cmd[i++] = curconfig[CookiePolicies].val.v;
819 cmd[i++] = curconfig[ScrollBars].val.b ? "-B" : "-b";
820 if (cookiefile && g_strcmp0(cookiefile, "")) {
822 cmd[i++] = cookiefile;
824 cmd[i++] = curconfig[DiskCache].val.b ? "-D" : "-d";
825 if (embed && !noembed) {
827 snprintf(tmp, LENGTH(tmp), "%lu", embed);
830 cmd[i++] = curconfig[RunInFullscreen].val.b ? "-F" : "-f" ;
831 cmd[i++] = curconfig[Geolocation].val.b ? "-G" : "-g" ;
832 cmd[i++] = curconfig[LoadImages].val.b ? "-I" : "-i" ;
833 cmd[i++] = curconfig[KioskMode].val.b ? "-K" : "-k" ;
834 cmd[i++] = curconfig[Style].val.b ? "-M" : "-m" ;
835 cmd[i++] = curconfig[Inspector].val.b ? "-N" : "-n" ;
836 cmd[i++] = curconfig[Plugins].val.b ? "-P" : "-p" ;
837 if (scriptfile && g_strcmp0(scriptfile, "")) {
839 cmd[i++] = scriptfile;
841 cmd[i++] = curconfig[JavaScript].val.b ? "-S" : "-s";
842 if (stylefile && g_strcmp0(stylefile, "")) {
844 cmd[i++] = stylefile;
846 if (fulluseragent && g_strcmp0(fulluseragent, "")) {
848 cmd[i++] = fulluseragent;
852 /* do not keep zoom level */
862 spawn(Client *c, const Arg *a)
866 close(ConnectionNumber(dpy));
868 execvp(((char **)a->v)[0], (char **)a->v);
869 fprintf(stderr, "%s: execvp %s", argv0, ((char **)a->v)[0]);
876 destroyclient(Client *c)
880 webkit_web_view_stop_loading(c->view);
881 /* Not needed, has already been called
882 gtk_widget_destroy(c->win);
885 for (p = clients; p && p->next != c; p = p->next)
898 destroyclient(clients);
906 newview(Client *c, WebKitWebView *rv)
909 WebKitSettings *settings;
910 WebKitUserContentManager *contentmanager;
911 WebKitWebContext *context;
916 webkit_web_view_new_with_related_view(rv));
918 settings = webkit_settings_new_with_settings(
919 "auto-load-images", curconfig[LoadImages].val.b,
920 "default-font-size", curconfig[FontSize].val.f,
921 "enable-caret-browsing", curconfig[CaretBrowsing].val.b,
922 "enable-developer-extras", curconfig[Inspector].val.b,
923 "enable-dns-prefetching", curconfig[DNSPrefetch].val.b,
924 "enable-frame-flattening", curconfig[FrameFlattening].val.b,
925 "enable-html5-database", curconfig[DiskCache].val.b,
926 "enable-html5-local-storage", curconfig[DiskCache].val.b,
927 "enable-javascript", curconfig[JavaScript].val.b,
928 "enable-plugins", curconfig[Plugins].val.b,
929 "enable-accelerated-2d-canvas", curconfig[AcceleratedCanvas].val.b,
930 "enable-site-specific-quirks", curconfig[SiteQuirks].val.b,
931 "media-playback-requires-user-gesture", curconfig[MediaManualPlay].val.b,
933 /* For mor interesting settings, have a look at
934 * http://webkitgtk.org/reference/webkit2gtk/stable/WebKitSettings.html */
936 if (strcmp(fulluseragent, "")) {
937 webkit_settings_set_user_agent(settings, fulluseragent);
938 } else if (surfuseragent) {
939 webkit_settings_set_user_agent_with_application_details(
940 settings, "Surf", VERSION);
942 useragent = webkit_settings_get_user_agent(settings);
944 contentmanager = webkit_user_content_manager_new();
946 context = webkit_web_context_new_with_website_data_manager(
947 webkit_website_data_manager_new(
948 "base-cache-directory", cachedir,
949 "base-data-directory", cachedir,
952 /* rendering process model, can be a shared unique one
953 * or one for each view */
954 webkit_web_context_set_process_model(context,
955 WEBKIT_PROCESS_MODEL_MULTIPLE_SECONDARY_PROCESSES);
957 webkit_web_context_set_tls_errors_policy(context,
958 curconfig[StrictSSL].val.b ? WEBKIT_TLS_ERRORS_POLICY_FAIL :
959 WEBKIT_TLS_ERRORS_POLICY_IGNORE);
961 webkit_web_context_set_cache_model(context,
962 curconfig[DiskCache].val.b ? WEBKIT_CACHE_MODEL_WEB_BROWSER :
963 WEBKIT_CACHE_MODEL_DOCUMENT_VIEWER);
965 /* Currently only works with text file to be compatible with curl */
966 webkit_cookie_manager_set_persistent_storage(
967 webkit_web_context_get_cookie_manager(context), cookiefile,
968 WEBKIT_COOKIE_PERSISTENT_STORAGE_TEXT);
970 webkit_cookie_manager_set_accept_policy(
971 webkit_web_context_get_cookie_manager(context),
974 webkit_web_context_set_preferred_languages(context,
975 curconfig[PreferredLanguages].val.v);
976 webkit_web_context_set_spell_checking_languages(context,
977 curconfig[SpellLanguages].val.v);
978 webkit_web_context_set_spell_checking_enabled(context,
979 curconfig[SpellChecking].val.b);
981 g_signal_connect(G_OBJECT(context), "download-started",
982 G_CALLBACK(downloadstarted), c);
984 v = g_object_new(WEBKIT_TYPE_WEB_VIEW,
985 "settings", settings,
986 "user-content-manager", contentmanager,
987 "web-context", context,
991 g_signal_connect(G_OBJECT(v), "notify::estimated-load-progress",
992 G_CALLBACK(progresschanged), c);
993 g_signal_connect(G_OBJECT(v), "notify::title",
994 G_CALLBACK(titlechanged), c);
995 g_signal_connect(G_OBJECT(v), "button-release-event",
996 G_CALLBACK(buttonreleased), c);
997 g_signal_connect(G_OBJECT(v), "close",
998 G_CALLBACK(closeview), c);
999 g_signal_connect(G_OBJECT(v), "create",
1000 G_CALLBACK(createview), c);
1001 g_signal_connect(G_OBJECT(v), "decide-policy",
1002 G_CALLBACK(decidepolicy), c);
1003 g_signal_connect(G_OBJECT(v), "load-changed",
1004 G_CALLBACK(loadchanged), c);
1005 g_signal_connect(G_OBJECT(v), "mouse-target-changed",
1006 G_CALLBACK(mousetargetchanged), c);
1007 g_signal_connect(G_OBJECT(v), "permission-request",
1008 G_CALLBACK(permissionrequested), c);
1009 g_signal_connect(G_OBJECT(v), "ready-to-show",
1010 G_CALLBACK(showview), c);
1016 createview(WebKitWebView *v, WebKitNavigationAction *a, Client *c)
1020 switch (webkit_navigation_action_get_navigation_type(a)) {
1021 case WEBKIT_NAVIGATION_TYPE_OTHER: /* fallthrough */
1023 * popup windows of type “other” are almost always triggered
1024 * by user gesture, so inverse the logic here
1026 /* instead of this, compare destination uri to mouse-over uri for validating window */
1027 if (webkit_navigation_action_is_user_gesture(a))
1029 case WEBKIT_NAVIGATION_TYPE_LINK_CLICKED: /* fallthrough */
1030 case WEBKIT_NAVIGATION_TYPE_FORM_SUBMITTED: /* fallthrough */
1031 case WEBKIT_NAVIGATION_TYPE_BACK_FORWARD: /* fallthrough */
1032 case WEBKIT_NAVIGATION_TYPE_RELOAD: /* fallthrough */
1033 case WEBKIT_NAVIGATION_TYPE_FORM_RESUBMITTED:
1040 return GTK_WIDGET(n->view);
1044 buttonreleased(GtkWidget *w, GdkEvent *e, Client *c)
1046 WebKitHitTestResultContext element;
1049 element = webkit_hit_test_result_get_context(c->mousepos);
1051 for (i = 0; i < LENGTH(buttons); ++i) {
1052 if (element & buttons[i].target &&
1053 e->button.button == buttons[i].button &&
1054 CLEANMASK(e->button.state) == CLEANMASK(buttons[i].mask) &&
1056 buttons[i].func(c, &buttons[i].arg, c->mousepos);
1057 return buttons[i].stopevent;
1065 processx(GdkXEvent *e, GdkEvent *event, gpointer d)
1067 Client *c = (Client *)d;
1071 if (((XEvent *)e)->type == PropertyNotify) {
1072 ev = &((XEvent *)e)->xproperty;
1073 if (ev->state == PropertyNewValue) {
1074 if (ev->atom == atoms[AtomFind]) {
1077 return GDK_FILTER_REMOVE;
1078 } else if (ev->atom == atoms[AtomGo]) {
1079 a.v = getatom(c, AtomGo);
1082 return GDK_FILTER_REMOVE;
1086 return GDK_FILTER_CONTINUE;
1090 winevent(GtkWidget *w, GdkEvent *e, Client *c)
1095 case GDK_ENTER_NOTIFY:
1096 c->overtitle = c->targeturi;
1100 if (!curconfig[KioskMode].val.b) {
1101 for (i = 0; i < LENGTH(keys); ++i) {
1102 if (gdk_keyval_to_lower(e->key.keyval) ==
1104 CLEANMASK(e->key.state) == keys[i].mod &&
1107 keys[i].func(c, &(keys[i].arg));
1112 case GDK_LEAVE_NOTIFY:
1113 c->overtitle = NULL;
1116 case GDK_WINDOW_STATE:
1117 if (e->window_state.changed_mask ==
1118 GDK_WINDOW_STATE_FULLSCREEN)
1119 c->fullscreen = e->window_state.new_window_state &
1120 GDK_WINDOW_STATE_FULLSCREEN;
1130 showview(WebKitWebView *v, Client *c)
1132 GdkRGBA bgcolor = { 0 };
1135 c->finder = webkit_web_view_get_find_controller(c->view);
1136 c->inspector = webkit_web_view_get_inspector(c->view);
1138 c->win = createwindow(c);
1140 gtk_container_add(GTK_CONTAINER(c->win), GTK_WIDGET(c->view));
1141 gtk_widget_show_all(c->win);
1142 gtk_widget_grab_focus(GTK_WIDGET(c->view));
1144 gwin = gtk_widget_get_window(GTK_WIDGET(c->win));
1145 c->xid = gdk_x11_window_get_xid(gwin);
1148 gdk_display_sync(gtk_widget_get_display(c->win));
1152 if (curconfig[HideBackground].val.b)
1153 webkit_web_view_set_background_color(c->view, &bgcolor);
1155 if (!curconfig[KioskMode].val.b) {
1156 gdk_window_set_events(gwin, GDK_ALL_EVENTS_MASK);
1157 gdk_window_add_filter(gwin, processx, c);
1160 if (curconfig[RunInFullscreen].val.b)
1161 togglefullscreen(c, NULL);
1163 if (curconfig[ZoomLevel].val.f != 1.0)
1164 webkit_web_view_set_zoom_level(c->view,
1165 curconfig[ZoomLevel].val.f);
1167 setatom(c, AtomFind, "");
1168 setatom(c, AtomUri, "about:blank");
1172 createwindow(Client *c)
1178 w = gtk_plug_new(embed);
1180 w = gtk_window_new(GTK_WINDOW_TOPLEVEL);
1182 wmstr = g_path_get_basename(argv0);
1183 gtk_window_set_wmclass(GTK_WINDOW(w), wmstr, "Surf");
1186 wmstr = g_strdup_printf("%s[%lu]", "Surf",
1187 webkit_web_view_get_page_id(c->view));
1188 gtk_window_set_role(GTK_WINDOW(w), wmstr);
1191 gtk_window_set_default_size(GTK_WINDOW(w), 800, 600);
1194 g_signal_connect(G_OBJECT(w), "destroy",
1195 G_CALLBACK(destroywin), c);
1196 g_signal_connect(G_OBJECT(w), "enter-notify-event",
1197 G_CALLBACK(winevent), c);
1198 g_signal_connect(G_OBJECT(w), "key-press-event",
1199 G_CALLBACK(winevent), c);
1200 g_signal_connect(G_OBJECT(w), "leave-notify-event",
1201 G_CALLBACK(winevent), c);
1202 g_signal_connect(G_OBJECT(w), "window-state-event",
1203 G_CALLBACK(winevent), c);
1209 loadchanged(WebKitWebView *v, WebKitLoadEvent e, Client *c)
1211 const char *title = geturi(c);
1214 case WEBKIT_LOAD_STARTED:
1215 curconfig = defconfig;
1216 setatom(c, AtomUri, title);
1218 c->tlsflags = G_TLS_CERTIFICATE_VALIDATE_ALL + 1;
1219 seturiparameters(c, geturi(c));
1221 case WEBKIT_LOAD_REDIRECTED:
1222 setatom(c, AtomUri, title);
1224 seturiparameters(c, geturi(c));
1226 case WEBKIT_LOAD_COMMITTED:
1227 if (!webkit_web_view_get_tls_info(c->view, NULL,
1229 c->tlsflags = G_TLS_CERTIFICATE_VALIDATE_ALL + 1;
1232 case WEBKIT_LOAD_FINISHED:
1233 /* Disabled until we write some WebKitWebExtension for
1234 * manipulating the DOM directly.
1235 evalscript(c, "document.documentElement.style.overflow = '%s'",
1236 enablescrollbars ? "auto" : "hidden");
1245 progresschanged(WebKitWebView *v, GParamSpec *ps, Client *c)
1247 c->progress = webkit_web_view_get_estimated_load_progress(c->view) *
1253 titlechanged(WebKitWebView *view, GParamSpec *ps, Client *c)
1255 c->title = webkit_web_view_get_title(c->view);
1260 mousetargetchanged(WebKitWebView *v, WebKitHitTestResult *h, guint modifiers,
1263 WebKitHitTestResultContext hc = webkit_hit_test_result_get_context(h);
1265 /* Keep the hit test to know where is the pointer on the next click */
1269 c->targeturi = webkit_hit_test_result_get_link_uri(h);
1270 else if (hc & OnImg)
1271 c->targeturi = webkit_hit_test_result_get_image_uri(h);
1272 else if (hc & OnMedia)
1273 c->targeturi = webkit_hit_test_result_get_media_uri(h);
1275 c->targeturi = NULL;
1277 c->overtitle = c->targeturi;
1282 permissionrequested(WebKitWebView *v, WebKitPermissionRequest *r, Client *c)
1284 if (WEBKIT_IS_GEOLOCATION_PERMISSION_REQUEST(r)) {
1285 if (curconfig[Geolocation].val.b)
1286 webkit_permission_request_allow(r);
1288 webkit_permission_request_deny(r);
1296 decidepolicy(WebKitWebView *v, WebKitPolicyDecision *d,
1297 WebKitPolicyDecisionType dt, Client *c)
1300 case WEBKIT_POLICY_DECISION_TYPE_NAVIGATION_ACTION:
1301 decidenavigation(d, c);
1303 case WEBKIT_POLICY_DECISION_TYPE_NEW_WINDOW_ACTION:
1304 decidenewwindow(d, c);
1306 case WEBKIT_POLICY_DECISION_TYPE_RESPONSE:
1307 decideresource(d, c);
1310 webkit_policy_decision_ignore(d);
1317 decidenavigation(WebKitPolicyDecision *d, Client *c)
1319 WebKitNavigationAction *a =
1320 webkit_navigation_policy_decision_get_navigation_action(
1321 WEBKIT_NAVIGATION_POLICY_DECISION(d));
1323 switch (webkit_navigation_action_get_navigation_type(a)) {
1324 case WEBKIT_NAVIGATION_TYPE_LINK_CLICKED: /* fallthrough */
1325 case WEBKIT_NAVIGATION_TYPE_FORM_SUBMITTED: /* fallthrough */
1326 case WEBKIT_NAVIGATION_TYPE_BACK_FORWARD: /* fallthrough */
1327 case WEBKIT_NAVIGATION_TYPE_RELOAD: /* fallthrough */
1328 case WEBKIT_NAVIGATION_TYPE_FORM_RESUBMITTED: /* fallthrough */
1329 case WEBKIT_NAVIGATION_TYPE_OTHER: /* fallthrough */
1331 /* Do not navigate to links with a "_blank" target (popup) */
1332 if (webkit_navigation_policy_decision_get_frame_name(
1333 WEBKIT_NAVIGATION_POLICY_DECISION(d))) {
1334 webkit_policy_decision_ignore(d);
1336 /* Filter out navigation to different domain ? */
1337 /* get action→urirequest, copy and load in new window+view
1338 * on Ctrl+Click ? */
1339 webkit_policy_decision_use(d);
1346 decidenewwindow(WebKitPolicyDecision *d, Client *c)
1349 WebKitNavigationAction *a =
1350 webkit_navigation_policy_decision_get_navigation_action(
1351 WEBKIT_NAVIGATION_POLICY_DECISION(d));
1354 switch (webkit_navigation_action_get_navigation_type(a)) {
1355 case WEBKIT_NAVIGATION_TYPE_LINK_CLICKED: /* fallthrough */
1356 case WEBKIT_NAVIGATION_TYPE_FORM_SUBMITTED: /* fallthrough */
1357 case WEBKIT_NAVIGATION_TYPE_BACK_FORWARD: /* fallthrough */
1358 case WEBKIT_NAVIGATION_TYPE_RELOAD: /* fallthrough */
1359 case WEBKIT_NAVIGATION_TYPE_FORM_RESUBMITTED:
1360 /* Filter domains here */
1361 /* If the value of “mouse-button” is not 0, then the navigation was triggered by a mouse event.
1362 * test for link clicked but no button ? */
1363 arg.v = webkit_uri_request_get_uri(
1364 webkit_navigation_action_get_request(a));
1365 newwindow(c, &arg, 0);
1367 case WEBKIT_NAVIGATION_TYPE_OTHER: /* fallthrough */
1372 webkit_policy_decision_ignore(d);
1376 decideresource(WebKitPolicyDecision *d, Client *c)
1379 WebKitResponsePolicyDecision *r = WEBKIT_RESPONSE_POLICY_DECISION(d);
1380 WebKitURIResponse *res =
1381 webkit_response_policy_decision_get_response(r);
1382 const gchar *uri = webkit_uri_response_get_uri(res);
1384 if (g_str_has_suffix(uri, "/favicon.ico")) {
1385 webkit_policy_decision_ignore(d);
1389 if (!g_str_has_prefix(uri, "http://")
1390 && !g_str_has_prefix(uri, "https://")
1391 && !g_str_has_prefix(uri, "about:")
1392 && !g_str_has_prefix(uri, "file://")
1393 && !g_str_has_prefix(uri, "data:")
1394 && !g_str_has_prefix(uri, "blob:")
1395 && strlen(uri) > 0) {
1396 for (i = 0; i < strlen(uri); i++) {
1397 if (!g_ascii_isprint(uri[i])) {
1403 handleplumb(c, uri);
1404 webkit_policy_decision_ignore(d);
1409 if (webkit_response_policy_decision_is_mime_type_supported(r)) {
1410 webkit_policy_decision_use(d);
1412 webkit_policy_decision_ignore(d);
1418 downloadstarted(WebKitWebContext *wc, WebKitDownload *d, Client *c)
1420 g_signal_connect(G_OBJECT(d), "notify::response",
1421 G_CALLBACK(responsereceived), c);
1425 responsereceived(WebKitDownload *d, GParamSpec *ps, Client *c)
1427 download(c, webkit_download_get_response(d));
1428 webkit_download_cancel(d);
1432 download(Client *c, WebKitURIResponse *r)
1434 Arg a = (Arg)DOWNLOAD(webkit_uri_response_get_uri(r), geturi(c));
1439 closeview(WebKitWebView *v, Client *c)
1441 gtk_widget_destroy(c->win);
1445 destroywin(GtkWidget* w, Client *c)
1453 pasteuri(GtkClipboard *clipboard, const char *text, gpointer d)
1455 Arg a = {.v = text };
1457 loaduri((Client *) d, &a);
1461 reload(Client *c, const Arg *a)
1464 webkit_web_view_reload_bypass_cache(c->view);
1466 webkit_web_view_reload(c->view);
1470 print(Client *c, const Arg *a)
1472 webkit_print_operation_run_dialog(webkit_print_operation_new(c->view),
1473 GTK_WINDOW(c->win));
1477 clipboard(Client *c, const Arg *a)
1479 if (a->b) { /* load clipboard uri */
1480 gtk_clipboard_request_text(gtk_clipboard_get(
1481 GDK_SELECTION_PRIMARY),
1483 } else { /* copy uri */
1484 gtk_clipboard_set_text(gtk_clipboard_get(
1485 GDK_SELECTION_PRIMARY), c->targeturi
1486 ? c->targeturi : geturi(c), -1);
1491 zoom(Client *c, const Arg *a)
1494 webkit_web_view_set_zoom_level(c->view,
1495 curconfig[ZoomLevel].val.f + 0.1);
1497 webkit_web_view_set_zoom_level(c->view,
1498 curconfig[ZoomLevel].val.f - 0.1);
1500 webkit_web_view_set_zoom_level(c->view, 1.0);
1502 curconfig[ZoomLevel].val.f = webkit_web_view_get_zoom_level(c->view);
1506 scroll(Client *c, const Arg *a)
1508 GdkEvent *ev = gdk_event_new(GDK_KEY_PRESS);
1510 gdk_event_set_device(ev, gdkkb);
1511 ev->key.window = gtk_widget_get_window(GTK_WIDGET(c->win));
1512 ev->key.state = GDK_CONTROL_MASK;
1513 ev->key.time = GDK_CURRENT_TIME;
1517 ev->key.keyval = GDK_KEY_Down;
1520 ev->key.keyval = GDK_KEY_Page_Down;
1523 ev->key.keyval = GDK_KEY_Left;
1526 ev->key.keyval = GDK_KEY_Right;
1529 ev->key.keyval = GDK_KEY_Page_Up;
1532 ev->key.keyval = GDK_KEY_Up;
1540 navigate(Client *c, const Arg *a)
1543 webkit_web_view_go_back(c->view);
1545 webkit_web_view_go_forward(c->view);
1549 stop(Client *c, const Arg *a)
1551 webkit_web_view_stop_loading(c->view);
1555 toggle(Client *c, const Arg *a)
1557 curconfig[a->i].val.b ^= 1;
1558 setparameter(c, 1, (ParamName)a->i, &curconfig[a->i].val);
1562 togglefullscreen(Client *c, const Arg *a)
1564 /* toggling value is handled in winevent() */
1566 gtk_window_unfullscreen(GTK_WINDOW(c->win));
1568 gtk_window_fullscreen(GTK_WINDOW(c->win));
1572 togglecookiepolicy(Client *c, const Arg *a)
1575 cookiepolicy %= strlen(curconfig[CookiePolicies].val.v);
1577 setparameter(c, 0, CookiePolicies, NULL);
1581 toggleinspector(Client *c, const Arg *a)
1583 if (webkit_web_inspector_is_attached(c->inspector))
1584 webkit_web_inspector_close(c->inspector);
1585 else if (curconfig[Inspector].val.b)
1586 webkit_web_inspector_show(c->inspector);
1590 find(Client *c, const Arg *a)
1596 webkit_find_controller_search_next(c->finder);
1598 webkit_find_controller_search_previous(c->finder);
1600 s = getatom(c, AtomFind);
1601 f = webkit_find_controller_get_search_text(c->finder);
1603 if (g_strcmp0(f, s) == 0) /* reset search */
1604 webkit_find_controller_search(c->finder, "", findopts,
1607 webkit_find_controller_search(c->finder, s, findopts,
1610 if (strcmp(s, "") == 0)
1611 webkit_find_controller_search_finish(c->finder);
1616 clicknavigate(Client *c, const Arg *a, WebKitHitTestResult *h)
1622 clicknewwindow(Client *c, const Arg *a, WebKitHitTestResult *h)
1626 arg.v = webkit_hit_test_result_get_link_uri(h);
1627 newwindow(c, &arg, a->b);
1631 clickexternplayer(Client *c, const Arg *a, WebKitHitTestResult *h)
1635 arg = (Arg)VIDEOPLAY(webkit_hit_test_result_get_media_uri(h));
1640 main(int argc, char *argv[])
1645 memset(&arg, 0, sizeof(arg));
1647 /* command line args */
1650 defconfig CSETV(CookiePolicies, EARGF(usage()));
1653 defconfig CSETB(ScrollBars, 0);
1656 defconfig CSETB(ScrollBars, 1);
1659 cookiefile = EARGF(usage());
1662 defconfig CSETB(DiskCache, 0);
1665 defconfig CSETB(DiskCache, 1);
1668 embed = strtol(EARGF(usage()), NULL, 0);
1671 defconfig CSETB(RunInFullscreen, 0);
1674 defconfig CSETB(RunInFullscreen, 1);
1677 defconfig CSETB(Geolocation, 0);
1680 defconfig CSETB(Geolocation, 1);
1683 defconfig CSETB(LoadImages, 0);
1686 defconfig CSETB(LoadImages, 1);
1689 defconfig CSETB(KioskMode, 0);
1692 defconfig CSETB(KioskMode, 1);
1695 defconfig CSETB(Style, 0);
1698 defconfig CSETB(Style, 1);
1701 defconfig CSETB(Inspector, 0);
1704 defconfig CSETB(Inspector, 1);
1707 defconfig CSETB(Plugins, 0);
1710 defconfig CSETB(Plugins, 1);
1713 scriptfile = EARGF(usage());
1716 defconfig CSETB(JavaScript, 0);
1719 defconfig CSETB(JavaScript, 1);
1722 stylefile = EARGF(usage());
1725 fulluseragent = EARGF(usage());
1728 die("surf-"VERSION", ©2009-2015 surf engineers, "
1729 "see LICENSE for details\n");
1734 defconfig CSETF(ZoomLevel, strtof(EARGF(usage()), NULL));
1742 arg.v = "about:blank";
1745 c = newclient(NULL);