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, isinspecting;
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 void beforerequest(WebKitWebView *w, WebKitWebFrame *f,
107 WebKitWebResource *r, WebKitNetworkRequest *req,
108 WebKitNetworkResponse *resp, Client *c);
109 static char *buildfile(const char *path);
110 static char *buildpath(const char *path);
111 static gboolean buttonreleased(GtkWidget *w, GdkEventKey *e, Client *c);
112 static void cleanup(void);
113 static void clipboard(Client *c, const Arg *arg);
115 static WebKitCookieAcceptPolicy cookiepolicy_get(void);
116 static char cookiepolicy_set(const WebKitCookieAcceptPolicy p);
118 static char *copystr(char **str, const char *src);
119 static GtkWidget *createview(WebKitWebView *v, WebKitNavigationAction *a,
121 static gboolean decidepolicy(WebKitWebView *v, WebKitPolicyDecision *d,
122 WebKitPolicyDecisionType dt, Client *c);
123 static void decidenavigation(WebKitPolicyDecision *d, Client *c);
124 static void decidenewwindow(WebKitPolicyDecision *d, Client *c);
125 static void decideresource(WebKitPolicyDecision *d, Client *c);
126 static gboolean deletion_interface(WebKitWebView *view,
127 WebKitDOMHTMLElement *arg1, Client *c);
128 static void destroyclient(Client *c);
129 static void destroywin(GtkWidget* w, Client *c);
130 static void die(const char *errstr, ...);
131 static void eval(Client *c, const Arg *arg);
132 static void find(Client *c, const Arg *arg);
133 static void fullscreen(Client *c, const Arg *arg);
134 static gboolean permissionrequested(WebKitWebView *v,
135 WebKitPermissionRequest *r, Client *c);
136 static const char *getatom(Client *c, int a);
137 static void gettogglestat(Client *c);
138 static void getpagestat(Client *c);
139 static char *geturi(Client *c);
140 static const gchar *getstyle(const char *uri);
141 static void setstyle(Client *c, const char *style);
143 static void handleplumb(Client *c, WebKitWebView *w, const gchar *uri);
145 static void downloadstarted(WebKitWebContext *wc, WebKitDownload *d,
147 static void responsereceived(WebKitDownload *d, GParamSpec *ps, Client *c);
148 static void download(Client *c, WebKitURIResponse *r);
150 static void inspector(Client *c, const Arg *arg);
151 static WebKitWebView *inspector_new(WebKitWebInspector *i, WebKitWebView *v,
153 static gboolean inspector_show(WebKitWebInspector *i, Client *c);
154 static gboolean inspector_close(WebKitWebInspector *i, Client *c);
155 static void inspector_finished(WebKitWebInspector *i, Client *c);
157 static gboolean keypress(GtkAccelGroup *group, GObject *obj, guint key,
158 GdkModifierType mods, Client *c);
159 static void mousetargetchanged(WebKitWebView *v, WebKitHitTestResult *h,
160 guint modifiers, Client *c);
161 static void loadchanged(WebKitWebView *v, WebKitLoadEvent e, Client *c);
162 static void loaduri(Client *c, const Arg *arg);
163 static void navigate(Client *c, const Arg *arg);
164 static Client *newclient(Client *c);
165 static WebKitWebView *newview(Client *c, WebKitWebView *rv);
166 static void showview(WebKitWebView *v, Client *c);
167 static void newwindow(Client *c, const Arg *arg, gboolean noembed);
168 static void pasteuri(GtkClipboard *clipboard, const char *text, gpointer d);
169 static gboolean contextmenu(WebKitWebView *view, GtkWidget *menu,
170 WebKitHitTestResult *target, gboolean keyboard,
172 static void menuactivate(GtkMenuItem *item, Client *c);
173 static void print(Client *c, const Arg *arg);
174 static GdkFilterReturn processx(GdkXEvent *xevent, GdkEvent *event,
176 static void progresschanged(WebKitWebView *v, GParamSpec *ps, Client *c);
177 static void linkopen(Client *c, const Arg *arg);
178 static void linkopenembed(Client *c, const Arg *arg);
179 static void reload(Client *c, const Arg *arg);
180 static void scroll_h(Client *c, const Arg *arg);
181 static void scroll_v(Client *c, const Arg *arg);
182 static void scroll(GtkAdjustment *a, const Arg *arg);
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 titlechangeleave(void *a, void *b, Client *c);
190 static void toggle(Client *c, const Arg *arg);
191 static void togglecookiepolicy(Client *c, const Arg *arg);
192 static void togglegeolocation(Client *c, const Arg *arg);
193 static void togglescrollbars(Client *c, const Arg *arg);
194 static void togglestyle(Client *c, const Arg *arg);
195 static void updatetitle(Client *c);
196 static void updatewinid(Client *c);
197 static void usage(void);
198 static void windowobjectcleared(GtkWidget *w, WebKitWebFrame *frame,
199 JSContextRef js, JSObjectRef win, Client *c);
200 static void zoom(Client *c, const Arg *arg);
202 /* configuration, allows nested code to access above variables */
206 addaccelgroup(Client *c)
209 GtkAccelGroup *group = gtk_accel_group_new();
212 for (i = 0; i < LENGTH(keys); i++) {
213 closure = g_cclosure_new(G_CALLBACK(keypress), c, NULL);
214 gtk_accel_group_connect(group, keys[i].keyval, keys[i].mod, 0,
217 gtk_window_add_accel_group(GTK_WINDOW(c->win), group);
221 beforerequest(WebKitWebView *w, WebKitWebFrame *f, WebKitWebResource *r,
222 WebKitNetworkRequest *req, WebKitNetworkResponse *resp,
225 const gchar *uri = webkit_network_request_get_uri(req);
228 if (g_str_has_suffix(uri, "/favicon.ico"))
229 webkit_network_request_set_uri(req, "about:blank");
231 if (!g_str_has_prefix(uri, "http://")
232 && !g_str_has_prefix(uri, "https://")
233 && !g_str_has_prefix(uri, "about:")
234 && !g_str_has_prefix(uri, "file://")
235 && !g_str_has_prefix(uri, "data:")
236 && !g_str_has_prefix(uri, "blob:")
237 && strlen(uri) > 0) {
238 for (i = 0; i < strlen(uri); i++) {
239 if (!g_ascii_isprint(uri[i])) {
245 handleplumb(c, w, uri);
250 buildfile(const char *path)
252 char *dname, *bname, *bpath, *fpath;
255 dname = g_path_get_dirname(path);
256 bname = g_path_get_basename(path);
258 bpath = buildpath(dname);
261 fpath = g_build_filename(bpath, bname, NULL);
265 if (!(f = fopen(fpath, "a")))
266 die("Could not open file: %s\n", fpath);
268 g_chmod(fpath, 0600); /* always */
275 buildpath(const char *path)
278 char *apath, *name, *p, *fpath;
280 if (path[0] == '~') {
281 if (path[1] == '/' || path[1] == '\0') {
282 p = (char *)&path[1];
283 pw = getpwuid(getuid());
285 if ((p = strchr(path, '/')))
286 name = g_strndup(&path[1], --p - path);
288 name = g_strdup(&path[1]);
290 if (!(pw = getpwnam(name))) {
291 die("Can't get user %s home directory: %s.\n",
296 apath = g_build_filename(pw->pw_dir, p, NULL);
298 apath = g_strdup(path);
301 /* creating directory */
302 if (g_mkdir_with_parents(apath, 0700) < 0)
303 die("Could not access directory: %s\n", apath);
305 fpath = realpath(apath, NULL);
312 buttonreleased(GtkWidget *w, GdkEventKey *e, Client *c)
314 WebKitHitTestResultContext element;
315 GdkEventButton *eb = (GdkEventButton*)e;
318 element = webkit_hit_test_result_get_context(c->mousepos);
320 for (i = 0; i < LENGTH(buttons); ++i) {
321 if (element & buttons[i].target &&
322 eb->button == buttons[i].button &&
323 CLEANMASK(eb->state) == CLEANMASK(buttons[i].mask) &&
325 buttons[i].func(c, &buttons[i].arg, c->mousepos);
326 return buttons[i].stopevent;
337 destroyclient(clients);
344 WebKitCookieAcceptPolicy
345 cookiepolicy_get(void)
347 switch (cookiepolicies[cookiepolicy]) {
349 return WEBKIT_COOKIE_POLICY_ACCEPT_NEVER;
351 return WEBKIT_COOKIE_POLICY_ACCEPT_NO_THIRD_PARTY;
357 return WEBKIT_COOKIE_POLICY_ACCEPT_ALWAYS;
361 cookiepolicy_set(const WebKitCookieAcceptPolicy ep)
364 case WEBKIT_COOKIE_POLICY_ACCEPT_NEVER:
366 case WEBKIT_COOKIE_POLICY_ACCEPT_NO_THIRD_PARTY:
368 case WEBKIT_COOKIE_POLICY_ACCEPT_ALWAYS:
377 evalscript(JSContextRef js, char *script, char* scriptname)
379 JSStringRef jsscript, jsscriptname;
380 JSValueRef exception = NULL;
382 jsscript = JSStringCreateWithUTF8CString(script);
383 jsscriptname = JSStringCreateWithUTF8CString(scriptname);
384 JSEvaluateScript(js, jsscript, JSContextGetGlobalObject(js),
385 jsscriptname, 0, &exception);
386 JSStringRelease(jsscript);
387 JSStringRelease(jsscriptname);
391 runscript(WebKitWebFrame *frame)
396 if (g_file_get_contents(scriptfile, &script, NULL, &error)) {
397 evalscript(webkit_web_frame_get_global_context(frame), script,
403 clipboard(Client *c, const Arg *arg)
405 gboolean paste = *(gboolean *)arg;
408 gtk_clipboard_request_text(gtk_clipboard_get(
409 GDK_SELECTION_PRIMARY),
412 gtk_clipboard_set_text(gtk_clipboard_get(
413 GDK_SELECTION_PRIMARY), c->linkhover
414 ? c->linkhover : geturi(c), -1);
419 copystr(char **str, const char *src)
432 createview(WebKitWebView *v, WebKitNavigationAction *a, Client *c)
436 switch (webkit_navigation_action_get_navigation_type(a)) {
437 case WEBKIT_NAVIGATION_TYPE_OTHER: /* fallthrough */
439 * popup windows of type “other” are almost always triggered
440 * by user gesture, so inverse the logic here
442 /* instead of this, compare destination uri to mouse-over uri for validating window */
443 if (webkit_navigation_action_is_user_gesture(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:
459 return GTK_WIDGET(n->view);
463 decidepolicy(WebKitWebView *v, WebKitPolicyDecision *d,
464 WebKitPolicyDecisionType dt, Client *c)
467 case WEBKIT_POLICY_DECISION_TYPE_NAVIGATION_ACTION:
468 decidenavigation(d, c);
470 case WEBKIT_POLICY_DECISION_TYPE_NEW_WINDOW_ACTION:
471 decidenewwindow(d, c);
473 case WEBKIT_POLICY_DECISION_TYPE_RESPONSE:
474 decideresource(d, c);
477 webkit_policy_decision_ignore(d);
484 decidenavigation(WebKitPolicyDecision *d, Client *c)
486 WebKitNavigationAction *a;
488 a = webkit_navigation_policy_decision_get_navigation_action(
489 WEBKIT_NAVIGATION_POLICY_DECISION(d));
491 switch (webkit_navigation_action_get_navigation_type(a)) {
492 case WEBKIT_NAVIGATION_TYPE_LINK_CLICKED: /* fallthrough */
493 case WEBKIT_NAVIGATION_TYPE_FORM_SUBMITTED: /* fallthrough */
494 case WEBKIT_NAVIGATION_TYPE_BACK_FORWARD: /* fallthrough */
495 case WEBKIT_NAVIGATION_TYPE_RELOAD: /* fallthrough */
496 case WEBKIT_NAVIGATION_TYPE_FORM_RESUBMITTED:
497 case WEBKIT_NAVIGATION_TYPE_OTHER: /* fallthrough */
499 /* Do not navigate to links with a "_blank" target (popup) */
500 if (webkit_navigation_policy_decision_get_frame_name(
501 WEBKIT_NAVIGATION_POLICY_DECISION(d))) {
502 webkit_policy_decision_ignore(d);
504 /* Filter out navigation to different domain ? */
505 /* get action→urirequest, copy and load in new window+view
507 webkit_policy_decision_use(d);
514 decidenewwindow(WebKitPolicyDecision *d, Client *c)
516 WebKitNavigationAction *a;
519 a = webkit_navigation_policy_decision_get_navigation_action(
520 WEBKIT_NAVIGATION_POLICY_DECISION(d));
522 switch (webkit_navigation_action_get_navigation_type(a)) {
523 case WEBKIT_NAVIGATION_TYPE_LINK_CLICKED: /* fallthrough */
524 case WEBKIT_NAVIGATION_TYPE_FORM_SUBMITTED: /* fallthrough */
525 case WEBKIT_NAVIGATION_TYPE_BACK_FORWARD: /* fallthrough */
526 case WEBKIT_NAVIGATION_TYPE_RELOAD: /* fallthrough */
527 case WEBKIT_NAVIGATION_TYPE_FORM_RESUBMITTED:
528 /* Filter domains here */
529 /* If the value of “mouse-button” is not 0, then the navigation was triggered by a mouse event.
530 * test for link clicked but no button ? */
531 arg.v = webkit_uri_request_get_uri(
532 webkit_navigation_action_get_request(a));
533 newwindow(c, &arg, 0);
535 case WEBKIT_NAVIGATION_TYPE_OTHER: /* fallthrough */
540 webkit_policy_decision_ignore(d);
544 decideresource(WebKitPolicyDecision *d, Client *c)
546 WebKitResponsePolicyDecision *r = WEBKIT_RESPONSE_POLICY_DECISION(d);
547 WebKitURIResponse *res;
549 if (webkit_response_policy_decision_is_mime_type_supported(r)) {
550 webkit_policy_decision_use(d);
552 res = webkit_response_policy_decision_get_response(r);
553 webkit_policy_decision_ignore(d);
559 deletion_interface(WebKitWebView *view, WebKitDOMHTMLElement *arg1, Client *c)
565 destroyclient(Client *c)
569 webkit_web_view_stop_loading(c->view);
570 gtk_widget_destroy(GTK_WIDGET(c->view));
571 gtk_widget_destroy(c->scroll);
572 gtk_widget_destroy(c->vbox);
573 gtk_widget_destroy(c->win);
575 for (p = clients; p && p->next != c; p = p->next)
587 destroywin(GtkWidget* w, Client *c)
593 die(const char *errstr, ...)
597 va_start(ap, errstr);
598 vfprintf(stderr, errstr, ap);
604 find(Client *c, const Arg *arg)
608 s = getatom(c, AtomFind);
609 gboolean forward = *(gboolean *)arg;
610 webkit_web_view_search_text(c->view, s, FALSE, forward, TRUE);
614 fullscreen(Client *c, const Arg *arg)
617 gtk_window_unfullscreen(GTK_WINDOW(c->win));
619 gtk_window_fullscreen(GTK_WINDOW(c->win));
620 c->fullscreen = !c->fullscreen;
624 permissionrequested(WebKitWebView *v, WebKitPermissionRequest *r, Client *c)
626 if (WEBKIT_IS_GEOLOCATION_PERMISSION_REQUEST(r)) {
627 if (allowgeolocation)
628 webkit_permission_request_allow(r);
630 webkit_permission_request_deny(r);
638 getatom(Client *c, int a)
640 static char buf[BUFSIZ];
643 unsigned long ldummy;
644 unsigned char *p = NULL;
646 XGetWindowProperty(dpy, c->xid,
647 atoms[a], 0L, BUFSIZ, False, XA_STRING,
648 &adummy, &idummy, &ldummy, &ldummy, &p);
650 strncpy(buf, (char *)p, LENGTH(buf)-1);
663 if (!(uri = (char *)webkit_web_view_get_uri(c->view)))
669 getstyle(const char *uri)
673 if (stylefile != NULL)
676 for (i = 0; i < LENGTH(styles); i++) {
677 if (styles[i].regex && !regexec(&(styles[i].re), uri, 0,
679 return styles[i].style;
686 setstyle(Client *c, const char *style)
688 WebKitWebSettings *settings = webkit_web_view_get_settings(c->view);
690 g_object_set(G_OBJECT(settings), "user-stylesheet-uri", style, NULL);
694 handleplumb(Client *c, WebKitWebView *w, const gchar *uri)
698 webkit_web_view_stop_loading(w);
699 arg = (Arg)PLUMB((char *)uri);
704 downloadstarted(WebKitWebContext *wc, WebKitDownload *d, Client *c)
706 g_signal_connect(G_OBJECT(d), "notify::response",
707 G_CALLBACK(responsereceived), c);
711 responsereceived(WebKitDownload *d, GParamSpec *ps, Client *c)
713 download(c, webkit_download_get_response(d));
714 webkit_download_cancel(d);
718 download(Client *c, WebKitURIResponse *r)
722 a = (Arg)DOWNLOAD(webkit_uri_response_get_uri(r), geturi(c));
727 inspector(Client *c, const Arg *arg)
729 if (enableinspector) {
731 webkit_web_inspector_close(c->inspector);
733 webkit_web_inspector_show(c->inspector);
738 inspector_new(WebKitWebInspector *i, WebKitWebView *v, Client *c)
740 return WEBKIT_WEB_VIEW(webkit_web_view_new());
744 inspector_show(WebKitWebInspector *i, Client *c)
751 w = webkit_web_inspector_get_web_view(i);
752 gtk_paned_pack2(GTK_PANED(c->pane), GTK_WIDGET(w), TRUE, TRUE);
753 gtk_widget_show(GTK_WIDGET(w));
754 c->isinspecting = true;
760 inspector_close(WebKitWebInspector *i, Client *c)
764 if (!c->isinspecting)
767 w = GTK_WIDGET(webkit_web_inspector_get_web_view(i));
769 gtk_widget_destroy(w);
770 c->isinspecting = false;
776 inspector_finished(WebKitWebInspector *i, Client *c)
778 g_free(c->inspector);
782 keypress(GtkAccelGroup *group, GObject *obj, guint key, GdkModifierType mods,
786 gboolean processed = FALSE;
788 mods = CLEANMASK(mods);
789 key = gdk_keyval_to_lower(key);
791 for (i = 0; i < LENGTH(keys); i++) {
792 if (key == keys[i].keyval
793 && mods == keys[i].mod
795 keys[i].func(c, &(keys[i].arg));
804 mousetargetchanged(WebKitWebView *v, WebKitHitTestResult *h, guint modifiers,
807 WebKitHitTestResultContext hc;
809 /* Keep the hit test to know where is the pointer on the next click */
812 hc = webkit_hit_test_result_get_context(h);
815 c->targeturi = webkit_hit_test_result_get_link_uri(h);
817 c->targeturi = webkit_hit_test_result_get_image_uri(h);
818 else if (hc & OnMedia)
819 c->targeturi = webkit_hit_test_result_get_media_uri(h);
826 loadchanged(WebKitWebView *v, WebKitLoadEvent e, Client *c)
829 case WEBKIT_LOAD_STARTED:
830 c->tlsflags = G_TLS_CERTIFICATE_VALIDATE_ALL + 1;
832 case WEBKIT_LOAD_REDIRECTED:
833 setatom(c, AtomUri, geturi(c));
835 case WEBKIT_LOAD_COMMITTED:
836 if (!webkit_web_view_get_tls_info(c->view, NULL, &(c->tlsflags)))
837 c->tlsflags = G_TLS_CERTIFICATE_VALIDATE_ALL + 1;
839 setatom(c, AtomUri, geturi(c));
842 setstyle(c, getstyle(geturi(c)));
844 case WEBKIT_LOAD_FINISHED:
845 /* Disabled until we write some WebKitWebExtension for
846 * manipulating the DOM directly.
847 evalscript(c, "document.documentElement.style.overflow = '%s'",
848 enablescrollbars ? "auto" : "hidden");
857 loaduri(Client *c, const Arg *arg)
860 const char *uri = (char *)arg->v;
861 Arg a = { .b = FALSE };
864 if (strcmp(uri, "") == 0)
867 /* In case it's a file path. */
868 if (stat(uri, &st) == 0) {
869 rp = realpath(uri, NULL);
870 u = g_strdup_printf("file://%s", rp);
873 u = g_strrstr(uri, "://") ? g_strdup(uri)
874 : g_strdup_printf("http://%s", uri);
877 setatom(c, AtomUri, uri);
879 /* prevents endless loop */
880 if (strcmp(u, geturi(c)) == 0) {
883 webkit_web_view_load_uri(c->view, u);
885 c->title = copystr(&c->title, u);
892 navigate(Client *c, const Arg *arg)
894 int steps = *(int *)arg;
895 webkit_web_view_go_back_or_forward(c->view, steps);
899 newclient(Client *rc)
904 if (!(c = calloc(1, sizeof(Client))))
905 die("Cannot malloc!\n");
913 c->view = newview(c, rc ? rc->view : NULL);
914 c->tlsflags = G_TLS_CERTIFICATE_VALIDATE_ALL + 1;
920 newview(Client *c, WebKitWebView *rv)
923 WebKitSettings *settings;
924 WebKitUserContentManager *contentmanager;
925 WebKitWebContext *context;
931 webkit_web_view_new_with_related_view(rv));
933 settings = webkit_settings_new_with_settings(
934 "auto-load-images", loadimages,
935 "default-font-size", defaultfontsize,
936 "enable-caret-browsing", enablecaretbrowsing,
937 "enable-developer-extras", enableinspector,
938 "enable-dns-prefetching", enablednsprefetching,
939 "enable-frame-flattening", enableframeflattening,
940 "enable-html5-database", enablecache,
941 "enable-html5-local-storage", enablecache,
942 "enable-javascript", enablescripts,
943 "enable-plugins", enableplugins,
945 if (!(ua = getenv("SURF_USERAGENT")))
947 webkit_settings_set_user_agent(settings, ua);
948 /* Have a look at http://webkitgtk.org/reference/webkit2gtk/stable/WebKitSettings.html
949 * for more interesting settings */
951 contentmanager = webkit_user_content_manager_new();
953 context = webkit_web_context_new_with_website_data_manager(
954 webkit_website_data_manager_new(
955 "base-cache-directory", cachedir,
956 "base-data-directory", cachedir,
959 /* rendering process model, can be a shared unique one or one for each
961 webkit_web_context_set_process_model(context,
962 WEBKIT_PROCESS_MODEL_MULTIPLE_SECONDARY_PROCESSES);
964 webkit_web_context_set_tls_errors_policy(context, strictssl ?
965 WEBKIT_TLS_ERRORS_POLICY_FAIL : WEBKIT_TLS_ERRORS_POLICY_IGNORE);
967 webkit_web_context_set_cache_model(context, enablecache ?
968 WEBKIT_CACHE_MODEL_WEB_BROWSER : WEBKIT_CACHE_MODEL_DOCUMENT_VIEWER);
970 /* Currently only works with text file to be compatible with curl */
971 webkit_cookie_manager_set_persistent_storage(
972 webkit_web_context_get_cookie_manager(context), cookiefile,
973 WEBKIT_COOKIE_PERSISTENT_STORAGE_TEXT);
975 webkit_cookie_manager_set_accept_policy(
976 webkit_web_context_get_cookie_manager(context),
979 g_signal_connect(G_OBJECT(context), "download-started",
980 G_CALLBACK(downloadstarted), c);
982 v = g_object_new(WEBKIT_TYPE_WEB_VIEW,
983 "settings", settings,
984 "user-content-manager", contentmanager,
985 "web-context", context,
989 g_signal_connect(G_OBJECT(v),
991 G_CALLBACK(titlechanged), c);
992 g_signal_connect(G_OBJECT(v),
993 "mouse-target-changed",
994 G_CALLBACK(mousetargetchanged), c);
995 g_signal_connect(G_OBJECT(v),
996 "permission-request",
997 G_CALLBACK(permissionrequested), c);
998 g_signal_connect(G_OBJECT(v),
1000 G_CALLBACK(createview), c);
1001 g_signal_connect(G_OBJECT(v), "ready-to-show",
1002 G_CALLBACK(showview), c);
1003 g_signal_connect(G_OBJECT(v),
1005 G_CALLBACK(decidepolicy), c);
1006 g_signal_connect(G_OBJECT(v),
1007 "window-object-cleared",
1008 G_CALLBACK(windowobjectcleared), c);
1009 g_signal_connect(G_OBJECT(v),
1011 G_CALLBACK(loadchanged), c);
1012 g_signal_connect(G_OBJECT(v),
1013 "notify::estimated-load-progress",
1014 G_CALLBACK(progresschanged), c);
1015 g_signal_connect(G_OBJECT(v),
1016 "button-release-event",
1017 G_CALLBACK(buttonreleased), c);
1018 g_signal_connect(G_OBJECT(v),
1020 G_CALLBACK(contextmenu), c);
1021 g_signal_connect(G_OBJECT(v),
1022 "resource-request-starting",
1023 G_CALLBACK(beforerequest), c);
1024 g_signal_connect(G_OBJECT(v),
1025 "should-show-delete-interface-for-element",
1026 G_CALLBACK(deletion_interface), c);
1032 showview(WebKitWebView *v, Client *c)
1034 GdkGeometry hints = { 1, 1 };
1035 GdkRGBA bgcolor = { 0 };
1040 c->win = gtk_plug_new(embed);
1042 c->win = gtk_window_new(GTK_WINDOW_TOPLEVEL);
1044 /* TA: 20091214: Despite what the GNOME docs say, the ICCCM
1045 * is always correct, so we should still call this function.
1046 * But when doing so, we *must* differentiate between a
1047 * WM_CLASS and a resource on the window. By convention, the
1048 * window class (WM_CLASS) is capped, while the resource is in
1049 * lowercase. Both these values come as a pair.
1051 gtk_window_set_wmclass(GTK_WINDOW(c->win), "surf", "Surf");
1053 /* TA: 20091214: And set the role here as well -- so that
1054 * sessions can pick this up.
1056 gtk_window_set_role(GTK_WINDOW(c->win), "Surf");
1058 gtk_window_set_default_size(GTK_WINDOW(c->win), 800, 600);
1059 g_signal_connect(G_OBJECT(c->win),
1061 G_CALLBACK(destroywin), c);
1062 g_signal_connect(G_OBJECT(c->win),
1063 "leave_notify_event",
1064 G_CALLBACK(titlechangeleave), c);
1070 gtk_container_add(GTK_CONTAINER(c->win), GTK_WIDGET(c->view));
1073 gtk_widget_grab_focus(GTK_WIDGET(c->view));
1074 gtk_widget_show(GTK_WIDGET(c->view));
1075 gtk_widget_show(c->win);
1076 gwin = gtk_widget_get_window(GTK_WIDGET(c->win));
1077 c->xid = gdk_x11_window_get_xid(gwin);
1078 gtk_window_set_geometry_hints(GTK_WINDOW(c->win), NULL, &hints,
1080 gdk_window_set_events(gwin, GDK_ALL_EVENTS_MASK);
1081 gdk_window_add_filter(gwin, processx, c);
1085 /* This might conflict with _zoomto96dpi_. */
1086 if (zoomlevel != 1.0)
1087 webkit_web_view_set_zoom_level(c->view, zoomlevel);
1089 if (runinfullscreen)
1090 fullscreen(c, NULL);
1092 setatom(c, AtomFind, "");
1093 setatom(c, AtomUri, "about:blank");
1095 webkit_web_view_set_background_color(c->view, &bgcolor);
1098 gdk_display_sync(gtk_widget_get_display(c->win));
1099 printf("%lu\n", c->xid);
1101 if (fclose(stdout) != 0) {
1102 die("Error closing stdout");
1108 newwindow(Client *c, const Arg *arg, gboolean noembed)
1111 const char *cmd[18], *uri;
1112 const Arg a = { .v = (void *)cmd };
1117 cmd[i++] = cookiepolicies;
1118 if (!enablescrollbars)
1120 if (embed && !noembed) {
1122 snprintf(tmp, LENGTH(tmp), "%u", (int)embed);
1125 if (!allowgeolocation)
1137 if (enablediskcache)
1140 cmd[i++] = cookiefile;
1142 uri = arg->v ? (char *)arg->v : c->linkhover;
1150 contextmenu(WebKitWebView *view, GtkWidget *menu, WebKitHitTestResult *target,
1151 gboolean keyboard, Client *c)
1153 GList *items = gtk_container_get_children(GTK_CONTAINER(GTK_MENU(menu)));
1155 for (GList *l = items; l; l = l->next)
1156 g_signal_connect(l->data, "activate", G_CALLBACK(menuactivate), c);
1163 menuactivate(GtkMenuItem *item, Client *c)
1166 * context-menu-action-2000 open link
1167 * context-menu-action-1 open link in window
1168 * context-menu-action-2 download linked file
1169 * context-menu-action-3 copy link location
1170 * context-menu-action-7 copy image address
1171 * context-menu-action-13 reload
1172 * context-menu-action-10 back
1173 * context-menu-action-11 forward
1174 * context-menu-action-12 stop
1177 const gchar *name, *uri;
1178 GtkClipboard *prisel, *clpbrd;
1180 name = gtk_actionable_get_action_name(GTK_ACTIONABLE(item));
1184 if (!g_strcmp0(name, "context-menu-action-3")) {
1185 prisel = gtk_clipboard_get(GDK_SELECTION_PRIMARY);
1186 gtk_clipboard_set_text(prisel, c->linkhover, -1);
1187 } else if (!g_strcmp0(name, "context-menu-action-7")) {
1188 prisel = gtk_clipboard_get(GDK_SELECTION_PRIMARY);
1189 clpbrd = gtk_clipboard_get(GDK_SELECTION_CLIPBOARD);
1190 uri = gtk_clipboard_wait_for_text(clpbrd);
1192 gtk_clipboard_set_text(prisel, uri, -1);
1197 pasteuri(GtkClipboard *clipboard, const char *text, gpointer d)
1199 Arg arg = {.v = text };
1201 loaduri((Client *) d, &arg);
1205 print(Client *c, const Arg *arg)
1207 webkit_web_frame_print(webkit_web_view_get_main_frame(c->view));
1211 processx(GdkXEvent *e, GdkEvent *event, gpointer d)
1213 Client *c = (Client *)d;
1217 if (((XEvent *)e)->type == PropertyNotify) {
1218 ev = &((XEvent *)e)->xproperty;
1219 if (ev->state == PropertyNewValue) {
1220 if (ev->atom == atoms[AtomFind]) {
1224 return GDK_FILTER_REMOVE;
1225 } else if (ev->atom == atoms[AtomGo]) {
1226 arg.v = getatom(c, AtomGo);
1229 return GDK_FILTER_REMOVE;
1233 return GDK_FILTER_CONTINUE;
1237 progresschanged(WebKitWebView *v, GParamSpec *ps, Client *c)
1239 c->progress = webkit_web_view_get_estimated_load_progress(c->view) *
1245 linkopen(Client *c, const Arg *arg)
1247 newwindow(NULL, arg, 1);
1251 linkopenembed(Client *c, const Arg *arg)
1253 newwindow(NULL, arg, 0);
1257 reload(Client *c, const Arg *arg)
1259 gboolean nocache = *(gboolean *)arg;
1261 webkit_web_view_reload_bypass_cache(c->view);
1263 webkit_web_view_reload(c->view);
1267 scroll_h(Client *c, const Arg *arg)
1269 scroll(gtk_scrolled_window_get_hadjustment(
1270 GTK_SCROLLED_WINDOW(c->scroll)), arg);
1274 scroll_v(Client *c, const Arg *arg)
1276 scroll(gtk_scrolled_window_get_vadjustment(
1277 GTK_SCROLLED_WINDOW(c->scroll)), arg);
1281 scroll(GtkAdjustment *a, const Arg *arg)
1285 v = gtk_adjustment_get_value(a);
1289 v += gtk_adjustment_get_page_increment(a) * (arg->i / 10000);
1294 v += gtk_adjustment_get_step_increment(a) * arg->i;
1298 v = MIN(v, gtk_adjustment_get_upper(a) -
1299 gtk_adjustment_get_page_size(a));
1300 gtk_adjustment_set_value(a, v);
1304 setatom(Client *c, int a, const char *v)
1307 XChangeProperty(dpy, c->xid,
1308 atoms[a], XA_STRING, 8, PropModeReplace,
1309 (unsigned char *)v, strlen(v) + 1);
1316 char *styledirfile, *stylepath;
1317 WebKitWebContext *context;
1318 GError *error = NULL;
1320 /* clean up any zombies immediately */
1322 gtk_init(NULL, NULL);
1324 dpy = GDK_DISPLAY_XDISPLAY(gdk_display_get_default());
1327 atoms[AtomFind] = XInternAtom(dpy, "_SURF_FIND", False);
1328 atoms[AtomGo] = XInternAtom(dpy, "_SURF_GO", False);
1329 atoms[AtomUri] = XInternAtom(dpy, "_SURF_URI", False);
1331 /* dirs and files */
1332 cookiefile = buildfile(cookiefile);
1333 scriptfile = buildfile(scriptfile);
1334 cachedir = buildpath(cachedir);
1335 if (stylefile == NULL) {
1336 styledir = buildpath(styledir);
1337 for (i = 0; i < LENGTH(styles); i++) {
1338 if (regcomp(&(styles[i].re), styles[i].regex,
1341 "Could not compile regex: %s\n",
1343 styles[i].regex = NULL;
1345 styledirfile = g_strconcat(styledir, "/",
1346 styles[i].style, NULL);
1347 stylepath = buildfile(styledirfile);
1348 styles[i].style = g_strconcat("file://", stylepath,
1350 g_free(styledirfile);
1355 stylepath = buildfile(stylefile);
1356 stylefile = g_strconcat("file://", stylepath, NULL);
1364 if (signal(SIGCHLD, sigchld) == SIG_ERR)
1365 die("Can't install SIGCHLD handler");
1366 while (0 < waitpid(-1, NULL, WNOHANG));
1370 spawn(Client *c, const Arg *arg)
1374 close(ConnectionNumber(dpy));
1376 execvp(((char **)arg->v)[0], (char **)arg->v);
1377 fprintf(stderr, "surf: execvp %s", ((char **)arg->v)[0]);
1384 eval(Client *c, const Arg *arg)
1386 WebKitWebFrame *frame = webkit_web_view_get_main_frame(c->view);
1387 evalscript(webkit_web_frame_get_global_context(frame),
1388 ((char **)arg->v)[0], "");
1392 stop(Client *c, const Arg *arg)
1394 webkit_web_view_stop_loading(c->view);
1398 titlechanged(WebKitWebView *view, GParamSpec *ps, Client *c)
1400 c->title = webkit_web_view_get_title(c->view);
1405 titlechangeleave(void *a, void *b, Client *c)
1407 c->linkhover = NULL;
1412 toggle(Client *c, const Arg *arg)
1414 WebKitWebSettings *settings;
1415 char *name = (char *)arg->v;
1417 Arg a = { .b = FALSE };
1419 settings = webkit_web_view_get_settings(c->view);
1420 g_object_get(G_OBJECT(settings), name, &value, NULL);
1421 g_object_set(G_OBJECT(settings), name, !value, NULL);
1427 togglecookiepolicy(Client *c, const Arg *arg)
1430 cookiepolicy %= strlen(cookiepolicies);
1432 webkit_cookie_manager_set_accept_policy(
1433 webkit_web_context_get_cookie_manager(
1434 webkit_web_view_get_context(c->view)),
1435 cookiepolicy_get());
1438 /* Do not reload. */
1442 togglegeolocation(Client *c, const Arg *arg)
1444 Arg a = { .b = FALSE };
1446 allowgeolocation ^= 1;
1451 twitch(Client *c, const Arg *arg)
1456 a = gtk_scrolled_window_get_vadjustment(GTK_SCROLLED_WINDOW(
1459 v = gtk_adjustment_get_value(a);
1464 v = MIN(v, gtk_adjustment_get_upper(a) -
1465 gtk_adjustment_get_page_size(a));
1466 gtk_adjustment_set_value(a, v);
1470 togglescrollbars(Client *c, const Arg *arg)
1472 GtkPolicyType vspolicy;
1475 gtk_scrolled_window_get_policy(GTK_SCROLLED_WINDOW(c->scroll), NULL,
1478 if (vspolicy == GTK_POLICY_AUTOMATIC) {
1479 gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(c->scroll),
1483 gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(c->scroll),
1484 GTK_POLICY_AUTOMATIC,
1485 GTK_POLICY_AUTOMATIC);
1494 togglestyle(Client *c, const Arg *arg)
1496 enablestyle = !enablestyle;
1497 setstyle(c, enablestyle ? getstyle(geturi(c)) : "");
1503 gettogglestat(Client *c)
1507 WebKitWebSettings *settings = webkit_web_view_get_settings(c->view);
1509 togglestat[p++] = cookiepolicy_set(cookiepolicy_get());
1511 g_object_get(G_OBJECT(settings), "enable-caret-browsing", &value,
1513 togglestat[p++] = value? 'C': 'c';
1515 togglestat[p++] = allowgeolocation? 'G': 'g';
1517 togglestat[p++] = enablediskcache? 'D': 'd';
1519 g_object_get(G_OBJECT(settings), "auto-load-images", &value, NULL);
1520 togglestat[p++] = value? 'I': 'i';
1522 g_object_get(G_OBJECT(settings), "enable-scripts", &value, NULL);
1523 togglestat[p++] = value? 'S': 's';
1525 g_object_get(G_OBJECT(settings), "enable-plugins", &value, NULL);
1526 togglestat[p++] = value? 'V': 'v';
1528 togglestat[p++] = enablestyle ? 'M': 'm';
1530 togglestat[p] = '\0';
1534 getpagestat(Client *c)
1536 const char *uri = geturi(c);
1538 pagestats[0] = c->tlsflags > G_TLS_CERTIFICATE_VALIDATE_ALL ? '-' :
1539 c->tlsflags > 0 ? 'U' : 'T';
1544 updatetitle(Client *c)
1548 if (showindicators) {
1553 t = g_strdup_printf("%s:%s | %s", togglestat, pagestat,
1555 } else if (c->progress != 100) {
1556 t = g_strdup_printf("[%i%%] %s:%s | %s", c->progress,
1557 togglestat, pagestat,
1558 c->title == NULL ? "" : c->title);
1560 t = g_strdup_printf("%s:%s | %s", togglestat, pagestat,
1561 c->title == NULL ? "" : c->title);
1564 gtk_window_set_title(GTK_WINDOW(c->win), t);
1567 gtk_window_set_title(GTK_WINDOW(c->win), (c->title == NULL) ?
1573 updatewinid(Client *c)
1575 snprintf(winid, LENGTH(winid), "%lu", c->xid);
1581 die("usage: %s [-bBdDfFgGiIkKmMnNpPsSvx] [-a cookiepolicies ] "
1582 "[-c cookiefile] [-e xid] [-r scriptfile] [-t stylefile] "
1583 "[-u useragent] [-z zoomlevel] [uri]\n", basename(argv0));
1587 windowobjectcleared(GtkWidget *w, WebKitWebFrame *frame, JSContextRef js,
1588 JSObjectRef win, Client *c)
1594 zoom(Client *c, const Arg *arg)
1599 webkit_web_view_zoom_out(c->view);
1600 } else if (arg->i > 0) {
1602 webkit_web_view_zoom_in(c->view);
1606 webkit_web_view_set_zoom_level(c->view, 1.0);
1611 main(int argc, char *argv[])
1616 memset(&arg, 0, sizeof(arg));
1618 /* command line args */
1621 cookiepolicies = EARGF(usage());
1624 enablescrollbars = 0;
1627 enablescrollbars = 1;
1630 cookiefile = EARGF(usage());
1633 enablediskcache = 0;
1636 enablediskcache = 1;
1639 embed = strtol(EARGF(usage()), NULL, 0);
1642 runinfullscreen = 0;
1645 runinfullscreen = 1;
1648 allowgeolocation = 0;
1651 allowgeolocation = 1;
1672 enableinspector = 0;
1675 enableinspector = 1;
1684 scriptfile = EARGF(usage());
1693 stylefile = EARGF(usage());
1696 useragent = EARGF(usage());
1699 die("surf-"VERSION", ©2009-2015 surf engineers, "
1700 "see LICENSE for details\n");
1705 zoomlevel = strtof(EARGF(usage()), NULL);
1714 c = newclient(NULL);
1717 loaduri(clients, &arg);
1724 return EXIT_SUCCESS;