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,
98 typedef struct Client {
101 WebKitWebInspector *inspector;
102 WebKitFindController *finder;
103 WebKitHitTestResult *mousepos;
104 GTlsCertificateFlags tlsflags;
106 int progress, fullscreen;
107 const char *title, *overtitle, *targeturi;
115 void (*func)(Client *c, const Arg *a);
123 void (*func)(Client *c, const Arg *a, WebKitHitTestResult *h);
125 unsigned int stopevent;
130 Parameter config[ParameterLast];
141 static void usage(void);
142 static void die(const char *errstr, ...);
143 static void setup(void);
144 static void sigchld(int unused);
145 static char *buildfile(const char *path);
146 static char *buildpath(const char *path);
147 static const char *getuserhomedir(const char *user);
148 static const char *getcurrentuserhomedir(void);
149 static Client *newclient(Client *c);
150 static void loaduri(Client *c, const Arg *a);
151 static const char *geturi(Client *c);
152 static void setatom(Client *c, int a, const char *v);
153 static const char *getatom(Client *c, int a);
154 static void updatetitle(Client *c);
155 static void gettogglestats(Client *c);
156 static void getpagestats(Client *c);
157 static WebKitCookieAcceptPolicy cookiepolicy_get(void);
158 static char cookiepolicy_set(const WebKitCookieAcceptPolicy p);
159 static void seturiparameters(Client *c, const char *uri);
160 static void setparameter(Client *c, int refresh, ParamName p, const Arg *a);
161 static const char *getstyle(const char *uri);
162 static void setstyle(Client *c, const char *stylefile);
163 static void runscript(Client *c);
164 static void evalscript(Client *c, const char *jsstr, ...);
165 static void updatewinid(Client *c);
166 static void handleplumb(Client *c, const char *uri);
167 static void newwindow(Client *c, const Arg *a, int noembed);
168 static void spawn(Client *c, const Arg *a);
169 static void destroyclient(Client *c);
170 static void cleanup(void);
173 static WebKitWebView *newview(Client *c, WebKitWebView *rv);
174 static GtkWidget *createview(WebKitWebView *v, WebKitNavigationAction *a,
176 static gboolean buttonreleased(GtkWidget *w, GdkEvent *e, Client *c);
177 static GdkFilterReturn processx(GdkXEvent *xevent, GdkEvent *event,
179 static gboolean winevent(GtkWidget *w, GdkEvent *e, Client *c);
180 static void showview(WebKitWebView *v, Client *c);
181 static GtkWidget *createwindow(Client *c);
182 static void loadchanged(WebKitWebView *v, WebKitLoadEvent e, Client *c);
183 static void progresschanged(WebKitWebView *v, GParamSpec *ps, Client *c);
184 static void titlechanged(WebKitWebView *view, GParamSpec *ps, Client *c);
185 static void mousetargetchanged(WebKitWebView *v, WebKitHitTestResult *h,
186 guint modifiers, Client *c);
187 static gboolean permissionrequested(WebKitWebView *v,
188 WebKitPermissionRequest *r, Client *c);
189 static gboolean decidepolicy(WebKitWebView *v, WebKitPolicyDecision *d,
190 WebKitPolicyDecisionType dt, Client *c);
191 static void decidenavigation(WebKitPolicyDecision *d, Client *c);
192 static void decidenewwindow(WebKitPolicyDecision *d, Client *c);
193 static void decideresource(WebKitPolicyDecision *d, Client *c);
194 static void downloadstarted(WebKitWebContext *wc, WebKitDownload *d,
196 static void responsereceived(WebKitDownload *d, GParamSpec *ps, Client *c);
197 static void download(Client *c, WebKitURIResponse *r);
198 static void closeview(WebKitWebView *v, Client *c);
199 static void destroywin(GtkWidget* w, Client *c);
202 static void pasteuri(GtkClipboard *clipboard, const char *text, gpointer d);
203 static void reload(Client *c, const Arg *a);
204 static void print(Client *c, const Arg *a);
205 static void clipboard(Client *c, const Arg *a);
206 static void zoom(Client *c, const Arg *a);
207 static void scroll(Client *c, const Arg *a);
208 static void navigate(Client *c, const Arg *a);
209 static void stop(Client *c, const Arg *a);
210 static void toggle(Client *c, const Arg *a);
211 static void togglefullscreen(Client *c, const Arg *a);
212 static void togglecookiepolicy(Client *c, const Arg *a);
213 static void toggleinspector(Client *c, const Arg *a);
214 static void find(Client *c, const Arg *a);
217 static void clicknavigate(Client *c, const Arg *a, WebKitHitTestResult *h);
218 static void clicknewwindow(Client *c, const Arg *a, WebKitHitTestResult *h);
219 static void clickexternplayer(Client *c, const Arg *a, WebKitHitTestResult *h);
221 static char winid[64];
222 static char togglestats[10];
223 static char pagestats[2];
224 static Atom atoms[AtomLast];
227 static int cookiepolicy;
229 static Client *clients;
230 static GdkDevice *gdkkb;
231 static char *stylefile;
232 static const char *useragent;
233 static Parameter *curconfig;
236 /* configuration, allows nested code to access above variables */
242 die("usage: %s [-bBdDfFgGiIkKmMnNpPsSvx] [-a cookiepolicies ] "
243 "[-c cookiefile] [-e xid] [-r scriptfile] [-t stylefile] "
244 "[-u useragent] [-z zoomlevel] [uri]\n", basename(argv0));
248 die(const char *errstr, ...)
252 va_start(ap, errstr);
253 vfprintf(stderr, errstr, ap);
264 /* clean up any zombies immediately */
266 gtk_init(NULL, NULL);
268 gdpy = gdk_display_get_default();
269 dpy = GDK_DISPLAY_XDISPLAY(gdpy);
271 curconfig = defconfig;
274 atoms[AtomFind] = XInternAtom(dpy, "_SURF_FIND", False);
275 atoms[AtomGo] = XInternAtom(dpy, "_SURF_GO", False);
276 atoms[AtomUri] = XInternAtom(dpy, "_SURF_URI", False);
279 cookiefile = buildfile(cookiefile);
280 scriptfile = buildfile(scriptfile);
281 cachedir = buildpath(cachedir);
283 gdkkb = gdk_seat_get_keyboard(gdk_display_get_default_seat(gdpy));
286 styledir = buildpath(styledir);
287 for (i = 0; i < LENGTH(styles); ++i) {
288 if (regcomp(&(styles[i].re), styles[i].regex,
291 "Could not compile regex: %s\n",
293 styles[i].regex = NULL;
295 styles[i].style = g_strconcat(styledir, "/",
296 styles[i].style, NULL);
300 stylefile = buildfile(stylefile);
303 for (i = 0; i < LENGTH(uriparams); ++i) {
304 if (!regcomp(&(uriparams[i].re), uriparams[i].uri,
306 /* copy default parameters if they are not already set
307 * or if they are forced */
308 for (j = 0; j < ParameterLast; ++j) {
309 if (!uriparams[i].config[j].force ||
311 uriparams[i].config[j] = defconfig[j];
315 "Could not compile regex: %s\n",
317 uriparams[i].uri = NULL;
325 if (signal(SIGCHLD, sigchld) == SIG_ERR)
326 die("Can't install SIGCHLD handler");
327 while (waitpid(-1, NULL, WNOHANG) > 0)
332 buildfile(const char *path)
334 char *dname, *bname, *bpath, *fpath;
337 dname = g_path_get_dirname(path);
338 bname = g_path_get_basename(path);
340 bpath = buildpath(dname);
343 fpath = g_build_filename(bpath, bname, NULL);
347 if (!(f = fopen(fpath, "a")))
348 die("Could not open file: %s\n", fpath);
350 g_chmod(fpath, 0600); /* always */
357 getuserhomedir(const char *user)
359 struct passwd *pw = getpwnam(user);
362 die("Can't get user %s login information.\n", user);
368 getcurrentuserhomedir(void)
374 homedir = getenv("HOME");
378 user = getenv("USER");
380 return getuserhomedir(user);
382 pw = getpwuid(getuid());
384 die("Can't get current user home directory\n");
390 buildpath(const char *path)
392 char *apath, *name, *p, *fpath;
395 if (path[0] == '~') {
396 if (path[1] == '/' || path[1] == '\0') {
397 p = (char *)&path[1];
398 homedir = getcurrentuserhomedir();
400 if ((p = strchr(path, '/')))
401 name = g_strndup(&path[1], --p - path);
403 name = g_strdup(&path[1]);
405 homedir = getuserhomedir(name);
408 apath = g_build_filename(homedir, p, NULL);
410 apath = g_strdup(path);
413 /* creating directory */
414 if (g_mkdir_with_parents(apath, 0700) < 0)
415 die("Could not access directory: %s\n", apath);
417 fpath = realpath(apath, NULL);
424 newclient(Client *rc)
428 if (!(c = calloc(1, sizeof(Client))))
429 die("Cannot malloc!\n");
435 c->tlsflags = G_TLS_CERTIFICATE_VALIDATE_ALL + 1;
436 c->view = newview(c, rc ? rc->view : NULL);
442 loaduri(Client *c, const Arg *a)
446 const char *uri = a->v;
448 if (g_strcmp0(uri, "") == 0)
451 if (g_str_has_prefix(uri, "http://") ||
452 g_str_has_prefix(uri, "https://") ||
453 g_str_has_prefix(uri, "file://") ||
454 g_str_has_prefix(uri, "about:")) {
456 } else if (!stat(uri, &st) && (path = realpath(uri, NULL))) {
457 url = g_strdup_printf("file://%s", path);
460 url = g_strdup_printf("http://%s", uri);
463 setatom(c, AtomUri, url);
465 if (strcmp(url, geturi(c)) == 0) {
468 webkit_web_view_load_uri(c->view, url);
480 if (!(uri = webkit_web_view_get_uri(c->view)))
486 setatom(Client *c, int a, const char *v)
489 XChangeProperty(dpy, c->xid,
490 atoms[a], XA_STRING, 8, PropModeReplace,
491 (unsigned char *)v, strlen(v) + 1);
495 getatom(Client *c, int a)
497 static char buf[BUFSIZ];
500 unsigned long ldummy;
501 unsigned char *p = NULL;
503 XGetWindowProperty(dpy, c->xid, atoms[a], 0L, BUFSIZ, False, XA_STRING,
504 &adummy, &idummy, &ldummy, &ldummy, &p);
506 strncpy(buf, (char *)p, LENGTH(buf) - 1);
515 updatetitle(Client *c)
518 const char *name = c->overtitle ? c->overtitle :
519 c->title ? c->title : "";
521 if (curconfig[ShowIndicators].val.b) {
525 if (c->progress != 100)
526 title = g_strdup_printf("[%i%%] %s:%s | %s",
527 c->progress, togglestats, pagestats, name);
529 title = g_strdup_printf("%s:%s | %s",
530 togglestats, pagestats, name);
532 gtk_window_set_title(GTK_WINDOW(c->win), title);
535 gtk_window_set_title(GTK_WINDOW(c->win), name);
540 gettogglestats(Client *c)
542 togglestats[0] = cookiepolicy_set(cookiepolicy_get());
543 togglestats[1] = curconfig[CaretBrowsing].val.b ? 'C' : 'c';
544 togglestats[2] = curconfig[Geolocation].val.b ? 'G' : 'g';
545 togglestats[3] = curconfig[DiskCache].val.b ? 'D' : 'd';
546 togglestats[4] = curconfig[LoadImages].val.b ? 'I' : 'i';
547 togglestats[5] = curconfig[JavaScript].val.b ? 'S' : 's';
548 togglestats[6] = curconfig[Plugins].val.b ? 'V' : 'v';
549 togglestats[7] = curconfig[Style].val.b ? 'M' : 'm';
550 togglestats[8] = curconfig[FrameFlattening].val.b ? 'F' : 'f';
551 togglestats[9] = '\0';
555 getpagestats(Client *c)
557 pagestats[0] = c->tlsflags > G_TLS_CERTIFICATE_VALIDATE_ALL ? '-' :
558 c->tlsflags > 0 ? 'U' : 'T';
562 WebKitCookieAcceptPolicy
563 cookiepolicy_get(void)
565 switch (((char *)curconfig[CookiePolicies].val.v)[cookiepolicy]) {
567 return WEBKIT_COOKIE_POLICY_ACCEPT_NEVER;
569 return WEBKIT_COOKIE_POLICY_ACCEPT_NO_THIRD_PARTY;
570 default: /* fallthrough */
572 return WEBKIT_COOKIE_POLICY_ACCEPT_ALWAYS;
577 cookiepolicy_set(const WebKitCookieAcceptPolicy p)
580 case WEBKIT_COOKIE_POLICY_ACCEPT_NEVER:
582 case WEBKIT_COOKIE_POLICY_ACCEPT_NO_THIRD_PARTY:
584 default: /* fallthrough */
585 case WEBKIT_COOKIE_POLICY_ACCEPT_ALWAYS:
591 seturiparameters(Client *c, const char *uri)
595 for (i = 0; i < LENGTH(uriparams); ++i) {
596 if (uriparams[i].uri &&
597 !regexec(&(uriparams[i].re), uri, 0, NULL, 0)) {
598 curconfig = uriparams[i].config;
603 for (i = 0; i < ParameterLast; ++i)
604 setparameter(c, 0, i, &curconfig[i].val);
608 setparameter(Client *c, int refresh, ParamName p, const Arg *a)
610 GdkRGBA bgcolor = { 0 };
611 WebKitSettings *s = webkit_web_view_get_settings(c->view);
615 webkit_settings_set_enable_caret_browsing(s, a->b);
619 webkit_cookie_manager_set_accept_policy(
620 webkit_web_context_get_cookie_manager(
621 webkit_web_view_get_context(c->view)),
626 webkit_web_context_set_cache_model(
627 webkit_web_view_get_context(c->view), a->b ?
628 WEBKIT_CACHE_MODEL_WEB_BROWSER :
629 WEBKIT_CACHE_MODEL_DOCUMENT_VIEWER);
630 return; /* do not update */
632 webkit_settings_set_enable_dns_prefetching(s, a->b);
633 return; /* do not update */
635 webkit_settings_set_default_font_size(s, a->i);
636 return; /* do not update */
637 case FrameFlattening:
638 webkit_settings_set_enable_frame_flattening(s, a->b);
645 webkit_web_view_set_background_color(c->view, &bgcolor);
646 return; /* do not update */
648 webkit_settings_set_enable_developer_extras(s, a->b);
649 return; /* do not update */
651 webkit_settings_set_enable_javascript(s, a->b);
654 return; /* do nothing */
656 webkit_settings_set_auto_load_images(s, a->b);
659 webkit_settings_set_enable_plugins(s, a->b);
661 case PreferredLanguages:
662 return; /* do nothing */
663 case RunInFullscreen:
664 return; /* do nothing */
666 /* Disabled until we write some WebKitWebExtension for
667 * manipulating the DOM directly.
668 enablescrollbars = !enablescrollbars;
669 evalscript(c, "document.documentElement.style.overflow = '%s'",
670 enablescrollbars ? "auto" : "hidden");
672 return; /* do not update */
676 webkit_web_context_set_spell_checking_enabled(
677 webkit_web_view_get_context(c->view), a->b);
678 return; /* do not update */
680 return; /* do nothing */
682 webkit_web_context_set_tls_errors_policy(
683 webkit_web_view_get_context(c->view), a->b ?
684 WEBKIT_TLS_ERRORS_POLICY_FAIL :
685 WEBKIT_TLS_ERRORS_POLICY_IGNORE);
686 return; /* do not update */
689 setstyle(c, getstyle(geturi(c)));
691 webkit_user_content_manager_remove_all_style_sheets(
692 webkit_web_view_get_user_content_manager(c->view));
696 webkit_web_view_set_zoom_level(c->view, a->f);
697 return; /* do not update */
699 return; /* do nothing */
708 getstyle(const char *uri)
715 for (i = 0; i < LENGTH(styles); ++i) {
716 if (styles[i].regex &&
717 !regexec(&(styles[i].re), uri, 0, NULL, 0))
718 return styles[i].style;
725 setstyle(Client *c, const char *stylefile)
729 if (!g_file_get_contents(stylefile, &style, NULL, NULL)) {
730 fprintf(stderr, "Could not read style file: %s\n", stylefile);
734 webkit_user_content_manager_add_style_sheet(
735 webkit_web_view_get_user_content_manager(c->view),
736 webkit_user_style_sheet_new(style,
737 WEBKIT_USER_CONTENT_INJECT_ALL_FRAMES,
738 WEBKIT_USER_STYLE_LEVEL_USER,
750 if (g_file_get_contents(scriptfile, &script, &l, NULL) && l)
751 evalscript(c, script);
756 evalscript(Client *c, const char *jsstr, ...)
762 script = g_strdup_vprintf(jsstr, ap);
765 webkit_web_view_run_javascript(c->view, script, NULL, NULL, NULL);
770 updatewinid(Client *c)
772 snprintf(winid, LENGTH(winid), "%lu", c->xid);
776 handleplumb(Client *c, const char *uri)
778 Arg a = (Arg)PLUMB(uri);
783 newwindow(Client *c, const Arg *a, int noembed)
787 const char *cmd[26], *uri;
788 const Arg arg = { .v = cmd };
792 cmd[i++] = curconfig[CookiePolicies].val.v;
793 cmd[i++] = curconfig[ScrollBars].val.b ? "-B" : "-b";
794 if (cookiefile && g_strcmp0(cookiefile, "")) {
796 cmd[i++] = cookiefile;
798 cmd[i++] = curconfig[DiskCache].val.b ? "-D" : "-d";
799 if (embed && !noembed) {
801 snprintf(tmp, LENGTH(tmp), "%lu", embed);
804 cmd[i++] = curconfig[RunInFullscreen].val.b ? "-F" : "-f" ;
805 cmd[i++] = curconfig[Geolocation].val.b ? "-G" : "-g" ;
806 cmd[i++] = curconfig[LoadImages].val.b ? "-I" : "-i" ;
807 cmd[i++] = curconfig[KioskMode].val.b ? "-K" : "-k" ;
808 cmd[i++] = curconfig[Style].val.b ? "-M" : "-m" ;
809 cmd[i++] = curconfig[Inspector].val.b ? "-N" : "-n" ;
810 cmd[i++] = curconfig[Plugins].val.b ? "-P" : "-p" ;
811 if (scriptfile && g_strcmp0(scriptfile, "")) {
813 cmd[i++] = scriptfile;
815 cmd[i++] = curconfig[JavaScript].val.b ? "-S" : "-s";
816 if (stylefile && g_strcmp0(stylefile, "")) {
818 cmd[i++] = stylefile;
820 if (fulluseragent && g_strcmp0(fulluseragent, "")) {
822 cmd[i++] = fulluseragent;
826 /* do not keep zoom level */
836 spawn(Client *c, const Arg *a)
840 close(ConnectionNumber(dpy));
842 execvp(((char **)a->v)[0], (char **)a->v);
843 fprintf(stderr, "%s: execvp %s", argv0, ((char **)a->v)[0]);
850 destroyclient(Client *c)
854 webkit_web_view_stop_loading(c->view);
855 /* Not needed, has already been called
856 gtk_widget_destroy(c->win);
859 for (p = clients; p && p->next != c; p = p->next)
872 destroyclient(clients);
880 newview(Client *c, WebKitWebView *rv)
883 WebKitSettings *settings;
884 WebKitUserContentManager *contentmanager;
885 WebKitWebContext *context;
890 webkit_web_view_new_with_related_view(rv));
892 settings = webkit_settings_new_with_settings(
893 "auto-load-images", curconfig[LoadImages].val.b,
894 "default-font-size", curconfig[FontSize].val.f,
895 "enable-caret-browsing", curconfig[CaretBrowsing].val.b,
896 "enable-developer-extras", curconfig[Inspector].val.b,
897 "enable-dns-prefetching", curconfig[DNSPrefetch].val.b,
898 "enable-frame-flattening", curconfig[FrameFlattening].val.b,
899 "enable-html5-database", curconfig[DiskCache].val.b,
900 "enable-html5-local-storage", curconfig[DiskCache].val.b,
901 "enable-javascript", curconfig[JavaScript].val.b,
902 "enable-plugins", curconfig[Plugins].val.b,
904 /* For mor interesting settings, have a look at
905 * http://webkitgtk.org/reference/webkit2gtk/stable/WebKitSettings.html */
907 if (strcmp(fulluseragent, "")) {
908 webkit_settings_set_user_agent(settings, fulluseragent);
909 } else if (surfuseragent) {
910 webkit_settings_set_user_agent_with_application_details(
911 settings, "Surf", VERSION);
913 useragent = webkit_settings_get_user_agent(settings);
915 contentmanager = webkit_user_content_manager_new();
917 context = webkit_web_context_new_with_website_data_manager(
918 webkit_website_data_manager_new(
919 "base-cache-directory", cachedir,
920 "base-data-directory", cachedir,
923 /* rendering process model, can be a shared unique one
924 * or one for each view */
925 webkit_web_context_set_process_model(context,
926 WEBKIT_PROCESS_MODEL_MULTIPLE_SECONDARY_PROCESSES);
928 webkit_web_context_set_tls_errors_policy(context,
929 curconfig[StrictSSL].val.b ? WEBKIT_TLS_ERRORS_POLICY_FAIL :
930 WEBKIT_TLS_ERRORS_POLICY_IGNORE);
932 webkit_web_context_set_cache_model(context,
933 curconfig[DiskCache].val.b ? WEBKIT_CACHE_MODEL_WEB_BROWSER :
934 WEBKIT_CACHE_MODEL_DOCUMENT_VIEWER);
936 /* Currently only works with text file to be compatible with curl */
937 webkit_cookie_manager_set_persistent_storage(
938 webkit_web_context_get_cookie_manager(context), cookiefile,
939 WEBKIT_COOKIE_PERSISTENT_STORAGE_TEXT);
941 webkit_cookie_manager_set_accept_policy(
942 webkit_web_context_get_cookie_manager(context),
945 webkit_web_context_set_preferred_languages(context,
946 curconfig[PreferredLanguages].val.v);
947 webkit_web_context_set_spell_checking_languages(context,
948 curconfig[SpellLanguages].val.v);
949 webkit_web_context_set_spell_checking_enabled(context,
950 curconfig[SpellChecking].val.b);
952 g_signal_connect(G_OBJECT(context), "download-started",
953 G_CALLBACK(downloadstarted), c);
955 v = g_object_new(WEBKIT_TYPE_WEB_VIEW,
956 "settings", settings,
957 "user-content-manager", contentmanager,
958 "web-context", context,
962 g_signal_connect(G_OBJECT(v), "notify::estimated-load-progress",
963 G_CALLBACK(progresschanged), c);
964 g_signal_connect(G_OBJECT(v), "notify::title",
965 G_CALLBACK(titlechanged), c);
966 g_signal_connect(G_OBJECT(v), "button-release-event",
967 G_CALLBACK(buttonreleased), c);
968 g_signal_connect(G_OBJECT(v), "close",
969 G_CALLBACK(closeview), c);
970 g_signal_connect(G_OBJECT(v), "create",
971 G_CALLBACK(createview), c);
972 g_signal_connect(G_OBJECT(v), "decide-policy",
973 G_CALLBACK(decidepolicy), c);
974 g_signal_connect(G_OBJECT(v), "load-changed",
975 G_CALLBACK(loadchanged), c);
976 g_signal_connect(G_OBJECT(v), "mouse-target-changed",
977 G_CALLBACK(mousetargetchanged), c);
978 g_signal_connect(G_OBJECT(v), "permission-request",
979 G_CALLBACK(permissionrequested), c);
980 g_signal_connect(G_OBJECT(v), "ready-to-show",
981 G_CALLBACK(showview), c);
987 createview(WebKitWebView *v, WebKitNavigationAction *a, Client *c)
991 switch (webkit_navigation_action_get_navigation_type(a)) {
992 case WEBKIT_NAVIGATION_TYPE_OTHER: /* fallthrough */
994 * popup windows of type “other” are almost always triggered
995 * by user gesture, so inverse the logic here
997 /* instead of this, compare destination uri to mouse-over uri for validating window */
998 if (webkit_navigation_action_is_user_gesture(a))
1000 case WEBKIT_NAVIGATION_TYPE_LINK_CLICKED: /* fallthrough */
1001 case WEBKIT_NAVIGATION_TYPE_FORM_SUBMITTED: /* fallthrough */
1002 case WEBKIT_NAVIGATION_TYPE_BACK_FORWARD: /* fallthrough */
1003 case WEBKIT_NAVIGATION_TYPE_RELOAD: /* fallthrough */
1004 case WEBKIT_NAVIGATION_TYPE_FORM_RESUBMITTED:
1011 return GTK_WIDGET(n->view);
1015 buttonreleased(GtkWidget *w, GdkEvent *e, Client *c)
1017 WebKitHitTestResultContext element;
1020 element = webkit_hit_test_result_get_context(c->mousepos);
1022 for (i = 0; i < LENGTH(buttons); ++i) {
1023 if (element & buttons[i].target &&
1024 e->button.button == buttons[i].button &&
1025 CLEANMASK(e->button.state) == CLEANMASK(buttons[i].mask) &&
1027 buttons[i].func(c, &buttons[i].arg, c->mousepos);
1028 return buttons[i].stopevent;
1036 processx(GdkXEvent *e, GdkEvent *event, gpointer d)
1038 Client *c = (Client *)d;
1042 if (((XEvent *)e)->type == PropertyNotify) {
1043 ev = &((XEvent *)e)->xproperty;
1044 if (ev->state == PropertyNewValue) {
1045 if (ev->atom == atoms[AtomFind]) {
1048 return GDK_FILTER_REMOVE;
1049 } else if (ev->atom == atoms[AtomGo]) {
1050 a.v = getatom(c, AtomGo);
1053 return GDK_FILTER_REMOVE;
1057 return GDK_FILTER_CONTINUE;
1061 winevent(GtkWidget *w, GdkEvent *e, Client *c)
1066 case GDK_ENTER_NOTIFY:
1067 c->overtitle = c->targeturi;
1071 if (!curconfig[KioskMode].val.b) {
1072 for (i = 0; i < LENGTH(keys); ++i) {
1073 if (gdk_keyval_to_lower(e->key.keyval) ==
1075 CLEANMASK(e->key.state) == keys[i].mod &&
1078 keys[i].func(c, &(keys[i].arg));
1083 case GDK_LEAVE_NOTIFY:
1084 c->overtitle = NULL;
1087 case GDK_WINDOW_STATE:
1088 if (e->window_state.changed_mask ==
1089 GDK_WINDOW_STATE_FULLSCREEN)
1090 c->fullscreen = e->window_state.new_window_state &
1091 GDK_WINDOW_STATE_FULLSCREEN;
1101 showview(WebKitWebView *v, Client *c)
1103 GdkRGBA bgcolor = { 0 };
1106 c->finder = webkit_web_view_get_find_controller(c->view);
1107 c->inspector = webkit_web_view_get_inspector(c->view);
1109 c->win = createwindow(c);
1111 gtk_container_add(GTK_CONTAINER(c->win), GTK_WIDGET(c->view));
1112 gtk_widget_show_all(c->win);
1113 gtk_widget_grab_focus(GTK_WIDGET(c->view));
1115 gwin = gtk_widget_get_window(GTK_WIDGET(c->win));
1116 c->xid = gdk_x11_window_get_xid(gwin);
1119 gdk_display_sync(gtk_widget_get_display(c->win));
1123 if (curconfig[HideBackground].val.b)
1124 webkit_web_view_set_background_color(c->view, &bgcolor);
1126 if (!curconfig[KioskMode].val.b) {
1127 gdk_window_set_events(gwin, GDK_ALL_EVENTS_MASK);
1128 gdk_window_add_filter(gwin, processx, c);
1131 if (curconfig[RunInFullscreen].val.b)
1132 togglefullscreen(c, NULL);
1134 if (curconfig[ZoomLevel].val.f != 1.0)
1135 webkit_web_view_set_zoom_level(c->view,
1136 curconfig[ZoomLevel].val.f);
1138 setatom(c, AtomFind, "");
1139 setatom(c, AtomUri, "about:blank");
1143 createwindow(Client *c)
1149 w = gtk_plug_new(embed);
1151 w = gtk_window_new(GTK_WINDOW_TOPLEVEL);
1153 wmstr = g_path_get_basename(argv0);
1154 gtk_window_set_wmclass(GTK_WINDOW(w), wmstr, "Surf");
1157 wmstr = g_strdup_printf("%s[%lu]", "Surf",
1158 webkit_web_view_get_page_id(c->view));
1159 gtk_window_set_role(GTK_WINDOW(w), wmstr);
1162 gtk_window_set_default_size(GTK_WINDOW(w), 800, 600);
1165 g_signal_connect(G_OBJECT(w), "destroy",
1166 G_CALLBACK(destroywin), c);
1167 g_signal_connect(G_OBJECT(w), "enter-notify-event",
1168 G_CALLBACK(winevent), c);
1169 g_signal_connect(G_OBJECT(w), "key-press-event",
1170 G_CALLBACK(winevent), c);
1171 g_signal_connect(G_OBJECT(w), "leave-notify-event",
1172 G_CALLBACK(winevent), c);
1173 g_signal_connect(G_OBJECT(w), "window-state-event",
1174 G_CALLBACK(winevent), c);
1180 loadchanged(WebKitWebView *v, WebKitLoadEvent e, Client *c)
1182 const char *title = geturi(c);
1185 case WEBKIT_LOAD_STARTED:
1186 curconfig = defconfig;
1187 setatom(c, AtomUri, title);
1189 c->tlsflags = G_TLS_CERTIFICATE_VALIDATE_ALL + 1;
1190 seturiparameters(c, geturi(c));
1192 case WEBKIT_LOAD_REDIRECTED:
1193 setatom(c, AtomUri, title);
1195 seturiparameters(c, geturi(c));
1197 case WEBKIT_LOAD_COMMITTED:
1198 if (!webkit_web_view_get_tls_info(c->view, NULL,
1200 c->tlsflags = G_TLS_CERTIFICATE_VALIDATE_ALL + 1;
1203 case WEBKIT_LOAD_FINISHED:
1204 /* Disabled until we write some WebKitWebExtension for
1205 * manipulating the DOM directly.
1206 evalscript(c, "document.documentElement.style.overflow = '%s'",
1207 enablescrollbars ? "auto" : "hidden");
1216 progresschanged(WebKitWebView *v, GParamSpec *ps, Client *c)
1218 c->progress = webkit_web_view_get_estimated_load_progress(c->view) *
1224 titlechanged(WebKitWebView *view, GParamSpec *ps, Client *c)
1226 c->title = webkit_web_view_get_title(c->view);
1231 mousetargetchanged(WebKitWebView *v, WebKitHitTestResult *h, guint modifiers,
1234 WebKitHitTestResultContext hc = webkit_hit_test_result_get_context(h);
1236 /* Keep the hit test to know where is the pointer on the next click */
1240 c->targeturi = webkit_hit_test_result_get_link_uri(h);
1241 else if (hc & OnImg)
1242 c->targeturi = webkit_hit_test_result_get_image_uri(h);
1243 else if (hc & OnMedia)
1244 c->targeturi = webkit_hit_test_result_get_media_uri(h);
1246 c->targeturi = NULL;
1248 c->overtitle = c->targeturi;
1253 permissionrequested(WebKitWebView *v, WebKitPermissionRequest *r, Client *c)
1255 if (WEBKIT_IS_GEOLOCATION_PERMISSION_REQUEST(r)) {
1256 if (curconfig[Geolocation].val.b)
1257 webkit_permission_request_allow(r);
1259 webkit_permission_request_deny(r);
1267 decidepolicy(WebKitWebView *v, WebKitPolicyDecision *d,
1268 WebKitPolicyDecisionType dt, Client *c)
1271 case WEBKIT_POLICY_DECISION_TYPE_NAVIGATION_ACTION:
1272 decidenavigation(d, c);
1274 case WEBKIT_POLICY_DECISION_TYPE_NEW_WINDOW_ACTION:
1275 decidenewwindow(d, c);
1277 case WEBKIT_POLICY_DECISION_TYPE_RESPONSE:
1278 decideresource(d, c);
1281 webkit_policy_decision_ignore(d);
1288 decidenavigation(WebKitPolicyDecision *d, Client *c)
1290 WebKitNavigationAction *a =
1291 webkit_navigation_policy_decision_get_navigation_action(
1292 WEBKIT_NAVIGATION_POLICY_DECISION(d));
1294 switch (webkit_navigation_action_get_navigation_type(a)) {
1295 case WEBKIT_NAVIGATION_TYPE_LINK_CLICKED: /* fallthrough */
1296 case WEBKIT_NAVIGATION_TYPE_FORM_SUBMITTED: /* fallthrough */
1297 case WEBKIT_NAVIGATION_TYPE_BACK_FORWARD: /* fallthrough */
1298 case WEBKIT_NAVIGATION_TYPE_RELOAD: /* fallthrough */
1299 case WEBKIT_NAVIGATION_TYPE_FORM_RESUBMITTED: /* fallthrough */
1300 case WEBKIT_NAVIGATION_TYPE_OTHER: /* fallthrough */
1302 /* Do not navigate to links with a "_blank" target (popup) */
1303 if (webkit_navigation_policy_decision_get_frame_name(
1304 WEBKIT_NAVIGATION_POLICY_DECISION(d))) {
1305 webkit_policy_decision_ignore(d);
1307 /* Filter out navigation to different domain ? */
1308 /* get action→urirequest, copy and load in new window+view
1309 * on Ctrl+Click ? */
1310 webkit_policy_decision_use(d);
1317 decidenewwindow(WebKitPolicyDecision *d, Client *c)
1320 WebKitNavigationAction *a =
1321 webkit_navigation_policy_decision_get_navigation_action(
1322 WEBKIT_NAVIGATION_POLICY_DECISION(d));
1325 switch (webkit_navigation_action_get_navigation_type(a)) {
1326 case WEBKIT_NAVIGATION_TYPE_LINK_CLICKED: /* fallthrough */
1327 case WEBKIT_NAVIGATION_TYPE_FORM_SUBMITTED: /* fallthrough */
1328 case WEBKIT_NAVIGATION_TYPE_BACK_FORWARD: /* fallthrough */
1329 case WEBKIT_NAVIGATION_TYPE_RELOAD: /* fallthrough */
1330 case WEBKIT_NAVIGATION_TYPE_FORM_RESUBMITTED:
1331 /* Filter domains here */
1332 /* If the value of “mouse-button” is not 0, then the navigation was triggered by a mouse event.
1333 * test for link clicked but no button ? */
1334 arg.v = webkit_uri_request_get_uri(
1335 webkit_navigation_action_get_request(a));
1336 newwindow(c, &arg, 0);
1338 case WEBKIT_NAVIGATION_TYPE_OTHER: /* fallthrough */
1343 webkit_policy_decision_ignore(d);
1347 decideresource(WebKitPolicyDecision *d, Client *c)
1350 WebKitResponsePolicyDecision *r = WEBKIT_RESPONSE_POLICY_DECISION(d);
1351 WebKitURIResponse *res =
1352 webkit_response_policy_decision_get_response(r);
1353 const gchar *uri = webkit_uri_response_get_uri(res);
1355 if (g_str_has_suffix(uri, "/favicon.ico")) {
1356 webkit_policy_decision_ignore(d);
1360 if (!g_str_has_prefix(uri, "http://")
1361 && !g_str_has_prefix(uri, "https://")
1362 && !g_str_has_prefix(uri, "about:")
1363 && !g_str_has_prefix(uri, "file://")
1364 && !g_str_has_prefix(uri, "data:")
1365 && !g_str_has_prefix(uri, "blob:")
1366 && strlen(uri) > 0) {
1367 for (i = 0; i < strlen(uri); i++) {
1368 if (!g_ascii_isprint(uri[i])) {
1374 handleplumb(c, uri);
1375 webkit_policy_decision_ignore(d);
1380 if (webkit_response_policy_decision_is_mime_type_supported(r)) {
1381 webkit_policy_decision_use(d);
1383 webkit_policy_decision_ignore(d);
1389 downloadstarted(WebKitWebContext *wc, WebKitDownload *d, Client *c)
1391 g_signal_connect(G_OBJECT(d), "notify::response",
1392 G_CALLBACK(responsereceived), c);
1396 responsereceived(WebKitDownload *d, GParamSpec *ps, Client *c)
1398 download(c, webkit_download_get_response(d));
1399 webkit_download_cancel(d);
1403 download(Client *c, WebKitURIResponse *r)
1405 Arg a = (Arg)DOWNLOAD(webkit_uri_response_get_uri(r), geturi(c));
1410 closeview(WebKitWebView *v, Client *c)
1412 gtk_widget_destroy(c->win);
1416 destroywin(GtkWidget* w, Client *c)
1424 pasteuri(GtkClipboard *clipboard, const char *text, gpointer d)
1426 Arg a = {.v = text };
1428 loaduri((Client *) d, &a);
1432 reload(Client *c, const Arg *a)
1435 webkit_web_view_reload_bypass_cache(c->view);
1437 webkit_web_view_reload(c->view);
1441 print(Client *c, const Arg *a)
1443 webkit_print_operation_run_dialog(webkit_print_operation_new(c->view),
1444 GTK_WINDOW(c->win));
1448 clipboard(Client *c, const Arg *a)
1450 if (a->b) { /* load clipboard uri */
1451 gtk_clipboard_request_text(gtk_clipboard_get(
1452 GDK_SELECTION_PRIMARY),
1454 } else { /* copy uri */
1455 gtk_clipboard_set_text(gtk_clipboard_get(
1456 GDK_SELECTION_PRIMARY), c->targeturi
1457 ? c->targeturi : geturi(c), -1);
1462 zoom(Client *c, const Arg *a)
1465 webkit_web_view_set_zoom_level(c->view,
1466 curconfig[ZoomLevel].val.f + 0.1);
1468 webkit_web_view_set_zoom_level(c->view,
1469 curconfig[ZoomLevel].val.f - 0.1);
1471 webkit_web_view_set_zoom_level(c->view, 1.0);
1473 curconfig[ZoomLevel].val.f = webkit_web_view_get_zoom_level(c->view);
1477 scroll(Client *c, const Arg *a)
1479 GdkEvent *ev = gdk_event_new(GDK_KEY_PRESS);
1481 gdk_event_set_device(ev, gdkkb);
1482 ev->key.window = gtk_widget_get_window(GTK_WIDGET(c->win));
1483 ev->key.state = GDK_CONTROL_MASK;
1484 ev->key.time = GDK_CURRENT_TIME;
1488 ev->key.keyval = GDK_KEY_Down;
1491 ev->key.keyval = GDK_KEY_Page_Down;
1494 ev->key.keyval = GDK_KEY_Left;
1497 ev->key.keyval = GDK_KEY_Right;
1500 ev->key.keyval = GDK_KEY_Page_Up;
1503 ev->key.keyval = GDK_KEY_Up;
1511 navigate(Client *c, const Arg *a)
1514 webkit_web_view_go_back(c->view);
1516 webkit_web_view_go_forward(c->view);
1520 stop(Client *c, const Arg *a)
1522 webkit_web_view_stop_loading(c->view);
1526 toggle(Client *c, const Arg *a)
1528 curconfig[a->i].val.b ^= 1;
1529 setparameter(c, 1, (ParamName)a->i, &curconfig[a->i].val);
1533 togglefullscreen(Client *c, const Arg *a)
1535 /* toggling value is handled in winevent() */
1537 gtk_window_unfullscreen(GTK_WINDOW(c->win));
1539 gtk_window_fullscreen(GTK_WINDOW(c->win));
1543 togglecookiepolicy(Client *c, const Arg *a)
1546 cookiepolicy %= strlen(curconfig[CookiePolicies].val.v);
1548 setparameter(c, 0, CookiePolicies, NULL);
1552 toggleinspector(Client *c, const Arg *a)
1554 if (webkit_web_inspector_is_attached(c->inspector))
1555 webkit_web_inspector_close(c->inspector);
1556 else if (curconfig[Inspector].val.b)
1557 webkit_web_inspector_show(c->inspector);
1561 find(Client *c, const Arg *a)
1567 webkit_find_controller_search_next(c->finder);
1569 webkit_find_controller_search_previous(c->finder);
1571 s = getatom(c, AtomFind);
1572 f = webkit_find_controller_get_search_text(c->finder);
1574 if (g_strcmp0(f, s) == 0) /* reset search */
1575 webkit_find_controller_search(c->finder, "", findopts,
1578 webkit_find_controller_search(c->finder, s, findopts,
1581 if (strcmp(s, "") == 0)
1582 webkit_find_controller_search_finish(c->finder);
1587 clicknavigate(Client *c, const Arg *a, WebKitHitTestResult *h)
1593 clicknewwindow(Client *c, const Arg *a, WebKitHitTestResult *h)
1597 arg.v = webkit_hit_test_result_get_link_uri(h);
1598 newwindow(c, &arg, a->b);
1602 clickexternplayer(Client *c, const Arg *a, WebKitHitTestResult *h)
1606 arg = (Arg)VIDEOPLAY(webkit_hit_test_result_get_media_uri(h));
1611 main(int argc, char *argv[])
1616 memset(&arg, 0, sizeof(arg));
1618 /* command line args */
1621 defconfig CSETV(CookiePolicies, EARGF(usage()));
1624 defconfig CSETB(ScrollBars, 0);
1627 defconfig CSETB(ScrollBars, 1);
1630 cookiefile = EARGF(usage());
1633 defconfig CSETB(DiskCache, 0);
1636 defconfig CSETB(DiskCache, 1);
1639 embed = strtol(EARGF(usage()), NULL, 0);
1642 defconfig CSETB(RunInFullscreen, 0);
1645 defconfig CSETB(RunInFullscreen, 1);
1648 defconfig CSETB(Geolocation, 0);
1651 defconfig CSETB(Geolocation, 1);
1654 defconfig CSETB(LoadImages, 0);
1657 defconfig CSETB(LoadImages, 1);
1660 defconfig CSETB(KioskMode, 0);
1663 defconfig CSETB(KioskMode, 1);
1666 defconfig CSETB(Style, 0);
1669 defconfig CSETB(Style, 1);
1672 defconfig CSETB(Inspector, 0);
1675 defconfig CSETB(Inspector, 1);
1678 defconfig CSETB(Plugins, 0);
1681 defconfig CSETB(Plugins, 1);
1684 scriptfile = EARGF(usage());
1687 defconfig CSETB(JavaScript, 0);
1690 defconfig CSETB(JavaScript, 1);
1693 stylefile = EARGF(usage());
1696 fulluseragent = EARGF(usage());
1699 die("surf-"VERSION", ©2009-2015 surf engineers, "
1700 "see LICENSE for details\n");
1705 defconfig CSETF(ZoomLevel, strtof(EARGF(usage()), NULL));
1713 arg.v = "about:blank";
1716 c = newclient(NULL);