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 Client *newclient(Client *c);
148 static void loaduri(Client *c, const Arg *a);
149 static const char *geturi(Client *c);
150 static void setatom(Client *c, int a, const char *v);
151 static const char *getatom(Client *c, int a);
152 static void updatetitle(Client *c);
153 static void gettogglestats(Client *c);
154 static void getpagestats(Client *c);
155 static WebKitCookieAcceptPolicy cookiepolicy_get(void);
156 static char cookiepolicy_set(const WebKitCookieAcceptPolicy p);
157 static void seturiparameters(Client *c, const char *uri);
158 static void setparameter(Client *c, int refresh, ParamName p, const Arg *a);
159 static const char *getstyle(const char *uri);
160 static void setstyle(Client *c, const char *stylefile);
161 static void runscript(Client *c);
162 static void evalscript(Client *c, const char *jsstr, ...);
163 static void updatewinid(Client *c);
164 static void handleplumb(Client *c, const char *uri);
165 static void newwindow(Client *c, const Arg *a, int noembed);
166 static void spawn(Client *c, const Arg *a);
167 static void destroyclient(Client *c);
168 static void cleanup(void);
171 static GdkDevice *getkbdevice(void);
172 static WebKitWebView *newview(Client *c, WebKitWebView *rv);
173 static GtkWidget *createview(WebKitWebView *v, WebKitNavigationAction *a,
175 static gboolean buttonreleased(GtkWidget *w, GdkEvent *e, Client *c);
176 static GdkFilterReturn processx(GdkXEvent *xevent, GdkEvent *event,
178 static gboolean winevent(GtkWidget *w, GdkEvent *e, Client *c);
179 static void showview(WebKitWebView *v, Client *c);
180 static GtkWidget *createwindow(Client *c);
181 static void loadchanged(WebKitWebView *v, WebKitLoadEvent e, Client *c);
182 static void progresschanged(WebKitWebView *v, GParamSpec *ps, Client *c);
183 static void titlechanged(WebKitWebView *view, GParamSpec *ps, Client *c);
184 static void mousetargetchanged(WebKitWebView *v, WebKitHitTestResult *h,
185 guint modifiers, Client *c);
186 static gboolean permissionrequested(WebKitWebView *v,
187 WebKitPermissionRequest *r, Client *c);
188 static gboolean decidepolicy(WebKitWebView *v, WebKitPolicyDecision *d,
189 WebKitPolicyDecisionType dt, Client *c);
190 static void decidenavigation(WebKitPolicyDecision *d, Client *c);
191 static void decidenewwindow(WebKitPolicyDecision *d, Client *c);
192 static void decideresource(WebKitPolicyDecision *d, Client *c);
193 static void downloadstarted(WebKitWebContext *wc, WebKitDownload *d,
195 static void responsereceived(WebKitDownload *d, GParamSpec *ps, Client *c);
196 static void download(Client *c, WebKitURIResponse *r);
197 static void closeview(WebKitWebView *v, Client *c);
198 static void destroywin(GtkWidget* w, Client *c);
201 static void pasteuri(GtkClipboard *clipboard, const char *text, gpointer d);
202 static void reload(Client *c, const Arg *a);
203 static void print(Client *c, const Arg *a);
204 static void clipboard(Client *c, const Arg *a);
205 static void zoom(Client *c, const Arg *a);
206 static void scroll(Client *c, const Arg *a);
207 static void navigate(Client *c, const Arg *a);
208 static void stop(Client *c, const Arg *a);
209 static void toggle(Client *c, const Arg *a);
210 static void togglefullscreen(Client *c, const Arg *a);
211 static void togglecookiepolicy(Client *c, const Arg *a);
212 static void toggleinspector(Client *c, const Arg *a);
213 static void find(Client *c, const Arg *a);
216 static void clicknavigate(Client *c, const Arg *a, WebKitHitTestResult *h);
217 static void clicknewwindow(Client *c, const Arg *a, WebKitHitTestResult *h);
218 static void clickexternplayer(Client *c, const Arg *a, WebKitHitTestResult *h);
220 static char winid[64];
221 static char togglestats[10];
222 static char pagestats[2];
223 static Atom atoms[AtomLast];
226 static int cookiepolicy;
228 static Client *clients;
229 static GdkDevice *gdkkb;
230 static char *stylefile;
231 static const char *useragent;
232 static Parameter *curconfig;
235 /* configuration, allows nested code to access above variables */
241 die("usage: %s [-bBdDfFgGiIkKmMnNpPsSvx] [-a cookiepolicies ] "
242 "[-c cookiefile] [-e xid] [-r scriptfile] [-t stylefile] "
243 "[-u useragent] [-z zoomlevel] [uri]\n", basename(argv0));
247 die(const char *errstr, ...)
251 va_start(ap, errstr);
252 vfprintf(stderr, errstr, ap);
262 /* clean up any zombies immediately */
264 gtk_init(NULL, NULL);
266 dpy = GDK_DISPLAY_XDISPLAY(gdk_display_get_default());
268 curconfig = defconfig;
271 atoms[AtomFind] = XInternAtom(dpy, "_SURF_FIND", False);
272 atoms[AtomGo] = XInternAtom(dpy, "_SURF_GO", False);
273 atoms[AtomUri] = XInternAtom(dpy, "_SURF_URI", False);
276 cookiefile = buildfile(cookiefile);
277 scriptfile = buildfile(scriptfile);
278 cachedir = buildpath(cachedir);
280 gdkkb = getkbdevice();
283 styledir = buildpath(styledir);
284 for (i = 0; i < LENGTH(styles); ++i) {
285 if (regcomp(&(styles[i].re), styles[i].regex,
288 "Could not compile regex: %s\n",
290 styles[i].regex = NULL;
292 styles[i].style = g_strconcat(styledir, "/",
293 styles[i].style, NULL);
297 stylefile = buildfile(stylefile);
300 for (i = 0; i < LENGTH(uriparams); ++i) {
301 if (!regcomp(&(uriparams[i].re), uriparams[i].uri,
303 /* copy default parameters if they are not already set
304 * or if they are forced */
305 for (j = 0; j < ParameterLast; ++j) {
306 if (!uriparams[i].config[j].force ||
308 uriparams[i].config[j] = defconfig[j];
312 "Could not compile regex: %s\n",
314 uriparams[i].uri = NULL;
322 if (signal(SIGCHLD, sigchld) == SIG_ERR)
323 die("Can't install SIGCHLD handler");
324 while (waitpid(-1, NULL, WNOHANG) > 0)
329 buildfile(const char *path)
331 char *dname, *bname, *bpath, *fpath;
334 dname = g_path_get_dirname(path);
335 bname = g_path_get_basename(path);
337 bpath = buildpath(dname);
340 fpath = g_build_filename(bpath, bname, NULL);
344 if (!(f = fopen(fpath, "a")))
345 die("Could not open file: %s\n", fpath);
347 g_chmod(fpath, 0600); /* always */
354 buildpath(const char *path)
357 char *apath, *name, *p, *fpath;
359 if (path[0] == '~') {
360 if (path[1] == '/' || path[1] == '\0') {
361 p = (char *)&path[1];
362 pw = getpwuid(getuid());
364 if ((p = strchr(path, '/')))
365 name = g_strndup(&path[1], --p - path);
367 name = g_strdup(&path[1]);
369 if (!(pw = getpwnam(name))) {
370 die("Can't get user %s home directory: %s.\n",
375 apath = g_build_filename(pw->pw_dir, p, NULL);
377 apath = g_strdup(path);
380 /* creating directory */
381 if (g_mkdir_with_parents(apath, 0700) < 0)
382 die("Could not access directory: %s\n", apath);
384 fpath = realpath(apath, NULL);
391 newclient(Client *rc)
395 if (!(c = calloc(1, sizeof(Client))))
396 die("Cannot malloc!\n");
402 c->tlsflags = G_TLS_CERTIFICATE_VALIDATE_ALL + 1;
403 c->view = newview(c, rc ? rc->view : NULL);
409 loaduri(Client *c, const Arg *a)
413 const char *uri = a->v;
415 if (g_strcmp0(uri, "") == 0)
418 if (g_strrstr(uri, "://") || g_str_has_prefix(uri, "about:")) {
420 } else if (!stat(uri, &st) && (path = realpath(uri, NULL))) {
421 url = g_strdup_printf("file://%s", path);
424 url = g_strdup_printf("http://%s", uri);
427 setatom(c, AtomUri, url);
429 if (strcmp(url, geturi(c)) == 0) {
432 webkit_web_view_load_uri(c->view, url);
444 if (!(uri = webkit_web_view_get_uri(c->view)))
450 setatom(Client *c, int a, const char *v)
453 XChangeProperty(dpy, c->xid,
454 atoms[a], XA_STRING, 8, PropModeReplace,
455 (unsigned char *)v, strlen(v) + 1);
459 getatom(Client *c, int a)
461 static char buf[BUFSIZ];
464 unsigned long ldummy;
465 unsigned char *p = NULL;
467 XGetWindowProperty(dpy, c->xid, atoms[a], 0L, BUFSIZ, False, XA_STRING,
468 &adummy, &idummy, &ldummy, &ldummy, &p);
470 strncpy(buf, (char *)p, LENGTH(buf) - 1);
479 updatetitle(Client *c)
482 const char *name = c->overtitle ? c->overtitle :
483 c->title ? c->title : "";
485 if (curconfig[ShowIndicators].val.b) {
489 if (c->progress != 100)
490 title = g_strdup_printf("[%i%%] %s:%s | %s",
491 c->progress, togglestats, pagestats, name);
493 title = g_strdup_printf("%s:%s | %s",
494 togglestats, pagestats, name);
496 gtk_window_set_title(GTK_WINDOW(c->win), title);
499 gtk_window_set_title(GTK_WINDOW(c->win), name);
504 gettogglestats(Client *c)
506 togglestats[0] = cookiepolicy_set(cookiepolicy_get());
507 togglestats[1] = curconfig[CaretBrowsing].val.b ? 'C' : 'c';
508 togglestats[2] = curconfig[Geolocation].val.b ? 'G' : 'g';
509 togglestats[3] = curconfig[DiskCache].val.b ? 'D' : 'd';
510 togglestats[4] = curconfig[LoadImages].val.b ? 'I' : 'i';
511 togglestats[5] = curconfig[JavaScript].val.b ? 'S' : 's';
512 togglestats[6] = curconfig[Plugins].val.b ? 'V' : 'v';
513 togglestats[7] = curconfig[Style].val.b ? 'M' : 'm';
514 togglestats[8] = curconfig[FrameFlattening].val.b ? 'F' : 'f';
515 togglestats[9] = '\0';
519 getpagestats(Client *c)
521 pagestats[0] = c->tlsflags > G_TLS_CERTIFICATE_VALIDATE_ALL ? '-' :
522 c->tlsflags > 0 ? 'U' : 'T';
526 WebKitCookieAcceptPolicy
527 cookiepolicy_get(void)
529 switch (((char *)curconfig[CookiePolicies].val.v)[cookiepolicy]) {
531 return WEBKIT_COOKIE_POLICY_ACCEPT_NEVER;
533 return WEBKIT_COOKIE_POLICY_ACCEPT_NO_THIRD_PARTY;
534 default: /* fallthrough */
536 return WEBKIT_COOKIE_POLICY_ACCEPT_ALWAYS;
541 cookiepolicy_set(const WebKitCookieAcceptPolicy p)
544 case WEBKIT_COOKIE_POLICY_ACCEPT_NEVER:
546 case WEBKIT_COOKIE_POLICY_ACCEPT_NO_THIRD_PARTY:
548 default: /* fallthrough */
549 case WEBKIT_COOKIE_POLICY_ACCEPT_ALWAYS:
555 seturiparameters(Client *c, const char *uri)
559 for (i = 0; i < LENGTH(uriparams); ++i) {
560 if (uriparams[i].uri &&
561 !regexec(&(uriparams[i].re), uri, 0, NULL, 0)) {
562 curconfig = uriparams[i].config;
567 for (i = 0; i < ParameterLast; ++i)
568 setparameter(c, 0, i, &curconfig[i].val);
572 setparameter(Client *c, int refresh, ParamName p, const Arg *a)
574 GdkRGBA bgcolor = { 0 };
575 WebKitSettings *s = webkit_web_view_get_settings(c->view);
579 webkit_settings_set_enable_caret_browsing(s, a->b);
583 webkit_cookie_manager_set_accept_policy(
584 webkit_web_context_get_cookie_manager(
585 webkit_web_view_get_context(c->view)),
590 webkit_web_context_set_cache_model(
591 webkit_web_view_get_context(c->view), a->b ?
592 WEBKIT_CACHE_MODEL_WEB_BROWSER :
593 WEBKIT_CACHE_MODEL_DOCUMENT_VIEWER);
594 return; /* do not update */
596 webkit_settings_set_enable_dns_prefetching(s, a->b);
597 return; /* do not update */
599 webkit_settings_set_default_font_size(s, a->i);
600 return; /* do not update */
601 case FrameFlattening:
602 webkit_settings_set_enable_frame_flattening(s, a->b);
609 webkit_web_view_set_background_color(c->view, &bgcolor);
610 return; /* do not update */
612 webkit_settings_set_enable_developer_extras(s, a->b);
613 return; /* do not update */
615 webkit_settings_set_enable_javascript(s, a->b);
618 return; /* do nothing */
620 webkit_settings_set_auto_load_images(s, a->b);
623 webkit_settings_set_enable_plugins(s, a->b);
625 case PreferredLanguages:
626 return; /* do nothing */
627 case RunInFullscreen:
628 return; /* do nothing */
630 /* Disabled until we write some WebKitWebExtension for
631 * manipulating the DOM directly.
632 enablescrollbars = !enablescrollbars;
633 evalscript(c, "document.documentElement.style.overflow = '%s'",
634 enablescrollbars ? "auto" : "hidden");
636 return; /* do not update */
640 webkit_web_context_set_spell_checking_enabled(
641 webkit_web_view_get_context(c->view), a->b);
642 return; /* do not update */
644 return; /* do nothing */
646 webkit_web_context_set_tls_errors_policy(
647 webkit_web_view_get_context(c->view), a->b ?
648 WEBKIT_TLS_ERRORS_POLICY_FAIL :
649 WEBKIT_TLS_ERRORS_POLICY_IGNORE);
650 return; /* do not update */
653 setstyle(c, getstyle(geturi(c)));
655 webkit_user_content_manager_remove_all_style_sheets(
656 webkit_web_view_get_user_content_manager(c->view));
660 webkit_web_view_set_zoom_level(c->view, a->f);
661 return; /* do not update */
663 return; /* do nothing */
672 getstyle(const char *uri)
679 for (i = 0; i < LENGTH(styles); ++i) {
680 if (styles[i].regex &&
681 !regexec(&(styles[i].re), uri, 0, NULL, 0))
682 return styles[i].style;
689 setstyle(Client *c, const char *stylefile)
693 if (!g_file_get_contents(stylefile, &style, NULL, NULL)) {
694 fprintf(stderr, "Could not read style file: %s\n", stylefile);
698 webkit_user_content_manager_add_style_sheet(
699 webkit_web_view_get_user_content_manager(c->view),
700 webkit_user_style_sheet_new(style,
701 WEBKIT_USER_CONTENT_INJECT_ALL_FRAMES,
702 WEBKIT_USER_STYLE_LEVEL_USER,
714 if (g_file_get_contents(scriptfile, &script, &l, NULL) && l)
715 evalscript(c, script);
720 evalscript(Client *c, const char *jsstr, ...)
726 script = g_strdup_vprintf(jsstr, ap);
729 webkit_web_view_run_javascript(c->view, script, NULL, NULL, NULL);
734 updatewinid(Client *c)
736 snprintf(winid, LENGTH(winid), "%lu", c->xid);
740 handleplumb(Client *c, const char *uri)
742 Arg a = (Arg)PLUMB(uri);
747 newwindow(Client *c, const Arg *a, int noembed)
751 const char *cmd[26], *uri;
752 const Arg arg = { .v = cmd };
756 cmd[i++] = curconfig[CookiePolicies].val.v;
757 cmd[i++] = curconfig[ScrollBars].val.b ? "-B" : "-b";
758 if (cookiefile && g_strcmp0(cookiefile, "")) {
760 cmd[i++] = cookiefile;
762 cmd[i++] = curconfig[DiskCache].val.b ? "-D" : "-d";
763 if (embed && !noembed) {
765 snprintf(tmp, LENGTH(tmp), "%lu", embed);
768 cmd[i++] = curconfig[RunInFullscreen].val.b ? "-F" : "-f" ;
769 cmd[i++] = curconfig[Geolocation].val.b ? "-G" : "-g" ;
770 cmd[i++] = curconfig[LoadImages].val.b ? "-I" : "-i" ;
771 cmd[i++] = curconfig[KioskMode].val.b ? "-K" : "-k" ;
772 cmd[i++] = curconfig[Style].val.b ? "-M" : "-m" ;
773 cmd[i++] = curconfig[Inspector].val.b ? "-N" : "-n" ;
774 cmd[i++] = curconfig[Plugins].val.b ? "-P" : "-p" ;
775 if (scriptfile && g_strcmp0(scriptfile, "")) {
777 cmd[i++] = scriptfile;
779 cmd[i++] = curconfig[JavaScript].val.b ? "-S" : "-s";
780 if (stylefile && g_strcmp0(stylefile, "")) {
782 cmd[i++] = stylefile;
784 if (fulluseragent && g_strcmp0(fulluseragent, "")) {
786 cmd[i++] = fulluseragent;
790 /* do not keep zoom level */
800 spawn(Client *c, const Arg *a)
804 close(ConnectionNumber(dpy));
806 execvp(((char **)a->v)[0], (char **)a->v);
807 fprintf(stderr, "%s: execvp %s", argv0, ((char **)a->v)[0]);
814 destroyclient(Client *c)
818 webkit_web_view_stop_loading(c->view);
819 /* Not needed, has already been called
820 gtk_widget_destroy(c->win);
823 for (p = clients; p && p->next != c; p = p->next)
836 destroyclient(clients);
846 GList *l, *gdl = gdk_device_manager_list_devices(
847 gdk_display_get_device_manager(gdk_display_get_default()),
848 GDK_DEVICE_TYPE_MASTER);
849 GdkDevice *gd = NULL;
851 for (l = gdl; l != NULL; l = l->next)
852 if (gdk_device_get_source(l->data) == GDK_SOURCE_KEYBOARD)
860 newview(Client *c, WebKitWebView *rv)
863 WebKitSettings *settings;
864 WebKitUserContentManager *contentmanager;
865 WebKitWebContext *context;
870 webkit_web_view_new_with_related_view(rv));
872 settings = webkit_settings_new_with_settings(
873 "auto-load-images", curconfig[LoadImages].val.b,
874 "default-font-size", curconfig[FontSize].val.f,
875 "enable-caret-browsing", curconfig[CaretBrowsing].val.b,
876 "enable-developer-extras", curconfig[Inspector].val.b,
877 "enable-dns-prefetching", curconfig[DNSPrefetch].val.b,
878 "enable-frame-flattening", curconfig[FrameFlattening].val.b,
879 "enable-html5-database", curconfig[DiskCache].val.b,
880 "enable-html5-local-storage", curconfig[DiskCache].val.b,
881 "enable-javascript", curconfig[JavaScript].val.b,
882 "enable-plugins", curconfig[Plugins].val.b,
884 /* For mor interesting settings, have a look at
885 * http://webkitgtk.org/reference/webkit2gtk/stable/WebKitSettings.html */
887 if (strcmp(fulluseragent, "")) {
888 webkit_settings_set_user_agent(settings, fulluseragent);
889 } else if (surfuseragent) {
890 webkit_settings_set_user_agent_with_application_details(
891 settings, "Surf", VERSION);
893 useragent = webkit_settings_get_user_agent(settings);
895 contentmanager = webkit_user_content_manager_new();
897 context = webkit_web_context_new_with_website_data_manager(
898 webkit_website_data_manager_new(
899 "base-cache-directory", cachedir,
900 "base-data-directory", cachedir,
903 /* rendering process model, can be a shared unique one
904 * or one for each view */
905 webkit_web_context_set_process_model(context,
906 WEBKIT_PROCESS_MODEL_MULTIPLE_SECONDARY_PROCESSES);
908 webkit_web_context_set_tls_errors_policy(context,
909 curconfig[StrictSSL].val.b ? WEBKIT_TLS_ERRORS_POLICY_FAIL :
910 WEBKIT_TLS_ERRORS_POLICY_IGNORE);
912 webkit_web_context_set_cache_model(context,
913 curconfig[DiskCache].val.b ? WEBKIT_CACHE_MODEL_WEB_BROWSER :
914 WEBKIT_CACHE_MODEL_DOCUMENT_VIEWER);
916 /* Currently only works with text file to be compatible with curl */
917 webkit_cookie_manager_set_persistent_storage(
918 webkit_web_context_get_cookie_manager(context), cookiefile,
919 WEBKIT_COOKIE_PERSISTENT_STORAGE_TEXT);
921 webkit_cookie_manager_set_accept_policy(
922 webkit_web_context_get_cookie_manager(context),
925 webkit_web_context_set_preferred_languages(context,
926 curconfig[PreferredLanguages].val.v);
927 webkit_web_context_set_spell_checking_languages(context,
928 curconfig[SpellLanguages].val.v);
929 webkit_web_context_set_spell_checking_enabled(context,
930 curconfig[SpellChecking].val.b);
932 g_signal_connect(G_OBJECT(context), "download-started",
933 G_CALLBACK(downloadstarted), c);
935 v = g_object_new(WEBKIT_TYPE_WEB_VIEW,
936 "settings", settings,
937 "user-content-manager", contentmanager,
938 "web-context", context,
942 g_signal_connect(G_OBJECT(v), "notify::estimated-load-progress",
943 G_CALLBACK(progresschanged), c);
944 g_signal_connect(G_OBJECT(v), "notify::title",
945 G_CALLBACK(titlechanged), c);
946 g_signal_connect(G_OBJECT(v), "button-release-event",
947 G_CALLBACK(buttonreleased), c);
948 g_signal_connect(G_OBJECT(v), "close",
949 G_CALLBACK(closeview), c);
950 g_signal_connect(G_OBJECT(v), "create",
951 G_CALLBACK(createview), c);
952 g_signal_connect(G_OBJECT(v), "decide-policy",
953 G_CALLBACK(decidepolicy), c);
954 g_signal_connect(G_OBJECT(v), "load-changed",
955 G_CALLBACK(loadchanged), c);
956 g_signal_connect(G_OBJECT(v), "mouse-target-changed",
957 G_CALLBACK(mousetargetchanged), c);
958 g_signal_connect(G_OBJECT(v), "permission-request",
959 G_CALLBACK(permissionrequested), c);
960 g_signal_connect(G_OBJECT(v), "ready-to-show",
961 G_CALLBACK(showview), c);
967 createview(WebKitWebView *v, WebKitNavigationAction *a, Client *c)
971 switch (webkit_navigation_action_get_navigation_type(a)) {
972 case WEBKIT_NAVIGATION_TYPE_OTHER: /* fallthrough */
974 * popup windows of type “other” are almost always triggered
975 * by user gesture, so inverse the logic here
977 /* instead of this, compare destination uri to mouse-over uri for validating window */
978 if (webkit_navigation_action_is_user_gesture(a))
980 case WEBKIT_NAVIGATION_TYPE_LINK_CLICKED: /* fallthrough */
981 case WEBKIT_NAVIGATION_TYPE_FORM_SUBMITTED: /* fallthrough */
982 case WEBKIT_NAVIGATION_TYPE_BACK_FORWARD: /* fallthrough */
983 case WEBKIT_NAVIGATION_TYPE_RELOAD: /* fallthrough */
984 case WEBKIT_NAVIGATION_TYPE_FORM_RESUBMITTED:
991 return GTK_WIDGET(n->view);
995 buttonreleased(GtkWidget *w, GdkEvent *e, Client *c)
997 WebKitHitTestResultContext element;
1000 element = webkit_hit_test_result_get_context(c->mousepos);
1002 for (i = 0; i < LENGTH(buttons); ++i) {
1003 if (element & buttons[i].target &&
1004 e->button.button == buttons[i].button &&
1005 CLEANMASK(e->button.state) == CLEANMASK(buttons[i].mask) &&
1007 buttons[i].func(c, &buttons[i].arg, c->mousepos);
1008 return buttons[i].stopevent;
1016 processx(GdkXEvent *e, GdkEvent *event, gpointer d)
1018 Client *c = (Client *)d;
1022 if (((XEvent *)e)->type == PropertyNotify) {
1023 ev = &((XEvent *)e)->xproperty;
1024 if (ev->state == PropertyNewValue) {
1025 if (ev->atom == atoms[AtomFind]) {
1028 return GDK_FILTER_REMOVE;
1029 } else if (ev->atom == atoms[AtomGo]) {
1030 a.v = getatom(c, AtomGo);
1033 return GDK_FILTER_REMOVE;
1037 return GDK_FILTER_CONTINUE;
1041 winevent(GtkWidget *w, GdkEvent *e, Client *c)
1046 case GDK_ENTER_NOTIFY:
1047 c->overtitle = c->targeturi;
1051 if (!curconfig[KioskMode].val.b) {
1052 for (i = 0; i < LENGTH(keys); ++i) {
1053 if (gdk_keyval_to_lower(e->key.keyval) ==
1055 CLEANMASK(e->key.state) == keys[i].mod &&
1058 keys[i].func(c, &(keys[i].arg));
1063 case GDK_LEAVE_NOTIFY:
1064 c->overtitle = NULL;
1067 case GDK_WINDOW_STATE:
1068 if (e->window_state.changed_mask ==
1069 GDK_WINDOW_STATE_FULLSCREEN)
1070 c->fullscreen = e->window_state.new_window_state &
1071 GDK_WINDOW_STATE_FULLSCREEN;
1081 showview(WebKitWebView *v, Client *c)
1083 GdkRGBA bgcolor = { 0 };
1086 c->finder = webkit_web_view_get_find_controller(c->view);
1087 if (curconfig[Inspector].val.b)
1088 c->inspector = webkit_web_view_get_inspector(c->view);
1090 c->win = createwindow(c);
1092 gtk_container_add(GTK_CONTAINER(c->win), GTK_WIDGET(c->view));
1093 gtk_widget_show_all(c->win);
1094 gtk_widget_grab_focus(GTK_WIDGET(c->view));
1096 gwin = gtk_widget_get_window(GTK_WIDGET(c->win));
1097 c->xid = gdk_x11_window_get_xid(gwin);
1100 gdk_display_sync(gtk_widget_get_display(c->win));
1104 if (curconfig[HideBackground].val.b)
1105 webkit_web_view_set_background_color(c->view, &bgcolor);
1107 if (!curconfig[KioskMode].val.b) {
1108 gdk_window_set_events(gwin, GDK_ALL_EVENTS_MASK);
1109 gdk_window_add_filter(gwin, processx, c);
1112 if (curconfig[RunInFullscreen].val.b)
1113 togglefullscreen(c, NULL);
1115 if (curconfig[ZoomLevel].val.f != 1.0)
1116 webkit_web_view_set_zoom_level(c->view,
1117 curconfig[ZoomLevel].val.f);
1119 setatom(c, AtomFind, "");
1120 setatom(c, AtomUri, "about:blank");
1124 createwindow(Client *c)
1130 w = gtk_plug_new(embed);
1132 w = gtk_window_new(GTK_WINDOW_TOPLEVEL);
1134 wmstr = g_path_get_basename(argv0);
1135 gtk_window_set_wmclass(GTK_WINDOW(w), wmstr, "Surf");
1138 wmstr = g_strdup_printf("%s[%lu]", "Surf",
1139 webkit_web_view_get_page_id(c->view));
1140 gtk_window_set_role(GTK_WINDOW(w), wmstr);
1143 gtk_window_set_default_size(GTK_WINDOW(w), 800, 600);
1146 g_signal_connect(G_OBJECT(w), "destroy",
1147 G_CALLBACK(destroywin), c);
1148 g_signal_connect(G_OBJECT(w), "enter-notify-event",
1149 G_CALLBACK(winevent), c);
1150 g_signal_connect(G_OBJECT(w), "key-press-event",
1151 G_CALLBACK(winevent), c);
1152 g_signal_connect(G_OBJECT(w), "leave-notify-event",
1153 G_CALLBACK(winevent), c);
1154 g_signal_connect(G_OBJECT(w), "window-state-event",
1155 G_CALLBACK(winevent), c);
1161 loadchanged(WebKitWebView *v, WebKitLoadEvent e, Client *c)
1163 const char *title = geturi(c);
1166 case WEBKIT_LOAD_STARTED:
1167 curconfig = defconfig;
1168 setatom(c, AtomUri, title);
1170 c->tlsflags = G_TLS_CERTIFICATE_VALIDATE_ALL + 1;
1172 case WEBKIT_LOAD_REDIRECTED:
1173 setatom(c, AtomUri, title);
1176 case WEBKIT_LOAD_COMMITTED:
1177 setatom(c, AtomUri, title);
1179 if (!webkit_web_view_get_tls_info(c->view, NULL,
1181 c->tlsflags = G_TLS_CERTIFICATE_VALIDATE_ALL + 1;
1183 setatom(c, AtomUri, geturi(c));
1184 seturiparameters(c, geturi(c));
1186 case WEBKIT_LOAD_FINISHED:
1187 /* Disabled until we write some WebKitWebExtension for
1188 * manipulating the DOM directly.
1189 evalscript(c, "document.documentElement.style.overflow = '%s'",
1190 enablescrollbars ? "auto" : "hidden");
1199 progresschanged(WebKitWebView *v, GParamSpec *ps, Client *c)
1201 c->progress = webkit_web_view_get_estimated_load_progress(c->view) *
1207 titlechanged(WebKitWebView *view, GParamSpec *ps, Client *c)
1209 c->title = webkit_web_view_get_title(c->view);
1214 mousetargetchanged(WebKitWebView *v, WebKitHitTestResult *h, guint modifiers,
1217 WebKitHitTestResultContext hc = webkit_hit_test_result_get_context(h);
1219 /* Keep the hit test to know where is the pointer on the next click */
1223 c->targeturi = webkit_hit_test_result_get_link_uri(h);
1224 else if (hc & OnImg)
1225 c->targeturi = webkit_hit_test_result_get_image_uri(h);
1226 else if (hc & OnMedia)
1227 c->targeturi = webkit_hit_test_result_get_media_uri(h);
1229 c->targeturi = NULL;
1231 c->overtitle = c->targeturi;
1236 permissionrequested(WebKitWebView *v, WebKitPermissionRequest *r, Client *c)
1238 if (WEBKIT_IS_GEOLOCATION_PERMISSION_REQUEST(r)) {
1239 if (curconfig[Geolocation].val.b)
1240 webkit_permission_request_allow(r);
1242 webkit_permission_request_deny(r);
1250 decidepolicy(WebKitWebView *v, WebKitPolicyDecision *d,
1251 WebKitPolicyDecisionType dt, Client *c)
1254 case WEBKIT_POLICY_DECISION_TYPE_NAVIGATION_ACTION:
1255 decidenavigation(d, c);
1257 case WEBKIT_POLICY_DECISION_TYPE_NEW_WINDOW_ACTION:
1258 decidenewwindow(d, c);
1260 case WEBKIT_POLICY_DECISION_TYPE_RESPONSE:
1261 decideresource(d, c);
1264 webkit_policy_decision_ignore(d);
1271 decidenavigation(WebKitPolicyDecision *d, Client *c)
1273 WebKitNavigationAction *a =
1274 webkit_navigation_policy_decision_get_navigation_action(
1275 WEBKIT_NAVIGATION_POLICY_DECISION(d));
1277 switch (webkit_navigation_action_get_navigation_type(a)) {
1278 case WEBKIT_NAVIGATION_TYPE_LINK_CLICKED: /* fallthrough */
1279 case WEBKIT_NAVIGATION_TYPE_FORM_SUBMITTED: /* fallthrough */
1280 case WEBKIT_NAVIGATION_TYPE_BACK_FORWARD: /* fallthrough */
1281 case WEBKIT_NAVIGATION_TYPE_RELOAD: /* fallthrough */
1282 case WEBKIT_NAVIGATION_TYPE_FORM_RESUBMITTED: /* fallthrough */
1283 case WEBKIT_NAVIGATION_TYPE_OTHER: /* fallthrough */
1285 /* Do not navigate to links with a "_blank" target (popup) */
1286 if (webkit_navigation_policy_decision_get_frame_name(
1287 WEBKIT_NAVIGATION_POLICY_DECISION(d))) {
1288 webkit_policy_decision_ignore(d);
1290 /* Filter out navigation to different domain ? */
1291 /* get action→urirequest, copy and load in new window+view
1292 * on Ctrl+Click ? */
1293 webkit_policy_decision_use(d);
1300 decidenewwindow(WebKitPolicyDecision *d, Client *c)
1303 WebKitNavigationAction *a =
1304 webkit_navigation_policy_decision_get_navigation_action(
1305 WEBKIT_NAVIGATION_POLICY_DECISION(d));
1308 switch (webkit_navigation_action_get_navigation_type(a)) {
1309 case WEBKIT_NAVIGATION_TYPE_LINK_CLICKED: /* fallthrough */
1310 case WEBKIT_NAVIGATION_TYPE_FORM_SUBMITTED: /* fallthrough */
1311 case WEBKIT_NAVIGATION_TYPE_BACK_FORWARD: /* fallthrough */
1312 case WEBKIT_NAVIGATION_TYPE_RELOAD: /* fallthrough */
1313 case WEBKIT_NAVIGATION_TYPE_FORM_RESUBMITTED:
1314 /* Filter domains here */
1315 /* If the value of “mouse-button” is not 0, then the navigation was triggered by a mouse event.
1316 * test for link clicked but no button ? */
1317 arg.v = webkit_uri_request_get_uri(
1318 webkit_navigation_action_get_request(a));
1319 newwindow(c, &arg, 0);
1321 case WEBKIT_NAVIGATION_TYPE_OTHER: /* fallthrough */
1326 webkit_policy_decision_ignore(d);
1330 decideresource(WebKitPolicyDecision *d, Client *c)
1333 WebKitResponsePolicyDecision *r = WEBKIT_RESPONSE_POLICY_DECISION(d);
1334 WebKitURIResponse *res =
1335 webkit_response_policy_decision_get_response(r);
1336 const gchar *uri = webkit_uri_response_get_uri(res);
1338 if (g_str_has_suffix(uri, "/favicon.ico")) {
1339 webkit_policy_decision_ignore(d);
1343 if (!g_str_has_prefix(uri, "http://")
1344 && !g_str_has_prefix(uri, "https://")
1345 && !g_str_has_prefix(uri, "about:")
1346 && !g_str_has_prefix(uri, "file://")
1347 && !g_str_has_prefix(uri, "data:")
1348 && !g_str_has_prefix(uri, "blob:")
1349 && strlen(uri) > 0) {
1350 for (i = 0; i < strlen(uri); i++) {
1351 if (!g_ascii_isprint(uri[i])) {
1357 handleplumb(c, uri);
1358 webkit_policy_decision_ignore(d);
1363 if (webkit_response_policy_decision_is_mime_type_supported(r)) {
1364 webkit_policy_decision_use(d);
1366 webkit_policy_decision_ignore(d);
1372 downloadstarted(WebKitWebContext *wc, WebKitDownload *d, Client *c)
1374 g_signal_connect(G_OBJECT(d), "notify::response",
1375 G_CALLBACK(responsereceived), c);
1379 responsereceived(WebKitDownload *d, GParamSpec *ps, Client *c)
1381 download(c, webkit_download_get_response(d));
1382 webkit_download_cancel(d);
1386 download(Client *c, WebKitURIResponse *r)
1388 Arg a = (Arg)DOWNLOAD(webkit_uri_response_get_uri(r), geturi(c));
1393 closeview(WebKitWebView *v, Client *c)
1395 gtk_widget_destroy(c->win);
1399 destroywin(GtkWidget* w, Client *c)
1407 pasteuri(GtkClipboard *clipboard, const char *text, gpointer d)
1409 Arg a = {.v = text };
1411 loaduri((Client *) d, &a);
1415 reload(Client *c, const Arg *a)
1418 webkit_web_view_reload_bypass_cache(c->view);
1420 webkit_web_view_reload(c->view);
1424 print(Client *c, const Arg *a)
1426 webkit_print_operation_run_dialog(webkit_print_operation_new(c->view),
1427 GTK_WINDOW(c->win));
1431 clipboard(Client *c, const Arg *a)
1433 if (a->b) { /* load clipboard uri */
1434 gtk_clipboard_request_text(gtk_clipboard_get(
1435 GDK_SELECTION_PRIMARY),
1437 } else { /* copy uri */
1438 gtk_clipboard_set_text(gtk_clipboard_get(
1439 GDK_SELECTION_PRIMARY), c->targeturi
1440 ? c->targeturi : geturi(c), -1);
1445 zoom(Client *c, const Arg *a)
1448 webkit_web_view_set_zoom_level(c->view,
1449 curconfig[ZoomLevel].val.f + 0.1);
1451 webkit_web_view_set_zoom_level(c->view,
1452 curconfig[ZoomLevel].val.f - 0.1);
1454 webkit_web_view_set_zoom_level(c->view, 1.0);
1456 curconfig[ZoomLevel].val.f = webkit_web_view_get_zoom_level(c->view);
1460 scroll(Client *c, const Arg *a)
1462 GdkEvent *ev = gdk_event_new(GDK_KEY_PRESS);
1464 gdk_event_set_device(ev, gdkkb);
1465 // gdk_event_set_screen(ev, gdk_screen_get_default());
1466 ev->key.window = gtk_widget_get_window(GTK_WIDGET(c->win));
1467 ev->key.state = GDK_CONTROL_MASK;
1468 ev->key.time = GDK_CURRENT_TIME;
1472 ev->key.keyval = GDK_KEY_Down;
1475 ev->key.keyval = GDK_KEY_Page_Down;
1478 ev->key.keyval = GDK_KEY_Left;
1481 ev->key.keyval = GDK_KEY_Right;
1484 ev->key.keyval = GDK_KEY_Page_Up;
1487 ev->key.keyval = GDK_KEY_Up;
1495 navigate(Client *c, const Arg *a)
1498 webkit_web_view_go_back(c->view);
1500 webkit_web_view_go_forward(c->view);
1504 stop(Client *c, const Arg *a)
1506 webkit_web_view_stop_loading(c->view);
1510 toggle(Client *c, const Arg *a)
1512 curconfig[a->i].val.b ^= 1;
1513 setparameter(c, 1, (ParamName)a->i, &curconfig[a->i].val);
1517 togglefullscreen(Client *c, const Arg *a)
1519 /* toggling value is handled in winevent() */
1521 gtk_window_unfullscreen(GTK_WINDOW(c->win));
1523 gtk_window_fullscreen(GTK_WINDOW(c->win));
1527 togglecookiepolicy(Client *c, const Arg *a)
1530 cookiepolicy %= strlen(curconfig[CookiePolicies].val.v);
1532 setparameter(c, 0, CookiePolicies, NULL);
1536 toggleinspector(Client *c, const Arg *a)
1538 if (curconfig[Inspector].val.b) {
1539 if (webkit_web_inspector_is_attached(c->inspector))
1540 webkit_web_inspector_close(c->inspector);
1542 webkit_web_inspector_show(c->inspector);
1547 find(Client *c, const Arg *a)
1553 webkit_find_controller_search_next(c->finder);
1555 webkit_find_controller_search_previous(c->finder);
1557 s = getatom(c, AtomFind);
1558 f = webkit_find_controller_get_search_text(c->finder);
1560 if (g_strcmp0(f, s) == 0) /* reset search */
1561 webkit_find_controller_search(c->finder, "", findopts,
1564 webkit_find_controller_search(c->finder, s, findopts,
1567 if (strcmp(s, "") == 0)
1568 webkit_find_controller_search_finish(c->finder);
1573 clicknavigate(Client *c, const Arg *a, WebKitHitTestResult *h)
1579 clicknewwindow(Client *c, const Arg *a, WebKitHitTestResult *h)
1583 arg.v = webkit_hit_test_result_get_link_uri(h);
1584 newwindow(c, &arg, a->b);
1588 clickexternplayer(Client *c, const Arg *a, WebKitHitTestResult *h)
1592 arg = (Arg)VIDEOPLAY(webkit_hit_test_result_get_media_uri(h));
1597 main(int argc, char *argv[])
1602 memset(&arg, 0, sizeof(arg));
1604 /* command line args */
1607 defconfig CSETV(CookiePolicies, EARGF(usage()));
1610 defconfig CSETB(ScrollBars, 0);
1613 defconfig CSETB(ScrollBars, 1);
1616 cookiefile = EARGF(usage());
1619 defconfig CSETB(DiskCache, 0);
1622 defconfig CSETB(DiskCache, 1);
1625 embed = strtol(EARGF(usage()), NULL, 0);
1628 defconfig CSETB(RunInFullscreen, 0);
1631 defconfig CSETB(RunInFullscreen, 1);
1634 defconfig CSETB(Geolocation, 0);
1637 defconfig CSETB(Geolocation, 1);
1640 defconfig CSETB(LoadImages, 0);
1643 defconfig CSETB(LoadImages, 1);
1646 defconfig CSETB(KioskMode, 0);
1649 defconfig CSETB(KioskMode, 1);
1652 defconfig CSETB(Style, 0);
1655 defconfig CSETB(Style, 1);
1658 defconfig CSETB(Inspector, 0);
1661 defconfig CSETB(Inspector, 1);
1664 defconfig CSETB(Plugins, 0);
1667 defconfig CSETB(Plugins, 1);
1670 scriptfile = EARGF(usage());
1673 defconfig CSETB(JavaScript, 0);
1676 defconfig CSETB(JavaScript, 1);
1679 stylefile = EARGF(usage());
1682 fulluseragent = EARGF(usage());
1685 die("surf-"VERSION", ©2009-2015 surf engineers, "
1686 "see LICENSE for details\n");
1691 defconfig CSETF(ZoomLevel, strtof(EARGF(usage()), NULL));
1699 arg.v = "about:blank";
1702 c = newclient(NULL);