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 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 *arg);
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 eval(Client *c, const Arg *arg);
128 static void find(Client *c, const Arg *arg);
129 static void fullscreen(Client *c, const Arg *arg);
130 static gboolean permissionrequested(WebKitWebView *v,
131 WebKitPermissionRequest *r, Client *c);
132 static const char *getatom(Client *c, int a);
133 static void gettogglestat(Client *c);
134 static void getpagestat(Client *c);
135 static char *geturi(Client *c);
136 static const gchar *getstyle(const char *uri);
137 static void setstyle(Client *c, const char *style);
139 static void handleplumb(Client *c, const gchar *uri);
141 static void downloadstarted(WebKitWebContext *wc, WebKitDownload *d,
143 static void responsereceived(WebKitDownload *d, GParamSpec *ps, Client *c);
144 static void download(Client *c, WebKitURIResponse *r);
146 static void inspector(Client *c, const Arg *arg);
147 static WebKitWebView *inspector_new(WebKitWebInspector *i, WebKitWebView *v,
149 static gboolean inspector_show(WebKitWebInspector *i, Client *c);
150 static gboolean inspector_close(WebKitWebInspector *i, Client *c);
151 static void inspector_finished(WebKitWebInspector *i, Client *c);
153 static gboolean keypress(GtkAccelGroup *group, GObject *obj, guint key,
154 GdkModifierType mods, Client *c);
155 static void mousetargetchanged(WebKitWebView *v, WebKitHitTestResult *h,
156 guint modifiers, Client *c);
157 static void loadchanged(WebKitWebView *v, WebKitLoadEvent e, Client *c);
158 static void loaduri(Client *c, const Arg *arg);
159 static void navigate(Client *c, const Arg *arg);
160 static Client *newclient(Client *c);
161 static WebKitWebView *newview(Client *c, WebKitWebView *rv);
162 static void showview(WebKitWebView *v, Client *c);
163 static void newwindow(Client *c, const Arg *arg, gboolean noembed);
164 static void pasteuri(GtkClipboard *clipboard, const char *text, gpointer d);
165 static void print(Client *c, const Arg *arg);
166 static GdkFilterReturn processx(GdkXEvent *xevent, GdkEvent *event,
168 static void progresschanged(WebKitWebView *v, GParamSpec *ps, Client *c);
169 static void linkopen(Client *c, const Arg *arg);
170 static void linkopenembed(Client *c, const Arg *arg);
171 static void reload(Client *c, const Arg *arg);
172 static void scroll_h(Client *c, const Arg *arg);
173 static void scroll_v(Client *c, const Arg *arg);
174 static void scroll(GtkAdjustment *a, const Arg *arg);
175 static void setatom(Client *c, int a, const char *v);
176 static void setup(void);
177 static void sigchld(int unused);
178 static void spawn(Client *c, const Arg *arg);
179 static void stop(Client *c, const Arg *arg);
180 static void titlechanged(WebKitWebView *view, GParamSpec *ps, Client *c);
181 static void titlechangeleave(void *a, void *b, Client *c);
182 static void toggle(Client *c, const Arg *arg);
183 static void togglecookiepolicy(Client *c, const Arg *arg);
184 static void togglegeolocation(Client *c, const Arg *arg);
185 static void togglescrollbars(Client *c, const Arg *arg);
186 static void togglestyle(Client *c, const Arg *arg);
187 static void updatetitle(Client *c);
188 static void updatewinid(Client *c);
189 static void usage(void);
190 static void windowobjectcleared(GtkWidget *w, WebKitWebFrame *frame,
191 JSContextRef js, JSObjectRef win, Client *c);
192 static void zoom(Client *c, const Arg *arg);
194 /* configuration, allows nested code to access above variables */
198 addaccelgroup(Client *c)
201 GtkAccelGroup *group = gtk_accel_group_new();
204 for (i = 0; i < LENGTH(keys); i++) {
205 closure = g_cclosure_new(G_CALLBACK(keypress), c, NULL);
206 gtk_accel_group_connect(group, keys[i].keyval, keys[i].mod, 0,
209 gtk_window_add_accel_group(GTK_WINDOW(c->win), group);
213 buildfile(const char *path)
215 char *dname, *bname, *bpath, *fpath;
218 dname = g_path_get_dirname(path);
219 bname = g_path_get_basename(path);
221 bpath = buildpath(dname);
224 fpath = g_build_filename(bpath, bname, NULL);
228 if (!(f = fopen(fpath, "a")))
229 die("Could not open file: %s\n", fpath);
231 g_chmod(fpath, 0600); /* always */
238 buildpath(const char *path)
241 char *apath, *name, *p, *fpath;
243 if (path[0] == '~') {
244 if (path[1] == '/' || path[1] == '\0') {
245 p = (char *)&path[1];
246 pw = getpwuid(getuid());
248 if ((p = strchr(path, '/')))
249 name = g_strndup(&path[1], --p - path);
251 name = g_strdup(&path[1]);
253 if (!(pw = getpwnam(name))) {
254 die("Can't get user %s home directory: %s.\n",
259 apath = g_build_filename(pw->pw_dir, p, NULL);
261 apath = g_strdup(path);
264 /* creating directory */
265 if (g_mkdir_with_parents(apath, 0700) < 0)
266 die("Could not access directory: %s\n", apath);
268 fpath = realpath(apath, NULL);
275 buttonreleased(GtkWidget *w, GdkEventKey *e, Client *c)
277 WebKitHitTestResultContext element;
278 GdkEventButton *eb = (GdkEventButton*)e;
281 element = webkit_hit_test_result_get_context(c->mousepos);
283 for (i = 0; i < LENGTH(buttons); ++i) {
284 if (element & buttons[i].target &&
285 eb->button == buttons[i].button &&
286 CLEANMASK(eb->state) == CLEANMASK(buttons[i].mask) &&
288 buttons[i].func(c, &buttons[i].arg, c->mousepos);
289 return buttons[i].stopevent;
300 destroyclient(clients);
307 WebKitCookieAcceptPolicy
308 cookiepolicy_get(void)
310 switch (cookiepolicies[cookiepolicy]) {
312 return WEBKIT_COOKIE_POLICY_ACCEPT_NEVER;
314 return WEBKIT_COOKIE_POLICY_ACCEPT_NO_THIRD_PARTY;
320 return WEBKIT_COOKIE_POLICY_ACCEPT_ALWAYS;
324 cookiepolicy_set(const WebKitCookieAcceptPolicy ep)
327 case WEBKIT_COOKIE_POLICY_ACCEPT_NEVER:
329 case WEBKIT_COOKIE_POLICY_ACCEPT_NO_THIRD_PARTY:
331 case WEBKIT_COOKIE_POLICY_ACCEPT_ALWAYS:
340 evalscript(JSContextRef js, char *script, char* scriptname)
342 JSStringRef jsscript, jsscriptname;
343 JSValueRef exception = NULL;
345 jsscript = JSStringCreateWithUTF8CString(script);
346 jsscriptname = JSStringCreateWithUTF8CString(scriptname);
347 JSEvaluateScript(js, jsscript, JSContextGetGlobalObject(js),
348 jsscriptname, 0, &exception);
349 JSStringRelease(jsscript);
350 JSStringRelease(jsscriptname);
354 runscript(WebKitWebFrame *frame)
359 if (g_file_get_contents(scriptfile, &script, NULL, &error)) {
360 evalscript(webkit_web_frame_get_global_context(frame), script,
366 clipboard(Client *c, const Arg *arg)
368 gboolean paste = *(gboolean *)arg;
371 gtk_clipboard_request_text(gtk_clipboard_get(
372 GDK_SELECTION_PRIMARY),
375 gtk_clipboard_set_text(gtk_clipboard_get(
376 GDK_SELECTION_PRIMARY), c->linkhover
377 ? c->linkhover : 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 *arg)
598 s = getatom(c, AtomFind);
599 gboolean forward = *(gboolean *)arg;
600 webkit_web_view_search_text(c->view, s, FALSE, forward, TRUE);
604 fullscreen(Client *c, const Arg *arg)
607 gtk_window_unfullscreen(GTK_WINDOW(c->win));
609 gtk_window_fullscreen(GTK_WINDOW(c->win));
610 c->fullscreen = !c->fullscreen;
614 permissionrequested(WebKitWebView *v, WebKitPermissionRequest *r, Client *c)
616 if (WEBKIT_IS_GEOLOCATION_PERMISSION_REQUEST(r)) {
617 if (allowgeolocation)
618 webkit_permission_request_allow(r);
620 webkit_permission_request_deny(r);
628 getatom(Client *c, int a)
630 static char buf[BUFSIZ];
633 unsigned long ldummy;
634 unsigned char *p = NULL;
636 XGetWindowProperty(dpy, c->xid,
637 atoms[a], 0L, BUFSIZ, False, XA_STRING,
638 &adummy, &idummy, &ldummy, &ldummy, &p);
640 strncpy(buf, (char *)p, LENGTH(buf)-1);
653 if (!(uri = (char *)webkit_web_view_get_uri(c->view)))
659 getstyle(const char *uri)
663 if (stylefile != NULL)
666 for (i = 0; i < LENGTH(styles); i++) {
667 if (styles[i].regex && !regexec(&(styles[i].re), uri, 0,
669 return styles[i].style;
676 setstyle(Client *c, const char *style)
678 WebKitWebSettings *settings = webkit_web_view_get_settings(c->view);
680 g_object_set(G_OBJECT(settings), "user-stylesheet-uri", style, NULL);
684 handleplumb(Client *c, const gchar *uri)
688 arg = (Arg)PLUMB(uri);
693 downloadstarted(WebKitWebContext *wc, WebKitDownload *d, Client *c)
695 g_signal_connect(G_OBJECT(d), "notify::response",
696 G_CALLBACK(responsereceived), c);
700 responsereceived(WebKitDownload *d, GParamSpec *ps, Client *c)
702 download(c, webkit_download_get_response(d));
703 webkit_download_cancel(d);
707 download(Client *c, WebKitURIResponse *r)
711 a = (Arg)DOWNLOAD(webkit_uri_response_get_uri(r), geturi(c));
716 inspector(Client *c, const Arg *arg)
718 if (enableinspector) {
720 webkit_web_inspector_close(c->inspector);
722 webkit_web_inspector_show(c->inspector);
727 inspector_new(WebKitWebInspector *i, WebKitWebView *v, Client *c)
729 return WEBKIT_WEB_VIEW(webkit_web_view_new());
733 inspector_show(WebKitWebInspector *i, Client *c)
740 w = webkit_web_inspector_get_web_view(i);
741 gtk_paned_pack2(GTK_PANED(c->pane), GTK_WIDGET(w), TRUE, TRUE);
742 gtk_widget_show(GTK_WIDGET(w));
743 c->isinspecting = true;
749 inspector_close(WebKitWebInspector *i, Client *c)
753 if (!c->isinspecting)
756 w = GTK_WIDGET(webkit_web_inspector_get_web_view(i));
758 gtk_widget_destroy(w);
759 c->isinspecting = false;
765 inspector_finished(WebKitWebInspector *i, Client *c)
767 g_free(c->inspector);
771 keypress(GtkAccelGroup *group, GObject *obj, guint key, GdkModifierType mods,
775 gboolean processed = FALSE;
777 mods = CLEANMASK(mods);
778 key = gdk_keyval_to_lower(key);
780 for (i = 0; i < LENGTH(keys); i++) {
781 if (key == keys[i].keyval
782 && mods == keys[i].mod
784 keys[i].func(c, &(keys[i].arg));
793 mousetargetchanged(WebKitWebView *v, WebKitHitTestResult *h, guint modifiers,
796 WebKitHitTestResultContext hc;
798 /* Keep the hit test to know where is the pointer on the next click */
801 hc = webkit_hit_test_result_get_context(h);
804 c->targeturi = webkit_hit_test_result_get_link_uri(h);
806 c->targeturi = webkit_hit_test_result_get_image_uri(h);
807 else if (hc & OnMedia)
808 c->targeturi = webkit_hit_test_result_get_media_uri(h);
815 loadchanged(WebKitWebView *v, WebKitLoadEvent e, Client *c)
818 case WEBKIT_LOAD_STARTED:
819 c->tlsflags = G_TLS_CERTIFICATE_VALIDATE_ALL + 1;
821 case WEBKIT_LOAD_REDIRECTED:
822 setatom(c, AtomUri, geturi(c));
824 case WEBKIT_LOAD_COMMITTED:
825 if (!webkit_web_view_get_tls_info(c->view, NULL, &(c->tlsflags)))
826 c->tlsflags = G_TLS_CERTIFICATE_VALIDATE_ALL + 1;
828 setatom(c, AtomUri, geturi(c));
831 setstyle(c, getstyle(geturi(c)));
833 case WEBKIT_LOAD_FINISHED:
834 /* Disabled until we write some WebKitWebExtension for
835 * manipulating the DOM directly.
836 evalscript(c, "document.documentElement.style.overflow = '%s'",
837 enablescrollbars ? "auto" : "hidden");
846 loaduri(Client *c, const Arg *arg)
849 const char *uri = (char *)arg->v;
850 Arg a = { .b = FALSE };
853 if (strcmp(uri, "") == 0)
856 /* In case it's a file path. */
857 if (stat(uri, &st) == 0) {
858 rp = realpath(uri, NULL);
859 u = g_strdup_printf("file://%s", rp);
862 u = g_strrstr(uri, "://") ? g_strdup(uri)
863 : g_strdup_printf("http://%s", uri);
866 setatom(c, AtomUri, uri);
868 /* prevents endless loop */
869 if (strcmp(u, geturi(c)) == 0) {
872 webkit_web_view_load_uri(c->view, u);
874 c->title = copystr(&c->title, u);
881 navigate(Client *c, const Arg *arg)
883 int steps = *(int *)arg;
884 webkit_web_view_go_back_or_forward(c->view, steps);
888 newclient(Client *rc)
893 if (!(c = calloc(1, sizeof(Client))))
894 die("Cannot malloc!\n");
902 c->view = newview(c, rc ? rc->view : NULL);
903 c->tlsflags = G_TLS_CERTIFICATE_VALIDATE_ALL + 1;
909 newview(Client *c, WebKitWebView *rv)
912 WebKitSettings *settings;
913 WebKitUserContentManager *contentmanager;
914 WebKitWebContext *context;
920 webkit_web_view_new_with_related_view(rv));
922 settings = webkit_settings_new_with_settings(
923 "auto-load-images", loadimages,
924 "default-font-size", defaultfontsize,
925 "enable-caret-browsing", enablecaretbrowsing,
926 "enable-developer-extras", enableinspector,
927 "enable-dns-prefetching", enablednsprefetching,
928 "enable-frame-flattening", enableframeflattening,
929 "enable-html5-database", enablecache,
930 "enable-html5-local-storage", enablecache,
931 "enable-javascript", enablescripts,
932 "enable-plugins", enableplugins,
934 if (!(ua = getenv("SURF_USERAGENT")))
936 webkit_settings_set_user_agent(settings, ua);
937 /* Have a look at http://webkitgtk.org/reference/webkit2gtk/stable/WebKitSettings.html
938 * for more interesting settings */
940 contentmanager = webkit_user_content_manager_new();
942 context = webkit_web_context_new_with_website_data_manager(
943 webkit_website_data_manager_new(
944 "base-cache-directory", cachedir,
945 "base-data-directory", cachedir,
948 /* rendering process model, can be a shared unique one or one for each
950 webkit_web_context_set_process_model(context,
951 WEBKIT_PROCESS_MODEL_MULTIPLE_SECONDARY_PROCESSES);
953 webkit_web_context_set_tls_errors_policy(context, strictssl ?
954 WEBKIT_TLS_ERRORS_POLICY_FAIL : WEBKIT_TLS_ERRORS_POLICY_IGNORE);
956 webkit_web_context_set_cache_model(context, enablecache ?
957 WEBKIT_CACHE_MODEL_WEB_BROWSER : WEBKIT_CACHE_MODEL_DOCUMENT_VIEWER);
959 /* Currently only works with text file to be compatible with curl */
960 webkit_cookie_manager_set_persistent_storage(
961 webkit_web_context_get_cookie_manager(context), cookiefile,
962 WEBKIT_COOKIE_PERSISTENT_STORAGE_TEXT);
964 webkit_cookie_manager_set_accept_policy(
965 webkit_web_context_get_cookie_manager(context),
968 g_signal_connect(G_OBJECT(context), "download-started",
969 G_CALLBACK(downloadstarted), c);
971 v = g_object_new(WEBKIT_TYPE_WEB_VIEW,
972 "settings", settings,
973 "user-content-manager", contentmanager,
974 "web-context", context,
978 g_signal_connect(G_OBJECT(v),
980 G_CALLBACK(titlechanged), c);
981 g_signal_connect(G_OBJECT(v),
982 "mouse-target-changed",
983 G_CALLBACK(mousetargetchanged), c);
984 g_signal_connect(G_OBJECT(v),
985 "permission-request",
986 G_CALLBACK(permissionrequested), c);
987 g_signal_connect(G_OBJECT(v),
989 G_CALLBACK(createview), c);
990 g_signal_connect(G_OBJECT(v), "ready-to-show",
991 G_CALLBACK(showview), c);
992 g_signal_connect(G_OBJECT(v),
994 G_CALLBACK(decidepolicy), c);
995 g_signal_connect(G_OBJECT(v),
996 "window-object-cleared",
997 G_CALLBACK(windowobjectcleared), c);
998 g_signal_connect(G_OBJECT(v),
1000 G_CALLBACK(loadchanged), c);
1001 g_signal_connect(G_OBJECT(v),
1002 "notify::estimated-load-progress",
1003 G_CALLBACK(progresschanged), c);
1004 g_signal_connect(G_OBJECT(v),
1005 "button-release-event",
1006 G_CALLBACK(buttonreleased), c);
1007 g_signal_connect(G_OBJECT(v), "close",
1008 G_CALLBACK(closeview), c);
1014 showview(WebKitWebView *v, Client *c)
1016 GdkGeometry hints = { 1, 1 };
1017 GdkRGBA bgcolor = { 0 };
1022 c->win = gtk_plug_new(embed);
1024 c->win = gtk_window_new(GTK_WINDOW_TOPLEVEL);
1026 /* TA: 20091214: Despite what the GNOME docs say, the ICCCM
1027 * is always correct, so we should still call this function.
1028 * But when doing so, we *must* differentiate between a
1029 * WM_CLASS and a resource on the window. By convention, the
1030 * window class (WM_CLASS) is capped, while the resource is in
1031 * lowercase. Both these values come as a pair.
1033 gtk_window_set_wmclass(GTK_WINDOW(c->win), "surf", "Surf");
1035 /* TA: 20091214: And set the role here as well -- so that
1036 * sessions can pick this up.
1038 gtk_window_set_role(GTK_WINDOW(c->win), "Surf");
1040 gtk_window_set_default_size(GTK_WINDOW(c->win), 800, 600);
1041 g_signal_connect(G_OBJECT(c->win),
1043 G_CALLBACK(destroywin), c);
1044 g_signal_connect(G_OBJECT(c->win),
1045 "leave_notify_event",
1046 G_CALLBACK(titlechangeleave), c);
1052 gtk_container_add(GTK_CONTAINER(c->win), GTK_WIDGET(c->view));
1055 gtk_widget_grab_focus(GTK_WIDGET(c->view));
1056 gtk_widget_show(GTK_WIDGET(c->view));
1057 gtk_widget_show(c->win);
1058 gwin = gtk_widget_get_window(GTK_WIDGET(c->win));
1059 c->xid = gdk_x11_window_get_xid(gwin);
1060 gtk_window_set_geometry_hints(GTK_WINDOW(c->win), NULL, &hints,
1062 gdk_window_set_events(gwin, GDK_ALL_EVENTS_MASK);
1063 gdk_window_add_filter(gwin, processx, c);
1067 /* This might conflict with _zoomto96dpi_. */
1068 if (zoomlevel != 1.0)
1069 webkit_web_view_set_zoom_level(c->view, zoomlevel);
1071 if (runinfullscreen)
1072 fullscreen(c, NULL);
1074 setatom(c, AtomFind, "");
1075 setatom(c, AtomUri, "about:blank");
1077 webkit_web_view_set_background_color(c->view, &bgcolor);
1080 gdk_display_sync(gtk_widget_get_display(c->win));
1081 printf("%lu\n", c->xid);
1083 if (fclose(stdout) != 0) {
1084 die("Error closing stdout");
1090 newwindow(Client *c, const Arg *arg, gboolean noembed)
1093 const char *cmd[18], *uri;
1094 const Arg a = { .v = (void *)cmd };
1099 cmd[i++] = cookiepolicies;
1100 if (!enablescrollbars)
1102 if (embed && !noembed) {
1104 snprintf(tmp, LENGTH(tmp), "%u", (int)embed);
1107 if (!allowgeolocation)
1119 if (enablediskcache)
1122 cmd[i++] = cookiefile;
1124 uri = arg->v ? (char *)arg->v : c->linkhover;
1132 pasteuri(GtkClipboard *clipboard, const char *text, gpointer d)
1134 Arg arg = {.v = text };
1136 loaduri((Client *) d, &arg);
1140 print(Client *c, const Arg *arg)
1142 webkit_web_frame_print(webkit_web_view_get_main_frame(c->view));
1146 processx(GdkXEvent *e, GdkEvent *event, gpointer d)
1148 Client *c = (Client *)d;
1152 if (((XEvent *)e)->type == PropertyNotify) {
1153 ev = &((XEvent *)e)->xproperty;
1154 if (ev->state == PropertyNewValue) {
1155 if (ev->atom == atoms[AtomFind]) {
1159 return GDK_FILTER_REMOVE;
1160 } else if (ev->atom == atoms[AtomGo]) {
1161 arg.v = getatom(c, AtomGo);
1164 return GDK_FILTER_REMOVE;
1168 return GDK_FILTER_CONTINUE;
1172 progresschanged(WebKitWebView *v, GParamSpec *ps, Client *c)
1174 c->progress = webkit_web_view_get_estimated_load_progress(c->view) *
1180 linkopen(Client *c, const Arg *arg)
1182 newwindow(NULL, arg, 1);
1186 linkopenembed(Client *c, const Arg *arg)
1188 newwindow(NULL, arg, 0);
1192 reload(Client *c, const Arg *arg)
1194 gboolean nocache = *(gboolean *)arg;
1196 webkit_web_view_reload_bypass_cache(c->view);
1198 webkit_web_view_reload(c->view);
1202 scroll_h(Client *c, const Arg *arg)
1204 scroll(gtk_scrolled_window_get_hadjustment(
1205 GTK_SCROLLED_WINDOW(c->scroll)), arg);
1209 scroll_v(Client *c, const Arg *arg)
1211 scroll(gtk_scrolled_window_get_vadjustment(
1212 GTK_SCROLLED_WINDOW(c->scroll)), arg);
1216 scroll(GtkAdjustment *a, const Arg *arg)
1220 v = gtk_adjustment_get_value(a);
1224 v += gtk_adjustment_get_page_increment(a) * (arg->i / 10000);
1229 v += gtk_adjustment_get_step_increment(a) * arg->i;
1233 v = MIN(v, gtk_adjustment_get_upper(a) -
1234 gtk_adjustment_get_page_size(a));
1235 gtk_adjustment_set_value(a, v);
1239 setatom(Client *c, int a, const char *v)
1242 XChangeProperty(dpy, c->xid,
1243 atoms[a], XA_STRING, 8, PropModeReplace,
1244 (unsigned char *)v, strlen(v) + 1);
1251 char *styledirfile, *stylepath;
1252 WebKitWebContext *context;
1253 GError *error = NULL;
1255 /* clean up any zombies immediately */
1257 gtk_init(NULL, NULL);
1259 dpy = GDK_DISPLAY_XDISPLAY(gdk_display_get_default());
1262 atoms[AtomFind] = XInternAtom(dpy, "_SURF_FIND", False);
1263 atoms[AtomGo] = XInternAtom(dpy, "_SURF_GO", False);
1264 atoms[AtomUri] = XInternAtom(dpy, "_SURF_URI", False);
1266 /* dirs and files */
1267 cookiefile = buildfile(cookiefile);
1268 scriptfile = buildfile(scriptfile);
1269 cachedir = buildpath(cachedir);
1270 if (stylefile == NULL) {
1271 styledir = buildpath(styledir);
1272 for (i = 0; i < LENGTH(styles); i++) {
1273 if (regcomp(&(styles[i].re), styles[i].regex,
1276 "Could not compile regex: %s\n",
1278 styles[i].regex = NULL;
1280 styledirfile = g_strconcat(styledir, "/",
1281 styles[i].style, NULL);
1282 stylepath = buildfile(styledirfile);
1283 styles[i].style = g_strconcat("file://", stylepath,
1285 g_free(styledirfile);
1290 stylepath = buildfile(stylefile);
1291 stylefile = g_strconcat("file://", stylepath, NULL);
1299 if (signal(SIGCHLD, sigchld) == SIG_ERR)
1300 die("Can't install SIGCHLD handler");
1301 while (0 < waitpid(-1, NULL, WNOHANG));
1305 spawn(Client *c, const Arg *arg)
1309 close(ConnectionNumber(dpy));
1311 execvp(((char **)arg->v)[0], (char **)arg->v);
1312 fprintf(stderr, "surf: execvp %s", ((char **)arg->v)[0]);
1319 eval(Client *c, const Arg *arg)
1321 WebKitWebFrame *frame = webkit_web_view_get_main_frame(c->view);
1322 evalscript(webkit_web_frame_get_global_context(frame),
1323 ((char **)arg->v)[0], "");
1327 stop(Client *c, const Arg *arg)
1329 webkit_web_view_stop_loading(c->view);
1333 titlechanged(WebKitWebView *view, GParamSpec *ps, Client *c)
1335 c->title = webkit_web_view_get_title(c->view);
1340 titlechangeleave(void *a, void *b, Client *c)
1342 c->linkhover = NULL;
1347 toggle(Client *c, const Arg *arg)
1349 WebKitWebSettings *settings;
1350 char *name = (char *)arg->v;
1352 Arg a = { .b = FALSE };
1354 settings = webkit_web_view_get_settings(c->view);
1355 g_object_get(G_OBJECT(settings), name, &value, NULL);
1356 g_object_set(G_OBJECT(settings), name, !value, NULL);
1362 togglecookiepolicy(Client *c, const Arg *arg)
1365 cookiepolicy %= strlen(cookiepolicies);
1367 webkit_cookie_manager_set_accept_policy(
1368 webkit_web_context_get_cookie_manager(
1369 webkit_web_view_get_context(c->view)),
1370 cookiepolicy_get());
1373 /* Do not reload. */
1377 togglegeolocation(Client *c, const Arg *arg)
1379 Arg a = { .b = FALSE };
1381 allowgeolocation ^= 1;
1386 twitch(Client *c, const Arg *arg)
1391 a = gtk_scrolled_window_get_vadjustment(GTK_SCROLLED_WINDOW(
1394 v = gtk_adjustment_get_value(a);
1399 v = MIN(v, gtk_adjustment_get_upper(a) -
1400 gtk_adjustment_get_page_size(a));
1401 gtk_adjustment_set_value(a, v);
1405 togglescrollbars(Client *c, const Arg *arg)
1407 GtkPolicyType vspolicy;
1410 gtk_scrolled_window_get_policy(GTK_SCROLLED_WINDOW(c->scroll), NULL,
1413 if (vspolicy == GTK_POLICY_AUTOMATIC) {
1414 gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(c->scroll),
1418 gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(c->scroll),
1419 GTK_POLICY_AUTOMATIC,
1420 GTK_POLICY_AUTOMATIC);
1429 togglestyle(Client *c, const Arg *arg)
1431 enablestyle = !enablestyle;
1432 setstyle(c, enablestyle ? getstyle(geturi(c)) : "");
1438 gettogglestat(Client *c)
1442 WebKitWebSettings *settings = webkit_web_view_get_settings(c->view);
1444 togglestat[p++] = cookiepolicy_set(cookiepolicy_get());
1446 g_object_get(G_OBJECT(settings), "enable-caret-browsing", &value,
1448 togglestat[p++] = value? 'C': 'c';
1450 togglestat[p++] = allowgeolocation? 'G': 'g';
1452 togglestat[p++] = enablediskcache? 'D': 'd';
1454 g_object_get(G_OBJECT(settings), "auto-load-images", &value, NULL);
1455 togglestat[p++] = value? 'I': 'i';
1457 g_object_get(G_OBJECT(settings), "enable-scripts", &value, NULL);
1458 togglestat[p++] = value? 'S': 's';
1460 g_object_get(G_OBJECT(settings), "enable-plugins", &value, NULL);
1461 togglestat[p++] = value? 'V': 'v';
1463 togglestat[p++] = enablestyle ? 'M': 'm';
1465 togglestat[p] = '\0';
1469 getpagestat(Client *c)
1471 const char *uri = geturi(c);
1473 pagestats[0] = c->tlsflags > G_TLS_CERTIFICATE_VALIDATE_ALL ? '-' :
1474 c->tlsflags > 0 ? 'U' : 'T';
1479 updatetitle(Client *c)
1483 if (showindicators) {
1488 t = g_strdup_printf("%s:%s | %s", togglestat, pagestat,
1490 } else if (c->progress != 100) {
1491 t = g_strdup_printf("[%i%%] %s:%s | %s", c->progress,
1492 togglestat, pagestat,
1493 c->title == NULL ? "" : c->title);
1495 t = g_strdup_printf("%s:%s | %s", togglestat, pagestat,
1496 c->title == NULL ? "" : c->title);
1499 gtk_window_set_title(GTK_WINDOW(c->win), t);
1502 gtk_window_set_title(GTK_WINDOW(c->win), (c->title == NULL) ?
1508 updatewinid(Client *c)
1510 snprintf(winid, LENGTH(winid), "%lu", c->xid);
1516 die("usage: %s [-bBdDfFgGiIkKmMnNpPsSvx] [-a cookiepolicies ] "
1517 "[-c cookiefile] [-e xid] [-r scriptfile] [-t stylefile] "
1518 "[-u useragent] [-z zoomlevel] [uri]\n", basename(argv0));
1522 windowobjectcleared(GtkWidget *w, WebKitWebFrame *frame, JSContextRef js,
1523 JSObjectRef win, Client *c)
1529 zoom(Client *c, const Arg *arg)
1534 webkit_web_view_zoom_out(c->view);
1535 } else if (arg->i > 0) {
1537 webkit_web_view_zoom_in(c->view);
1541 webkit_web_view_set_zoom_level(c->view, 1.0);
1546 main(int argc, char *argv[])
1551 memset(&arg, 0, sizeof(arg));
1553 /* command line args */
1556 cookiepolicies = EARGF(usage());
1559 enablescrollbars = 0;
1562 enablescrollbars = 1;
1565 cookiefile = EARGF(usage());
1568 enablediskcache = 0;
1571 enablediskcache = 1;
1574 embed = strtol(EARGF(usage()), NULL, 0);
1577 runinfullscreen = 0;
1580 runinfullscreen = 1;
1583 allowgeolocation = 0;
1586 allowgeolocation = 1;
1607 enableinspector = 0;
1610 enableinspector = 1;
1619 scriptfile = EARGF(usage());
1628 stylefile = EARGF(usage());
1631 useragent = EARGF(usage());
1634 die("surf-"VERSION", ©2009-2015 surf engineers, "
1635 "see LICENSE for details\n");
1640 zoomlevel = strtof(EARGF(usage()), NULL);
1649 c = newclient(NULL);
1652 loaduri(clients, &arg);
1659 return EXIT_SUCCESS;