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 GdkDevice *getkbdevice(void);
174 static WebKitWebView *newview(Client *c, WebKitWebView *rv);
175 static GtkWidget *createview(WebKitWebView *v, WebKitNavigationAction *a,
177 static gboolean buttonreleased(GtkWidget *w, GdkEvent *e, Client *c);
178 static GdkFilterReturn processx(GdkXEvent *xevent, GdkEvent *event,
180 static gboolean winevent(GtkWidget *w, GdkEvent *e, Client *c);
181 static void showview(WebKitWebView *v, Client *c);
182 static GtkWidget *createwindow(Client *c);
183 static void loadchanged(WebKitWebView *v, WebKitLoadEvent e, Client *c);
184 static void progresschanged(WebKitWebView *v, GParamSpec *ps, Client *c);
185 static void titlechanged(WebKitWebView *view, GParamSpec *ps, Client *c);
186 static void mousetargetchanged(WebKitWebView *v, WebKitHitTestResult *h,
187 guint modifiers, Client *c);
188 static gboolean permissionrequested(WebKitWebView *v,
189 WebKitPermissionRequest *r, Client *c);
190 static gboolean decidepolicy(WebKitWebView *v, WebKitPolicyDecision *d,
191 WebKitPolicyDecisionType dt, Client *c);
192 static void decidenavigation(WebKitPolicyDecision *d, Client *c);
193 static void decidenewwindow(WebKitPolicyDecision *d, Client *c);
194 static void decideresource(WebKitPolicyDecision *d, Client *c);
195 static void downloadstarted(WebKitWebContext *wc, WebKitDownload *d,
197 static void responsereceived(WebKitDownload *d, GParamSpec *ps, Client *c);
198 static void download(Client *c, WebKitURIResponse *r);
199 static void closeview(WebKitWebView *v, Client *c);
200 static void destroywin(GtkWidget* w, Client *c);
203 static void pasteuri(GtkClipboard *clipboard, const char *text, gpointer d);
204 static void reload(Client *c, const Arg *a);
205 static void print(Client *c, const Arg *a);
206 static void clipboard(Client *c, const Arg *a);
207 static void zoom(Client *c, const Arg *a);
208 static void scroll(Client *c, const Arg *a);
209 static void navigate(Client *c, const Arg *a);
210 static void stop(Client *c, const Arg *a);
211 static void toggle(Client *c, const Arg *a);
212 static void togglefullscreen(Client *c, const Arg *a);
213 static void togglecookiepolicy(Client *c, const Arg *a);
214 static void toggleinspector(Client *c, const Arg *a);
215 static void find(Client *c, const Arg *a);
218 static void clicknavigate(Client *c, const Arg *a, WebKitHitTestResult *h);
219 static void clicknewwindow(Client *c, const Arg *a, WebKitHitTestResult *h);
220 static void clickexternplayer(Client *c, const Arg *a, WebKitHitTestResult *h);
222 static char winid[64];
223 static char togglestats[10];
224 static char pagestats[2];
225 static Atom atoms[AtomLast];
228 static int cookiepolicy;
230 static Client *clients;
231 static GdkDevice *gdkkb;
232 static char *stylefile;
233 static const char *useragent;
234 static Parameter *curconfig;
237 /* configuration, allows nested code to access above variables */
243 die("usage: %s [-bBdDfFgGiIkKmMnNpPsSvx] [-a cookiepolicies ] "
244 "[-c cookiefile] [-e xid] [-r scriptfile] [-t stylefile] "
245 "[-u useragent] [-z zoomlevel] [uri]\n", basename(argv0));
249 die(const char *errstr, ...)
253 va_start(ap, errstr);
254 vfprintf(stderr, errstr, ap);
264 /* clean up any zombies immediately */
266 gtk_init(NULL, NULL);
268 dpy = GDK_DISPLAY_XDISPLAY(gdk_display_get_default());
270 curconfig = defconfig;
273 atoms[AtomFind] = XInternAtom(dpy, "_SURF_FIND", False);
274 atoms[AtomGo] = XInternAtom(dpy, "_SURF_GO", False);
275 atoms[AtomUri] = XInternAtom(dpy, "_SURF_URI", False);
278 cookiefile = buildfile(cookiefile);
279 scriptfile = buildfile(scriptfile);
280 cachedir = buildpath(cachedir);
282 gdkkb = getkbdevice();
285 styledir = buildpath(styledir);
286 for (i = 0; i < LENGTH(styles); ++i) {
287 if (regcomp(&(styles[i].re), styles[i].regex,
290 "Could not compile regex: %s\n",
292 styles[i].regex = NULL;
294 styles[i].style = g_strconcat(styledir, "/",
295 styles[i].style, NULL);
299 stylefile = buildfile(stylefile);
302 for (i = 0; i < LENGTH(uriparams); ++i) {
303 if (!regcomp(&(uriparams[i].re), uriparams[i].uri,
305 /* copy default parameters if they are not already set
306 * or if they are forced */
307 for (j = 0; j < ParameterLast; ++j) {
308 if (!uriparams[i].config[j].force ||
310 uriparams[i].config[j] = defconfig[j];
314 "Could not compile regex: %s\n",
316 uriparams[i].uri = NULL;
324 if (signal(SIGCHLD, sigchld) == SIG_ERR)
325 die("Can't install SIGCHLD handler");
326 while (waitpid(-1, NULL, WNOHANG) > 0)
331 buildfile(const char *path)
333 char *dname, *bname, *bpath, *fpath;
336 dname = g_path_get_dirname(path);
337 bname = g_path_get_basename(path);
339 bpath = buildpath(dname);
342 fpath = g_build_filename(bpath, bname, NULL);
346 if (!(f = fopen(fpath, "a")))
347 die("Could not open file: %s\n", fpath);
349 g_chmod(fpath, 0600); /* always */
356 getuserhomedir(const char *user)
358 struct passwd *pw = getpwnam(user);
361 die("Can't get user %s login information.\n", user);
367 getcurrentuserhomedir(void)
373 homedir = getenv("HOME");
377 user = getenv("USER");
379 return getuserhomedir(user);
381 pw = getpwuid(getuid());
383 die("Can't get current user home directory\n");
389 buildpath(const char *path)
391 char *apath, *name, *p, *fpath;
394 if (path[0] == '~') {
395 if (path[1] == '/' || path[1] == '\0') {
396 p = (char *)&path[1];
397 homedir = getcurrentuserhomedir();
399 if ((p = strchr(path, '/')))
400 name = g_strndup(&path[1], --p - path);
402 name = g_strdup(&path[1]);
404 homedir = getuserhomedir(name);
407 apath = g_build_filename(homedir, p, NULL);
409 apath = g_strdup(path);
412 /* creating directory */
413 if (g_mkdir_with_parents(apath, 0700) < 0)
414 die("Could not access directory: %s\n", apath);
416 fpath = realpath(apath, NULL);
423 newclient(Client *rc)
427 if (!(c = calloc(1, sizeof(Client))))
428 die("Cannot malloc!\n");
434 c->tlsflags = G_TLS_CERTIFICATE_VALIDATE_ALL + 1;
435 c->view = newview(c, rc ? rc->view : NULL);
441 loaduri(Client *c, const Arg *a)
445 const char *uri = a->v;
447 if (g_strcmp0(uri, "") == 0)
450 if (g_str_has_prefix(uri, "http://") ||
451 g_str_has_prefix(uri, "https://") ||
452 g_str_has_prefix(uri, "file://") ||
453 g_str_has_prefix(uri, "about:")) {
455 } else if (!stat(uri, &st) && (path = realpath(uri, NULL))) {
456 url = g_strdup_printf("file://%s", path);
459 url = g_strdup_printf("http://%s", uri);
462 setatom(c, AtomUri, url);
464 if (strcmp(url, geturi(c)) == 0) {
467 webkit_web_view_load_uri(c->view, url);
479 if (!(uri = webkit_web_view_get_uri(c->view)))
485 setatom(Client *c, int a, const char *v)
488 XChangeProperty(dpy, c->xid,
489 atoms[a], XA_STRING, 8, PropModeReplace,
490 (unsigned char *)v, strlen(v) + 1);
494 getatom(Client *c, int a)
496 static char buf[BUFSIZ];
499 unsigned long ldummy;
500 unsigned char *p = NULL;
502 XGetWindowProperty(dpy, c->xid, atoms[a], 0L, BUFSIZ, False, XA_STRING,
503 &adummy, &idummy, &ldummy, &ldummy, &p);
505 strncpy(buf, (char *)p, LENGTH(buf) - 1);
514 updatetitle(Client *c)
517 const char *name = c->overtitle ? c->overtitle :
518 c->title ? c->title : "";
520 if (curconfig[ShowIndicators].val.b) {
524 if (c->progress != 100)
525 title = g_strdup_printf("[%i%%] %s:%s | %s",
526 c->progress, togglestats, pagestats, name);
528 title = g_strdup_printf("%s:%s | %s",
529 togglestats, pagestats, name);
531 gtk_window_set_title(GTK_WINDOW(c->win), title);
534 gtk_window_set_title(GTK_WINDOW(c->win), name);
539 gettogglestats(Client *c)
541 togglestats[0] = cookiepolicy_set(cookiepolicy_get());
542 togglestats[1] = curconfig[CaretBrowsing].val.b ? 'C' : 'c';
543 togglestats[2] = curconfig[Geolocation].val.b ? 'G' : 'g';
544 togglestats[3] = curconfig[DiskCache].val.b ? 'D' : 'd';
545 togglestats[4] = curconfig[LoadImages].val.b ? 'I' : 'i';
546 togglestats[5] = curconfig[JavaScript].val.b ? 'S' : 's';
547 togglestats[6] = curconfig[Plugins].val.b ? 'V' : 'v';
548 togglestats[7] = curconfig[Style].val.b ? 'M' : 'm';
549 togglestats[8] = curconfig[FrameFlattening].val.b ? 'F' : 'f';
550 togglestats[9] = '\0';
554 getpagestats(Client *c)
556 pagestats[0] = c->tlsflags > G_TLS_CERTIFICATE_VALIDATE_ALL ? '-' :
557 c->tlsflags > 0 ? 'U' : 'T';
561 WebKitCookieAcceptPolicy
562 cookiepolicy_get(void)
564 switch (((char *)curconfig[CookiePolicies].val.v)[cookiepolicy]) {
566 return WEBKIT_COOKIE_POLICY_ACCEPT_NEVER;
568 return WEBKIT_COOKIE_POLICY_ACCEPT_NO_THIRD_PARTY;
569 default: /* fallthrough */
571 return WEBKIT_COOKIE_POLICY_ACCEPT_ALWAYS;
576 cookiepolicy_set(const WebKitCookieAcceptPolicy p)
579 case WEBKIT_COOKIE_POLICY_ACCEPT_NEVER:
581 case WEBKIT_COOKIE_POLICY_ACCEPT_NO_THIRD_PARTY:
583 default: /* fallthrough */
584 case WEBKIT_COOKIE_POLICY_ACCEPT_ALWAYS:
590 seturiparameters(Client *c, const char *uri)
594 for (i = 0; i < LENGTH(uriparams); ++i) {
595 if (uriparams[i].uri &&
596 !regexec(&(uriparams[i].re), uri, 0, NULL, 0)) {
597 curconfig = uriparams[i].config;
602 for (i = 0; i < ParameterLast; ++i)
603 setparameter(c, 0, i, &curconfig[i].val);
607 setparameter(Client *c, int refresh, ParamName p, const Arg *a)
609 GdkRGBA bgcolor = { 0 };
610 WebKitSettings *s = webkit_web_view_get_settings(c->view);
614 webkit_settings_set_enable_caret_browsing(s, a->b);
618 webkit_cookie_manager_set_accept_policy(
619 webkit_web_context_get_cookie_manager(
620 webkit_web_view_get_context(c->view)),
625 webkit_web_context_set_cache_model(
626 webkit_web_view_get_context(c->view), a->b ?
627 WEBKIT_CACHE_MODEL_WEB_BROWSER :
628 WEBKIT_CACHE_MODEL_DOCUMENT_VIEWER);
629 return; /* do not update */
631 webkit_settings_set_enable_dns_prefetching(s, a->b);
632 return; /* do not update */
634 webkit_settings_set_default_font_size(s, a->i);
635 return; /* do not update */
636 case FrameFlattening:
637 webkit_settings_set_enable_frame_flattening(s, a->b);
644 webkit_web_view_set_background_color(c->view, &bgcolor);
645 return; /* do not update */
647 webkit_settings_set_enable_developer_extras(s, a->b);
648 return; /* do not update */
650 webkit_settings_set_enable_javascript(s, a->b);
653 return; /* do nothing */
655 webkit_settings_set_auto_load_images(s, a->b);
658 webkit_settings_set_enable_plugins(s, a->b);
660 case PreferredLanguages:
661 return; /* do nothing */
662 case RunInFullscreen:
663 return; /* do nothing */
665 /* Disabled until we write some WebKitWebExtension for
666 * manipulating the DOM directly.
667 enablescrollbars = !enablescrollbars;
668 evalscript(c, "document.documentElement.style.overflow = '%s'",
669 enablescrollbars ? "auto" : "hidden");
671 return; /* do not update */
675 webkit_web_context_set_spell_checking_enabled(
676 webkit_web_view_get_context(c->view), a->b);
677 return; /* do not update */
679 return; /* do nothing */
681 webkit_web_context_set_tls_errors_policy(
682 webkit_web_view_get_context(c->view), a->b ?
683 WEBKIT_TLS_ERRORS_POLICY_FAIL :
684 WEBKIT_TLS_ERRORS_POLICY_IGNORE);
685 return; /* do not update */
688 setstyle(c, getstyle(geturi(c)));
690 webkit_user_content_manager_remove_all_style_sheets(
691 webkit_web_view_get_user_content_manager(c->view));
695 webkit_web_view_set_zoom_level(c->view, a->f);
696 return; /* do not update */
698 return; /* do nothing */
707 getstyle(const char *uri)
714 for (i = 0; i < LENGTH(styles); ++i) {
715 if (styles[i].regex &&
716 !regexec(&(styles[i].re), uri, 0, NULL, 0))
717 return styles[i].style;
724 setstyle(Client *c, const char *stylefile)
728 if (!g_file_get_contents(stylefile, &style, NULL, NULL)) {
729 fprintf(stderr, "Could not read style file: %s\n", stylefile);
733 webkit_user_content_manager_add_style_sheet(
734 webkit_web_view_get_user_content_manager(c->view),
735 webkit_user_style_sheet_new(style,
736 WEBKIT_USER_CONTENT_INJECT_ALL_FRAMES,
737 WEBKIT_USER_STYLE_LEVEL_USER,
749 if (g_file_get_contents(scriptfile, &script, &l, NULL) && l)
750 evalscript(c, script);
755 evalscript(Client *c, const char *jsstr, ...)
761 script = g_strdup_vprintf(jsstr, ap);
764 webkit_web_view_run_javascript(c->view, script, NULL, NULL, NULL);
769 updatewinid(Client *c)
771 snprintf(winid, LENGTH(winid), "%lu", c->xid);
775 handleplumb(Client *c, const char *uri)
777 Arg a = (Arg)PLUMB(uri);
782 newwindow(Client *c, const Arg *a, int noembed)
786 const char *cmd[26], *uri;
787 const Arg arg = { .v = cmd };
791 cmd[i++] = curconfig[CookiePolicies].val.v;
792 cmd[i++] = curconfig[ScrollBars].val.b ? "-B" : "-b";
793 if (cookiefile && g_strcmp0(cookiefile, "")) {
795 cmd[i++] = cookiefile;
797 cmd[i++] = curconfig[DiskCache].val.b ? "-D" : "-d";
798 if (embed && !noembed) {
800 snprintf(tmp, LENGTH(tmp), "%lu", embed);
803 cmd[i++] = curconfig[RunInFullscreen].val.b ? "-F" : "-f" ;
804 cmd[i++] = curconfig[Geolocation].val.b ? "-G" : "-g" ;
805 cmd[i++] = curconfig[LoadImages].val.b ? "-I" : "-i" ;
806 cmd[i++] = curconfig[KioskMode].val.b ? "-K" : "-k" ;
807 cmd[i++] = curconfig[Style].val.b ? "-M" : "-m" ;
808 cmd[i++] = curconfig[Inspector].val.b ? "-N" : "-n" ;
809 cmd[i++] = curconfig[Plugins].val.b ? "-P" : "-p" ;
810 if (scriptfile && g_strcmp0(scriptfile, "")) {
812 cmd[i++] = scriptfile;
814 cmd[i++] = curconfig[JavaScript].val.b ? "-S" : "-s";
815 if (stylefile && g_strcmp0(stylefile, "")) {
817 cmd[i++] = stylefile;
819 if (fulluseragent && g_strcmp0(fulluseragent, "")) {
821 cmd[i++] = fulluseragent;
825 /* do not keep zoom level */
835 spawn(Client *c, const Arg *a)
839 close(ConnectionNumber(dpy));
841 execvp(((char **)a->v)[0], (char **)a->v);
842 fprintf(stderr, "%s: execvp %s", argv0, ((char **)a->v)[0]);
849 destroyclient(Client *c)
853 webkit_web_view_stop_loading(c->view);
854 /* Not needed, has already been called
855 gtk_widget_destroy(c->win);
858 for (p = clients; p && p->next != c; p = p->next)
871 destroyclient(clients);
881 GList *l, *gdl = gdk_device_manager_list_devices(
882 gdk_display_get_device_manager(gdk_display_get_default()),
883 GDK_DEVICE_TYPE_MASTER);
884 GdkDevice *gd = NULL;
886 for (l = gdl; l != NULL; l = l->next)
887 if (gdk_device_get_source(l->data) == GDK_SOURCE_KEYBOARD)
895 newview(Client *c, WebKitWebView *rv)
898 WebKitSettings *settings;
899 WebKitUserContentManager *contentmanager;
900 WebKitWebContext *context;
905 webkit_web_view_new_with_related_view(rv));
907 settings = webkit_settings_new_with_settings(
908 "auto-load-images", curconfig[LoadImages].val.b,
909 "default-font-size", curconfig[FontSize].val.f,
910 "enable-caret-browsing", curconfig[CaretBrowsing].val.b,
911 "enable-developer-extras", curconfig[Inspector].val.b,
912 "enable-dns-prefetching", curconfig[DNSPrefetch].val.b,
913 "enable-frame-flattening", curconfig[FrameFlattening].val.b,
914 "enable-html5-database", curconfig[DiskCache].val.b,
915 "enable-html5-local-storage", curconfig[DiskCache].val.b,
916 "enable-javascript", curconfig[JavaScript].val.b,
917 "enable-plugins", curconfig[Plugins].val.b,
919 /* For mor interesting settings, have a look at
920 * http://webkitgtk.org/reference/webkit2gtk/stable/WebKitSettings.html */
922 if (strcmp(fulluseragent, "")) {
923 webkit_settings_set_user_agent(settings, fulluseragent);
924 } else if (surfuseragent) {
925 webkit_settings_set_user_agent_with_application_details(
926 settings, "Surf", VERSION);
928 useragent = webkit_settings_get_user_agent(settings);
930 contentmanager = webkit_user_content_manager_new();
932 context = webkit_web_context_new_with_website_data_manager(
933 webkit_website_data_manager_new(
934 "base-cache-directory", cachedir,
935 "base-data-directory", cachedir,
938 /* rendering process model, can be a shared unique one
939 * or one for each view */
940 webkit_web_context_set_process_model(context,
941 WEBKIT_PROCESS_MODEL_MULTIPLE_SECONDARY_PROCESSES);
943 webkit_web_context_set_tls_errors_policy(context,
944 curconfig[StrictSSL].val.b ? WEBKIT_TLS_ERRORS_POLICY_FAIL :
945 WEBKIT_TLS_ERRORS_POLICY_IGNORE);
947 webkit_web_context_set_cache_model(context,
948 curconfig[DiskCache].val.b ? WEBKIT_CACHE_MODEL_WEB_BROWSER :
949 WEBKIT_CACHE_MODEL_DOCUMENT_VIEWER);
951 /* Currently only works with text file to be compatible with curl */
952 webkit_cookie_manager_set_persistent_storage(
953 webkit_web_context_get_cookie_manager(context), cookiefile,
954 WEBKIT_COOKIE_PERSISTENT_STORAGE_TEXT);
956 webkit_cookie_manager_set_accept_policy(
957 webkit_web_context_get_cookie_manager(context),
960 webkit_web_context_set_preferred_languages(context,
961 curconfig[PreferredLanguages].val.v);
962 webkit_web_context_set_spell_checking_languages(context,
963 curconfig[SpellLanguages].val.v);
964 webkit_web_context_set_spell_checking_enabled(context,
965 curconfig[SpellChecking].val.b);
967 g_signal_connect(G_OBJECT(context), "download-started",
968 G_CALLBACK(downloadstarted), c);
970 v = g_object_new(WEBKIT_TYPE_WEB_VIEW,
971 "settings", settings,
972 "user-content-manager", contentmanager,
973 "web-context", context,
977 g_signal_connect(G_OBJECT(v), "notify::estimated-load-progress",
978 G_CALLBACK(progresschanged), c);
979 g_signal_connect(G_OBJECT(v), "notify::title",
980 G_CALLBACK(titlechanged), c);
981 g_signal_connect(G_OBJECT(v), "button-release-event",
982 G_CALLBACK(buttonreleased), c);
983 g_signal_connect(G_OBJECT(v), "close",
984 G_CALLBACK(closeview), c);
985 g_signal_connect(G_OBJECT(v), "create",
986 G_CALLBACK(createview), c);
987 g_signal_connect(G_OBJECT(v), "decide-policy",
988 G_CALLBACK(decidepolicy), c);
989 g_signal_connect(G_OBJECT(v), "load-changed",
990 G_CALLBACK(loadchanged), c);
991 g_signal_connect(G_OBJECT(v), "mouse-target-changed",
992 G_CALLBACK(mousetargetchanged), c);
993 g_signal_connect(G_OBJECT(v), "permission-request",
994 G_CALLBACK(permissionrequested), c);
995 g_signal_connect(G_OBJECT(v), "ready-to-show",
996 G_CALLBACK(showview), c);
1002 createview(WebKitWebView *v, WebKitNavigationAction *a, Client *c)
1006 switch (webkit_navigation_action_get_navigation_type(a)) {
1007 case WEBKIT_NAVIGATION_TYPE_OTHER: /* fallthrough */
1009 * popup windows of type “other” are almost always triggered
1010 * by user gesture, so inverse the logic here
1012 /* instead of this, compare destination uri to mouse-over uri for validating window */
1013 if (webkit_navigation_action_is_user_gesture(a))
1015 case WEBKIT_NAVIGATION_TYPE_LINK_CLICKED: /* fallthrough */
1016 case WEBKIT_NAVIGATION_TYPE_FORM_SUBMITTED: /* fallthrough */
1017 case WEBKIT_NAVIGATION_TYPE_BACK_FORWARD: /* fallthrough */
1018 case WEBKIT_NAVIGATION_TYPE_RELOAD: /* fallthrough */
1019 case WEBKIT_NAVIGATION_TYPE_FORM_RESUBMITTED:
1026 return GTK_WIDGET(n->view);
1030 buttonreleased(GtkWidget *w, GdkEvent *e, Client *c)
1032 WebKitHitTestResultContext element;
1035 element = webkit_hit_test_result_get_context(c->mousepos);
1037 for (i = 0; i < LENGTH(buttons); ++i) {
1038 if (element & buttons[i].target &&
1039 e->button.button == buttons[i].button &&
1040 CLEANMASK(e->button.state) == CLEANMASK(buttons[i].mask) &&
1042 buttons[i].func(c, &buttons[i].arg, c->mousepos);
1043 return buttons[i].stopevent;
1051 processx(GdkXEvent *e, GdkEvent *event, gpointer d)
1053 Client *c = (Client *)d;
1057 if (((XEvent *)e)->type == PropertyNotify) {
1058 ev = &((XEvent *)e)->xproperty;
1059 if (ev->state == PropertyNewValue) {
1060 if (ev->atom == atoms[AtomFind]) {
1063 return GDK_FILTER_REMOVE;
1064 } else if (ev->atom == atoms[AtomGo]) {
1065 a.v = getatom(c, AtomGo);
1068 return GDK_FILTER_REMOVE;
1072 return GDK_FILTER_CONTINUE;
1076 winevent(GtkWidget *w, GdkEvent *e, Client *c)
1081 case GDK_ENTER_NOTIFY:
1082 c->overtitle = c->targeturi;
1086 if (!curconfig[KioskMode].val.b) {
1087 for (i = 0; i < LENGTH(keys); ++i) {
1088 if (gdk_keyval_to_lower(e->key.keyval) ==
1090 CLEANMASK(e->key.state) == keys[i].mod &&
1093 keys[i].func(c, &(keys[i].arg));
1098 case GDK_LEAVE_NOTIFY:
1099 c->overtitle = NULL;
1102 case GDK_WINDOW_STATE:
1103 if (e->window_state.changed_mask ==
1104 GDK_WINDOW_STATE_FULLSCREEN)
1105 c->fullscreen = e->window_state.new_window_state &
1106 GDK_WINDOW_STATE_FULLSCREEN;
1116 showview(WebKitWebView *v, Client *c)
1118 GdkRGBA bgcolor = { 0 };
1121 c->finder = webkit_web_view_get_find_controller(c->view);
1122 c->inspector = webkit_web_view_get_inspector(c->view);
1124 c->win = createwindow(c);
1126 gtk_container_add(GTK_CONTAINER(c->win), GTK_WIDGET(c->view));
1127 gtk_widget_show_all(c->win);
1128 gtk_widget_grab_focus(GTK_WIDGET(c->view));
1130 gwin = gtk_widget_get_window(GTK_WIDGET(c->win));
1131 c->xid = gdk_x11_window_get_xid(gwin);
1134 gdk_display_sync(gtk_widget_get_display(c->win));
1138 if (curconfig[HideBackground].val.b)
1139 webkit_web_view_set_background_color(c->view, &bgcolor);
1141 if (!curconfig[KioskMode].val.b) {
1142 gdk_window_set_events(gwin, GDK_ALL_EVENTS_MASK);
1143 gdk_window_add_filter(gwin, processx, c);
1146 if (curconfig[RunInFullscreen].val.b)
1147 togglefullscreen(c, NULL);
1149 if (curconfig[ZoomLevel].val.f != 1.0)
1150 webkit_web_view_set_zoom_level(c->view,
1151 curconfig[ZoomLevel].val.f);
1153 setatom(c, AtomFind, "");
1154 setatom(c, AtomUri, "about:blank");
1158 createwindow(Client *c)
1164 w = gtk_plug_new(embed);
1166 w = gtk_window_new(GTK_WINDOW_TOPLEVEL);
1168 wmstr = g_path_get_basename(argv0);
1169 gtk_window_set_wmclass(GTK_WINDOW(w), wmstr, "Surf");
1172 wmstr = g_strdup_printf("%s[%lu]", "Surf",
1173 webkit_web_view_get_page_id(c->view));
1174 gtk_window_set_role(GTK_WINDOW(w), wmstr);
1177 gtk_window_set_default_size(GTK_WINDOW(w), 800, 600);
1180 g_signal_connect(G_OBJECT(w), "destroy",
1181 G_CALLBACK(destroywin), c);
1182 g_signal_connect(G_OBJECT(w), "enter-notify-event",
1183 G_CALLBACK(winevent), c);
1184 g_signal_connect(G_OBJECT(w), "key-press-event",
1185 G_CALLBACK(winevent), c);
1186 g_signal_connect(G_OBJECT(w), "leave-notify-event",
1187 G_CALLBACK(winevent), c);
1188 g_signal_connect(G_OBJECT(w), "window-state-event",
1189 G_CALLBACK(winevent), c);
1195 loadchanged(WebKitWebView *v, WebKitLoadEvent e, Client *c)
1197 const char *title = geturi(c);
1200 case WEBKIT_LOAD_STARTED:
1201 curconfig = defconfig;
1202 setatom(c, AtomUri, title);
1204 c->tlsflags = G_TLS_CERTIFICATE_VALIDATE_ALL + 1;
1205 seturiparameters(c, geturi(c));
1207 case WEBKIT_LOAD_REDIRECTED:
1208 setatom(c, AtomUri, title);
1210 seturiparameters(c, geturi(c));
1212 case WEBKIT_LOAD_COMMITTED:
1213 if (!webkit_web_view_get_tls_info(c->view, NULL,
1215 c->tlsflags = G_TLS_CERTIFICATE_VALIDATE_ALL + 1;
1218 case WEBKIT_LOAD_FINISHED:
1219 /* Disabled until we write some WebKitWebExtension for
1220 * manipulating the DOM directly.
1221 evalscript(c, "document.documentElement.style.overflow = '%s'",
1222 enablescrollbars ? "auto" : "hidden");
1231 progresschanged(WebKitWebView *v, GParamSpec *ps, Client *c)
1233 c->progress = webkit_web_view_get_estimated_load_progress(c->view) *
1239 titlechanged(WebKitWebView *view, GParamSpec *ps, Client *c)
1241 c->title = webkit_web_view_get_title(c->view);
1246 mousetargetchanged(WebKitWebView *v, WebKitHitTestResult *h, guint modifiers,
1249 WebKitHitTestResultContext hc = webkit_hit_test_result_get_context(h);
1251 /* Keep the hit test to know where is the pointer on the next click */
1255 c->targeturi = webkit_hit_test_result_get_link_uri(h);
1256 else if (hc & OnImg)
1257 c->targeturi = webkit_hit_test_result_get_image_uri(h);
1258 else if (hc & OnMedia)
1259 c->targeturi = webkit_hit_test_result_get_media_uri(h);
1261 c->targeturi = NULL;
1263 c->overtitle = c->targeturi;
1268 permissionrequested(WebKitWebView *v, WebKitPermissionRequest *r, Client *c)
1270 if (WEBKIT_IS_GEOLOCATION_PERMISSION_REQUEST(r)) {
1271 if (curconfig[Geolocation].val.b)
1272 webkit_permission_request_allow(r);
1274 webkit_permission_request_deny(r);
1282 decidepolicy(WebKitWebView *v, WebKitPolicyDecision *d,
1283 WebKitPolicyDecisionType dt, Client *c)
1286 case WEBKIT_POLICY_DECISION_TYPE_NAVIGATION_ACTION:
1287 decidenavigation(d, c);
1289 case WEBKIT_POLICY_DECISION_TYPE_NEW_WINDOW_ACTION:
1290 decidenewwindow(d, c);
1292 case WEBKIT_POLICY_DECISION_TYPE_RESPONSE:
1293 decideresource(d, c);
1296 webkit_policy_decision_ignore(d);
1303 decidenavigation(WebKitPolicyDecision *d, Client *c)
1305 WebKitNavigationAction *a =
1306 webkit_navigation_policy_decision_get_navigation_action(
1307 WEBKIT_NAVIGATION_POLICY_DECISION(d));
1309 switch (webkit_navigation_action_get_navigation_type(a)) {
1310 case WEBKIT_NAVIGATION_TYPE_LINK_CLICKED: /* fallthrough */
1311 case WEBKIT_NAVIGATION_TYPE_FORM_SUBMITTED: /* fallthrough */
1312 case WEBKIT_NAVIGATION_TYPE_BACK_FORWARD: /* fallthrough */
1313 case WEBKIT_NAVIGATION_TYPE_RELOAD: /* fallthrough */
1314 case WEBKIT_NAVIGATION_TYPE_FORM_RESUBMITTED: /* fallthrough */
1315 case WEBKIT_NAVIGATION_TYPE_OTHER: /* fallthrough */
1317 /* Do not navigate to links with a "_blank" target (popup) */
1318 if (webkit_navigation_policy_decision_get_frame_name(
1319 WEBKIT_NAVIGATION_POLICY_DECISION(d))) {
1320 webkit_policy_decision_ignore(d);
1322 /* Filter out navigation to different domain ? */
1323 /* get action→urirequest, copy and load in new window+view
1324 * on Ctrl+Click ? */
1325 webkit_policy_decision_use(d);
1332 decidenewwindow(WebKitPolicyDecision *d, Client *c)
1335 WebKitNavigationAction *a =
1336 webkit_navigation_policy_decision_get_navigation_action(
1337 WEBKIT_NAVIGATION_POLICY_DECISION(d));
1340 switch (webkit_navigation_action_get_navigation_type(a)) {
1341 case WEBKIT_NAVIGATION_TYPE_LINK_CLICKED: /* fallthrough */
1342 case WEBKIT_NAVIGATION_TYPE_FORM_SUBMITTED: /* fallthrough */
1343 case WEBKIT_NAVIGATION_TYPE_BACK_FORWARD: /* fallthrough */
1344 case WEBKIT_NAVIGATION_TYPE_RELOAD: /* fallthrough */
1345 case WEBKIT_NAVIGATION_TYPE_FORM_RESUBMITTED:
1346 /* Filter domains here */
1347 /* If the value of “mouse-button” is not 0, then the navigation was triggered by a mouse event.
1348 * test for link clicked but no button ? */
1349 arg.v = webkit_uri_request_get_uri(
1350 webkit_navigation_action_get_request(a));
1351 newwindow(c, &arg, 0);
1353 case WEBKIT_NAVIGATION_TYPE_OTHER: /* fallthrough */
1358 webkit_policy_decision_ignore(d);
1362 decideresource(WebKitPolicyDecision *d, Client *c)
1365 WebKitResponsePolicyDecision *r = WEBKIT_RESPONSE_POLICY_DECISION(d);
1366 WebKitURIResponse *res =
1367 webkit_response_policy_decision_get_response(r);
1368 const gchar *uri = webkit_uri_response_get_uri(res);
1370 if (g_str_has_suffix(uri, "/favicon.ico")) {
1371 webkit_policy_decision_ignore(d);
1375 if (!g_str_has_prefix(uri, "http://")
1376 && !g_str_has_prefix(uri, "https://")
1377 && !g_str_has_prefix(uri, "about:")
1378 && !g_str_has_prefix(uri, "file://")
1379 && !g_str_has_prefix(uri, "data:")
1380 && !g_str_has_prefix(uri, "blob:")
1381 && strlen(uri) > 0) {
1382 for (i = 0; i < strlen(uri); i++) {
1383 if (!g_ascii_isprint(uri[i])) {
1389 handleplumb(c, uri);
1390 webkit_policy_decision_ignore(d);
1395 if (webkit_response_policy_decision_is_mime_type_supported(r)) {
1396 webkit_policy_decision_use(d);
1398 webkit_policy_decision_ignore(d);
1404 downloadstarted(WebKitWebContext *wc, WebKitDownload *d, Client *c)
1406 g_signal_connect(G_OBJECT(d), "notify::response",
1407 G_CALLBACK(responsereceived), c);
1411 responsereceived(WebKitDownload *d, GParamSpec *ps, Client *c)
1413 download(c, webkit_download_get_response(d));
1414 webkit_download_cancel(d);
1418 download(Client *c, WebKitURIResponse *r)
1420 Arg a = (Arg)DOWNLOAD(webkit_uri_response_get_uri(r), geturi(c));
1425 closeview(WebKitWebView *v, Client *c)
1427 gtk_widget_destroy(c->win);
1431 destroywin(GtkWidget* w, Client *c)
1439 pasteuri(GtkClipboard *clipboard, const char *text, gpointer d)
1441 Arg a = {.v = text };
1443 loaduri((Client *) d, &a);
1447 reload(Client *c, const Arg *a)
1450 webkit_web_view_reload_bypass_cache(c->view);
1452 webkit_web_view_reload(c->view);
1456 print(Client *c, const Arg *a)
1458 webkit_print_operation_run_dialog(webkit_print_operation_new(c->view),
1459 GTK_WINDOW(c->win));
1463 clipboard(Client *c, const Arg *a)
1465 if (a->b) { /* load clipboard uri */
1466 gtk_clipboard_request_text(gtk_clipboard_get(
1467 GDK_SELECTION_PRIMARY),
1469 } else { /* copy uri */
1470 gtk_clipboard_set_text(gtk_clipboard_get(
1471 GDK_SELECTION_PRIMARY), c->targeturi
1472 ? c->targeturi : geturi(c), -1);
1477 zoom(Client *c, const Arg *a)
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,
1484 curconfig[ZoomLevel].val.f - 0.1);
1486 webkit_web_view_set_zoom_level(c->view, 1.0);
1488 curconfig[ZoomLevel].val.f = webkit_web_view_get_zoom_level(c->view);
1492 scroll(Client *c, const Arg *a)
1494 GdkEvent *ev = gdk_event_new(GDK_KEY_PRESS);
1496 gdk_event_set_device(ev, gdkkb);
1497 ev->key.window = gtk_widget_get_window(GTK_WIDGET(c->win));
1498 ev->key.state = GDK_CONTROL_MASK;
1499 ev->key.time = GDK_CURRENT_TIME;
1503 ev->key.keyval = GDK_KEY_Down;
1506 ev->key.keyval = GDK_KEY_Page_Down;
1509 ev->key.keyval = GDK_KEY_Left;
1512 ev->key.keyval = GDK_KEY_Right;
1515 ev->key.keyval = GDK_KEY_Page_Up;
1518 ev->key.keyval = GDK_KEY_Up;
1526 navigate(Client *c, const Arg *a)
1529 webkit_web_view_go_back(c->view);
1531 webkit_web_view_go_forward(c->view);
1535 stop(Client *c, const Arg *a)
1537 webkit_web_view_stop_loading(c->view);
1541 toggle(Client *c, const Arg *a)
1543 curconfig[a->i].val.b ^= 1;
1544 setparameter(c, 1, (ParamName)a->i, &curconfig[a->i].val);
1548 togglefullscreen(Client *c, const Arg *a)
1550 /* toggling value is handled in winevent() */
1552 gtk_window_unfullscreen(GTK_WINDOW(c->win));
1554 gtk_window_fullscreen(GTK_WINDOW(c->win));
1558 togglecookiepolicy(Client *c, const Arg *a)
1561 cookiepolicy %= strlen(curconfig[CookiePolicies].val.v);
1563 setparameter(c, 0, CookiePolicies, NULL);
1567 toggleinspector(Client *c, const Arg *a)
1569 if (webkit_web_inspector_is_attached(c->inspector))
1570 webkit_web_inspector_close(c->inspector);
1571 else if (curconfig[Inspector].val.b)
1572 webkit_web_inspector_show(c->inspector);
1576 find(Client *c, const Arg *a)
1582 webkit_find_controller_search_next(c->finder);
1584 webkit_find_controller_search_previous(c->finder);
1586 s = getatom(c, AtomFind);
1587 f = webkit_find_controller_get_search_text(c->finder);
1589 if (g_strcmp0(f, s) == 0) /* reset search */
1590 webkit_find_controller_search(c->finder, "", findopts,
1593 webkit_find_controller_search(c->finder, s, findopts,
1596 if (strcmp(s, "") == 0)
1597 webkit_find_controller_search_finish(c->finder);
1602 clicknavigate(Client *c, const Arg *a, WebKitHitTestResult *h)
1608 clicknewwindow(Client *c, const Arg *a, WebKitHitTestResult *h)
1612 arg.v = webkit_hit_test_result_get_link_uri(h);
1613 newwindow(c, &arg, a->b);
1617 clickexternplayer(Client *c, const Arg *a, WebKitHitTestResult *h)
1621 arg = (Arg)VIDEOPLAY(webkit_hit_test_result_get_media_uri(h));
1626 main(int argc, char *argv[])
1631 memset(&arg, 0, sizeof(arg));
1633 /* command line args */
1636 defconfig CSETV(CookiePolicies, EARGF(usage()));
1639 defconfig CSETB(ScrollBars, 0);
1642 defconfig CSETB(ScrollBars, 1);
1645 cookiefile = EARGF(usage());
1648 defconfig CSETB(DiskCache, 0);
1651 defconfig CSETB(DiskCache, 1);
1654 embed = strtol(EARGF(usage()), NULL, 0);
1657 defconfig CSETB(RunInFullscreen, 0);
1660 defconfig CSETB(RunInFullscreen, 1);
1663 defconfig CSETB(Geolocation, 0);
1666 defconfig CSETB(Geolocation, 1);
1669 defconfig CSETB(LoadImages, 0);
1672 defconfig CSETB(LoadImages, 1);
1675 defconfig CSETB(KioskMode, 0);
1678 defconfig CSETB(KioskMode, 1);
1681 defconfig CSETB(Style, 0);
1684 defconfig CSETB(Style, 1);
1687 defconfig CSETB(Inspector, 0);
1690 defconfig CSETB(Inspector, 1);
1693 defconfig CSETB(Plugins, 0);
1696 defconfig CSETB(Plugins, 1);
1699 scriptfile = EARGF(usage());
1702 defconfig CSETB(JavaScript, 0);
1705 defconfig CSETB(JavaScript, 1);
1708 stylefile = EARGF(usage());
1711 fulluseragent = EARGF(usage());
1714 die("surf-"VERSION", ©2009-2015 surf engineers, "
1715 "see LICENSE for details\n");
1720 defconfig CSETF(ZoomLevel, strtof(EARGF(usage()), NULL));
1728 arg.v = "about:blank";
1731 c = newclient(NULL);