1 /* See LICENSE file for copyright and license details.
3 * To understand surf, start reading main().
12 #include <gdk/gdkkeysyms.h>
14 #include <sys/types.h>
20 #include <webkit2/webkit2.h>
21 #include <glib/gstdio.h>
22 #include <JavaScriptCore/JavaScript.h>
34 #define LENGTH(x) (sizeof(x) / sizeof(x[0]))
35 #define CLEANMASK(mask) (mask & (MODKEY|GDK_SHIFT_MASK))
37 enum { AtomFind, AtomGo, AtomUri, AtomLast };
40 OnDoc = WEBKIT_HIT_TEST_RESULT_CONTEXT_DOCUMENT,
41 OnLink = WEBKIT_HIT_TEST_RESULT_CONTEXT_LINK,
42 OnImg = WEBKIT_HIT_TEST_RESULT_CONTEXT_IMAGE,
43 OnMedia = WEBKIT_HIT_TEST_RESULT_CONTEXT_MEDIA,
44 OnEdit = WEBKIT_HIT_TEST_RESULT_CONTEXT_EDITABLE,
45 OnBar = WEBKIT_HIT_TEST_RESULT_CONTEXT_SCROLLBAR,
46 OnSel = WEBKIT_HIT_TEST_RESULT_CONTEXT_SELECTION,
47 OnAny = OnDoc | OnLink | OnImg | OnMedia | OnEdit | OnBar | OnSel,
60 typedef union Arg Arg;
67 typedef struct Client {
71 WebKitWebInspector *inspector;
72 WebKitFindController *finder;
73 WebKitHitTestResult *mousepos;
74 GTlsCertificateFlags tlsflags;
75 const char *title, *targeturi;
85 void (*func)(Client *c, const Arg *arg);
93 void (*func)(Client *c, const Arg *a, WebKitHitTestResult *h);
95 unsigned int stopevent;
105 static Atom atoms[AtomLast];
106 static Client *clients = NULL;
107 static Window embed = 0;
108 static gboolean showxid = FALSE;
109 static char winid[64];
110 static char togglestats[10];
111 static char pagestats[2];
112 static int cookiepolicy;
113 static char *stylefile = NULL;
114 static const char *useragent;
116 static void addaccelgroup(Client *c);
117 static char *buildfile(const char *path);
118 static char *buildpath(const char *path);
119 static gboolean buttonreleased(GtkWidget *w, GdkEventKey *e, Client *c);
120 static void cleanup(void);
121 static void clipboard(Client *c, const Arg *a);
123 static WebKitCookieAcceptPolicy cookiepolicy_get(void);
124 static char cookiepolicy_set(const WebKitCookieAcceptPolicy p);
126 static GtkWidget *createview(WebKitWebView *v, WebKitNavigationAction *a,
128 static gboolean decidepolicy(WebKitWebView *v, WebKitPolicyDecision *d,
129 WebKitPolicyDecisionType dt, Client *c);
130 static void decidenavigation(WebKitPolicyDecision *d, Client *c);
131 static void decidenewwindow(WebKitPolicyDecision *d, Client *c);
132 static void decideresource(WebKitPolicyDecision *d, Client *c);
133 static void closeview(WebKitWebView *v, Client *c);
134 static void destroyclient(Client *c);
135 static void destroywin(GtkWidget* w, Client *c);
136 static void die(const char *errstr, ...);
137 static void evalscript(Client *c, const char *jsstr, ...);
138 static void runscript(Client *c);
139 static void find(Client *c, const Arg *a);
140 static void togglefullscreen(Client *c, const Arg *a);
141 static gboolean permissionrequested(WebKitWebView *v,
142 WebKitPermissionRequest *r, Client *c);
143 static const char *getatom(Client *c, int a);
144 static void gettogglestats(Client *c);
145 static void getpagestats(Client *c);
146 static char *geturi(Client *c);
147 static const gchar *getstyle(const char *uri);
148 static void setstyle(Client *c, const char *stylefile);
150 static void handleplumb(Client *c, const gchar *uri);
152 static void downloadstarted(WebKitWebContext *wc, WebKitDownload *d,
154 static void responsereceived(WebKitDownload *d, GParamSpec *ps, Client *c);
155 static void download(Client *c, WebKitURIResponse *r);
157 static void toggleinspector(Client *c, const Arg *a);
159 static gboolean keypress(GtkAccelGroup *group, GObject *obj, guint key,
160 GdkModifierType mods, Client *c);
161 static void mousetargetchanged(WebKitWebView *v, WebKitHitTestResult *h,
162 guint modifiers, Client *c);
163 static void loadchanged(WebKitWebView *v, WebKitLoadEvent e, Client *c);
164 static void loaduri(Client *c, const Arg *a);
165 static void navigate(Client *c, const Arg *a);
166 static void clicknavigate(Client *c, const Arg *a, WebKitHitTestResult *h);
167 static Client *newclient(Client *c);
168 static WebKitWebView *newview(Client *c, WebKitWebView *rv);
169 static void showview(WebKitWebView *v, Client *c);
170 static void newwindow(Client *c, const Arg *arg, gboolean noembed);
171 static GtkWidget *createwindow(Client *c);
172 static void pasteuri(GtkClipboard *clipboard, const char *text, gpointer d);
173 static void print(Client *c, const Arg *a);
174 static GdkFilterReturn processx(GdkXEvent *xevent, GdkEvent *event,
176 static gboolean winevent(GtkWidget *w, GdkEvent *e, Client *c);
177 static void progresschanged(WebKitWebView *v, GParamSpec *ps, Client *c);
178 static void clicknewwindow(Client *c, const Arg *a, WebKitHitTestResult *h);
179 static void reload(Client *c, const Arg *arg);
180 static void scroll_h(Client *c, const Arg *a);
181 static void scroll_v(Client *c, const Arg *a);
182 static void setatom(Client *c, int a, const char *v);
183 static void setup(void);
184 static void sigchld(int unused);
185 static void spawn(Client *c, const Arg *arg);
186 static void stop(Client *c, const Arg *arg);
187 static void titlechanged(WebKitWebView *view, GParamSpec *ps, Client *c);
188 static void toggle(Client *c, const Arg *a);
189 static void togglecookiepolicy(Client *c, const Arg *arg);
190 static void togglestyle(Client *c, const Arg *arg);
191 static void updatetitle(Client *c);
192 static void updatewinid(Client *c);
193 static void usage(void);
194 static void zoom(Client *c, const Arg *a);
196 /* configuration, allows nested code to access above variables */
200 addaccelgroup(Client *c)
203 GtkAccelGroup *group = gtk_accel_group_new();
206 for (i = 0; i < LENGTH(keys); i++) {
207 closure = g_cclosure_new(G_CALLBACK(keypress), c, NULL);
208 gtk_accel_group_connect(group, keys[i].keyval, keys[i].mod, 0,
211 gtk_window_add_accel_group(GTK_WINDOW(c->win), group);
215 buildfile(const char *path)
217 char *dname, *bname, *bpath, *fpath;
220 dname = g_path_get_dirname(path);
221 bname = g_path_get_basename(path);
223 bpath = buildpath(dname);
226 fpath = g_build_filename(bpath, bname, NULL);
230 if (!(f = fopen(fpath, "a")))
231 die("Could not open file: %s\n", fpath);
233 g_chmod(fpath, 0600); /* always */
240 buildpath(const char *path)
243 char *apath, *name, *p, *fpath;
245 if (path[0] == '~') {
246 if (path[1] == '/' || path[1] == '\0') {
247 p = (char *)&path[1];
248 pw = getpwuid(getuid());
250 if ((p = strchr(path, '/')))
251 name = g_strndup(&path[1], --p - path);
253 name = g_strdup(&path[1]);
255 if (!(pw = getpwnam(name))) {
256 die("Can't get user %s home directory: %s.\n",
261 apath = g_build_filename(pw->pw_dir, p, NULL);
263 apath = g_strdup(path);
266 /* creating directory */
267 if (g_mkdir_with_parents(apath, 0700) < 0)
268 die("Could not access directory: %s\n", apath);
270 fpath = realpath(apath, NULL);
277 buttonreleased(GtkWidget *w, GdkEventKey *e, Client *c)
279 WebKitHitTestResultContext element;
280 GdkEventButton *eb = (GdkEventButton*)e;
283 element = webkit_hit_test_result_get_context(c->mousepos);
285 for (i = 0; i < LENGTH(buttons); ++i) {
286 if (element & buttons[i].target &&
287 eb->button == buttons[i].button &&
288 CLEANMASK(eb->state) == CLEANMASK(buttons[i].mask) &&
290 buttons[i].func(c, &buttons[i].arg, c->mousepos);
291 return buttons[i].stopevent;
302 destroyclient(clients);
309 WebKitCookieAcceptPolicy
310 cookiepolicy_get(void)
312 switch (cookiepolicies[cookiepolicy]) {
314 return WEBKIT_COOKIE_POLICY_ACCEPT_NEVER;
316 return WEBKIT_COOKIE_POLICY_ACCEPT_NO_THIRD_PARTY;
322 return WEBKIT_COOKIE_POLICY_ACCEPT_ALWAYS;
326 cookiepolicy_set(const WebKitCookieAcceptPolicy ep)
329 case WEBKIT_COOKIE_POLICY_ACCEPT_NEVER:
331 case WEBKIT_COOKIE_POLICY_ACCEPT_NO_THIRD_PARTY:
333 case WEBKIT_COOKIE_POLICY_ACCEPT_ALWAYS:
342 evalscript(Client *c, const char *jsstr, ...)
348 script = g_strdup_vprintf(jsstr, ap);
351 webkit_web_view_run_javascript(c->view, script, NULL, NULL, NULL);
361 if (g_file_get_contents(scriptfile, &script, &l, NULL) && l)
362 evalscript(c, script);
367 clipboard(Client *c, const Arg *a)
369 if (a->b) { /* load clipboard uri */
370 gtk_clipboard_request_text(gtk_clipboard_get(
371 GDK_SELECTION_PRIMARY),
373 } else { /* copy uri */
374 gtk_clipboard_set_text(gtk_clipboard_get(
375 GDK_SELECTION_PRIMARY), c->targeturi
376 ? c->targeturi : geturi(c), -1);
381 createview(WebKitWebView *v, WebKitNavigationAction *a, Client *c)
385 switch (webkit_navigation_action_get_navigation_type(a)) {
386 case WEBKIT_NAVIGATION_TYPE_OTHER: /* fallthrough */
388 * popup windows of type “other” are almost always triggered
389 * by user gesture, so inverse the logic here
391 /* instead of this, compare destination uri to mouse-over uri for validating window */
392 if (webkit_navigation_action_is_user_gesture(a)) {
396 case WEBKIT_NAVIGATION_TYPE_LINK_CLICKED: /* fallthrough */
397 case WEBKIT_NAVIGATION_TYPE_FORM_SUBMITTED: /* fallthrough */
398 case WEBKIT_NAVIGATION_TYPE_BACK_FORWARD: /* fallthrough */
399 case WEBKIT_NAVIGATION_TYPE_RELOAD: /* fallthrough */
400 case WEBKIT_NAVIGATION_TYPE_FORM_RESUBMITTED:
408 return GTK_WIDGET(n->view);
412 decidepolicy(WebKitWebView *v, WebKitPolicyDecision *d,
413 WebKitPolicyDecisionType dt, Client *c)
416 case WEBKIT_POLICY_DECISION_TYPE_NAVIGATION_ACTION:
417 decidenavigation(d, c);
419 case WEBKIT_POLICY_DECISION_TYPE_NEW_WINDOW_ACTION:
420 decidenewwindow(d, c);
422 case WEBKIT_POLICY_DECISION_TYPE_RESPONSE:
423 decideresource(d, c);
426 webkit_policy_decision_ignore(d);
433 decidenavigation(WebKitPolicyDecision *d, Client *c)
435 WebKitNavigationAction *a;
437 a = webkit_navigation_policy_decision_get_navigation_action(
438 WEBKIT_NAVIGATION_POLICY_DECISION(d));
440 switch (webkit_navigation_action_get_navigation_type(a)) {
441 case WEBKIT_NAVIGATION_TYPE_LINK_CLICKED: /* fallthrough */
442 case WEBKIT_NAVIGATION_TYPE_FORM_SUBMITTED: /* fallthrough */
443 case WEBKIT_NAVIGATION_TYPE_BACK_FORWARD: /* fallthrough */
444 case WEBKIT_NAVIGATION_TYPE_RELOAD: /* fallthrough */
445 case WEBKIT_NAVIGATION_TYPE_FORM_RESUBMITTED:
446 case WEBKIT_NAVIGATION_TYPE_OTHER: /* fallthrough */
448 /* Do not navigate to links with a "_blank" target (popup) */
449 if (webkit_navigation_policy_decision_get_frame_name(
450 WEBKIT_NAVIGATION_POLICY_DECISION(d))) {
451 webkit_policy_decision_ignore(d);
453 /* Filter out navigation to different domain ? */
454 /* get action→urirequest, copy and load in new window+view
456 webkit_policy_decision_use(d);
463 decidenewwindow(WebKitPolicyDecision *d, Client *c)
465 WebKitNavigationAction *a;
468 a = webkit_navigation_policy_decision_get_navigation_action(
469 WEBKIT_NAVIGATION_POLICY_DECISION(d));
471 switch (webkit_navigation_action_get_navigation_type(a)) {
472 case WEBKIT_NAVIGATION_TYPE_LINK_CLICKED: /* fallthrough */
473 case WEBKIT_NAVIGATION_TYPE_FORM_SUBMITTED: /* fallthrough */
474 case WEBKIT_NAVIGATION_TYPE_BACK_FORWARD: /* fallthrough */
475 case WEBKIT_NAVIGATION_TYPE_RELOAD: /* fallthrough */
476 case WEBKIT_NAVIGATION_TYPE_FORM_RESUBMITTED:
477 /* Filter domains here */
478 /* If the value of “mouse-button” is not 0, then the navigation was triggered by a mouse event.
479 * test for link clicked but no button ? */
480 arg.v = webkit_uri_request_get_uri(
481 webkit_navigation_action_get_request(a));
482 newwindow(c, &arg, 0);
484 case WEBKIT_NAVIGATION_TYPE_OTHER: /* fallthrough */
489 webkit_policy_decision_ignore(d);
493 decideresource(WebKitPolicyDecision *d, Client *c)
497 WebKitResponsePolicyDecision *r = WEBKIT_RESPONSE_POLICY_DECISION(d);
498 WebKitURIResponse *res;
500 res = webkit_response_policy_decision_get_response(r);
501 uri = webkit_uri_response_get_uri(res);
503 if (g_str_has_suffix(uri, "/favicon.ico"))
504 webkit_uri_request_set_uri(
505 webkit_response_policy_decision_get_request(r),
508 if (!g_str_has_prefix(uri, "http://")
509 && !g_str_has_prefix(uri, "https://")
510 && !g_str_has_prefix(uri, "about:")
511 && !g_str_has_prefix(uri, "file://")
512 && !g_str_has_prefix(uri, "data:")
513 && !g_str_has_prefix(uri, "blob:")
514 && strlen(uri) > 0) {
515 for (i = 0; i < strlen(uri); i++) {
516 if (!g_ascii_isprint(uri[i])) {
523 webkit_policy_decision_ignore(d);
527 if (webkit_response_policy_decision_is_mime_type_supported(r)) {
528 webkit_policy_decision_use(d);
530 webkit_policy_decision_ignore(d);
536 destroyclient(Client *c)
540 webkit_web_view_stop_loading(c->view);
541 /* Not needed, has already been called
542 gtk_widget_destroy(c->win);
545 for (p = clients; p && p->next != c; p = p->next)
555 closeview(WebKitWebView *v, Client *c)
557 gtk_widget_destroy(c->win);
561 destroywin(GtkWidget* w, Client *c)
569 die(const char *errstr, ...)
573 va_start(ap, errstr);
574 vfprintf(stderr, errstr, ap);
580 find(Client *c, const Arg *a)
586 webkit_find_controller_search_next(c->finder);
588 webkit_find_controller_search_previous(c->finder);
590 s = getatom(c, AtomFind);
591 f = webkit_find_controller_get_search_text(c->finder);
593 if (g_strcmp0(f, s) == 0) /* reset search */
594 webkit_find_controller_search(c->finder, "", findopts, G_MAXUINT);
596 webkit_find_controller_search(c->finder, s, findopts, G_MAXUINT);
598 if (strcmp(s, "") == 0)
599 webkit_find_controller_search_finish(c->finder);
604 togglefullscreen(Client *c, const Arg *a)
606 /* toggling value is handled in winevent() */
608 gtk_window_unfullscreen(GTK_WINDOW(c->win));
610 gtk_window_fullscreen(GTK_WINDOW(c->win));
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 *stylefile)
680 if (!g_file_get_contents(stylefile, &style, NULL, NULL)) {
681 fprintf(stderr, "Could not read style file: %s\n", stylefile);
685 webkit_user_content_manager_add_style_sheet(
686 webkit_web_view_get_user_content_manager(c->view),
687 webkit_user_style_sheet_new(style,
688 WEBKIT_USER_CONTENT_INJECT_ALL_FRAMES,
689 WEBKIT_USER_STYLE_LEVEL_USER,
696 handleplumb(Client *c, const gchar *uri)
700 arg = (Arg)PLUMB(uri);
705 downloadstarted(WebKitWebContext *wc, WebKitDownload *d, Client *c)
707 g_signal_connect(G_OBJECT(d), "notify::response",
708 G_CALLBACK(responsereceived), c);
712 responsereceived(WebKitDownload *d, GParamSpec *ps, Client *c)
714 download(c, webkit_download_get_response(d));
715 webkit_download_cancel(d);
719 download(Client *c, WebKitURIResponse *r)
723 a = (Arg)DOWNLOAD(webkit_uri_response_get_uri(r), geturi(c));
728 toggleinspector(Client *c, const Arg *a)
730 if (enableinspector) {
731 if (webkit_web_inspector_is_attached(c->inspector))
732 webkit_web_inspector_close(c->inspector);
734 webkit_web_inspector_show(c->inspector);
739 keypress(GtkAccelGroup *group, GObject *obj, guint key, GdkModifierType mods,
743 gboolean processed = FALSE;
745 mods = CLEANMASK(mods);
746 key = gdk_keyval_to_lower(key);
748 for (i = 0; i < LENGTH(keys); i++) {
749 if (key == keys[i].keyval
750 && mods == keys[i].mod
752 keys[i].func(c, &(keys[i].arg));
761 mousetargetchanged(WebKitWebView *v, WebKitHitTestResult *h, guint modifiers,
764 WebKitHitTestResultContext hc;
766 /* Keep the hit test to know where is the pointer on the next click */
769 hc = webkit_hit_test_result_get_context(h);
772 c->targeturi = webkit_hit_test_result_get_link_uri(h);
774 c->targeturi = webkit_hit_test_result_get_image_uri(h);
775 else if (hc & OnMedia)
776 c->targeturi = webkit_hit_test_result_get_media_uri(h);
783 loadchanged(WebKitWebView *v, WebKitLoadEvent e, Client *c)
786 case WEBKIT_LOAD_STARTED:
787 c->tlsflags = G_TLS_CERTIFICATE_VALIDATE_ALL + 1;
789 case WEBKIT_LOAD_REDIRECTED:
790 setatom(c, AtomUri, geturi(c));
792 case WEBKIT_LOAD_COMMITTED:
793 if (!webkit_web_view_get_tls_info(c->view, NULL, &(c->tlsflags)))
794 c->tlsflags = G_TLS_CERTIFICATE_VALIDATE_ALL + 1;
796 setatom(c, AtomUri, geturi(c));
799 setstyle(c, getstyle(geturi(c)));
801 case WEBKIT_LOAD_FINISHED:
802 /* Disabled until we write some WebKitWebExtension for
803 * manipulating the DOM directly.
804 evalscript(c, "document.documentElement.style.overflow = '%s'",
805 enablescrollbars ? "auto" : "hidden");
814 loaduri(Client *c, const Arg *a)
818 const char *uri = (char *)a->v;
820 if (g_strcmp0(uri, "") == 0)
823 if (g_strrstr(uri, "://") || g_str_has_prefix(uri, "about:")) {
825 } else if (!stat(uri, &st) && (path = realpath(uri, NULL))) {
826 url = g_strdup_printf("file://%s", path);
829 url = g_strdup_printf("http://%s", uri);
832 setatom(c, AtomUri, url);
834 if (strcmp(url, geturi(c)) == 0) {
837 webkit_web_view_load_uri(c->view, url);
838 c->title = geturi(c);
846 navigate(Client *c, const Arg *a)
849 webkit_web_view_go_back(c->view);
851 webkit_web_view_go_forward(c->view);
855 clicknavigate(Client *c, const Arg *a, WebKitHitTestResult *h)
861 newclient(Client *rc)
865 if (!(c = calloc(1, sizeof(Client))))
866 die("Cannot malloc!\n");
874 c->view = newview(c, rc ? rc->view : NULL);
875 c->tlsflags = G_TLS_CERTIFICATE_VALIDATE_ALL + 1;
881 newview(Client *c, WebKitWebView *rv)
884 WebKitSettings *settings;
885 WebKitUserContentManager *contentmanager;
886 WebKitWebContext *context;
891 webkit_web_view_new_with_related_view(rv));
893 settings = webkit_settings_new_with_settings(
894 "auto-load-images", loadimages,
895 "default-font-size", defaultfontsize,
896 "enable-caret-browsing", enablecaretbrowsing,
897 "enable-developer-extras", enableinspector,
898 "enable-dns-prefetching", enablednsprefetching,
899 "enable-frame-flattening", enableframeflattening,
900 "enable-html5-database", enablecache,
901 "enable-html5-local-storage", enablecache,
902 "enable-javascript", enablescripts,
903 "enable-plugins", enableplugins,
905 /* Have a look at http://webkitgtk.org/reference/webkit2gtk/stable/WebKitSettings.html
906 * for more interesting settings */
908 if (strcmp(fulluseragent, "")) {
909 webkit_settings_set_user_agent(settings, fulluseragent);
910 } else if (surfuseragent) {
911 webkit_settings_set_user_agent_with_application_details(
912 settings, "Surf", VERSION);
914 useragent = webkit_settings_get_user_agent(settings);
916 contentmanager = webkit_user_content_manager_new();
918 context = webkit_web_context_new_with_website_data_manager(
919 webkit_website_data_manager_new(
920 "base-cache-directory", cachedir,
921 "base-data-directory", cachedir,
924 /* rendering process model, can be a shared unique one or one for each
926 webkit_web_context_set_process_model(context,
927 WEBKIT_PROCESS_MODEL_MULTIPLE_SECONDARY_PROCESSES);
929 webkit_web_context_set_tls_errors_policy(context, strictssl ?
930 WEBKIT_TLS_ERRORS_POLICY_FAIL : WEBKIT_TLS_ERRORS_POLICY_IGNORE);
932 webkit_web_context_set_cache_model(context, enablecache ?
933 WEBKIT_CACHE_MODEL_WEB_BROWSER : WEBKIT_CACHE_MODEL_DOCUMENT_VIEWER);
935 /* Currently only works with text file to be compatible with curl */
936 webkit_cookie_manager_set_persistent_storage(
937 webkit_web_context_get_cookie_manager(context), cookiefile,
938 WEBKIT_COOKIE_PERSISTENT_STORAGE_TEXT);
940 webkit_cookie_manager_set_accept_policy(
941 webkit_web_context_get_cookie_manager(context),
944 g_signal_connect(G_OBJECT(context), "download-started",
945 G_CALLBACK(downloadstarted), c);
947 v = g_object_new(WEBKIT_TYPE_WEB_VIEW,
948 "settings", settings,
949 "user-content-manager", contentmanager,
950 "web-context", context,
954 g_signal_connect(G_OBJECT(v),
956 G_CALLBACK(titlechanged), c);
957 g_signal_connect(G_OBJECT(v),
958 "mouse-target-changed",
959 G_CALLBACK(mousetargetchanged), c);
960 g_signal_connect(G_OBJECT(v),
961 "permission-request",
962 G_CALLBACK(permissionrequested), c);
963 g_signal_connect(G_OBJECT(v),
965 G_CALLBACK(createview), c);
966 g_signal_connect(G_OBJECT(v), "ready-to-show",
967 G_CALLBACK(showview), c);
968 g_signal_connect(G_OBJECT(v),
970 G_CALLBACK(decidepolicy), c);
971 g_signal_connect(G_OBJECT(v),
973 G_CALLBACK(loadchanged), c);
974 g_signal_connect(G_OBJECT(v),
975 "notify::estimated-load-progress",
976 G_CALLBACK(progresschanged), c);
977 g_signal_connect(G_OBJECT(v),
978 "button-release-event",
979 G_CALLBACK(buttonreleased), c);
980 g_signal_connect(G_OBJECT(v), "close",
981 G_CALLBACK(closeview), c);
987 showview(WebKitWebView *v, Client *c)
989 GdkGeometry hints = { 1, 1 };
990 GdkRGBA bgcolor = { 0 };
993 c->win = createwindow(c);
996 c->inspector = webkit_web_view_get_inspector(c->view);
998 c->finder = webkit_web_view_get_find_controller(c->view);
1004 gtk_container_add(GTK_CONTAINER(c->win), GTK_WIDGET(c->view));
1007 gtk_widget_grab_focus(GTK_WIDGET(c->view));
1008 gtk_widget_show(GTK_WIDGET(c->view));
1009 gtk_widget_show(c->win);
1010 gwin = gtk_widget_get_window(GTK_WIDGET(c->win));
1011 c->xid = gdk_x11_window_get_xid(gwin);
1012 gtk_window_set_geometry_hints(GTK_WINDOW(c->win), NULL, &hints,
1014 gdk_window_set_events(gwin, GDK_ALL_EVENTS_MASK);
1015 gdk_window_add_filter(gwin, processx, c);
1017 if (zoomlevel != 1.0)
1018 webkit_web_view_set_zoom_level(c->view, zoomlevel);
1020 if (runinfullscreen)
1021 togglefullscreen(c, NULL);
1023 setatom(c, AtomFind, "");
1024 setatom(c, AtomUri, "about:blank");
1026 webkit_web_view_set_background_color(c->view, &bgcolor);
1029 gdk_display_sync(gtk_widget_get_display(c->win));
1030 printf("%lu\n", c->xid);
1032 if (fclose(stdout) != 0) {
1033 die("Error closing stdout");
1039 newwindow(Client *c, const Arg *a, int noembed)
1043 const char *cmd[26], *uri;
1044 const Arg arg = { .v = cmd };
1048 cmd[i++] = cookiepolicies;
1049 cmd[i++] = enablescrollbars ? "-B" : "-b";
1050 if (cookiefile && g_strcmp0(cookiefile, "")) {
1052 cmd[i++] = cookiefile;
1054 cmd[i++] = enablecache ? "-D" : "-d";
1055 if (embed && !noembed) {
1057 snprintf(tmp, LENGTH(tmp), "%lu", embed);
1060 cmd[i++] = runinfullscreen ? "-F" : "-f";
1061 cmd[i++] = allowgeolocation ? "-G" : "-g";
1062 cmd[i++] = loadimages ? "-I" : "-i";
1063 cmd[i++] = kioskmode ? "-K" : "-k";
1064 cmd[i++] = enablestyle ? "-M" : "-m";
1065 cmd[i++] = enableinspector ? "-N" : "-n";
1066 cmd[i++] = enableplugins ? "-P" : "-p";
1067 if (scriptfile && g_strcmp0(scriptfile, "")) {
1069 cmd[i++] = scriptfile;
1071 cmd[i++] = enablescripts ? "-S" : "-s";
1072 if (stylefile && g_strcmp0(stylefile, "")) {
1074 cmd[i++] = stylefile;
1076 if (fulluseragent && g_strcmp0(fulluseragent, "")) {
1078 cmd[i++] = fulluseragent;
1082 /* do not keep zoom level */
1092 createwindow(Client *c)
1097 w = gtk_plug_new(embed);
1099 w = gtk_window_new(GTK_WINDOW_TOPLEVEL);
1101 /* TA: 20091214: Despite what the GNOME docs say, the ICCCM
1102 * is always correct, so we should still call this function.
1103 * But when doing so, we *must* differentiate between a
1104 * WM_CLASS and a resource on the window. By convention, the
1105 * window class (WM_CLASS) is capped, while the resource is in
1106 * lowercase. Both these values come as a pair.
1108 gtk_window_set_wmclass(GTK_WINDOW(w), "surf", "Surf");
1110 /* TA: 20091214: And set the role here as well -- so that
1111 * sessions can pick this up.
1113 gtk_window_set_role(GTK_WINDOW(w), "Surf");
1115 gtk_window_set_default_size(GTK_WINDOW(w), 800, 600);
1118 g_signal_connect(G_OBJECT(w), "destroy",
1119 G_CALLBACK(destroywin), c);
1120 g_signal_connect(G_OBJECT(w), "leave-notify-event",
1121 G_CALLBACK(winevent), c);
1122 g_signal_connect(G_OBJECT(w), "window-state-event",
1123 G_CALLBACK(winevent), c);
1129 pasteuri(GtkClipboard *clipboard, const char *text, gpointer d)
1131 Arg arg = {.v = text };
1133 loaduri((Client *) d, &arg);
1137 print(Client *c, const Arg *a)
1139 webkit_print_operation_run_dialog(webkit_print_operation_new(c->view),
1140 GTK_WINDOW(c->win));
1144 processx(GdkXEvent *e, GdkEvent *event, gpointer d)
1146 Client *c = (Client *)d;
1150 if (((XEvent *)e)->type == PropertyNotify) {
1151 ev = &((XEvent *)e)->xproperty;
1152 if (ev->state == PropertyNewValue) {
1153 if (ev->atom == atoms[AtomFind]) {
1156 return GDK_FILTER_REMOVE;
1157 } else if (ev->atom == atoms[AtomGo]) {
1158 arg.v = getatom(c, AtomGo);
1161 return GDK_FILTER_REMOVE;
1165 return GDK_FILTER_CONTINUE;
1169 progresschanged(WebKitWebView *v, GParamSpec *ps, Client *c)
1171 c->progress = webkit_web_view_get_estimated_load_progress(c->view) *
1177 clicknewwindow(Client *c, const Arg *a, WebKitHitTestResult *h)
1181 arg.v = webkit_hit_test_result_get_link_uri(h);
1182 newwindow(c, &arg, a->b);
1186 reload(Client *c, const Arg *arg)
1188 gboolean nocache = *(gboolean *)arg;
1190 webkit_web_view_reload_bypass_cache(c->view);
1192 webkit_web_view_reload(c->view);
1196 scroll_h(Client *c, const Arg *a)
1198 evalscript(c, "window.scrollBy(%d * (window.innerWidth / 100), 0)",
1203 scroll_v(Client *c, const Arg *a)
1205 evalscript(c, "window.scrollBy(0, %d * (window.innerHeight / 100))",
1210 setatom(Client *c, int a, const char *v)
1213 XChangeProperty(dpy, c->xid,
1214 atoms[a], XA_STRING, 8, PropModeReplace,
1215 (unsigned char *)v, strlen(v) + 1);
1223 /* clean up any zombies immediately */
1225 gtk_init(NULL, NULL);
1227 dpy = GDK_DISPLAY_XDISPLAY(gdk_display_get_default());
1230 atoms[AtomFind] = XInternAtom(dpy, "_SURF_FIND", False);
1231 atoms[AtomGo] = XInternAtom(dpy, "_SURF_GO", False);
1232 atoms[AtomUri] = XInternAtom(dpy, "_SURF_URI", False);
1234 /* dirs and files */
1235 cookiefile = buildfile(cookiefile);
1236 scriptfile = buildfile(scriptfile);
1237 cachedir = buildpath(cachedir);
1239 if (stylefile == NULL) {
1240 styledir = buildpath(styledir);
1241 for (i = 0; i < LENGTH(styles); i++) {
1242 if (regcomp(&(styles[i].re), styles[i].regex,
1245 "Could not compile regex: %s\n",
1247 styles[i].regex = NULL;
1249 styles[i].style = g_strconcat(styledir, "/",
1250 styles[i].style, NULL);
1254 stylefile = buildfile(stylefile);
1261 if (signal(SIGCHLD, sigchld) == SIG_ERR)
1262 die("Can't install SIGCHLD handler");
1263 while (0 < waitpid(-1, NULL, WNOHANG));
1267 spawn(Client *c, const Arg *arg)
1271 close(ConnectionNumber(dpy));
1273 execvp(((char **)arg->v)[0], (char **)arg->v);
1274 fprintf(stderr, "surf: execvp %s", ((char **)arg->v)[0]);
1281 stop(Client *c, const Arg *arg)
1283 webkit_web_view_stop_loading(c->view);
1287 titlechanged(WebKitWebView *view, GParamSpec *ps, Client *c)
1289 c->title = webkit_web_view_get_title(c->view);
1294 winevent(GtkWidget *w, GdkEvent *e, Client *c)
1297 case GDK_LEAVE_NOTIFY:
1298 c->targeturi = NULL;
1301 case GDK_WINDOW_STATE: /* fallthrough */
1302 if (e->window_state.changed_mask ==
1303 GDK_WINDOW_STATE_FULLSCREEN) {
1304 c->fullscreen = e->window_state.new_window_state &
1305 GDK_WINDOW_STATE_FULLSCREEN;
1316 toggle(Client *c, const Arg *a)
1320 s = webkit_web_view_get_settings(c->view);
1322 switch ((unsigned int)a->i) {
1324 enablecaretbrowsing = !enablecaretbrowsing;
1325 webkit_settings_set_enable_caret_browsing(s,
1326 enablecaretbrowsing);
1328 return; /* do not reload */
1330 case FrameFlattening:
1331 enableframeflattening = !enableframeflattening;
1332 webkit_settings_set_enable_frame_flattening(s,
1333 enableframeflattening);
1336 allowgeolocation = !allowgeolocation;
1339 enablescripts = !enablescripts;
1340 webkit_settings_set_enable_javascript(s, enablescripts);
1343 loadimages = !loadimages;
1344 webkit_settings_set_auto_load_images(s, loadimages);
1347 enableplugins = !enableplugins;
1348 webkit_settings_set_enable_plugins(s, enableplugins);
1351 /* Disabled until we write some WebKitWebExtension for
1352 * manipulating the DOM directly.
1353 enablescrollbars = !enablescrollbars;
1354 evalscript(c, "document.documentElement.style.overflow = '%s'",
1355 enablescrollbars ? "auto" : "hidden");
1357 return; /* do not reload */
1366 togglecookiepolicy(Client *c, const Arg *arg)
1369 cookiepolicy %= strlen(cookiepolicies);
1371 webkit_cookie_manager_set_accept_policy(
1372 webkit_web_context_get_cookie_manager(
1373 webkit_web_view_get_context(c->view)),
1374 cookiepolicy_get());
1377 /* Do not reload. */
1381 togglestyle(Client *c, const Arg *arg)
1383 enablestyle = !enablestyle;
1384 setstyle(c, enablestyle ? getstyle(geturi(c)) : "");
1390 gettogglestats(Client *c)
1392 togglestats[0] = cookiepolicy_set(cookiepolicy_get());
1393 togglestats[1] = enablecaretbrowsing ? 'C' : 'c';
1394 togglestats[2] = allowgeolocation ? 'G' : 'g';
1395 togglestats[3] = enablecache ? 'D' : 'd';
1396 togglestats[4] = loadimages ? 'I' : 'i';
1397 togglestats[5] = enablescripts ? 'S': 's';
1398 togglestats[6] = enableplugins ? 'V' : 'v';
1399 togglestats[7] = enablestyle ? 'M' : 'm';
1400 togglestats[8] = enableframeflattening ? 'F' : 'f';
1401 togglestats[9] = '\0';
1405 getpagestats(Client *c)
1407 pagestats[0] = c->tlsflags > G_TLS_CERTIFICATE_VALIDATE_ALL ? '-' :
1408 c->tlsflags > 0 ? 'U' : 'T';
1409 pagestats[1] = '\0';
1413 updatetitle(Client *c)
1417 if (showindicators) {
1421 if (c->progress != 100) {
1422 title = g_strdup_printf("[%i%%] %s:%s | %s",
1423 c->progress, togglestats, pagestats,
1424 c->targeturi ? c->targeturi : c->title);
1426 title = g_strdup_printf("%s:%s | %s",
1427 togglestats, pagestats,
1428 c->targeturi ? c->targeturi : c->title);
1431 gtk_window_set_title(GTK_WINDOW(c->win), title);
1434 gtk_window_set_title(GTK_WINDOW(c->win), c->title ?
1440 updatewinid(Client *c)
1442 snprintf(winid, LENGTH(winid), "%lu", c->xid);
1448 die("usage: %s [-bBdDfFgGiIkKmMnNpPsSvx] [-a cookiepolicies ] "
1449 "[-c cookiefile] [-e xid] [-r scriptfile] [-t stylefile] "
1450 "[-u useragent] [-z zoomlevel] [uri]\n", basename(argv0));
1454 zoom(Client *c, const Arg *a)
1457 webkit_web_view_set_zoom_level(c->view, zoomlevel + 0.1);
1459 webkit_web_view_set_zoom_level(c->view, zoomlevel - 0.1);
1461 webkit_web_view_set_zoom_level(c->view, 1.0);
1463 zoomlevel = webkit_web_view_get_zoom_level(c->view);
1467 main(int argc, char *argv[])
1472 memset(&arg, 0, sizeof(arg));
1474 /* command line args */
1477 cookiepolicies = EARGF(usage());
1480 enablescrollbars = 0;
1483 enablescrollbars = 1;
1486 cookiefile = EARGF(usage());
1495 embed = strtol(EARGF(usage()), NULL, 0);
1498 runinfullscreen = 0;
1501 runinfullscreen = 1;
1504 allowgeolocation = 0;
1507 allowgeolocation = 1;
1528 enableinspector = 0;
1531 enableinspector = 1;
1540 scriptfile = EARGF(usage());
1549 stylefile = EARGF(usage());
1552 useragent = EARGF(usage());
1555 die("surf-"VERSION", ©2009-2015 surf engineers, "
1556 "see LICENSE for details\n");
1561 zoomlevel = strtof(EARGF(usage()), NULL);
1570 c = newclient(NULL);
1573 loaduri(clients, &arg);
1580 return EXIT_SUCCESS;