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 get_user_homedir(const char *user) {
355 struct passwd *pw = getpwnam(user);
357 die("Can't get user `%s' home directory.\n", user);
363 get_current_user_homedir() {
368 homedir = getenv("HOME");
373 user = getenv("USER");
375 return get_user_homedir(user);
378 pw = getpwuid(getuid());
380 die("Can't get current user home directory\n");
386 buildpath(const char *path)
388 char *apath, *name, *p, *fpath;
390 if (path[0] == '~') {
392 if (path[1] == '/' || path[1] == '\0') {
393 p = (char *)&path[1];
394 homedir = get_current_user_homedir();
396 if ((p = strchr(path, '/')))
397 name = g_strndup(&path[1], --p - path);
399 name = g_strdup(&path[1]);
401 homedir = get_user_homedir(name);
404 apath = g_build_filename(homedir, p, NULL);
406 apath = g_strdup(path);
409 /* creating directory */
410 if (g_mkdir_with_parents(apath, 0700) < 0)
411 die("Could not access directory: %s\n", apath);
413 fpath = realpath(apath, NULL);
420 newclient(Client *rc)
424 if (!(c = calloc(1, sizeof(Client))))
425 die("Cannot malloc!\n");
431 c->tlsflags = G_TLS_CERTIFICATE_VALIDATE_ALL + 1;
432 c->view = newview(c, rc ? rc->view : NULL);
438 loaduri(Client *c, const Arg *a)
442 const char *uri = a->v;
444 if (g_strcmp0(uri, "") == 0)
447 if (g_str_has_prefix(uri, "http://") ||
448 g_str_has_prefix(uri, "https://") ||
449 g_str_has_prefix(uri, "file://") ||
450 g_str_has_prefix(uri, "about:")) {
452 } else if (!stat(uri, &st) && (path = realpath(uri, NULL))) {
453 url = g_strdup_printf("file://%s", path);
456 url = g_strdup_printf("http://%s", uri);
459 setatom(c, AtomUri, url);
461 if (strcmp(url, geturi(c)) == 0) {
464 webkit_web_view_load_uri(c->view, url);
476 if (!(uri = webkit_web_view_get_uri(c->view)))
482 setatom(Client *c, int a, const char *v)
485 XChangeProperty(dpy, c->xid,
486 atoms[a], XA_STRING, 8, PropModeReplace,
487 (unsigned char *)v, strlen(v) + 1);
491 getatom(Client *c, int a)
493 static char buf[BUFSIZ];
496 unsigned long ldummy;
497 unsigned char *p = NULL;
499 XGetWindowProperty(dpy, c->xid, atoms[a], 0L, BUFSIZ, False, XA_STRING,
500 &adummy, &idummy, &ldummy, &ldummy, &p);
502 strncpy(buf, (char *)p, LENGTH(buf) - 1);
511 updatetitle(Client *c)
514 const char *name = c->overtitle ? c->overtitle :
515 c->title ? c->title : "";
517 if (curconfig[ShowIndicators].val.b) {
521 if (c->progress != 100)
522 title = g_strdup_printf("[%i%%] %s:%s | %s",
523 c->progress, togglestats, pagestats, name);
525 title = g_strdup_printf("%s:%s | %s",
526 togglestats, pagestats, name);
528 gtk_window_set_title(GTK_WINDOW(c->win), title);
531 gtk_window_set_title(GTK_WINDOW(c->win), name);
536 gettogglestats(Client *c)
538 togglestats[0] = cookiepolicy_set(cookiepolicy_get());
539 togglestats[1] = curconfig[CaretBrowsing].val.b ? 'C' : 'c';
540 togglestats[2] = curconfig[Geolocation].val.b ? 'G' : 'g';
541 togglestats[3] = curconfig[DiskCache].val.b ? 'D' : 'd';
542 togglestats[4] = curconfig[LoadImages].val.b ? 'I' : 'i';
543 togglestats[5] = curconfig[JavaScript].val.b ? 'S' : 's';
544 togglestats[6] = curconfig[Plugins].val.b ? 'V' : 'v';
545 togglestats[7] = curconfig[Style].val.b ? 'M' : 'm';
546 togglestats[8] = curconfig[FrameFlattening].val.b ? 'F' : 'f';
547 togglestats[9] = '\0';
551 getpagestats(Client *c)
553 pagestats[0] = c->tlsflags > G_TLS_CERTIFICATE_VALIDATE_ALL ? '-' :
554 c->tlsflags > 0 ? 'U' : 'T';
558 WebKitCookieAcceptPolicy
559 cookiepolicy_get(void)
561 switch (((char *)curconfig[CookiePolicies].val.v)[cookiepolicy]) {
563 return WEBKIT_COOKIE_POLICY_ACCEPT_NEVER;
565 return WEBKIT_COOKIE_POLICY_ACCEPT_NO_THIRD_PARTY;
566 default: /* fallthrough */
568 return WEBKIT_COOKIE_POLICY_ACCEPT_ALWAYS;
573 cookiepolicy_set(const WebKitCookieAcceptPolicy p)
576 case WEBKIT_COOKIE_POLICY_ACCEPT_NEVER:
578 case WEBKIT_COOKIE_POLICY_ACCEPT_NO_THIRD_PARTY:
580 default: /* fallthrough */
581 case WEBKIT_COOKIE_POLICY_ACCEPT_ALWAYS:
587 seturiparameters(Client *c, const char *uri)
591 for (i = 0; i < LENGTH(uriparams); ++i) {
592 if (uriparams[i].uri &&
593 !regexec(&(uriparams[i].re), uri, 0, NULL, 0)) {
594 curconfig = uriparams[i].config;
599 for (i = 0; i < ParameterLast; ++i)
600 setparameter(c, 0, i, &curconfig[i].val);
604 setparameter(Client *c, int refresh, ParamName p, const Arg *a)
606 GdkRGBA bgcolor = { 0 };
607 WebKitSettings *s = webkit_web_view_get_settings(c->view);
611 webkit_settings_set_enable_caret_browsing(s, a->b);
615 webkit_cookie_manager_set_accept_policy(
616 webkit_web_context_get_cookie_manager(
617 webkit_web_view_get_context(c->view)),
622 webkit_web_context_set_cache_model(
623 webkit_web_view_get_context(c->view), a->b ?
624 WEBKIT_CACHE_MODEL_WEB_BROWSER :
625 WEBKIT_CACHE_MODEL_DOCUMENT_VIEWER);
626 return; /* do not update */
628 webkit_settings_set_enable_dns_prefetching(s, a->b);
629 return; /* do not update */
631 webkit_settings_set_default_font_size(s, a->i);
632 return; /* do not update */
633 case FrameFlattening:
634 webkit_settings_set_enable_frame_flattening(s, a->b);
641 webkit_web_view_set_background_color(c->view, &bgcolor);
642 return; /* do not update */
644 webkit_settings_set_enable_developer_extras(s, a->b);
645 return; /* do not update */
647 webkit_settings_set_enable_javascript(s, a->b);
650 return; /* do nothing */
652 webkit_settings_set_auto_load_images(s, a->b);
655 webkit_settings_set_enable_plugins(s, a->b);
657 case PreferredLanguages:
658 return; /* do nothing */
659 case RunInFullscreen:
660 return; /* do nothing */
662 /* Disabled until we write some WebKitWebExtension for
663 * manipulating the DOM directly.
664 enablescrollbars = !enablescrollbars;
665 evalscript(c, "document.documentElement.style.overflow = '%s'",
666 enablescrollbars ? "auto" : "hidden");
668 return; /* do not update */
672 webkit_web_context_set_spell_checking_enabled(
673 webkit_web_view_get_context(c->view), a->b);
674 return; /* do not update */
676 return; /* do nothing */
678 webkit_web_context_set_tls_errors_policy(
679 webkit_web_view_get_context(c->view), a->b ?
680 WEBKIT_TLS_ERRORS_POLICY_FAIL :
681 WEBKIT_TLS_ERRORS_POLICY_IGNORE);
682 return; /* do not update */
685 setstyle(c, getstyle(geturi(c)));
687 webkit_user_content_manager_remove_all_style_sheets(
688 webkit_web_view_get_user_content_manager(c->view));
692 webkit_web_view_set_zoom_level(c->view, a->f);
693 return; /* do not update */
695 return; /* do nothing */
704 getstyle(const char *uri)
711 for (i = 0; i < LENGTH(styles); ++i) {
712 if (styles[i].regex &&
713 !regexec(&(styles[i].re), uri, 0, NULL, 0))
714 return styles[i].style;
721 setstyle(Client *c, const char *stylefile)
725 if (!g_file_get_contents(stylefile, &style, NULL, NULL)) {
726 fprintf(stderr, "Could not read style file: %s\n", stylefile);
730 webkit_user_content_manager_add_style_sheet(
731 webkit_web_view_get_user_content_manager(c->view),
732 webkit_user_style_sheet_new(style,
733 WEBKIT_USER_CONTENT_INJECT_ALL_FRAMES,
734 WEBKIT_USER_STYLE_LEVEL_USER,
746 if (g_file_get_contents(scriptfile, &script, &l, NULL) && l)
747 evalscript(c, script);
752 evalscript(Client *c, const char *jsstr, ...)
758 script = g_strdup_vprintf(jsstr, ap);
761 webkit_web_view_run_javascript(c->view, script, NULL, NULL, NULL);
766 updatewinid(Client *c)
768 snprintf(winid, LENGTH(winid), "%lu", c->xid);
772 handleplumb(Client *c, const char *uri)
774 Arg a = (Arg)PLUMB(uri);
779 newwindow(Client *c, const Arg *a, int noembed)
783 const char *cmd[26], *uri;
784 const Arg arg = { .v = cmd };
788 cmd[i++] = curconfig[CookiePolicies].val.v;
789 cmd[i++] = curconfig[ScrollBars].val.b ? "-B" : "-b";
790 if (cookiefile && g_strcmp0(cookiefile, "")) {
792 cmd[i++] = cookiefile;
794 cmd[i++] = curconfig[DiskCache].val.b ? "-D" : "-d";
795 if (embed && !noembed) {
797 snprintf(tmp, LENGTH(tmp), "%lu", embed);
800 cmd[i++] = curconfig[RunInFullscreen].val.b ? "-F" : "-f" ;
801 cmd[i++] = curconfig[Geolocation].val.b ? "-G" : "-g" ;
802 cmd[i++] = curconfig[LoadImages].val.b ? "-I" : "-i" ;
803 cmd[i++] = curconfig[KioskMode].val.b ? "-K" : "-k" ;
804 cmd[i++] = curconfig[Style].val.b ? "-M" : "-m" ;
805 cmd[i++] = curconfig[Inspector].val.b ? "-N" : "-n" ;
806 cmd[i++] = curconfig[Plugins].val.b ? "-P" : "-p" ;
807 if (scriptfile && g_strcmp0(scriptfile, "")) {
809 cmd[i++] = scriptfile;
811 cmd[i++] = curconfig[JavaScript].val.b ? "-S" : "-s";
812 if (stylefile && g_strcmp0(stylefile, "")) {
814 cmd[i++] = stylefile;
816 if (fulluseragent && g_strcmp0(fulluseragent, "")) {
818 cmd[i++] = fulluseragent;
822 /* do not keep zoom level */
832 spawn(Client *c, const Arg *a)
836 close(ConnectionNumber(dpy));
838 execvp(((char **)a->v)[0], (char **)a->v);
839 fprintf(stderr, "%s: execvp %s", argv0, ((char **)a->v)[0]);
846 destroyclient(Client *c)
850 webkit_web_view_stop_loading(c->view);
851 /* Not needed, has already been called
852 gtk_widget_destroy(c->win);
855 for (p = clients; p && p->next != c; p = p->next)
868 destroyclient(clients);
878 GList *l, *gdl = gdk_device_manager_list_devices(
879 gdk_display_get_device_manager(gdk_display_get_default()),
880 GDK_DEVICE_TYPE_MASTER);
881 GdkDevice *gd = NULL;
883 for (l = gdl; l != NULL; l = l->next)
884 if (gdk_device_get_source(l->data) == GDK_SOURCE_KEYBOARD)
892 newview(Client *c, WebKitWebView *rv)
895 WebKitSettings *settings;
896 WebKitUserContentManager *contentmanager;
897 WebKitWebContext *context;
902 webkit_web_view_new_with_related_view(rv));
904 settings = webkit_settings_new_with_settings(
905 "auto-load-images", curconfig[LoadImages].val.b,
906 "default-font-size", curconfig[FontSize].val.f,
907 "enable-caret-browsing", curconfig[CaretBrowsing].val.b,
908 "enable-developer-extras", curconfig[Inspector].val.b,
909 "enable-dns-prefetching", curconfig[DNSPrefetch].val.b,
910 "enable-frame-flattening", curconfig[FrameFlattening].val.b,
911 "enable-html5-database", curconfig[DiskCache].val.b,
912 "enable-html5-local-storage", curconfig[DiskCache].val.b,
913 "enable-javascript", curconfig[JavaScript].val.b,
914 "enable-plugins", curconfig[Plugins].val.b,
916 /* For mor interesting settings, have a look at
917 * http://webkitgtk.org/reference/webkit2gtk/stable/WebKitSettings.html */
919 if (strcmp(fulluseragent, "")) {
920 webkit_settings_set_user_agent(settings, fulluseragent);
921 } else if (surfuseragent) {
922 webkit_settings_set_user_agent_with_application_details(
923 settings, "Surf", VERSION);
925 useragent = webkit_settings_get_user_agent(settings);
927 contentmanager = webkit_user_content_manager_new();
929 context = webkit_web_context_new_with_website_data_manager(
930 webkit_website_data_manager_new(
931 "base-cache-directory", cachedir,
932 "base-data-directory", cachedir,
935 /* rendering process model, can be a shared unique one
936 * or one for each view */
937 webkit_web_context_set_process_model(context,
938 WEBKIT_PROCESS_MODEL_MULTIPLE_SECONDARY_PROCESSES);
940 webkit_web_context_set_tls_errors_policy(context,
941 curconfig[StrictSSL].val.b ? WEBKIT_TLS_ERRORS_POLICY_FAIL :
942 WEBKIT_TLS_ERRORS_POLICY_IGNORE);
944 webkit_web_context_set_cache_model(context,
945 curconfig[DiskCache].val.b ? WEBKIT_CACHE_MODEL_WEB_BROWSER :
946 WEBKIT_CACHE_MODEL_DOCUMENT_VIEWER);
948 /* Currently only works with text file to be compatible with curl */
949 webkit_cookie_manager_set_persistent_storage(
950 webkit_web_context_get_cookie_manager(context), cookiefile,
951 WEBKIT_COOKIE_PERSISTENT_STORAGE_TEXT);
953 webkit_cookie_manager_set_accept_policy(
954 webkit_web_context_get_cookie_manager(context),
957 webkit_web_context_set_preferred_languages(context,
958 curconfig[PreferredLanguages].val.v);
959 webkit_web_context_set_spell_checking_languages(context,
960 curconfig[SpellLanguages].val.v);
961 webkit_web_context_set_spell_checking_enabled(context,
962 curconfig[SpellChecking].val.b);
964 g_signal_connect(G_OBJECT(context), "download-started",
965 G_CALLBACK(downloadstarted), c);
967 v = g_object_new(WEBKIT_TYPE_WEB_VIEW,
968 "settings", settings,
969 "user-content-manager", contentmanager,
970 "web-context", context,
974 g_signal_connect(G_OBJECT(v), "notify::estimated-load-progress",
975 G_CALLBACK(progresschanged), c);
976 g_signal_connect(G_OBJECT(v), "notify::title",
977 G_CALLBACK(titlechanged), c);
978 g_signal_connect(G_OBJECT(v), "button-release-event",
979 G_CALLBACK(buttonreleased), c);
980 g_signal_connect(G_OBJECT(v), "close",
981 G_CALLBACK(closeview), c);
982 g_signal_connect(G_OBJECT(v), "create",
983 G_CALLBACK(createview), c);
984 g_signal_connect(G_OBJECT(v), "decide-policy",
985 G_CALLBACK(decidepolicy), c);
986 g_signal_connect(G_OBJECT(v), "load-changed",
987 G_CALLBACK(loadchanged), c);
988 g_signal_connect(G_OBJECT(v), "mouse-target-changed",
989 G_CALLBACK(mousetargetchanged), c);
990 g_signal_connect(G_OBJECT(v), "permission-request",
991 G_CALLBACK(permissionrequested), c);
992 g_signal_connect(G_OBJECT(v), "ready-to-show",
993 G_CALLBACK(showview), c);
999 createview(WebKitWebView *v, WebKitNavigationAction *a, Client *c)
1003 switch (webkit_navigation_action_get_navigation_type(a)) {
1004 case WEBKIT_NAVIGATION_TYPE_OTHER: /* fallthrough */
1006 * popup windows of type “other” are almost always triggered
1007 * by user gesture, so inverse the logic here
1009 /* instead of this, compare destination uri to mouse-over uri for validating window */
1010 if (webkit_navigation_action_is_user_gesture(a))
1012 case WEBKIT_NAVIGATION_TYPE_LINK_CLICKED: /* fallthrough */
1013 case WEBKIT_NAVIGATION_TYPE_FORM_SUBMITTED: /* fallthrough */
1014 case WEBKIT_NAVIGATION_TYPE_BACK_FORWARD: /* fallthrough */
1015 case WEBKIT_NAVIGATION_TYPE_RELOAD: /* fallthrough */
1016 case WEBKIT_NAVIGATION_TYPE_FORM_RESUBMITTED:
1023 return GTK_WIDGET(n->view);
1027 buttonreleased(GtkWidget *w, GdkEvent *e, Client *c)
1029 WebKitHitTestResultContext element;
1032 element = webkit_hit_test_result_get_context(c->mousepos);
1034 for (i = 0; i < LENGTH(buttons); ++i) {
1035 if (element & buttons[i].target &&
1036 e->button.button == buttons[i].button &&
1037 CLEANMASK(e->button.state) == CLEANMASK(buttons[i].mask) &&
1039 buttons[i].func(c, &buttons[i].arg, c->mousepos);
1040 return buttons[i].stopevent;
1048 processx(GdkXEvent *e, GdkEvent *event, gpointer d)
1050 Client *c = (Client *)d;
1054 if (((XEvent *)e)->type == PropertyNotify) {
1055 ev = &((XEvent *)e)->xproperty;
1056 if (ev->state == PropertyNewValue) {
1057 if (ev->atom == atoms[AtomFind]) {
1060 return GDK_FILTER_REMOVE;
1061 } else if (ev->atom == atoms[AtomGo]) {
1062 a.v = getatom(c, AtomGo);
1065 return GDK_FILTER_REMOVE;
1069 return GDK_FILTER_CONTINUE;
1073 winevent(GtkWidget *w, GdkEvent *e, Client *c)
1078 case GDK_ENTER_NOTIFY:
1079 c->overtitle = c->targeturi;
1083 if (!curconfig[KioskMode].val.b) {
1084 for (i = 0; i < LENGTH(keys); ++i) {
1085 if (gdk_keyval_to_lower(e->key.keyval) ==
1087 CLEANMASK(e->key.state) == keys[i].mod &&
1090 keys[i].func(c, &(keys[i].arg));
1095 case GDK_LEAVE_NOTIFY:
1096 c->overtitle = NULL;
1099 case GDK_WINDOW_STATE:
1100 if (e->window_state.changed_mask ==
1101 GDK_WINDOW_STATE_FULLSCREEN)
1102 c->fullscreen = e->window_state.new_window_state &
1103 GDK_WINDOW_STATE_FULLSCREEN;
1113 showview(WebKitWebView *v, Client *c)
1115 GdkRGBA bgcolor = { 0 };
1118 c->finder = webkit_web_view_get_find_controller(c->view);
1119 c->inspector = webkit_web_view_get_inspector(c->view);
1121 c->win = createwindow(c);
1123 gtk_container_add(GTK_CONTAINER(c->win), GTK_WIDGET(c->view));
1124 gtk_widget_show_all(c->win);
1125 gtk_widget_grab_focus(GTK_WIDGET(c->view));
1127 gwin = gtk_widget_get_window(GTK_WIDGET(c->win));
1128 c->xid = gdk_x11_window_get_xid(gwin);
1131 gdk_display_sync(gtk_widget_get_display(c->win));
1135 if (curconfig[HideBackground].val.b)
1136 webkit_web_view_set_background_color(c->view, &bgcolor);
1138 if (!curconfig[KioskMode].val.b) {
1139 gdk_window_set_events(gwin, GDK_ALL_EVENTS_MASK);
1140 gdk_window_add_filter(gwin, processx, c);
1143 if (curconfig[RunInFullscreen].val.b)
1144 togglefullscreen(c, NULL);
1146 if (curconfig[ZoomLevel].val.f != 1.0)
1147 webkit_web_view_set_zoom_level(c->view,
1148 curconfig[ZoomLevel].val.f);
1150 setatom(c, AtomFind, "");
1151 setatom(c, AtomUri, "about:blank");
1155 createwindow(Client *c)
1161 w = gtk_plug_new(embed);
1163 w = gtk_window_new(GTK_WINDOW_TOPLEVEL);
1165 wmstr = g_path_get_basename(argv0);
1166 gtk_window_set_wmclass(GTK_WINDOW(w), wmstr, "Surf");
1169 wmstr = g_strdup_printf("%s[%lu]", "Surf",
1170 webkit_web_view_get_page_id(c->view));
1171 gtk_window_set_role(GTK_WINDOW(w), wmstr);
1174 gtk_window_set_default_size(GTK_WINDOW(w), 800, 600);
1177 g_signal_connect(G_OBJECT(w), "destroy",
1178 G_CALLBACK(destroywin), c);
1179 g_signal_connect(G_OBJECT(w), "enter-notify-event",
1180 G_CALLBACK(winevent), c);
1181 g_signal_connect(G_OBJECT(w), "key-press-event",
1182 G_CALLBACK(winevent), c);
1183 g_signal_connect(G_OBJECT(w), "leave-notify-event",
1184 G_CALLBACK(winevent), c);
1185 g_signal_connect(G_OBJECT(w), "window-state-event",
1186 G_CALLBACK(winevent), c);
1192 loadchanged(WebKitWebView *v, WebKitLoadEvent e, Client *c)
1194 const char *title = geturi(c);
1197 case WEBKIT_LOAD_STARTED:
1198 curconfig = defconfig;
1199 setatom(c, AtomUri, title);
1201 c->tlsflags = G_TLS_CERTIFICATE_VALIDATE_ALL + 1;
1202 seturiparameters(c, geturi(c));
1204 case WEBKIT_LOAD_REDIRECTED:
1205 setatom(c, AtomUri, title);
1207 seturiparameters(c, geturi(c));
1209 case WEBKIT_LOAD_COMMITTED:
1210 if (!webkit_web_view_get_tls_info(c->view, NULL,
1212 c->tlsflags = G_TLS_CERTIFICATE_VALIDATE_ALL + 1;
1215 case WEBKIT_LOAD_FINISHED:
1216 /* Disabled until we write some WebKitWebExtension for
1217 * manipulating the DOM directly.
1218 evalscript(c, "document.documentElement.style.overflow = '%s'",
1219 enablescrollbars ? "auto" : "hidden");
1228 progresschanged(WebKitWebView *v, GParamSpec *ps, Client *c)
1230 c->progress = webkit_web_view_get_estimated_load_progress(c->view) *
1236 titlechanged(WebKitWebView *view, GParamSpec *ps, Client *c)
1238 c->title = webkit_web_view_get_title(c->view);
1243 mousetargetchanged(WebKitWebView *v, WebKitHitTestResult *h, guint modifiers,
1246 WebKitHitTestResultContext hc = webkit_hit_test_result_get_context(h);
1248 /* Keep the hit test to know where is the pointer on the next click */
1252 c->targeturi = webkit_hit_test_result_get_link_uri(h);
1253 else if (hc & OnImg)
1254 c->targeturi = webkit_hit_test_result_get_image_uri(h);
1255 else if (hc & OnMedia)
1256 c->targeturi = webkit_hit_test_result_get_media_uri(h);
1258 c->targeturi = NULL;
1260 c->overtitle = c->targeturi;
1265 permissionrequested(WebKitWebView *v, WebKitPermissionRequest *r, Client *c)
1267 if (WEBKIT_IS_GEOLOCATION_PERMISSION_REQUEST(r)) {
1268 if (curconfig[Geolocation].val.b)
1269 webkit_permission_request_allow(r);
1271 webkit_permission_request_deny(r);
1279 decidepolicy(WebKitWebView *v, WebKitPolicyDecision *d,
1280 WebKitPolicyDecisionType dt, Client *c)
1283 case WEBKIT_POLICY_DECISION_TYPE_NAVIGATION_ACTION:
1284 decidenavigation(d, c);
1286 case WEBKIT_POLICY_DECISION_TYPE_NEW_WINDOW_ACTION:
1287 decidenewwindow(d, c);
1289 case WEBKIT_POLICY_DECISION_TYPE_RESPONSE:
1290 decideresource(d, c);
1293 webkit_policy_decision_ignore(d);
1300 decidenavigation(WebKitPolicyDecision *d, Client *c)
1302 WebKitNavigationAction *a =
1303 webkit_navigation_policy_decision_get_navigation_action(
1304 WEBKIT_NAVIGATION_POLICY_DECISION(d));
1306 switch (webkit_navigation_action_get_navigation_type(a)) {
1307 case WEBKIT_NAVIGATION_TYPE_LINK_CLICKED: /* fallthrough */
1308 case WEBKIT_NAVIGATION_TYPE_FORM_SUBMITTED: /* fallthrough */
1309 case WEBKIT_NAVIGATION_TYPE_BACK_FORWARD: /* fallthrough */
1310 case WEBKIT_NAVIGATION_TYPE_RELOAD: /* fallthrough */
1311 case WEBKIT_NAVIGATION_TYPE_FORM_RESUBMITTED: /* fallthrough */
1312 case WEBKIT_NAVIGATION_TYPE_OTHER: /* fallthrough */
1314 /* Do not navigate to links with a "_blank" target (popup) */
1315 if (webkit_navigation_policy_decision_get_frame_name(
1316 WEBKIT_NAVIGATION_POLICY_DECISION(d))) {
1317 webkit_policy_decision_ignore(d);
1319 /* Filter out navigation to different domain ? */
1320 /* get action→urirequest, copy and load in new window+view
1321 * on Ctrl+Click ? */
1322 webkit_policy_decision_use(d);
1329 decidenewwindow(WebKitPolicyDecision *d, Client *c)
1332 WebKitNavigationAction *a =
1333 webkit_navigation_policy_decision_get_navigation_action(
1334 WEBKIT_NAVIGATION_POLICY_DECISION(d));
1337 switch (webkit_navigation_action_get_navigation_type(a)) {
1338 case WEBKIT_NAVIGATION_TYPE_LINK_CLICKED: /* fallthrough */
1339 case WEBKIT_NAVIGATION_TYPE_FORM_SUBMITTED: /* fallthrough */
1340 case WEBKIT_NAVIGATION_TYPE_BACK_FORWARD: /* fallthrough */
1341 case WEBKIT_NAVIGATION_TYPE_RELOAD: /* fallthrough */
1342 case WEBKIT_NAVIGATION_TYPE_FORM_RESUBMITTED:
1343 /* Filter domains here */
1344 /* If the value of “mouse-button” is not 0, then the navigation was triggered by a mouse event.
1345 * test for link clicked but no button ? */
1346 arg.v = webkit_uri_request_get_uri(
1347 webkit_navigation_action_get_request(a));
1348 newwindow(c, &arg, 0);
1350 case WEBKIT_NAVIGATION_TYPE_OTHER: /* fallthrough */
1355 webkit_policy_decision_ignore(d);
1359 decideresource(WebKitPolicyDecision *d, Client *c)
1362 WebKitResponsePolicyDecision *r = WEBKIT_RESPONSE_POLICY_DECISION(d);
1363 WebKitURIResponse *res =
1364 webkit_response_policy_decision_get_response(r);
1365 const gchar *uri = webkit_uri_response_get_uri(res);
1367 if (g_str_has_suffix(uri, "/favicon.ico")) {
1368 webkit_policy_decision_ignore(d);
1372 if (!g_str_has_prefix(uri, "http://")
1373 && !g_str_has_prefix(uri, "https://")
1374 && !g_str_has_prefix(uri, "about:")
1375 && !g_str_has_prefix(uri, "file://")
1376 && !g_str_has_prefix(uri, "data:")
1377 && !g_str_has_prefix(uri, "blob:")
1378 && strlen(uri) > 0) {
1379 for (i = 0; i < strlen(uri); i++) {
1380 if (!g_ascii_isprint(uri[i])) {
1386 handleplumb(c, uri);
1387 webkit_policy_decision_ignore(d);
1392 if (webkit_response_policy_decision_is_mime_type_supported(r)) {
1393 webkit_policy_decision_use(d);
1395 webkit_policy_decision_ignore(d);
1401 downloadstarted(WebKitWebContext *wc, WebKitDownload *d, Client *c)
1403 g_signal_connect(G_OBJECT(d), "notify::response",
1404 G_CALLBACK(responsereceived), c);
1408 responsereceived(WebKitDownload *d, GParamSpec *ps, Client *c)
1410 download(c, webkit_download_get_response(d));
1411 webkit_download_cancel(d);
1415 download(Client *c, WebKitURIResponse *r)
1417 Arg a = (Arg)DOWNLOAD(webkit_uri_response_get_uri(r), geturi(c));
1422 closeview(WebKitWebView *v, Client *c)
1424 gtk_widget_destroy(c->win);
1428 destroywin(GtkWidget* w, Client *c)
1436 pasteuri(GtkClipboard *clipboard, const char *text, gpointer d)
1438 Arg a = {.v = text };
1440 loaduri((Client *) d, &a);
1444 reload(Client *c, const Arg *a)
1447 webkit_web_view_reload_bypass_cache(c->view);
1449 webkit_web_view_reload(c->view);
1453 print(Client *c, const Arg *a)
1455 webkit_print_operation_run_dialog(webkit_print_operation_new(c->view),
1456 GTK_WINDOW(c->win));
1460 clipboard(Client *c, const Arg *a)
1462 if (a->b) { /* load clipboard uri */
1463 gtk_clipboard_request_text(gtk_clipboard_get(
1464 GDK_SELECTION_PRIMARY),
1466 } else { /* copy uri */
1467 gtk_clipboard_set_text(gtk_clipboard_get(
1468 GDK_SELECTION_PRIMARY), c->targeturi
1469 ? c->targeturi : geturi(c), -1);
1474 zoom(Client *c, const Arg *a)
1477 webkit_web_view_set_zoom_level(c->view,
1478 curconfig[ZoomLevel].val.f + 0.1);
1480 webkit_web_view_set_zoom_level(c->view,
1481 curconfig[ZoomLevel].val.f - 0.1);
1483 webkit_web_view_set_zoom_level(c->view, 1.0);
1485 curconfig[ZoomLevel].val.f = webkit_web_view_get_zoom_level(c->view);
1489 scroll(Client *c, const Arg *a)
1491 GdkEvent *ev = gdk_event_new(GDK_KEY_PRESS);
1493 gdk_event_set_device(ev, gdkkb);
1494 ev->key.window = gtk_widget_get_window(GTK_WIDGET(c->win));
1495 ev->key.state = GDK_CONTROL_MASK;
1496 ev->key.time = GDK_CURRENT_TIME;
1500 ev->key.keyval = GDK_KEY_Down;
1503 ev->key.keyval = GDK_KEY_Page_Down;
1506 ev->key.keyval = GDK_KEY_Left;
1509 ev->key.keyval = GDK_KEY_Right;
1512 ev->key.keyval = GDK_KEY_Page_Up;
1515 ev->key.keyval = GDK_KEY_Up;
1523 navigate(Client *c, const Arg *a)
1526 webkit_web_view_go_back(c->view);
1528 webkit_web_view_go_forward(c->view);
1532 stop(Client *c, const Arg *a)
1534 webkit_web_view_stop_loading(c->view);
1538 toggle(Client *c, const Arg *a)
1540 curconfig[a->i].val.b ^= 1;
1541 setparameter(c, 1, (ParamName)a->i, &curconfig[a->i].val);
1545 togglefullscreen(Client *c, const Arg *a)
1547 /* toggling value is handled in winevent() */
1549 gtk_window_unfullscreen(GTK_WINDOW(c->win));
1551 gtk_window_fullscreen(GTK_WINDOW(c->win));
1555 togglecookiepolicy(Client *c, const Arg *a)
1558 cookiepolicy %= strlen(curconfig[CookiePolicies].val.v);
1560 setparameter(c, 0, CookiePolicies, NULL);
1564 toggleinspector(Client *c, const Arg *a)
1566 if (webkit_web_inspector_is_attached(c->inspector))
1567 webkit_web_inspector_close(c->inspector);
1568 else if (curconfig[Inspector].val.b)
1569 webkit_web_inspector_show(c->inspector);
1573 find(Client *c, const Arg *a)
1579 webkit_find_controller_search_next(c->finder);
1581 webkit_find_controller_search_previous(c->finder);
1583 s = getatom(c, AtomFind);
1584 f = webkit_find_controller_get_search_text(c->finder);
1586 if (g_strcmp0(f, s) == 0) /* reset search */
1587 webkit_find_controller_search(c->finder, "", findopts,
1590 webkit_find_controller_search(c->finder, s, findopts,
1593 if (strcmp(s, "") == 0)
1594 webkit_find_controller_search_finish(c->finder);
1599 clicknavigate(Client *c, const Arg *a, WebKitHitTestResult *h)
1605 clicknewwindow(Client *c, const Arg *a, WebKitHitTestResult *h)
1609 arg.v = webkit_hit_test_result_get_link_uri(h);
1610 newwindow(c, &arg, a->b);
1614 clickexternplayer(Client *c, const Arg *a, WebKitHitTestResult *h)
1618 arg = (Arg)VIDEOPLAY(webkit_hit_test_result_get_media_uri(h));
1623 main(int argc, char *argv[])
1628 memset(&arg, 0, sizeof(arg));
1630 /* command line args */
1633 defconfig CSETV(CookiePolicies, EARGF(usage()));
1636 defconfig CSETB(ScrollBars, 0);
1639 defconfig CSETB(ScrollBars, 1);
1642 cookiefile = EARGF(usage());
1645 defconfig CSETB(DiskCache, 0);
1648 defconfig CSETB(DiskCache, 1);
1651 embed = strtol(EARGF(usage()), NULL, 0);
1654 defconfig CSETB(RunInFullscreen, 0);
1657 defconfig CSETB(RunInFullscreen, 1);
1660 defconfig CSETB(Geolocation, 0);
1663 defconfig CSETB(Geolocation, 1);
1666 defconfig CSETB(LoadImages, 0);
1669 defconfig CSETB(LoadImages, 1);
1672 defconfig CSETB(KioskMode, 0);
1675 defconfig CSETB(KioskMode, 1);
1678 defconfig CSETB(Style, 0);
1681 defconfig CSETB(Style, 1);
1684 defconfig CSETB(Inspector, 0);
1687 defconfig CSETB(Inspector, 1);
1690 defconfig CSETB(Plugins, 0);
1693 defconfig CSETB(Plugins, 1);
1696 scriptfile = EARGF(usage());
1699 defconfig CSETB(JavaScript, 0);
1702 defconfig CSETB(JavaScript, 1);
1705 stylefile = EARGF(usage());
1708 fulluseragent = EARGF(usage());
1711 die("surf-"VERSION", ©2009-2015 surf engineers, "
1712 "see LICENSE for details\n");
1717 defconfig CSETF(ZoomLevel, strtof(EARGF(usage()), NULL));
1725 arg.v = "about:blank";
1728 c = newclient(NULL);