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,
50 typedef union Arg Arg;
57 typedef struct Client {
61 WebKitWebInspector *inspector;
62 WebKitHitTestResult *mousepos;
63 GTlsCertificateFlags tlsflags;
64 const char *title, *targeturi;
68 gboolean zoomed, fullscreen;
74 void (*func)(Client *c, const Arg *arg);
82 void (*func)(Client *c, const Arg *a, WebKitHitTestResult *h);
84 unsigned int stopevent;
94 static Atom atoms[AtomLast];
95 static Client *clients = NULL;
96 static Window embed = 0;
97 static gboolean showxid = FALSE;
98 static char winid[64];
99 static char togglestat[9];
100 static char pagestat[3];
101 static GTlsDatabase *tlsdb;
102 static int cookiepolicy;
103 static char *stylefile = NULL;
105 static void addaccelgroup(Client *c);
106 static char *buildfile(const char *path);
107 static char *buildpath(const char *path);
108 static gboolean buttonreleased(GtkWidget *w, GdkEventKey *e, Client *c);
109 static void cleanup(void);
110 static void clipboard(Client *c, const Arg *a);
112 static WebKitCookieAcceptPolicy cookiepolicy_get(void);
113 static char cookiepolicy_set(const WebKitCookieAcceptPolicy p);
115 static char *copystr(char **str, const char *src);
116 static GtkWidget *createview(WebKitWebView *v, WebKitNavigationAction *a,
118 static gboolean decidepolicy(WebKitWebView *v, WebKitPolicyDecision *d,
119 WebKitPolicyDecisionType dt, Client *c);
120 static void decidenavigation(WebKitPolicyDecision *d, Client *c);
121 static void decidenewwindow(WebKitPolicyDecision *d, Client *c);
122 static void decideresource(WebKitPolicyDecision *d, Client *c);
123 static void closeview(WebKitWebView *v, Client *c);
124 static void destroyclient(Client *c);
125 static void destroywin(GtkWidget* w, Client *c);
126 static void die(const char *errstr, ...);
127 static void evalscript(Client *c, const char *jsstr, ...);
128 static void runscript(Client *c);
129 static void find(Client *c, const Arg *arg);
130 static void togglefullscreen(Client *c, const Arg *a);
131 static gboolean permissionrequested(WebKitWebView *v,
132 WebKitPermissionRequest *r, Client *c);
133 static const char *getatom(Client *c, int a);
134 static void gettogglestat(Client *c);
135 static void getpagestat(Client *c);
136 static char *geturi(Client *c);
137 static const gchar *getstyle(const char *uri);
138 static void setstyle(Client *c, const char *stylefile);
140 static void handleplumb(Client *c, const gchar *uri);
142 static void downloadstarted(WebKitWebContext *wc, WebKitDownload *d,
144 static void responsereceived(WebKitDownload *d, GParamSpec *ps, Client *c);
145 static void download(Client *c, WebKitURIResponse *r);
147 static void toggleinspector(Client *c, const Arg *a);
149 static gboolean keypress(GtkAccelGroup *group, GObject *obj, guint key,
150 GdkModifierType mods, Client *c);
151 static void mousetargetchanged(WebKitWebView *v, WebKitHitTestResult *h,
152 guint modifiers, Client *c);
153 static void loadchanged(WebKitWebView *v, WebKitLoadEvent e, Client *c);
154 static void loaduri(Client *c, const Arg *arg);
155 static void navigate(Client *c, const Arg *arg);
156 static Client *newclient(Client *c);
157 static WebKitWebView *newview(Client *c, WebKitWebView *rv);
158 static void showview(WebKitWebView *v, Client *c);
159 static void newwindow(Client *c, const Arg *arg, gboolean noembed);
160 static GtkWidget *createwindow(Client *c);
161 static void pasteuri(GtkClipboard *clipboard, const char *text, gpointer d);
162 static void print(Client *c, const Arg *a);
163 static GdkFilterReturn processx(GdkXEvent *xevent, GdkEvent *event,
165 static gboolean winevent(GtkWidget *w, GdkEvent *e, Client *c);
166 static void progresschanged(WebKitWebView *v, GParamSpec *ps, Client *c);
167 static void linkopen(Client *c, const Arg *arg);
168 static void linkopenembed(Client *c, const Arg *arg);
169 static void reload(Client *c, const Arg *arg);
170 static void scroll_h(Client *c, const Arg *arg);
171 static void scroll_v(Client *c, const Arg *arg);
172 static void scroll(GtkAdjustment *a, const Arg *arg);
173 static void setatom(Client *c, int a, const char *v);
174 static void setup(void);
175 static void sigchld(int unused);
176 static void spawn(Client *c, const Arg *arg);
177 static void stop(Client *c, const Arg *arg);
178 static void titlechanged(WebKitWebView *view, GParamSpec *ps, Client *c);
179 static void toggle(Client *c, const Arg *arg);
180 static void togglecookiepolicy(Client *c, const Arg *arg);
181 static void togglegeolocation(Client *c, const Arg *arg);
182 static void togglescrollbars(Client *c, const Arg *arg);
183 static void togglestyle(Client *c, const Arg *arg);
184 static void updatetitle(Client *c);
185 static void updatewinid(Client *c);
186 static void usage(void);
187 static void zoom(Client *c, const Arg *arg);
189 /* configuration, allows nested code to access above variables */
193 addaccelgroup(Client *c)
196 GtkAccelGroup *group = gtk_accel_group_new();
199 for (i = 0; i < LENGTH(keys); i++) {
200 closure = g_cclosure_new(G_CALLBACK(keypress), c, NULL);
201 gtk_accel_group_connect(group, keys[i].keyval, keys[i].mod, 0,
204 gtk_window_add_accel_group(GTK_WINDOW(c->win), group);
208 buildfile(const char *path)
210 char *dname, *bname, *bpath, *fpath;
213 dname = g_path_get_dirname(path);
214 bname = g_path_get_basename(path);
216 bpath = buildpath(dname);
219 fpath = g_build_filename(bpath, bname, NULL);
223 if (!(f = fopen(fpath, "a")))
224 die("Could not open file: %s\n", fpath);
226 g_chmod(fpath, 0600); /* always */
233 buildpath(const char *path)
236 char *apath, *name, *p, *fpath;
238 if (path[0] == '~') {
239 if (path[1] == '/' || path[1] == '\0') {
240 p = (char *)&path[1];
241 pw = getpwuid(getuid());
243 if ((p = strchr(path, '/')))
244 name = g_strndup(&path[1], --p - path);
246 name = g_strdup(&path[1]);
248 if (!(pw = getpwnam(name))) {
249 die("Can't get user %s home directory: %s.\n",
254 apath = g_build_filename(pw->pw_dir, p, NULL);
256 apath = g_strdup(path);
259 /* creating directory */
260 if (g_mkdir_with_parents(apath, 0700) < 0)
261 die("Could not access directory: %s\n", apath);
263 fpath = realpath(apath, NULL);
270 buttonreleased(GtkWidget *w, GdkEventKey *e, Client *c)
272 WebKitHitTestResultContext element;
273 GdkEventButton *eb = (GdkEventButton*)e;
276 element = webkit_hit_test_result_get_context(c->mousepos);
278 for (i = 0; i < LENGTH(buttons); ++i) {
279 if (element & buttons[i].target &&
280 eb->button == buttons[i].button &&
281 CLEANMASK(eb->state) == CLEANMASK(buttons[i].mask) &&
283 buttons[i].func(c, &buttons[i].arg, c->mousepos);
284 return buttons[i].stopevent;
295 destroyclient(clients);
302 WebKitCookieAcceptPolicy
303 cookiepolicy_get(void)
305 switch (cookiepolicies[cookiepolicy]) {
307 return WEBKIT_COOKIE_POLICY_ACCEPT_NEVER;
309 return WEBKIT_COOKIE_POLICY_ACCEPT_NO_THIRD_PARTY;
315 return WEBKIT_COOKIE_POLICY_ACCEPT_ALWAYS;
319 cookiepolicy_set(const WebKitCookieAcceptPolicy ep)
322 case WEBKIT_COOKIE_POLICY_ACCEPT_NEVER:
324 case WEBKIT_COOKIE_POLICY_ACCEPT_NO_THIRD_PARTY:
326 case WEBKIT_COOKIE_POLICY_ACCEPT_ALWAYS:
335 evalscript(Client *c, const char *jsstr, ...)
341 script = g_strdup_vprintf(jsstr, ap);
344 webkit_web_view_run_javascript(c->view, script, NULL, NULL, NULL);
354 if (g_file_get_contents(scriptfile, &script, &l, NULL) && l)
355 evalscript(c, script);
360 clipboard(Client *c, const Arg *a)
362 if (a->b) { /* load clipboard uri */
363 gtk_clipboard_request_text(gtk_clipboard_get(
364 GDK_SELECTION_PRIMARY),
366 } else { /* copy uri */
367 gtk_clipboard_set_text(gtk_clipboard_get(
368 GDK_SELECTION_PRIMARY), c->targeturi
369 ? c->targeturi : geturi(c), -1);
374 copystr(char **str, const char *src)
387 createview(WebKitWebView *v, WebKitNavigationAction *a, Client *c)
391 switch (webkit_navigation_action_get_navigation_type(a)) {
392 case WEBKIT_NAVIGATION_TYPE_OTHER: /* fallthrough */
394 * popup windows of type “other” are almost always triggered
395 * by user gesture, so inverse the logic here
397 /* instead of this, compare destination uri to mouse-over uri for validating window */
398 if (webkit_navigation_action_is_user_gesture(a)) {
402 case WEBKIT_NAVIGATION_TYPE_LINK_CLICKED: /* fallthrough */
403 case WEBKIT_NAVIGATION_TYPE_FORM_SUBMITTED: /* fallthrough */
404 case WEBKIT_NAVIGATION_TYPE_BACK_FORWARD: /* fallthrough */
405 case WEBKIT_NAVIGATION_TYPE_RELOAD: /* fallthrough */
406 case WEBKIT_NAVIGATION_TYPE_FORM_RESUBMITTED:
414 return GTK_WIDGET(n->view);
418 decidepolicy(WebKitWebView *v, WebKitPolicyDecision *d,
419 WebKitPolicyDecisionType dt, Client *c)
422 case WEBKIT_POLICY_DECISION_TYPE_NAVIGATION_ACTION:
423 decidenavigation(d, c);
425 case WEBKIT_POLICY_DECISION_TYPE_NEW_WINDOW_ACTION:
426 decidenewwindow(d, c);
428 case WEBKIT_POLICY_DECISION_TYPE_RESPONSE:
429 decideresource(d, c);
432 webkit_policy_decision_ignore(d);
439 decidenavigation(WebKitPolicyDecision *d, Client *c)
441 WebKitNavigationAction *a;
443 a = webkit_navigation_policy_decision_get_navigation_action(
444 WEBKIT_NAVIGATION_POLICY_DECISION(d));
446 switch (webkit_navigation_action_get_navigation_type(a)) {
447 case WEBKIT_NAVIGATION_TYPE_LINK_CLICKED: /* fallthrough */
448 case WEBKIT_NAVIGATION_TYPE_FORM_SUBMITTED: /* fallthrough */
449 case WEBKIT_NAVIGATION_TYPE_BACK_FORWARD: /* fallthrough */
450 case WEBKIT_NAVIGATION_TYPE_RELOAD: /* fallthrough */
451 case WEBKIT_NAVIGATION_TYPE_FORM_RESUBMITTED:
452 case WEBKIT_NAVIGATION_TYPE_OTHER: /* fallthrough */
454 /* Do not navigate to links with a "_blank" target (popup) */
455 if (webkit_navigation_policy_decision_get_frame_name(
456 WEBKIT_NAVIGATION_POLICY_DECISION(d))) {
457 webkit_policy_decision_ignore(d);
459 /* Filter out navigation to different domain ? */
460 /* get action→urirequest, copy and load in new window+view
462 webkit_policy_decision_use(d);
469 decidenewwindow(WebKitPolicyDecision *d, Client *c)
471 WebKitNavigationAction *a;
474 a = webkit_navigation_policy_decision_get_navigation_action(
475 WEBKIT_NAVIGATION_POLICY_DECISION(d));
477 switch (webkit_navigation_action_get_navigation_type(a)) {
478 case WEBKIT_NAVIGATION_TYPE_LINK_CLICKED: /* fallthrough */
479 case WEBKIT_NAVIGATION_TYPE_FORM_SUBMITTED: /* fallthrough */
480 case WEBKIT_NAVIGATION_TYPE_BACK_FORWARD: /* fallthrough */
481 case WEBKIT_NAVIGATION_TYPE_RELOAD: /* fallthrough */
482 case WEBKIT_NAVIGATION_TYPE_FORM_RESUBMITTED:
483 /* Filter domains here */
484 /* If the value of “mouse-button” is not 0, then the navigation was triggered by a mouse event.
485 * test for link clicked but no button ? */
486 arg.v = webkit_uri_request_get_uri(
487 webkit_navigation_action_get_request(a));
488 newwindow(c, &arg, 0);
490 case WEBKIT_NAVIGATION_TYPE_OTHER: /* fallthrough */
495 webkit_policy_decision_ignore(d);
499 decideresource(WebKitPolicyDecision *d, Client *c)
503 WebKitResponsePolicyDecision *r = WEBKIT_RESPONSE_POLICY_DECISION(d);
504 WebKitURIResponse *res;
506 res = webkit_response_policy_decision_get_response(r);
507 uri = webkit_uri_response_get_uri(res);
509 if (g_str_has_suffix(uri, "/favicon.ico"))
510 webkit_uri_request_set_uri(
511 webkit_response_policy_decision_get_request(r),
514 if (!g_str_has_prefix(uri, "http://")
515 && !g_str_has_prefix(uri, "https://")
516 && !g_str_has_prefix(uri, "about:")
517 && !g_str_has_prefix(uri, "file://")
518 && !g_str_has_prefix(uri, "data:")
519 && !g_str_has_prefix(uri, "blob:")
520 && strlen(uri) > 0) {
521 for (i = 0; i < strlen(uri); i++) {
522 if (!g_ascii_isprint(uri[i])) {
529 webkit_policy_decision_ignore(d);
533 if (webkit_response_policy_decision_is_mime_type_supported(r)) {
534 webkit_policy_decision_use(d);
536 webkit_policy_decision_ignore(d);
542 destroyclient(Client *c)
546 webkit_web_view_stop_loading(c->view);
547 /* Not needed, has already been called
548 gtk_widget_destroy(c->win);
551 for (p = clients; p && p->next != c; p = p->next)
561 closeview(WebKitWebView *v, Client *c)
563 gtk_widget_destroy(c->win);
567 destroywin(GtkWidget* w, Client *c)
575 die(const char *errstr, ...)
579 va_start(ap, errstr);
580 vfprintf(stderr, errstr, ap);
586 find(Client *c, const Arg *arg)
590 s = getatom(c, AtomFind);
591 gboolean forward = *(gboolean *)arg;
592 webkit_web_view_search_text(c->view, s, FALSE, forward, TRUE);
596 togglefullscreen(Client *c, const Arg *a)
598 /* toggling value is handled in winevent() */
600 gtk_window_unfullscreen(GTK_WINDOW(c->win));
602 gtk_window_fullscreen(GTK_WINDOW(c->win));
606 permissionrequested(WebKitWebView *v, WebKitPermissionRequest *r, Client *c)
608 if (WEBKIT_IS_GEOLOCATION_PERMISSION_REQUEST(r)) {
609 if (allowgeolocation)
610 webkit_permission_request_allow(r);
612 webkit_permission_request_deny(r);
620 getatom(Client *c, int a)
622 static char buf[BUFSIZ];
625 unsigned long ldummy;
626 unsigned char *p = NULL;
628 XGetWindowProperty(dpy, c->xid,
629 atoms[a], 0L, BUFSIZ, False, XA_STRING,
630 &adummy, &idummy, &ldummy, &ldummy, &p);
632 strncpy(buf, (char *)p, LENGTH(buf)-1);
645 if (!(uri = (char *)webkit_web_view_get_uri(c->view)))
651 getstyle(const char *uri)
655 if (stylefile != NULL)
658 for (i = 0; i < LENGTH(styles); i++) {
659 if (styles[i].regex && !regexec(&(styles[i].re), uri, 0,
661 return styles[i].style;
668 setstyle(Client *c, const char *stylefile)
672 if (!g_file_get_contents(stylefile, &style, NULL, NULL)) {
673 fprintf(stderr, "Could not read style file: %s\n", stylefile);
677 webkit_user_content_manager_add_style_sheet(
678 webkit_web_view_get_user_content_manager(c->view),
679 webkit_user_style_sheet_new(style,
680 WEBKIT_USER_CONTENT_INJECT_ALL_FRAMES,
681 WEBKIT_USER_STYLE_LEVEL_USER,
688 handleplumb(Client *c, const gchar *uri)
692 arg = (Arg)PLUMB(uri);
697 downloadstarted(WebKitWebContext *wc, WebKitDownload *d, Client *c)
699 g_signal_connect(G_OBJECT(d), "notify::response",
700 G_CALLBACK(responsereceived), c);
704 responsereceived(WebKitDownload *d, GParamSpec *ps, Client *c)
706 download(c, webkit_download_get_response(d));
707 webkit_download_cancel(d);
711 download(Client *c, WebKitURIResponse *r)
715 a = (Arg)DOWNLOAD(webkit_uri_response_get_uri(r), geturi(c));
720 toggleinspector(Client *c, const Arg *a)
722 if (enableinspector) {
723 if (webkit_web_inspector_is_attached(c->inspector))
724 webkit_web_inspector_close(c->inspector);
726 webkit_web_inspector_show(c->inspector);
731 keypress(GtkAccelGroup *group, GObject *obj, guint key, GdkModifierType mods,
735 gboolean processed = FALSE;
737 mods = CLEANMASK(mods);
738 key = gdk_keyval_to_lower(key);
740 for (i = 0; i < LENGTH(keys); i++) {
741 if (key == keys[i].keyval
742 && mods == keys[i].mod
744 keys[i].func(c, &(keys[i].arg));
753 mousetargetchanged(WebKitWebView *v, WebKitHitTestResult *h, guint modifiers,
756 WebKitHitTestResultContext hc;
758 /* Keep the hit test to know where is the pointer on the next click */
761 hc = webkit_hit_test_result_get_context(h);
764 c->targeturi = webkit_hit_test_result_get_link_uri(h);
766 c->targeturi = webkit_hit_test_result_get_image_uri(h);
767 else if (hc & OnMedia)
768 c->targeturi = webkit_hit_test_result_get_media_uri(h);
775 loadchanged(WebKitWebView *v, WebKitLoadEvent e, Client *c)
778 case WEBKIT_LOAD_STARTED:
779 c->tlsflags = G_TLS_CERTIFICATE_VALIDATE_ALL + 1;
781 case WEBKIT_LOAD_REDIRECTED:
782 setatom(c, AtomUri, geturi(c));
784 case WEBKIT_LOAD_COMMITTED:
785 if (!webkit_web_view_get_tls_info(c->view, NULL, &(c->tlsflags)))
786 c->tlsflags = G_TLS_CERTIFICATE_VALIDATE_ALL + 1;
788 setatom(c, AtomUri, geturi(c));
791 setstyle(c, getstyle(geturi(c)));
793 case WEBKIT_LOAD_FINISHED:
794 /* Disabled until we write some WebKitWebExtension for
795 * manipulating the DOM directly.
796 evalscript(c, "document.documentElement.style.overflow = '%s'",
797 enablescrollbars ? "auto" : "hidden");
806 loaduri(Client *c, const Arg *arg)
809 const char *uri = (char *)arg->v;
810 Arg a = { .b = FALSE };
813 if (strcmp(uri, "") == 0)
816 /* In case it's a file path. */
817 if (stat(uri, &st) == 0) {
818 rp = realpath(uri, NULL);
819 u = g_strdup_printf("file://%s", rp);
822 u = g_strrstr(uri, "://") ? g_strdup(uri)
823 : g_strdup_printf("http://%s", uri);
826 setatom(c, AtomUri, uri);
828 /* prevents endless loop */
829 if (strcmp(u, geturi(c)) == 0) {
832 webkit_web_view_load_uri(c->view, u);
834 c->title = copystr(&c->title, u);
841 navigate(Client *c, const Arg *arg)
843 int steps = *(int *)arg;
844 webkit_web_view_go_back_or_forward(c->view, steps);
848 newclient(Client *rc)
853 if (!(c = calloc(1, sizeof(Client))))
854 die("Cannot malloc!\n");
862 c->view = newview(c, rc ? rc->view : NULL);
863 c->tlsflags = G_TLS_CERTIFICATE_VALIDATE_ALL + 1;
869 newview(Client *c, WebKitWebView *rv)
872 WebKitSettings *settings;
873 WebKitUserContentManager *contentmanager;
874 WebKitWebContext *context;
880 webkit_web_view_new_with_related_view(rv));
882 settings = webkit_settings_new_with_settings(
883 "auto-load-images", loadimages,
884 "default-font-size", defaultfontsize,
885 "enable-caret-browsing", enablecaretbrowsing,
886 "enable-developer-extras", enableinspector,
887 "enable-dns-prefetching", enablednsprefetching,
888 "enable-frame-flattening", enableframeflattening,
889 "enable-html5-database", enablecache,
890 "enable-html5-local-storage", enablecache,
891 "enable-javascript", enablescripts,
892 "enable-plugins", enableplugins,
894 if (!(ua = getenv("SURF_USERAGENT")))
896 webkit_settings_set_user_agent(settings, ua);
897 /* Have a look at http://webkitgtk.org/reference/webkit2gtk/stable/WebKitSettings.html
898 * for more interesting settings */
900 contentmanager = webkit_user_content_manager_new();
902 context = webkit_web_context_new_with_website_data_manager(
903 webkit_website_data_manager_new(
904 "base-cache-directory", cachedir,
905 "base-data-directory", cachedir,
908 /* rendering process model, can be a shared unique one or one for each
910 webkit_web_context_set_process_model(context,
911 WEBKIT_PROCESS_MODEL_MULTIPLE_SECONDARY_PROCESSES);
913 webkit_web_context_set_tls_errors_policy(context, strictssl ?
914 WEBKIT_TLS_ERRORS_POLICY_FAIL : WEBKIT_TLS_ERRORS_POLICY_IGNORE);
916 webkit_web_context_set_cache_model(context, enablecache ?
917 WEBKIT_CACHE_MODEL_WEB_BROWSER : WEBKIT_CACHE_MODEL_DOCUMENT_VIEWER);
919 /* Currently only works with text file to be compatible with curl */
920 webkit_cookie_manager_set_persistent_storage(
921 webkit_web_context_get_cookie_manager(context), cookiefile,
922 WEBKIT_COOKIE_PERSISTENT_STORAGE_TEXT);
924 webkit_cookie_manager_set_accept_policy(
925 webkit_web_context_get_cookie_manager(context),
928 g_signal_connect(G_OBJECT(context), "download-started",
929 G_CALLBACK(downloadstarted), c);
931 v = g_object_new(WEBKIT_TYPE_WEB_VIEW,
932 "settings", settings,
933 "user-content-manager", contentmanager,
934 "web-context", context,
938 g_signal_connect(G_OBJECT(v),
940 G_CALLBACK(titlechanged), c);
941 g_signal_connect(G_OBJECT(v),
942 "mouse-target-changed",
943 G_CALLBACK(mousetargetchanged), c);
944 g_signal_connect(G_OBJECT(v),
945 "permission-request",
946 G_CALLBACK(permissionrequested), c);
947 g_signal_connect(G_OBJECT(v),
949 G_CALLBACK(createview), c);
950 g_signal_connect(G_OBJECT(v), "ready-to-show",
951 G_CALLBACK(showview), c);
952 g_signal_connect(G_OBJECT(v),
954 G_CALLBACK(decidepolicy), c);
955 g_signal_connect(G_OBJECT(v),
957 G_CALLBACK(loadchanged), c);
958 g_signal_connect(G_OBJECT(v),
959 "notify::estimated-load-progress",
960 G_CALLBACK(progresschanged), c);
961 g_signal_connect(G_OBJECT(v),
962 "button-release-event",
963 G_CALLBACK(buttonreleased), c);
964 g_signal_connect(G_OBJECT(v), "close",
965 G_CALLBACK(closeview), c);
971 showview(WebKitWebView *v, Client *c)
973 GdkGeometry hints = { 1, 1 };
974 GdkRGBA bgcolor = { 0 };
977 c->win = createwindow(c);
980 c->inspector = webkit_web_view_get_inspector(c->view);
986 gtk_container_add(GTK_CONTAINER(c->win), GTK_WIDGET(c->view));
989 gtk_widget_grab_focus(GTK_WIDGET(c->view));
990 gtk_widget_show(GTK_WIDGET(c->view));
991 gtk_widget_show(c->win);
992 gwin = gtk_widget_get_window(GTK_WIDGET(c->win));
993 c->xid = gdk_x11_window_get_xid(gwin);
994 gtk_window_set_geometry_hints(GTK_WINDOW(c->win), NULL, &hints,
996 gdk_window_set_events(gwin, GDK_ALL_EVENTS_MASK);
997 gdk_window_add_filter(gwin, processx, c);
999 /* This might conflict with _zoomto96dpi_. */
1000 if (zoomlevel != 1.0)
1001 webkit_web_view_set_zoom_level(c->view, zoomlevel);
1003 if (runinfullscreen)
1004 togglefullscreen(c, NULL);
1006 setatom(c, AtomFind, "");
1007 setatom(c, AtomUri, "about:blank");
1009 webkit_web_view_set_background_color(c->view, &bgcolor);
1012 gdk_display_sync(gtk_widget_get_display(c->win));
1013 printf("%lu\n", c->xid);
1015 if (fclose(stdout) != 0) {
1016 die("Error closing stdout");
1022 newwindow(Client *c, const Arg *arg, gboolean noembed)
1025 const char *cmd[18], *uri;
1026 const Arg a = { .v = (void *)cmd };
1031 cmd[i++] = cookiepolicies;
1032 if (!enablescrollbars)
1034 if (embed && !noembed) {
1036 snprintf(tmp, LENGTH(tmp), "%u", (int)embed);
1039 if (!allowgeolocation)
1051 if (enablediskcache)
1054 cmd[i++] = cookiefile;
1056 uri = arg->v ? (char *)arg->v : c->linkhover;
1064 createwindow(Client *c)
1069 w = gtk_plug_new(embed);
1071 w = gtk_window_new(GTK_WINDOW_TOPLEVEL);
1073 /* TA: 20091214: Despite what the GNOME docs say, the ICCCM
1074 * is always correct, so we should still call this function.
1075 * But when doing so, we *must* differentiate between a
1076 * WM_CLASS and a resource on the window. By convention, the
1077 * window class (WM_CLASS) is capped, while the resource is in
1078 * lowercase. Both these values come as a pair.
1080 gtk_window_set_wmclass(GTK_WINDOW(w), "surf", "Surf");
1082 /* TA: 20091214: And set the role here as well -- so that
1083 * sessions can pick this up.
1085 gtk_window_set_role(GTK_WINDOW(w), "Surf");
1087 gtk_window_set_default_size(GTK_WINDOW(w), 800, 600);
1090 g_signal_connect(G_OBJECT(w), "destroy",
1091 G_CALLBACK(destroywin), c);
1092 g_signal_connect(G_OBJECT(w), "leave-notify-event",
1093 G_CALLBACK(winevent), c);
1094 g_signal_connect(G_OBJECT(w), "window-state-event",
1095 G_CALLBACK(winevent), c);
1101 pasteuri(GtkClipboard *clipboard, const char *text, gpointer d)
1103 Arg arg = {.v = text };
1105 loaduri((Client *) d, &arg);
1109 print(Client *c, const Arg *a)
1111 webkit_print_operation_run_dialog(webkit_print_operation_new(c->view),
1112 GTK_WINDOW(c->win));
1116 processx(GdkXEvent *e, GdkEvent *event, gpointer d)
1118 Client *c = (Client *)d;
1122 if (((XEvent *)e)->type == PropertyNotify) {
1123 ev = &((XEvent *)e)->xproperty;
1124 if (ev->state == PropertyNewValue) {
1125 if (ev->atom == atoms[AtomFind]) {
1129 return GDK_FILTER_REMOVE;
1130 } else if (ev->atom == atoms[AtomGo]) {
1131 arg.v = getatom(c, AtomGo);
1134 return GDK_FILTER_REMOVE;
1138 return GDK_FILTER_CONTINUE;
1142 progresschanged(WebKitWebView *v, GParamSpec *ps, Client *c)
1144 c->progress = webkit_web_view_get_estimated_load_progress(c->view) *
1150 linkopen(Client *c, const Arg *arg)
1152 newwindow(NULL, arg, 1);
1156 linkopenembed(Client *c, const Arg *arg)
1158 newwindow(NULL, arg, 0);
1162 reload(Client *c, const Arg *arg)
1164 gboolean nocache = *(gboolean *)arg;
1166 webkit_web_view_reload_bypass_cache(c->view);
1168 webkit_web_view_reload(c->view);
1172 scroll_h(Client *c, const Arg *arg)
1174 scroll(gtk_scrolled_window_get_hadjustment(
1175 GTK_SCROLLED_WINDOW(c->scroll)), arg);
1179 scroll_v(Client *c, const Arg *arg)
1181 scroll(gtk_scrolled_window_get_vadjustment(
1182 GTK_SCROLLED_WINDOW(c->scroll)), arg);
1186 scroll(GtkAdjustment *a, const Arg *arg)
1190 v = gtk_adjustment_get_value(a);
1194 v += gtk_adjustment_get_page_increment(a) * (arg->i / 10000);
1199 v += gtk_adjustment_get_step_increment(a) * arg->i;
1203 v = MIN(v, gtk_adjustment_get_upper(a) -
1204 gtk_adjustment_get_page_size(a));
1205 gtk_adjustment_set_value(a, v);
1209 setatom(Client *c, int a, const char *v)
1212 XChangeProperty(dpy, c->xid,
1213 atoms[a], XA_STRING, 8, PropModeReplace,
1214 (unsigned char *)v, strlen(v) + 1);
1221 WebKitWebContext *context;
1222 GError *error = NULL;
1224 /* clean up any zombies immediately */
1226 gtk_init(NULL, NULL);
1228 dpy = GDK_DISPLAY_XDISPLAY(gdk_display_get_default());
1231 atoms[AtomFind] = XInternAtom(dpy, "_SURF_FIND", False);
1232 atoms[AtomGo] = XInternAtom(dpy, "_SURF_GO", False);
1233 atoms[AtomUri] = XInternAtom(dpy, "_SURF_URI", False);
1235 /* dirs and files */
1236 cookiefile = buildfile(cookiefile);
1237 scriptfile = buildfile(scriptfile);
1238 cachedir = buildpath(cachedir);
1240 if (stylefile == NULL) {
1241 styledir = buildpath(styledir);
1242 for (i = 0; i < LENGTH(styles); i++) {
1243 if (regcomp(&(styles[i].re), styles[i].regex,
1246 "Could not compile regex: %s\n",
1248 styles[i].regex = NULL;
1250 styles[i].style = g_strconcat(styledir, "/",
1251 styles[i].style, NULL);
1255 stylefile = buildfile(stylefile);
1262 if (signal(SIGCHLD, sigchld) == SIG_ERR)
1263 die("Can't install SIGCHLD handler");
1264 while (0 < waitpid(-1, NULL, WNOHANG));
1268 spawn(Client *c, const Arg *arg)
1272 close(ConnectionNumber(dpy));
1274 execvp(((char **)arg->v)[0], (char **)arg->v);
1275 fprintf(stderr, "surf: execvp %s", ((char **)arg->v)[0]);
1282 stop(Client *c, const Arg *arg)
1284 webkit_web_view_stop_loading(c->view);
1288 titlechanged(WebKitWebView *view, GParamSpec *ps, Client *c)
1290 c->title = webkit_web_view_get_title(c->view);
1295 winevent(GtkWidget *w, GdkEvent *e, Client *c)
1298 case GDK_LEAVE_NOTIFY:
1299 c->targeturi = NULL;
1302 case GDK_WINDOW_STATE: /* fallthrough */
1303 if (e->window_state.changed_mask ==
1304 GDK_WINDOW_STATE_FULLSCREEN) {
1305 c->fullscreen = e->window_state.new_window_state &
1306 GDK_WINDOW_STATE_FULLSCREEN;
1317 toggle(Client *c, const Arg *arg)
1319 WebKitWebSettings *settings;
1320 char *name = (char *)arg->v;
1322 Arg a = { .b = FALSE };
1324 settings = webkit_web_view_get_settings(c->view);
1325 g_object_get(G_OBJECT(settings), name, &value, NULL);
1326 g_object_set(G_OBJECT(settings), name, !value, NULL);
1332 togglecookiepolicy(Client *c, const Arg *arg)
1335 cookiepolicy %= strlen(cookiepolicies);
1337 webkit_cookie_manager_set_accept_policy(
1338 webkit_web_context_get_cookie_manager(
1339 webkit_web_view_get_context(c->view)),
1340 cookiepolicy_get());
1343 /* Do not reload. */
1347 togglegeolocation(Client *c, const Arg *arg)
1349 Arg a = { .b = FALSE };
1351 allowgeolocation ^= 1;
1356 twitch(Client *c, const Arg *arg)
1361 a = gtk_scrolled_window_get_vadjustment(GTK_SCROLLED_WINDOW(
1364 v = gtk_adjustment_get_value(a);
1369 v = MIN(v, gtk_adjustment_get_upper(a) -
1370 gtk_adjustment_get_page_size(a));
1371 gtk_adjustment_set_value(a, v);
1375 togglescrollbars(Client *c, const Arg *arg)
1377 GtkPolicyType vspolicy;
1380 gtk_scrolled_window_get_policy(GTK_SCROLLED_WINDOW(c->scroll), NULL,
1383 if (vspolicy == GTK_POLICY_AUTOMATIC) {
1384 gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(c->scroll),
1388 gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(c->scroll),
1389 GTK_POLICY_AUTOMATIC,
1390 GTK_POLICY_AUTOMATIC);
1399 togglestyle(Client *c, const Arg *arg)
1401 enablestyle = !enablestyle;
1402 setstyle(c, enablestyle ? getstyle(geturi(c)) : "");
1408 gettogglestat(Client *c)
1412 WebKitWebSettings *settings = webkit_web_view_get_settings(c->view);
1414 togglestat[p++] = cookiepolicy_set(cookiepolicy_get());
1416 g_object_get(G_OBJECT(settings), "enable-caret-browsing", &value,
1418 togglestat[p++] = value? 'C': 'c';
1420 togglestat[p++] = allowgeolocation? 'G': 'g';
1422 togglestat[p++] = enablediskcache? 'D': 'd';
1424 g_object_get(G_OBJECT(settings), "auto-load-images", &value, NULL);
1425 togglestat[p++] = value? 'I': 'i';
1427 g_object_get(G_OBJECT(settings), "enable-scripts", &value, NULL);
1428 togglestat[p++] = value? 'S': 's';
1430 g_object_get(G_OBJECT(settings), "enable-plugins", &value, NULL);
1431 togglestat[p++] = value? 'V': 'v';
1433 togglestat[p++] = enablestyle ? 'M': 'm';
1435 togglestat[p] = '\0';
1439 getpagestat(Client *c)
1441 const char *uri = geturi(c);
1443 pagestats[0] = c->tlsflags > G_TLS_CERTIFICATE_VALIDATE_ALL ? '-' :
1444 c->tlsflags > 0 ? 'U' : 'T';
1449 updatetitle(Client *c)
1453 if (showindicators) {
1458 t = g_strdup_printf("%s:%s | %s", togglestat, pagestat,
1460 } else if (c->progress != 100) {
1461 t = g_strdup_printf("[%i%%] %s:%s | %s", c->progress,
1462 togglestat, pagestat,
1463 c->title == NULL ? "" : c->title);
1465 t = g_strdup_printf("%s:%s | %s", togglestat, pagestat,
1466 c->title == NULL ? "" : c->title);
1469 gtk_window_set_title(GTK_WINDOW(c->win), t);
1472 gtk_window_set_title(GTK_WINDOW(c->win), (c->title == NULL) ?
1478 updatewinid(Client *c)
1480 snprintf(winid, LENGTH(winid), "%lu", c->xid);
1486 die("usage: %s [-bBdDfFgGiIkKmMnNpPsSvx] [-a cookiepolicies ] "
1487 "[-c cookiefile] [-e xid] [-r scriptfile] [-t stylefile] "
1488 "[-u useragent] [-z zoomlevel] [uri]\n", basename(argv0));
1492 zoom(Client *c, const Arg *arg)
1497 webkit_web_view_zoom_out(c->view);
1498 } else if (arg->i > 0) {
1500 webkit_web_view_zoom_in(c->view);
1504 webkit_web_view_set_zoom_level(c->view, 1.0);
1509 main(int argc, char *argv[])
1514 memset(&arg, 0, sizeof(arg));
1516 /* command line args */
1519 cookiepolicies = EARGF(usage());
1522 enablescrollbars = 0;
1525 enablescrollbars = 1;
1528 cookiefile = EARGF(usage());
1531 enablediskcache = 0;
1534 enablediskcache = 1;
1537 embed = strtol(EARGF(usage()), NULL, 0);
1540 runinfullscreen = 0;
1543 runinfullscreen = 1;
1546 allowgeolocation = 0;
1549 allowgeolocation = 1;
1570 enableinspector = 0;
1573 enableinspector = 1;
1582 scriptfile = EARGF(usage());
1591 stylefile = EARGF(usage());
1594 useragent = EARGF(usage());
1597 die("surf-"VERSION", ©2009-2015 surf engineers, "
1598 "see LICENSE for details\n");
1603 zoomlevel = strtof(EARGF(usage()), NULL);
1612 c = newclient(NULL);
1615 loaduri(clients, &arg);
1622 return EXIT_SUCCESS;