1 /* See LICENSE file for copyright and license details.
3 * To understand surf, start reading main().
12 #include <gdk/gdkkeysyms.h>
14 #include <sys/types.h>
20 #include <webkit2/webkit2.h>
21 #include <glib/gstdio.h>
22 #include <JavaScriptCore/JavaScript.h>
34 #define LENGTH(x) (sizeof(x) / sizeof(x[0]))
35 #define CLEANMASK(mask) (mask & (MODKEY|GDK_SHIFT_MASK))
37 enum { AtomFind, AtomGo, AtomUri, AtomLast };
40 OnDoc = WEBKIT_HIT_TEST_RESULT_CONTEXT_DOCUMENT,
41 OnLink = WEBKIT_HIT_TEST_RESULT_CONTEXT_LINK,
42 OnImg = WEBKIT_HIT_TEST_RESULT_CONTEXT_IMAGE,
43 OnMedia = WEBKIT_HIT_TEST_RESULT_CONTEXT_MEDIA,
44 OnEdit = WEBKIT_HIT_TEST_RESULT_CONTEXT_EDITABLE,
45 OnBar = WEBKIT_HIT_TEST_RESULT_CONTEXT_SCROLLBAR,
46 OnSel = WEBKIT_HIT_TEST_RESULT_CONTEXT_SELECTION,
47 OnAny = OnDoc | OnLink | OnImg | OnMedia | OnEdit | OnBar | OnSel,
60 typedef union Arg Arg;
67 typedef struct Client {
71 WebKitWebInspector *inspector;
72 WebKitFindController *finder;
73 WebKitHitTestResult *mousepos;
74 GTlsCertificateFlags tlsflags;
75 const char *title, *targeturi;
85 void (*func)(Client *c, const Arg *arg);
93 void (*func)(Client *c, const Arg *a, WebKitHitTestResult *h);
95 unsigned int stopevent;
105 static Atom atoms[AtomLast];
106 static Client *clients = NULL;
107 static Window embed = 0;
108 static gboolean showxid = FALSE;
109 static char winid[64];
110 static char togglestats[10];
111 static char pagestats[2];
112 static GTlsDatabase *tlsdb;
113 static int cookiepolicy;
114 static char *stylefile = NULL;
116 static void addaccelgroup(Client *c);
117 static char *buildfile(const char *path);
118 static char *buildpath(const char *path);
119 static gboolean buttonreleased(GtkWidget *w, GdkEventKey *e, Client *c);
120 static void cleanup(void);
121 static void clipboard(Client *c, const Arg *a);
123 static WebKitCookieAcceptPolicy cookiepolicy_get(void);
124 static char cookiepolicy_set(const WebKitCookieAcceptPolicy p);
126 static char *copystr(char **str, const char *src);
127 static GtkWidget *createview(WebKitWebView *v, WebKitNavigationAction *a,
129 static gboolean decidepolicy(WebKitWebView *v, WebKitPolicyDecision *d,
130 WebKitPolicyDecisionType dt, Client *c);
131 static void decidenavigation(WebKitPolicyDecision *d, Client *c);
132 static void decidenewwindow(WebKitPolicyDecision *d, Client *c);
133 static void decideresource(WebKitPolicyDecision *d, Client *c);
134 static void closeview(WebKitWebView *v, Client *c);
135 static void destroyclient(Client *c);
136 static void destroywin(GtkWidget* w, Client *c);
137 static void die(const char *errstr, ...);
138 static void evalscript(Client *c, const char *jsstr, ...);
139 static void runscript(Client *c);
140 static void find(Client *c, const Arg *a);
141 static void togglefullscreen(Client *c, const Arg *a);
142 static gboolean permissionrequested(WebKitWebView *v,
143 WebKitPermissionRequest *r, Client *c);
144 static const char *getatom(Client *c, int a);
145 static void gettogglestats(Client *c);
146 static void getpagestats(Client *c);
147 static char *geturi(Client *c);
148 static const gchar *getstyle(const char *uri);
149 static void setstyle(Client *c, const char *stylefile);
151 static void handleplumb(Client *c, const gchar *uri);
153 static void downloadstarted(WebKitWebContext *wc, WebKitDownload *d,
155 static void responsereceived(WebKitDownload *d, GParamSpec *ps, Client *c);
156 static void download(Client *c, WebKitURIResponse *r);
158 static void toggleinspector(Client *c, const Arg *a);
160 static gboolean keypress(GtkAccelGroup *group, GObject *obj, guint key,
161 GdkModifierType mods, Client *c);
162 static void mousetargetchanged(WebKitWebView *v, WebKitHitTestResult *h,
163 guint modifiers, Client *c);
164 static void loadchanged(WebKitWebView *v, WebKitLoadEvent e, Client *c);
165 static void loaduri(Client *c, const Arg *a);
166 static void navigate(Client *c, const Arg *a);
167 static void clicknavigate(Client *c, const Arg *a, WebKitHitTestResult *h);
168 static Client *newclient(Client *c);
169 static WebKitWebView *newview(Client *c, WebKitWebView *rv);
170 static void showview(WebKitWebView *v, Client *c);
171 static void newwindow(Client *c, const Arg *arg, gboolean noembed);
172 static GtkWidget *createwindow(Client *c);
173 static void pasteuri(GtkClipboard *clipboard, const char *text, gpointer d);
174 static void print(Client *c, const Arg *a);
175 static GdkFilterReturn processx(GdkXEvent *xevent, GdkEvent *event,
177 static gboolean winevent(GtkWidget *w, GdkEvent *e, Client *c);
178 static void progresschanged(WebKitWebView *v, GParamSpec *ps, Client *c);
179 static void clicknewwindow(Client *c, const Arg *a, WebKitHitTestResult *h);
180 static void reload(Client *c, const Arg *arg);
181 static void scroll_h(Client *c, const Arg *a);
182 static void scroll_v(Client *c, const Arg *a);
183 static void setatom(Client *c, int a, const char *v);
184 static void setup(void);
185 static void sigchld(int unused);
186 static void spawn(Client *c, const Arg *arg);
187 static void stop(Client *c, const Arg *arg);
188 static void titlechanged(WebKitWebView *view, GParamSpec *ps, Client *c);
189 static void toggle(Client *c, const Arg *a);
190 static void togglecookiepolicy(Client *c, const Arg *arg);
191 static void togglestyle(Client *c, const Arg *arg);
192 static void updatetitle(Client *c);
193 static void updatewinid(Client *c);
194 static void usage(void);
195 static void zoom(Client *c, const Arg *a);
197 /* configuration, allows nested code to access above variables */
201 addaccelgroup(Client *c)
204 GtkAccelGroup *group = gtk_accel_group_new();
207 for (i = 0; i < LENGTH(keys); i++) {
208 closure = g_cclosure_new(G_CALLBACK(keypress), c, NULL);
209 gtk_accel_group_connect(group, keys[i].keyval, keys[i].mod, 0,
212 gtk_window_add_accel_group(GTK_WINDOW(c->win), group);
216 buildfile(const char *path)
218 char *dname, *bname, *bpath, *fpath;
221 dname = g_path_get_dirname(path);
222 bname = g_path_get_basename(path);
224 bpath = buildpath(dname);
227 fpath = g_build_filename(bpath, bname, NULL);
231 if (!(f = fopen(fpath, "a")))
232 die("Could not open file: %s\n", fpath);
234 g_chmod(fpath, 0600); /* always */
241 buildpath(const char *path)
244 char *apath, *name, *p, *fpath;
246 if (path[0] == '~') {
247 if (path[1] == '/' || path[1] == '\0') {
248 p = (char *)&path[1];
249 pw = getpwuid(getuid());
251 if ((p = strchr(path, '/')))
252 name = g_strndup(&path[1], --p - path);
254 name = g_strdup(&path[1]);
256 if (!(pw = getpwnam(name))) {
257 die("Can't get user %s home directory: %s.\n",
262 apath = g_build_filename(pw->pw_dir, p, NULL);
264 apath = g_strdup(path);
267 /* creating directory */
268 if (g_mkdir_with_parents(apath, 0700) < 0)
269 die("Could not access directory: %s\n", apath);
271 fpath = realpath(apath, NULL);
278 buttonreleased(GtkWidget *w, GdkEventKey *e, Client *c)
280 WebKitHitTestResultContext element;
281 GdkEventButton *eb = (GdkEventButton*)e;
284 element = webkit_hit_test_result_get_context(c->mousepos);
286 for (i = 0; i < LENGTH(buttons); ++i) {
287 if (element & buttons[i].target &&
288 eb->button == buttons[i].button &&
289 CLEANMASK(eb->state) == CLEANMASK(buttons[i].mask) &&
291 buttons[i].func(c, &buttons[i].arg, c->mousepos);
292 return buttons[i].stopevent;
303 destroyclient(clients);
310 WebKitCookieAcceptPolicy
311 cookiepolicy_get(void)
313 switch (cookiepolicies[cookiepolicy]) {
315 return WEBKIT_COOKIE_POLICY_ACCEPT_NEVER;
317 return WEBKIT_COOKIE_POLICY_ACCEPT_NO_THIRD_PARTY;
323 return WEBKIT_COOKIE_POLICY_ACCEPT_ALWAYS;
327 cookiepolicy_set(const WebKitCookieAcceptPolicy ep)
330 case WEBKIT_COOKIE_POLICY_ACCEPT_NEVER:
332 case WEBKIT_COOKIE_POLICY_ACCEPT_NO_THIRD_PARTY:
334 case WEBKIT_COOKIE_POLICY_ACCEPT_ALWAYS:
343 evalscript(Client *c, const char *jsstr, ...)
349 script = g_strdup_vprintf(jsstr, ap);
352 webkit_web_view_run_javascript(c->view, script, NULL, NULL, NULL);
362 if (g_file_get_contents(scriptfile, &script, &l, NULL) && l)
363 evalscript(c, script);
368 clipboard(Client *c, const Arg *a)
370 if (a->b) { /* load clipboard uri */
371 gtk_clipboard_request_text(gtk_clipboard_get(
372 GDK_SELECTION_PRIMARY),
374 } else { /* copy uri */
375 gtk_clipboard_set_text(gtk_clipboard_get(
376 GDK_SELECTION_PRIMARY), c->targeturi
377 ? c->targeturi : geturi(c), -1);
382 copystr(char **str, const char *src)
395 createview(WebKitWebView *v, WebKitNavigationAction *a, Client *c)
399 switch (webkit_navigation_action_get_navigation_type(a)) {
400 case WEBKIT_NAVIGATION_TYPE_OTHER: /* fallthrough */
402 * popup windows of type “other” are almost always triggered
403 * by user gesture, so inverse the logic here
405 /* instead of this, compare destination uri to mouse-over uri for validating window */
406 if (webkit_navigation_action_is_user_gesture(a)) {
410 case WEBKIT_NAVIGATION_TYPE_LINK_CLICKED: /* fallthrough */
411 case WEBKIT_NAVIGATION_TYPE_FORM_SUBMITTED: /* fallthrough */
412 case WEBKIT_NAVIGATION_TYPE_BACK_FORWARD: /* fallthrough */
413 case WEBKIT_NAVIGATION_TYPE_RELOAD: /* fallthrough */
414 case WEBKIT_NAVIGATION_TYPE_FORM_RESUBMITTED:
422 return GTK_WIDGET(n->view);
426 decidepolicy(WebKitWebView *v, WebKitPolicyDecision *d,
427 WebKitPolicyDecisionType dt, Client *c)
430 case WEBKIT_POLICY_DECISION_TYPE_NAVIGATION_ACTION:
431 decidenavigation(d, c);
433 case WEBKIT_POLICY_DECISION_TYPE_NEW_WINDOW_ACTION:
434 decidenewwindow(d, c);
436 case WEBKIT_POLICY_DECISION_TYPE_RESPONSE:
437 decideresource(d, c);
440 webkit_policy_decision_ignore(d);
447 decidenavigation(WebKitPolicyDecision *d, Client *c)
449 WebKitNavigationAction *a;
451 a = webkit_navigation_policy_decision_get_navigation_action(
452 WEBKIT_NAVIGATION_POLICY_DECISION(d));
454 switch (webkit_navigation_action_get_navigation_type(a)) {
455 case WEBKIT_NAVIGATION_TYPE_LINK_CLICKED: /* fallthrough */
456 case WEBKIT_NAVIGATION_TYPE_FORM_SUBMITTED: /* fallthrough */
457 case WEBKIT_NAVIGATION_TYPE_BACK_FORWARD: /* fallthrough */
458 case WEBKIT_NAVIGATION_TYPE_RELOAD: /* fallthrough */
459 case WEBKIT_NAVIGATION_TYPE_FORM_RESUBMITTED:
460 case WEBKIT_NAVIGATION_TYPE_OTHER: /* fallthrough */
462 /* Do not navigate to links with a "_blank" target (popup) */
463 if (webkit_navigation_policy_decision_get_frame_name(
464 WEBKIT_NAVIGATION_POLICY_DECISION(d))) {
465 webkit_policy_decision_ignore(d);
467 /* Filter out navigation to different domain ? */
468 /* get action→urirequest, copy and load in new window+view
470 webkit_policy_decision_use(d);
477 decidenewwindow(WebKitPolicyDecision *d, Client *c)
479 WebKitNavigationAction *a;
482 a = webkit_navigation_policy_decision_get_navigation_action(
483 WEBKIT_NAVIGATION_POLICY_DECISION(d));
485 switch (webkit_navigation_action_get_navigation_type(a)) {
486 case WEBKIT_NAVIGATION_TYPE_LINK_CLICKED: /* fallthrough */
487 case WEBKIT_NAVIGATION_TYPE_FORM_SUBMITTED: /* fallthrough */
488 case WEBKIT_NAVIGATION_TYPE_BACK_FORWARD: /* fallthrough */
489 case WEBKIT_NAVIGATION_TYPE_RELOAD: /* fallthrough */
490 case WEBKIT_NAVIGATION_TYPE_FORM_RESUBMITTED:
491 /* Filter domains here */
492 /* If the value of “mouse-button” is not 0, then the navigation was triggered by a mouse event.
493 * test for link clicked but no button ? */
494 arg.v = webkit_uri_request_get_uri(
495 webkit_navigation_action_get_request(a));
496 newwindow(c, &arg, 0);
498 case WEBKIT_NAVIGATION_TYPE_OTHER: /* fallthrough */
503 webkit_policy_decision_ignore(d);
507 decideresource(WebKitPolicyDecision *d, Client *c)
511 WebKitResponsePolicyDecision *r = WEBKIT_RESPONSE_POLICY_DECISION(d);
512 WebKitURIResponse *res;
514 res = webkit_response_policy_decision_get_response(r);
515 uri = webkit_uri_response_get_uri(res);
517 if (g_str_has_suffix(uri, "/favicon.ico"))
518 webkit_uri_request_set_uri(
519 webkit_response_policy_decision_get_request(r),
522 if (!g_str_has_prefix(uri, "http://")
523 && !g_str_has_prefix(uri, "https://")
524 && !g_str_has_prefix(uri, "about:")
525 && !g_str_has_prefix(uri, "file://")
526 && !g_str_has_prefix(uri, "data:")
527 && !g_str_has_prefix(uri, "blob:")
528 && strlen(uri) > 0) {
529 for (i = 0; i < strlen(uri); i++) {
530 if (!g_ascii_isprint(uri[i])) {
537 webkit_policy_decision_ignore(d);
541 if (webkit_response_policy_decision_is_mime_type_supported(r)) {
542 webkit_policy_decision_use(d);
544 webkit_policy_decision_ignore(d);
550 destroyclient(Client *c)
554 webkit_web_view_stop_loading(c->view);
555 /* Not needed, has already been called
556 gtk_widget_destroy(c->win);
559 for (p = clients; p && p->next != c; p = p->next)
569 closeview(WebKitWebView *v, Client *c)
571 gtk_widget_destroy(c->win);
575 destroywin(GtkWidget* w, Client *c)
583 die(const char *errstr, ...)
587 va_start(ap, errstr);
588 vfprintf(stderr, errstr, ap);
594 find(Client *c, const Arg *a)
600 webkit_find_controller_search_next(c->finder);
602 webkit_find_controller_search_previous(c->finder);
604 s = getatom(c, AtomFind);
605 f = webkit_find_controller_get_search_text(c->finder);
607 if (g_strcmp0(f, s) == 0) /* reset search */
608 webkit_find_controller_search(c->finder, "", findopts, G_MAXUINT);
610 webkit_find_controller_search(c->finder, s, findopts, G_MAXUINT);
612 if (strcmp(s, "") == 0)
613 webkit_find_controller_search_finish(c->finder);
618 togglefullscreen(Client *c, const Arg *a)
620 /* toggling value is handled in winevent() */
622 gtk_window_unfullscreen(GTK_WINDOW(c->win));
624 gtk_window_fullscreen(GTK_WINDOW(c->win));
628 permissionrequested(WebKitWebView *v, WebKitPermissionRequest *r, Client *c)
630 if (WEBKIT_IS_GEOLOCATION_PERMISSION_REQUEST(r)) {
631 if (allowgeolocation)
632 webkit_permission_request_allow(r);
634 webkit_permission_request_deny(r);
642 getatom(Client *c, int a)
644 static char buf[BUFSIZ];
647 unsigned long ldummy;
648 unsigned char *p = NULL;
650 XGetWindowProperty(dpy, c->xid,
651 atoms[a], 0L, BUFSIZ, False, XA_STRING,
652 &adummy, &idummy, &ldummy, &ldummy, &p);
654 strncpy(buf, (char *)p, LENGTH(buf)-1);
667 if (!(uri = (char *)webkit_web_view_get_uri(c->view)))
673 getstyle(const char *uri)
677 if (stylefile != NULL)
680 for (i = 0; i < LENGTH(styles); i++) {
681 if (styles[i].regex && !regexec(&(styles[i].re), uri, 0,
683 return styles[i].style;
690 setstyle(Client *c, const char *stylefile)
694 if (!g_file_get_contents(stylefile, &style, NULL, NULL)) {
695 fprintf(stderr, "Could not read style file: %s\n", stylefile);
699 webkit_user_content_manager_add_style_sheet(
700 webkit_web_view_get_user_content_manager(c->view),
701 webkit_user_style_sheet_new(style,
702 WEBKIT_USER_CONTENT_INJECT_ALL_FRAMES,
703 WEBKIT_USER_STYLE_LEVEL_USER,
710 handleplumb(Client *c, const gchar *uri)
714 arg = (Arg)PLUMB(uri);
719 downloadstarted(WebKitWebContext *wc, WebKitDownload *d, Client *c)
721 g_signal_connect(G_OBJECT(d), "notify::response",
722 G_CALLBACK(responsereceived), c);
726 responsereceived(WebKitDownload *d, GParamSpec *ps, Client *c)
728 download(c, webkit_download_get_response(d));
729 webkit_download_cancel(d);
733 download(Client *c, WebKitURIResponse *r)
737 a = (Arg)DOWNLOAD(webkit_uri_response_get_uri(r), geturi(c));
742 toggleinspector(Client *c, const Arg *a)
744 if (enableinspector) {
745 if (webkit_web_inspector_is_attached(c->inspector))
746 webkit_web_inspector_close(c->inspector);
748 webkit_web_inspector_show(c->inspector);
753 keypress(GtkAccelGroup *group, GObject *obj, guint key, GdkModifierType mods,
757 gboolean processed = FALSE;
759 mods = CLEANMASK(mods);
760 key = gdk_keyval_to_lower(key);
762 for (i = 0; i < LENGTH(keys); i++) {
763 if (key == keys[i].keyval
764 && mods == keys[i].mod
766 keys[i].func(c, &(keys[i].arg));
775 mousetargetchanged(WebKitWebView *v, WebKitHitTestResult *h, guint modifiers,
778 WebKitHitTestResultContext hc;
780 /* Keep the hit test to know where is the pointer on the next click */
783 hc = webkit_hit_test_result_get_context(h);
786 c->targeturi = webkit_hit_test_result_get_link_uri(h);
788 c->targeturi = webkit_hit_test_result_get_image_uri(h);
789 else if (hc & OnMedia)
790 c->targeturi = webkit_hit_test_result_get_media_uri(h);
797 loadchanged(WebKitWebView *v, WebKitLoadEvent e, Client *c)
800 case WEBKIT_LOAD_STARTED:
801 c->tlsflags = G_TLS_CERTIFICATE_VALIDATE_ALL + 1;
803 case WEBKIT_LOAD_REDIRECTED:
804 setatom(c, AtomUri, geturi(c));
806 case WEBKIT_LOAD_COMMITTED:
807 if (!webkit_web_view_get_tls_info(c->view, NULL, &(c->tlsflags)))
808 c->tlsflags = G_TLS_CERTIFICATE_VALIDATE_ALL + 1;
810 setatom(c, AtomUri, geturi(c));
813 setstyle(c, getstyle(geturi(c)));
815 case WEBKIT_LOAD_FINISHED:
816 /* Disabled until we write some WebKitWebExtension for
817 * manipulating the DOM directly.
818 evalscript(c, "document.documentElement.style.overflow = '%s'",
819 enablescrollbars ? "auto" : "hidden");
828 loaduri(Client *c, const Arg *a)
832 const char *uri = (char *)a->v;
834 if (g_strcmp0(uri, "") == 0)
837 if (g_strrstr(uri, "://") || g_str_has_prefix(uri, "about:")) {
839 } else if (!stat(uri, &st) && (path = realpath(uri, NULL))) {
840 url = g_strdup_printf("file://%s", path);
843 url = g_strdup_printf("http://%s", uri);
846 setatom(c, AtomUri, url);
848 if (strcmp(url, geturi(c)) == 0) {
851 webkit_web_view_load_uri(c->view, url);
852 c->title = geturi(c);
860 navigate(Client *c, const Arg *a)
863 webkit_web_view_go_back(c->view);
865 webkit_web_view_go_forward(c->view);
869 clicknavigate(Client *c, const Arg *a, WebKitHitTestResult *h)
875 newclient(Client *rc)
880 if (!(c = calloc(1, sizeof(Client))))
881 die("Cannot malloc!\n");
889 c->view = newview(c, rc ? rc->view : NULL);
890 c->tlsflags = G_TLS_CERTIFICATE_VALIDATE_ALL + 1;
896 newview(Client *c, WebKitWebView *rv)
899 WebKitSettings *settings;
900 WebKitUserContentManager *contentmanager;
901 WebKitWebContext *context;
907 webkit_web_view_new_with_related_view(rv));
909 settings = webkit_settings_new_with_settings(
910 "auto-load-images", loadimages,
911 "default-font-size", defaultfontsize,
912 "enable-caret-browsing", enablecaretbrowsing,
913 "enable-developer-extras", enableinspector,
914 "enable-dns-prefetching", enablednsprefetching,
915 "enable-frame-flattening", enableframeflattening,
916 "enable-html5-database", enablecache,
917 "enable-html5-local-storage", enablecache,
918 "enable-javascript", enablescripts,
919 "enable-plugins", enableplugins,
921 if (!(ua = getenv("SURF_USERAGENT")))
923 webkit_settings_set_user_agent(settings, ua);
924 /* Have a look at http://webkitgtk.org/reference/webkit2gtk/stable/WebKitSettings.html
925 * for more interesting 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 or one for each
937 webkit_web_context_set_process_model(context,
938 WEBKIT_PROCESS_MODEL_MULTIPLE_SECONDARY_PROCESSES);
940 webkit_web_context_set_tls_errors_policy(context, strictssl ?
941 WEBKIT_TLS_ERRORS_POLICY_FAIL : WEBKIT_TLS_ERRORS_POLICY_IGNORE);
943 webkit_web_context_set_cache_model(context, enablecache ?
944 WEBKIT_CACHE_MODEL_WEB_BROWSER : WEBKIT_CACHE_MODEL_DOCUMENT_VIEWER);
946 /* Currently only works with text file to be compatible with curl */
947 webkit_cookie_manager_set_persistent_storage(
948 webkit_web_context_get_cookie_manager(context), cookiefile,
949 WEBKIT_COOKIE_PERSISTENT_STORAGE_TEXT);
951 webkit_cookie_manager_set_accept_policy(
952 webkit_web_context_get_cookie_manager(context),
955 g_signal_connect(G_OBJECT(context), "download-started",
956 G_CALLBACK(downloadstarted), c);
958 v = g_object_new(WEBKIT_TYPE_WEB_VIEW,
959 "settings", settings,
960 "user-content-manager", contentmanager,
961 "web-context", context,
965 g_signal_connect(G_OBJECT(v),
967 G_CALLBACK(titlechanged), c);
968 g_signal_connect(G_OBJECT(v),
969 "mouse-target-changed",
970 G_CALLBACK(mousetargetchanged), c);
971 g_signal_connect(G_OBJECT(v),
972 "permission-request",
973 G_CALLBACK(permissionrequested), c);
974 g_signal_connect(G_OBJECT(v),
976 G_CALLBACK(createview), c);
977 g_signal_connect(G_OBJECT(v), "ready-to-show",
978 G_CALLBACK(showview), c);
979 g_signal_connect(G_OBJECT(v),
981 G_CALLBACK(decidepolicy), c);
982 g_signal_connect(G_OBJECT(v),
984 G_CALLBACK(loadchanged), c);
985 g_signal_connect(G_OBJECT(v),
986 "notify::estimated-load-progress",
987 G_CALLBACK(progresschanged), c);
988 g_signal_connect(G_OBJECT(v),
989 "button-release-event",
990 G_CALLBACK(buttonreleased), c);
991 g_signal_connect(G_OBJECT(v), "close",
992 G_CALLBACK(closeview), c);
998 showview(WebKitWebView *v, Client *c)
1000 GdkGeometry hints = { 1, 1 };
1001 GdkRGBA bgcolor = { 0 };
1004 c->win = createwindow(c);
1006 if (enableinspector)
1007 c->inspector = webkit_web_view_get_inspector(c->view);
1009 c->finder = webkit_web_view_get_find_controller(c->view);
1015 gtk_container_add(GTK_CONTAINER(c->win), GTK_WIDGET(c->view));
1018 gtk_widget_grab_focus(GTK_WIDGET(c->view));
1019 gtk_widget_show(GTK_WIDGET(c->view));
1020 gtk_widget_show(c->win);
1021 gwin = gtk_widget_get_window(GTK_WIDGET(c->win));
1022 c->xid = gdk_x11_window_get_xid(gwin);
1023 gtk_window_set_geometry_hints(GTK_WINDOW(c->win), NULL, &hints,
1025 gdk_window_set_events(gwin, GDK_ALL_EVENTS_MASK);
1026 gdk_window_add_filter(gwin, processx, c);
1028 if (zoomlevel != 1.0)
1029 webkit_web_view_set_zoom_level(c->view, zoomlevel);
1031 if (runinfullscreen)
1032 togglefullscreen(c, NULL);
1034 setatom(c, AtomFind, "");
1035 setatom(c, AtomUri, "about:blank");
1037 webkit_web_view_set_background_color(c->view, &bgcolor);
1040 gdk_display_sync(gtk_widget_get_display(c->win));
1041 printf("%lu\n", c->xid);
1043 if (fclose(stdout) != 0) {
1044 die("Error closing stdout");
1050 newwindow(Client *c, const Arg *arg, gboolean noembed)
1053 const char *cmd[18], *uri;
1054 const Arg a = { .v = (void *)cmd };
1059 cmd[i++] = cookiepolicies;
1060 if (!enablescrollbars)
1062 if (embed && !noembed) {
1064 snprintf(tmp, LENGTH(tmp), "%u", (int)embed);
1067 if (!allowgeolocation)
1082 cmd[i++] = cookiefile;
1084 uri = arg->v ? (char *)arg->v : c->linkhover;
1092 createwindow(Client *c)
1097 w = gtk_plug_new(embed);
1099 w = gtk_window_new(GTK_WINDOW_TOPLEVEL);
1101 /* TA: 20091214: Despite what the GNOME docs say, the ICCCM
1102 * is always correct, so we should still call this function.
1103 * But when doing so, we *must* differentiate between a
1104 * WM_CLASS and a resource on the window. By convention, the
1105 * window class (WM_CLASS) is capped, while the resource is in
1106 * lowercase. Both these values come as a pair.
1108 gtk_window_set_wmclass(GTK_WINDOW(w), "surf", "Surf");
1110 /* TA: 20091214: And set the role here as well -- so that
1111 * sessions can pick this up.
1113 gtk_window_set_role(GTK_WINDOW(w), "Surf");
1115 gtk_window_set_default_size(GTK_WINDOW(w), 800, 600);
1118 g_signal_connect(G_OBJECT(w), "destroy",
1119 G_CALLBACK(destroywin), c);
1120 g_signal_connect(G_OBJECT(w), "leave-notify-event",
1121 G_CALLBACK(winevent), c);
1122 g_signal_connect(G_OBJECT(w), "window-state-event",
1123 G_CALLBACK(winevent), c);
1129 pasteuri(GtkClipboard *clipboard, const char *text, gpointer d)
1131 Arg arg = {.v = text };
1133 loaduri((Client *) d, &arg);
1137 print(Client *c, const Arg *a)
1139 webkit_print_operation_run_dialog(webkit_print_operation_new(c->view),
1140 GTK_WINDOW(c->win));
1144 processx(GdkXEvent *e, GdkEvent *event, gpointer d)
1146 Client *c = (Client *)d;
1150 if (((XEvent *)e)->type == PropertyNotify) {
1151 ev = &((XEvent *)e)->xproperty;
1152 if (ev->state == PropertyNewValue) {
1153 if (ev->atom == atoms[AtomFind]) {
1156 return GDK_FILTER_REMOVE;
1157 } else if (ev->atom == atoms[AtomGo]) {
1158 arg.v = getatom(c, AtomGo);
1161 return GDK_FILTER_REMOVE;
1165 return GDK_FILTER_CONTINUE;
1169 progresschanged(WebKitWebView *v, GParamSpec *ps, Client *c)
1171 c->progress = webkit_web_view_get_estimated_load_progress(c->view) *
1177 clicknewwindow(Client *c, const Arg *a, WebKitHitTestResult *h)
1181 arg.v = webkit_hit_test_result_get_link_uri(h);
1182 newwindow(c, &arg, a->b);
1186 reload(Client *c, const Arg *arg)
1188 gboolean nocache = *(gboolean *)arg;
1190 webkit_web_view_reload_bypass_cache(c->view);
1192 webkit_web_view_reload(c->view);
1196 scroll_h(Client *c, const Arg *a)
1198 evalscript(c, "window.scrollBy(%d * (window.innerWidth / 100), 0)",
1203 scroll_v(Client *c, const Arg *a)
1205 evalscript(c, "window.scrollBy(0, %d * (window.innerHeight / 100))",
1210 setatom(Client *c, int a, const char *v)
1213 XChangeProperty(dpy, c->xid,
1214 atoms[a], XA_STRING, 8, PropModeReplace,
1215 (unsigned char *)v, strlen(v) + 1);
1222 WebKitWebContext *context;
1223 GError *error = NULL;
1225 /* clean up any zombies immediately */
1227 gtk_init(NULL, NULL);
1229 dpy = GDK_DISPLAY_XDISPLAY(gdk_display_get_default());
1232 atoms[AtomFind] = XInternAtom(dpy, "_SURF_FIND", False);
1233 atoms[AtomGo] = XInternAtom(dpy, "_SURF_GO", False);
1234 atoms[AtomUri] = XInternAtom(dpy, "_SURF_URI", False);
1236 /* dirs and files */
1237 cookiefile = buildfile(cookiefile);
1238 scriptfile = buildfile(scriptfile);
1239 cachedir = buildpath(cachedir);
1241 if (stylefile == NULL) {
1242 styledir = buildpath(styledir);
1243 for (i = 0; i < LENGTH(styles); i++) {
1244 if (regcomp(&(styles[i].re), styles[i].regex,
1247 "Could not compile regex: %s\n",
1249 styles[i].regex = NULL;
1251 styles[i].style = g_strconcat(styledir, "/",
1252 styles[i].style, NULL);
1256 stylefile = buildfile(stylefile);
1263 if (signal(SIGCHLD, sigchld) == SIG_ERR)
1264 die("Can't install SIGCHLD handler");
1265 while (0 < waitpid(-1, NULL, WNOHANG));
1269 spawn(Client *c, const Arg *arg)
1273 close(ConnectionNumber(dpy));
1275 execvp(((char **)arg->v)[0], (char **)arg->v);
1276 fprintf(stderr, "surf: execvp %s", ((char **)arg->v)[0]);
1283 stop(Client *c, const Arg *arg)
1285 webkit_web_view_stop_loading(c->view);
1289 titlechanged(WebKitWebView *view, GParamSpec *ps, Client *c)
1291 c->title = webkit_web_view_get_title(c->view);
1296 winevent(GtkWidget *w, GdkEvent *e, Client *c)
1299 case GDK_LEAVE_NOTIFY:
1300 c->targeturi = NULL;
1303 case GDK_WINDOW_STATE: /* fallthrough */
1304 if (e->window_state.changed_mask ==
1305 GDK_WINDOW_STATE_FULLSCREEN) {
1306 c->fullscreen = e->window_state.new_window_state &
1307 GDK_WINDOW_STATE_FULLSCREEN;
1318 toggle(Client *c, const Arg *a)
1322 s = webkit_web_view_get_settings(c->view);
1324 switch ((unsigned int)a->i) {
1326 enablecaretbrowsing = !enablecaretbrowsing;
1327 webkit_settings_set_enable_caret_browsing(s,
1328 enablecaretbrowsing);
1330 return; /* do not reload */
1332 case FrameFlattening:
1333 enableframeflattening = !enableframeflattening;
1334 webkit_settings_set_enable_frame_flattening(s,
1335 enableframeflattening);
1338 allowgeolocation = !allowgeolocation;
1341 enablescripts = !enablescripts;
1342 webkit_settings_set_enable_javascript(s, enablescripts);
1345 loadimages = !loadimages;
1346 webkit_settings_set_auto_load_images(s, loadimages);
1349 enableplugins = !enableplugins;
1350 webkit_settings_set_enable_plugins(s, enableplugins);
1353 /* Disabled until we write some WebKitWebExtension for
1354 * manipulating the DOM directly.
1355 enablescrollbars = !enablescrollbars;
1356 evalscript(c, "document.documentElement.style.overflow = '%s'",
1357 enablescrollbars ? "auto" : "hidden");
1359 return; /* do not reload */
1368 togglecookiepolicy(Client *c, const Arg *arg)
1371 cookiepolicy %= strlen(cookiepolicies);
1373 webkit_cookie_manager_set_accept_policy(
1374 webkit_web_context_get_cookie_manager(
1375 webkit_web_view_get_context(c->view)),
1376 cookiepolicy_get());
1379 /* Do not reload. */
1383 togglestyle(Client *c, const Arg *arg)
1385 enablestyle = !enablestyle;
1386 setstyle(c, enablestyle ? getstyle(geturi(c)) : "");
1392 gettogglestats(Client *c)
1394 togglestats[0] = cookiepolicy_set(cookiepolicy_get());
1395 togglestats[1] = enablecaretbrowsing ? 'C' : 'c';
1396 togglestats[2] = allowgeolocation ? 'G' : 'g';
1397 togglestats[3] = enablecache ? 'D' : 'd';
1398 togglestats[4] = loadimages ? 'I' : 'i';
1399 togglestats[5] = enablescripts ? 'S': 's';
1400 togglestats[6] = enableplugins ? 'V' : 'v';
1401 togglestats[7] = enablestyle ? 'M' : 'm';
1402 togglestats[8] = enableframeflattening ? 'F' : 'f';
1403 togglestats[9] = '\0';
1407 getpagestats(Client *c)
1409 pagestats[0] = c->tlsflags > G_TLS_CERTIFICATE_VALIDATE_ALL ? '-' :
1410 c->tlsflags > 0 ? 'U' : 'T';
1411 pagestats[1] = '\0';
1415 updatetitle(Client *c)
1419 if (showindicators) {
1424 t = g_strdup_printf("%s:%s | %s", togglestats, pagestats,
1426 } else if (c->progress != 100) {
1427 t = g_strdup_printf("[%i%%] %s:%s | %s", c->progress,
1428 togglestats, pagestats,
1429 c->title == NULL ? "" : c->title);
1431 t = g_strdup_printf("%s:%s | %s", togglestats, pagestats,
1432 c->title == NULL ? "" : c->title);
1435 gtk_window_set_title(GTK_WINDOW(c->win), t);
1438 gtk_window_set_title(GTK_WINDOW(c->win), (c->title == NULL) ?
1444 updatewinid(Client *c)
1446 snprintf(winid, LENGTH(winid), "%lu", c->xid);
1452 die("usage: %s [-bBdDfFgGiIkKmMnNpPsSvx] [-a cookiepolicies ] "
1453 "[-c cookiefile] [-e xid] [-r scriptfile] [-t stylefile] "
1454 "[-u useragent] [-z zoomlevel] [uri]\n", basename(argv0));
1458 zoom(Client *c, const Arg *a)
1461 webkit_web_view_set_zoom_level(c->view, zoomlevel + 0.1);
1463 webkit_web_view_set_zoom_level(c->view, zoomlevel - 0.1);
1465 webkit_web_view_set_zoom_level(c->view, 1.0);
1467 zoomlevel = webkit_web_view_get_zoom_level(c->view);
1471 main(int argc, char *argv[])
1476 memset(&arg, 0, sizeof(arg));
1478 /* command line args */
1481 cookiepolicies = EARGF(usage());
1484 enablescrollbars = 0;
1487 enablescrollbars = 1;
1490 cookiefile = EARGF(usage());
1499 embed = strtol(EARGF(usage()), NULL, 0);
1502 runinfullscreen = 0;
1505 runinfullscreen = 1;
1508 allowgeolocation = 0;
1511 allowgeolocation = 1;
1532 enableinspector = 0;
1535 enableinspector = 1;
1544 scriptfile = EARGF(usage());
1553 stylefile = EARGF(usage());
1556 useragent = EARGF(usage());
1559 die("surf-"VERSION", ©2009-2015 surf engineers, "
1560 "see LICENSE for details\n");
1565 zoomlevel = strtof(EARGF(usage()), NULL);
1574 c = newclient(NULL);
1577 loaduri(clients, &arg);
1584 return EXIT_SUCCESS;