1 /* See LICENSE file for copyright and license details.
3 * To understand surf, start reading main().
20 #include <gdk/gdkkeysyms.h>
22 #include <glib/gstdio.h>
25 #include <JavaScriptCore/JavaScript.h>
26 #include <webkit2/webkit2.h>
28 #include <X11/Xatom.h>
32 #define LENGTH(x) (sizeof(x) / sizeof(x[0]))
33 #define CLEANMASK(mask) (mask & (MODKEY|GDK_SHIFT_MASK))
34 #define SETB(p, s) [p] = { { .b = s }, }
35 #define SETI(p, s) [p] = { { .i = s }, }
36 #define SETV(p, s) [p] = { { .v = s }, }
37 #define SETF(p, s) [p] = { { .f = s }, }
38 #define FSETB(p, s) [p] = { { .b = s }, 1 }
39 #define FSETI(p, s) [p] = { { .i = s }, 1 }
40 #define FSETV(p, s) [p] = { { .v = s }, 1 }
41 #define FSETF(p, s) [p] = { { .f = s }, 1 }
42 #define CSETB(p, s) [p] = (Parameter){ { .b = s }, 1 }
43 #define CSETI(p, s) [p] = (Parameter){ { .i = s }, 1 }
44 #define CSETV(p, s) [p] = (Parameter){ { .v = s }, 1 }
45 #define CSETF(p, s) [p] = (Parameter){ { .f = s }, 1 }
47 enum { AtomFind, AtomGo, AtomUri, AtomLast };
50 OnDoc = WEBKIT_HIT_TEST_RESULT_CONTEXT_DOCUMENT,
51 OnLink = WEBKIT_HIT_TEST_RESULT_CONTEXT_LINK,
52 OnImg = WEBKIT_HIT_TEST_RESULT_CONTEXT_IMAGE,
53 OnMedia = WEBKIT_HIT_TEST_RESULT_CONTEXT_MEDIA,
54 OnEdit = WEBKIT_HIT_TEST_RESULT_CONTEXT_EDITABLE,
55 OnBar = WEBKIT_HIT_TEST_RESULT_CONTEXT_SCROLLBAR,
56 OnSel = WEBKIT_HIT_TEST_RESULT_CONTEXT_SELECTION,
57 OnAny = OnDoc | OnLink | OnImg | OnMedia | OnEdit | OnBar | OnSel,
98 typedef struct Client {
101 WebKitWebInspector *inspector;
102 WebKitFindController *finder;
103 WebKitHitTestResult *mousepos;
104 GTlsCertificateFlags tlsflags;
106 int progress, fullscreen;
107 const char *title, *overtitle, *targeturi;
115 void (*func)(Client *c, const Arg *a);
123 void (*func)(Client *c, const Arg *a, WebKitHitTestResult *h);
125 unsigned int stopevent;
130 Parameter config[ParameterLast];
141 static void usage(void);
142 static void die(const char *errstr, ...);
143 static void setup(void);
144 static void sigchld(int unused);
145 static char *buildfile(const char *path);
146 static char *buildpath(const char *path);
147 static const char *getuserhomedir(const char *user);
148 static const char *getcurrentuserhomedir(void);
149 static Client *newclient(Client *c);
150 static void loaduri(Client *c, const Arg *a);
151 static const char *geturi(Client *c);
152 static void setatom(Client *c, int a, const char *v);
153 static const char *getatom(Client *c, int a);
154 static void updatetitle(Client *c);
155 static void gettogglestats(Client *c);
156 static void getpagestats(Client *c);
157 static WebKitCookieAcceptPolicy cookiepolicy_get(void);
158 static char cookiepolicy_set(const WebKitCookieAcceptPolicy p);
159 static void seturiparameters(Client *c, const char *uri);
160 static void setparameter(Client *c, int refresh, ParamName p, const Arg *a);
161 static const char *getstyle(const char *uri);
162 static void setstyle(Client *c, const char *stylefile);
163 static void runscript(Client *c);
164 static void evalscript(Client *c, const char *jsstr, ...);
165 static void updatewinid(Client *c);
166 static void handleplumb(Client *c, const char *uri);
167 static void newwindow(Client *c, const Arg *a, int noembed);
168 static void spawn(Client *c, const Arg *a);
169 static void destroyclient(Client *c);
170 static void cleanup(void);
173 static WebKitWebView *newview(Client *c, WebKitWebView *rv);
174 static GtkWidget *createview(WebKitWebView *v, WebKitNavigationAction *a,
176 static gboolean buttonreleased(GtkWidget *w, GdkEvent *e, Client *c);
177 static GdkFilterReturn processx(GdkXEvent *xevent, GdkEvent *event,
179 static gboolean winevent(GtkWidget *w, GdkEvent *e, Client *c);
180 static void showview(WebKitWebView *v, Client *c);
181 static GtkWidget *createwindow(Client *c);
182 static void loadchanged(WebKitWebView *v, WebKitLoadEvent e, Client *c);
183 static void progresschanged(WebKitWebView *v, GParamSpec *ps, Client *c);
184 static void titlechanged(WebKitWebView *view, GParamSpec *ps, Client *c);
185 static void mousetargetchanged(WebKitWebView *v, WebKitHitTestResult *h,
186 guint modifiers, Client *c);
187 static gboolean permissionrequested(WebKitWebView *v,
188 WebKitPermissionRequest *r, Client *c);
189 static gboolean decidepolicy(WebKitWebView *v, WebKitPolicyDecision *d,
190 WebKitPolicyDecisionType dt, Client *c);
191 static void decidenavigation(WebKitPolicyDecision *d, Client *c);
192 static void decidenewwindow(WebKitPolicyDecision *d, Client *c);
193 static void decideresource(WebKitPolicyDecision *d, Client *c);
194 static void downloadstarted(WebKitWebContext *wc, WebKitDownload *d,
196 static void responsereceived(WebKitDownload *d, GParamSpec *ps, Client *c);
197 static void download(Client *c, WebKitURIResponse *r);
198 static void closeview(WebKitWebView *v, Client *c);
199 static void destroywin(GtkWidget* w, Client *c);
202 static void pasteuri(GtkClipboard *clipboard, const char *text, gpointer d);
203 static void reload(Client *c, const Arg *a);
204 static void print(Client *c, const Arg *a);
205 static void clipboard(Client *c, const Arg *a);
206 static void zoom(Client *c, const Arg *a);
207 static void scroll(Client *c, const Arg *a);
208 static void navigate(Client *c, const Arg *a);
209 static void stop(Client *c, const Arg *a);
210 static void toggle(Client *c, const Arg *a);
211 static void togglefullscreen(Client *c, const Arg *a);
212 static void togglecookiepolicy(Client *c, const Arg *a);
213 static void toggleinspector(Client *c, const Arg *a);
214 static void find(Client *c, const Arg *a);
217 static void clicknavigate(Client *c, const Arg *a, WebKitHitTestResult *h);
218 static void clicknewwindow(Client *c, const Arg *a, WebKitHitTestResult *h);
219 static void clickexternplayer(Client *c, const Arg *a, WebKitHitTestResult *h);
221 static char winid[64];
222 static char togglestats[10];
223 static char pagestats[2];
224 static Atom atoms[AtomLast];
227 static int cookiepolicy;
229 static Client *clients;
230 static GdkDevice *gdkkb;
231 static char *stylefile;
232 static const char *useragent;
233 static Parameter *curconfig;
236 /* configuration, allows nested code to access above variables */
242 die("usage: %s [-bBdDfFgGiIkKmMnNpPsSvx] [-a cookiepolicies ] "
243 "[-c cookiefile] [-e xid] [-r scriptfile] [-t stylefile] "
244 "[-u useragent] [-z zoomlevel] [uri]\n", basename(argv0));
248 die(const char *errstr, ...)
252 va_start(ap, errstr);
253 vfprintf(stderr, errstr, ap);
261 GdkDisplay *gdpy = gdk_display_get_default();
264 /* clean up any zombies immediately */
266 gtk_init(NULL, NULL);
268 dpy = GDK_DISPLAY_XDISPLAY(gdpy);
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 = gdk_seat_get_keyboard(gdk_display_get_default_seat(gdpy));
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);
879 newview(Client *c, WebKitWebView *rv)
882 WebKitSettings *settings;
883 WebKitUserContentManager *contentmanager;
884 WebKitWebContext *context;
889 webkit_web_view_new_with_related_view(rv));
891 settings = webkit_settings_new_with_settings(
892 "auto-load-images", curconfig[LoadImages].val.b,
893 "default-font-size", curconfig[FontSize].val.f,
894 "enable-caret-browsing", curconfig[CaretBrowsing].val.b,
895 "enable-developer-extras", curconfig[Inspector].val.b,
896 "enable-dns-prefetching", curconfig[DNSPrefetch].val.b,
897 "enable-frame-flattening", curconfig[FrameFlattening].val.b,
898 "enable-html5-database", curconfig[DiskCache].val.b,
899 "enable-html5-local-storage", curconfig[DiskCache].val.b,
900 "enable-javascript", curconfig[JavaScript].val.b,
901 "enable-plugins", curconfig[Plugins].val.b,
903 /* For mor interesting settings, have a look at
904 * http://webkitgtk.org/reference/webkit2gtk/stable/WebKitSettings.html */
906 if (strcmp(fulluseragent, "")) {
907 webkit_settings_set_user_agent(settings, fulluseragent);
908 } else if (surfuseragent) {
909 webkit_settings_set_user_agent_with_application_details(
910 settings, "Surf", VERSION);
912 useragent = webkit_settings_get_user_agent(settings);
914 contentmanager = webkit_user_content_manager_new();
916 context = webkit_web_context_new_with_website_data_manager(
917 webkit_website_data_manager_new(
918 "base-cache-directory", cachedir,
919 "base-data-directory", cachedir,
922 /* rendering process model, can be a shared unique one
923 * or one for each view */
924 webkit_web_context_set_process_model(context,
925 WEBKIT_PROCESS_MODEL_MULTIPLE_SECONDARY_PROCESSES);
927 webkit_web_context_set_tls_errors_policy(context,
928 curconfig[StrictSSL].val.b ? WEBKIT_TLS_ERRORS_POLICY_FAIL :
929 WEBKIT_TLS_ERRORS_POLICY_IGNORE);
931 webkit_web_context_set_cache_model(context,
932 curconfig[DiskCache].val.b ? WEBKIT_CACHE_MODEL_WEB_BROWSER :
933 WEBKIT_CACHE_MODEL_DOCUMENT_VIEWER);
935 /* Currently only works with text file to be compatible with curl */
936 webkit_cookie_manager_set_persistent_storage(
937 webkit_web_context_get_cookie_manager(context), cookiefile,
938 WEBKIT_COOKIE_PERSISTENT_STORAGE_TEXT);
940 webkit_cookie_manager_set_accept_policy(
941 webkit_web_context_get_cookie_manager(context),
944 webkit_web_context_set_preferred_languages(context,
945 curconfig[PreferredLanguages].val.v);
946 webkit_web_context_set_spell_checking_languages(context,
947 curconfig[SpellLanguages].val.v);
948 webkit_web_context_set_spell_checking_enabled(context,
949 curconfig[SpellChecking].val.b);
951 g_signal_connect(G_OBJECT(context), "download-started",
952 G_CALLBACK(downloadstarted), c);
954 v = g_object_new(WEBKIT_TYPE_WEB_VIEW,
955 "settings", settings,
956 "user-content-manager", contentmanager,
957 "web-context", context,
961 g_signal_connect(G_OBJECT(v), "notify::estimated-load-progress",
962 G_CALLBACK(progresschanged), c);
963 g_signal_connect(G_OBJECT(v), "notify::title",
964 G_CALLBACK(titlechanged), c);
965 g_signal_connect(G_OBJECT(v), "button-release-event",
966 G_CALLBACK(buttonreleased), c);
967 g_signal_connect(G_OBJECT(v), "close",
968 G_CALLBACK(closeview), c);
969 g_signal_connect(G_OBJECT(v), "create",
970 G_CALLBACK(createview), c);
971 g_signal_connect(G_OBJECT(v), "decide-policy",
972 G_CALLBACK(decidepolicy), c);
973 g_signal_connect(G_OBJECT(v), "load-changed",
974 G_CALLBACK(loadchanged), c);
975 g_signal_connect(G_OBJECT(v), "mouse-target-changed",
976 G_CALLBACK(mousetargetchanged), c);
977 g_signal_connect(G_OBJECT(v), "permission-request",
978 G_CALLBACK(permissionrequested), c);
979 g_signal_connect(G_OBJECT(v), "ready-to-show",
980 G_CALLBACK(showview), c);
986 createview(WebKitWebView *v, WebKitNavigationAction *a, Client *c)
990 switch (webkit_navigation_action_get_navigation_type(a)) {
991 case WEBKIT_NAVIGATION_TYPE_OTHER: /* fallthrough */
993 * popup windows of type “other” are almost always triggered
994 * by user gesture, so inverse the logic here
996 /* instead of this, compare destination uri to mouse-over uri for validating window */
997 if (webkit_navigation_action_is_user_gesture(a))
999 case WEBKIT_NAVIGATION_TYPE_LINK_CLICKED: /* fallthrough */
1000 case WEBKIT_NAVIGATION_TYPE_FORM_SUBMITTED: /* fallthrough */
1001 case WEBKIT_NAVIGATION_TYPE_BACK_FORWARD: /* fallthrough */
1002 case WEBKIT_NAVIGATION_TYPE_RELOAD: /* fallthrough */
1003 case WEBKIT_NAVIGATION_TYPE_FORM_RESUBMITTED:
1010 return GTK_WIDGET(n->view);
1014 buttonreleased(GtkWidget *w, GdkEvent *e, Client *c)
1016 WebKitHitTestResultContext element;
1019 element = webkit_hit_test_result_get_context(c->mousepos);
1021 for (i = 0; i < LENGTH(buttons); ++i) {
1022 if (element & buttons[i].target &&
1023 e->button.button == buttons[i].button &&
1024 CLEANMASK(e->button.state) == CLEANMASK(buttons[i].mask) &&
1026 buttons[i].func(c, &buttons[i].arg, c->mousepos);
1027 return buttons[i].stopevent;
1035 processx(GdkXEvent *e, GdkEvent *event, gpointer d)
1037 Client *c = (Client *)d;
1041 if (((XEvent *)e)->type == PropertyNotify) {
1042 ev = &((XEvent *)e)->xproperty;
1043 if (ev->state == PropertyNewValue) {
1044 if (ev->atom == atoms[AtomFind]) {
1047 return GDK_FILTER_REMOVE;
1048 } else if (ev->atom == atoms[AtomGo]) {
1049 a.v = getatom(c, AtomGo);
1052 return GDK_FILTER_REMOVE;
1056 return GDK_FILTER_CONTINUE;
1060 winevent(GtkWidget *w, GdkEvent *e, Client *c)
1065 case GDK_ENTER_NOTIFY:
1066 c->overtitle = c->targeturi;
1070 if (!curconfig[KioskMode].val.b) {
1071 for (i = 0; i < LENGTH(keys); ++i) {
1072 if (gdk_keyval_to_lower(e->key.keyval) ==
1074 CLEANMASK(e->key.state) == keys[i].mod &&
1077 keys[i].func(c, &(keys[i].arg));
1082 case GDK_LEAVE_NOTIFY:
1083 c->overtitle = NULL;
1086 case GDK_WINDOW_STATE:
1087 if (e->window_state.changed_mask ==
1088 GDK_WINDOW_STATE_FULLSCREEN)
1089 c->fullscreen = e->window_state.new_window_state &
1090 GDK_WINDOW_STATE_FULLSCREEN;
1100 showview(WebKitWebView *v, Client *c)
1102 GdkRGBA bgcolor = { 0 };
1105 c->finder = webkit_web_view_get_find_controller(c->view);
1106 c->inspector = webkit_web_view_get_inspector(c->view);
1108 c->win = createwindow(c);
1110 gtk_container_add(GTK_CONTAINER(c->win), GTK_WIDGET(c->view));
1111 gtk_widget_show_all(c->win);
1112 gtk_widget_grab_focus(GTK_WIDGET(c->view));
1114 gwin = gtk_widget_get_window(GTK_WIDGET(c->win));
1115 c->xid = gdk_x11_window_get_xid(gwin);
1118 gdk_display_sync(gtk_widget_get_display(c->win));
1122 if (curconfig[HideBackground].val.b)
1123 webkit_web_view_set_background_color(c->view, &bgcolor);
1125 if (!curconfig[KioskMode].val.b) {
1126 gdk_window_set_events(gwin, GDK_ALL_EVENTS_MASK);
1127 gdk_window_add_filter(gwin, processx, c);
1130 if (curconfig[RunInFullscreen].val.b)
1131 togglefullscreen(c, NULL);
1133 if (curconfig[ZoomLevel].val.f != 1.0)
1134 webkit_web_view_set_zoom_level(c->view,
1135 curconfig[ZoomLevel].val.f);
1137 setatom(c, AtomFind, "");
1138 setatom(c, AtomUri, "about:blank");
1142 createwindow(Client *c)
1148 w = gtk_plug_new(embed);
1150 w = gtk_window_new(GTK_WINDOW_TOPLEVEL);
1152 wmstr = g_path_get_basename(argv0);
1153 gtk_window_set_wmclass(GTK_WINDOW(w), wmstr, "Surf");
1156 wmstr = g_strdup_printf("%s[%lu]", "Surf",
1157 webkit_web_view_get_page_id(c->view));
1158 gtk_window_set_role(GTK_WINDOW(w), wmstr);
1161 gtk_window_set_default_size(GTK_WINDOW(w), 800, 600);
1164 g_signal_connect(G_OBJECT(w), "destroy",
1165 G_CALLBACK(destroywin), c);
1166 g_signal_connect(G_OBJECT(w), "enter-notify-event",
1167 G_CALLBACK(winevent), c);
1168 g_signal_connect(G_OBJECT(w), "key-press-event",
1169 G_CALLBACK(winevent), c);
1170 g_signal_connect(G_OBJECT(w), "leave-notify-event",
1171 G_CALLBACK(winevent), c);
1172 g_signal_connect(G_OBJECT(w), "window-state-event",
1173 G_CALLBACK(winevent), c);
1179 loadchanged(WebKitWebView *v, WebKitLoadEvent e, Client *c)
1181 const char *title = geturi(c);
1184 case WEBKIT_LOAD_STARTED:
1185 curconfig = defconfig;
1186 setatom(c, AtomUri, title);
1188 c->tlsflags = G_TLS_CERTIFICATE_VALIDATE_ALL + 1;
1189 seturiparameters(c, geturi(c));
1191 case WEBKIT_LOAD_REDIRECTED:
1192 setatom(c, AtomUri, title);
1194 seturiparameters(c, geturi(c));
1196 case WEBKIT_LOAD_COMMITTED:
1197 if (!webkit_web_view_get_tls_info(c->view, NULL,
1199 c->tlsflags = G_TLS_CERTIFICATE_VALIDATE_ALL + 1;
1202 case WEBKIT_LOAD_FINISHED:
1203 /* Disabled until we write some WebKitWebExtension for
1204 * manipulating the DOM directly.
1205 evalscript(c, "document.documentElement.style.overflow = '%s'",
1206 enablescrollbars ? "auto" : "hidden");
1215 progresschanged(WebKitWebView *v, GParamSpec *ps, Client *c)
1217 c->progress = webkit_web_view_get_estimated_load_progress(c->view) *
1223 titlechanged(WebKitWebView *view, GParamSpec *ps, Client *c)
1225 c->title = webkit_web_view_get_title(c->view);
1230 mousetargetchanged(WebKitWebView *v, WebKitHitTestResult *h, guint modifiers,
1233 WebKitHitTestResultContext hc = webkit_hit_test_result_get_context(h);
1235 /* Keep the hit test to know where is the pointer on the next click */
1239 c->targeturi = webkit_hit_test_result_get_link_uri(h);
1240 else if (hc & OnImg)
1241 c->targeturi = webkit_hit_test_result_get_image_uri(h);
1242 else if (hc & OnMedia)
1243 c->targeturi = webkit_hit_test_result_get_media_uri(h);
1245 c->targeturi = NULL;
1247 c->overtitle = c->targeturi;
1252 permissionrequested(WebKitWebView *v, WebKitPermissionRequest *r, Client *c)
1254 if (WEBKIT_IS_GEOLOCATION_PERMISSION_REQUEST(r)) {
1255 if (curconfig[Geolocation].val.b)
1256 webkit_permission_request_allow(r);
1258 webkit_permission_request_deny(r);
1266 decidepolicy(WebKitWebView *v, WebKitPolicyDecision *d,
1267 WebKitPolicyDecisionType dt, Client *c)
1270 case WEBKIT_POLICY_DECISION_TYPE_NAVIGATION_ACTION:
1271 decidenavigation(d, c);
1273 case WEBKIT_POLICY_DECISION_TYPE_NEW_WINDOW_ACTION:
1274 decidenewwindow(d, c);
1276 case WEBKIT_POLICY_DECISION_TYPE_RESPONSE:
1277 decideresource(d, c);
1280 webkit_policy_decision_ignore(d);
1287 decidenavigation(WebKitPolicyDecision *d, Client *c)
1289 WebKitNavigationAction *a =
1290 webkit_navigation_policy_decision_get_navigation_action(
1291 WEBKIT_NAVIGATION_POLICY_DECISION(d));
1293 switch (webkit_navigation_action_get_navigation_type(a)) {
1294 case WEBKIT_NAVIGATION_TYPE_LINK_CLICKED: /* fallthrough */
1295 case WEBKIT_NAVIGATION_TYPE_FORM_SUBMITTED: /* fallthrough */
1296 case WEBKIT_NAVIGATION_TYPE_BACK_FORWARD: /* fallthrough */
1297 case WEBKIT_NAVIGATION_TYPE_RELOAD: /* fallthrough */
1298 case WEBKIT_NAVIGATION_TYPE_FORM_RESUBMITTED: /* fallthrough */
1299 case WEBKIT_NAVIGATION_TYPE_OTHER: /* fallthrough */
1301 /* Do not navigate to links with a "_blank" target (popup) */
1302 if (webkit_navigation_policy_decision_get_frame_name(
1303 WEBKIT_NAVIGATION_POLICY_DECISION(d))) {
1304 webkit_policy_decision_ignore(d);
1306 /* Filter out navigation to different domain ? */
1307 /* get action→urirequest, copy and load in new window+view
1308 * on Ctrl+Click ? */
1309 webkit_policy_decision_use(d);
1316 decidenewwindow(WebKitPolicyDecision *d, Client *c)
1319 WebKitNavigationAction *a =
1320 webkit_navigation_policy_decision_get_navigation_action(
1321 WEBKIT_NAVIGATION_POLICY_DECISION(d));
1324 switch (webkit_navigation_action_get_navigation_type(a)) {
1325 case WEBKIT_NAVIGATION_TYPE_LINK_CLICKED: /* fallthrough */
1326 case WEBKIT_NAVIGATION_TYPE_FORM_SUBMITTED: /* fallthrough */
1327 case WEBKIT_NAVIGATION_TYPE_BACK_FORWARD: /* fallthrough */
1328 case WEBKIT_NAVIGATION_TYPE_RELOAD: /* fallthrough */
1329 case WEBKIT_NAVIGATION_TYPE_FORM_RESUBMITTED:
1330 /* Filter domains here */
1331 /* If the value of “mouse-button” is not 0, then the navigation was triggered by a mouse event.
1332 * test for link clicked but no button ? */
1333 arg.v = webkit_uri_request_get_uri(
1334 webkit_navigation_action_get_request(a));
1335 newwindow(c, &arg, 0);
1337 case WEBKIT_NAVIGATION_TYPE_OTHER: /* fallthrough */
1342 webkit_policy_decision_ignore(d);
1346 decideresource(WebKitPolicyDecision *d, Client *c)
1349 WebKitResponsePolicyDecision *r = WEBKIT_RESPONSE_POLICY_DECISION(d);
1350 WebKitURIResponse *res =
1351 webkit_response_policy_decision_get_response(r);
1352 const gchar *uri = webkit_uri_response_get_uri(res);
1354 if (g_str_has_suffix(uri, "/favicon.ico")) {
1355 webkit_policy_decision_ignore(d);
1359 if (!g_str_has_prefix(uri, "http://")
1360 && !g_str_has_prefix(uri, "https://")
1361 && !g_str_has_prefix(uri, "about:")
1362 && !g_str_has_prefix(uri, "file://")
1363 && !g_str_has_prefix(uri, "data:")
1364 && !g_str_has_prefix(uri, "blob:")
1365 && strlen(uri) > 0) {
1366 for (i = 0; i < strlen(uri); i++) {
1367 if (!g_ascii_isprint(uri[i])) {
1373 handleplumb(c, uri);
1374 webkit_policy_decision_ignore(d);
1379 if (webkit_response_policy_decision_is_mime_type_supported(r)) {
1380 webkit_policy_decision_use(d);
1382 webkit_policy_decision_ignore(d);
1388 downloadstarted(WebKitWebContext *wc, WebKitDownload *d, Client *c)
1390 g_signal_connect(G_OBJECT(d), "notify::response",
1391 G_CALLBACK(responsereceived), c);
1395 responsereceived(WebKitDownload *d, GParamSpec *ps, Client *c)
1397 download(c, webkit_download_get_response(d));
1398 webkit_download_cancel(d);
1402 download(Client *c, WebKitURIResponse *r)
1404 Arg a = (Arg)DOWNLOAD(webkit_uri_response_get_uri(r), geturi(c));
1409 closeview(WebKitWebView *v, Client *c)
1411 gtk_widget_destroy(c->win);
1415 destroywin(GtkWidget* w, Client *c)
1423 pasteuri(GtkClipboard *clipboard, const char *text, gpointer d)
1425 Arg a = {.v = text };
1427 loaduri((Client *) d, &a);
1431 reload(Client *c, const Arg *a)
1434 webkit_web_view_reload_bypass_cache(c->view);
1436 webkit_web_view_reload(c->view);
1440 print(Client *c, const Arg *a)
1442 webkit_print_operation_run_dialog(webkit_print_operation_new(c->view),
1443 GTK_WINDOW(c->win));
1447 clipboard(Client *c, const Arg *a)
1449 if (a->b) { /* load clipboard uri */
1450 gtk_clipboard_request_text(gtk_clipboard_get(
1451 GDK_SELECTION_PRIMARY),
1453 } else { /* copy uri */
1454 gtk_clipboard_set_text(gtk_clipboard_get(
1455 GDK_SELECTION_PRIMARY), c->targeturi
1456 ? c->targeturi : geturi(c), -1);
1461 zoom(Client *c, const Arg *a)
1464 webkit_web_view_set_zoom_level(c->view,
1465 curconfig[ZoomLevel].val.f + 0.1);
1467 webkit_web_view_set_zoom_level(c->view,
1468 curconfig[ZoomLevel].val.f - 0.1);
1470 webkit_web_view_set_zoom_level(c->view, 1.0);
1472 curconfig[ZoomLevel].val.f = webkit_web_view_get_zoom_level(c->view);
1476 scroll(Client *c, const Arg *a)
1478 GdkEvent *ev = gdk_event_new(GDK_KEY_PRESS);
1480 gdk_event_set_device(ev, gdkkb);
1481 ev->key.window = gtk_widget_get_window(GTK_WIDGET(c->win));
1482 ev->key.state = GDK_CONTROL_MASK;
1483 ev->key.time = GDK_CURRENT_TIME;
1487 ev->key.keyval = GDK_KEY_Down;
1490 ev->key.keyval = GDK_KEY_Page_Down;
1493 ev->key.keyval = GDK_KEY_Left;
1496 ev->key.keyval = GDK_KEY_Right;
1499 ev->key.keyval = GDK_KEY_Page_Up;
1502 ev->key.keyval = GDK_KEY_Up;
1510 navigate(Client *c, const Arg *a)
1513 webkit_web_view_go_back(c->view);
1515 webkit_web_view_go_forward(c->view);
1519 stop(Client *c, const Arg *a)
1521 webkit_web_view_stop_loading(c->view);
1525 toggle(Client *c, const Arg *a)
1527 curconfig[a->i].val.b ^= 1;
1528 setparameter(c, 1, (ParamName)a->i, &curconfig[a->i].val);
1532 togglefullscreen(Client *c, const Arg *a)
1534 /* toggling value is handled in winevent() */
1536 gtk_window_unfullscreen(GTK_WINDOW(c->win));
1538 gtk_window_fullscreen(GTK_WINDOW(c->win));
1542 togglecookiepolicy(Client *c, const Arg *a)
1545 cookiepolicy %= strlen(curconfig[CookiePolicies].val.v);
1547 setparameter(c, 0, CookiePolicies, NULL);
1551 toggleinspector(Client *c, const Arg *a)
1553 if (webkit_web_inspector_is_attached(c->inspector))
1554 webkit_web_inspector_close(c->inspector);
1555 else if (curconfig[Inspector].val.b)
1556 webkit_web_inspector_show(c->inspector);
1560 find(Client *c, const Arg *a)
1566 webkit_find_controller_search_next(c->finder);
1568 webkit_find_controller_search_previous(c->finder);
1570 s = getatom(c, AtomFind);
1571 f = webkit_find_controller_get_search_text(c->finder);
1573 if (g_strcmp0(f, s) == 0) /* reset search */
1574 webkit_find_controller_search(c->finder, "", findopts,
1577 webkit_find_controller_search(c->finder, s, findopts,
1580 if (strcmp(s, "") == 0)
1581 webkit_find_controller_search_finish(c->finder);
1586 clicknavigate(Client *c, const Arg *a, WebKitHitTestResult *h)
1592 clicknewwindow(Client *c, const Arg *a, WebKitHitTestResult *h)
1596 arg.v = webkit_hit_test_result_get_link_uri(h);
1597 newwindow(c, &arg, a->b);
1601 clickexternplayer(Client *c, const Arg *a, WebKitHitTestResult *h)
1605 arg = (Arg)VIDEOPLAY(webkit_hit_test_result_get_media_uri(h));
1610 main(int argc, char *argv[])
1615 memset(&arg, 0, sizeof(arg));
1617 /* command line args */
1620 defconfig CSETV(CookiePolicies, EARGF(usage()));
1623 defconfig CSETB(ScrollBars, 0);
1626 defconfig CSETB(ScrollBars, 1);
1629 cookiefile = EARGF(usage());
1632 defconfig CSETB(DiskCache, 0);
1635 defconfig CSETB(DiskCache, 1);
1638 embed = strtol(EARGF(usage()), NULL, 0);
1641 defconfig CSETB(RunInFullscreen, 0);
1644 defconfig CSETB(RunInFullscreen, 1);
1647 defconfig CSETB(Geolocation, 0);
1650 defconfig CSETB(Geolocation, 1);
1653 defconfig CSETB(LoadImages, 0);
1656 defconfig CSETB(LoadImages, 1);
1659 defconfig CSETB(KioskMode, 0);
1662 defconfig CSETB(KioskMode, 1);
1665 defconfig CSETB(Style, 0);
1668 defconfig CSETB(Style, 1);
1671 defconfig CSETB(Inspector, 0);
1674 defconfig CSETB(Inspector, 1);
1677 defconfig CSETB(Plugins, 0);
1680 defconfig CSETB(Plugins, 1);
1683 scriptfile = EARGF(usage());
1686 defconfig CSETB(JavaScript, 0);
1689 defconfig CSETB(JavaScript, 1);
1692 stylefile = EARGF(usage());
1695 fulluseragent = EARGF(usage());
1698 die("surf-"VERSION", ©2009-2015 surf engineers, "
1699 "see LICENSE for details\n");
1704 defconfig CSETF(ZoomLevel, strtof(EARGF(usage()), NULL));
1712 arg.v = "about:blank";
1715 c = newclient(NULL);