Surf now parses hex window ids properly from tabbed.
[surf.git] / surf.c
1 /* See LICENSE file for copyright and license details.
2  *
3  * To understand surf, start reading main().
4  */
5 #include <signal.h>
6 #include <X11/X.h>
7 #include <X11/Xatom.h>
8 #include <gtk/gtk.h>
9 #include <gdk/gdkx.h>
10 #include <gdk/gdk.h>
11 #include <gdk/gdkkeysyms.h>
12 #include <string.h>
13 #include <sys/types.h>
14 #include <sys/wait.h>
15 #include <unistd.h>
16 #include <stdlib.h>
17 #include <stdio.h>
18 #include <webkit/webkit.h>
19 #include <glib/gstdio.h>
20 #include <JavaScriptCore/JavaScript.h>
21 #include <sys/file.h>
22
23 #define LENGTH(x)               (sizeof x / sizeof x[0])
24
25 enum { AtomFind, AtomGo, AtomUri, AtomLast };
26
27 typedef union Arg Arg;
28 union Arg {
29         gboolean b;
30         gint i;
31         const void *v;
32 };
33
34 typedef struct Client {
35         GtkWidget *win, *scroll, *vbox, *indicator;
36         WebKitWebView *view;
37         char *title, *linkhover;
38         const char *uri, *needle;
39         gint progress;
40         gboolean sslfailed;
41         struct Client *next;
42         gboolean zoomed;
43 } Client;
44
45 typedef struct {
46         char *label;
47         void (*func)(Client *c, const Arg *arg);
48         const Arg arg;
49 } Item;
50
51 typedef struct {
52         guint mod;
53         guint keyval;
54         void (*func)(Client *c, const Arg *arg);
55         const Arg arg;
56 } Key;
57
58 static Display *dpy;
59 static Atom atoms[AtomLast];
60 static Client *clients = NULL;
61 static GdkNativeWindow embed = 0;
62 static gboolean showxid = FALSE;
63 static char winid[64];
64 static char *progname;
65 static gboolean loadimage = 1, plugin = 1, script = 1;
66
67 static char *buildpath(const char *path);
68 static void cleanup(void);
69 static void clipboard(Client *c, const Arg *arg);
70 static char *copystr(char **str, const char *src);
71 static WebKitWebView *createwindow(WebKitWebView *v, WebKitWebFrame *f, Client *c);
72 static gboolean decidedownload(WebKitWebView *v, WebKitWebFrame *f, WebKitNetworkRequest *r, gchar *m,  WebKitWebPolicyDecision *p, Client *c);
73 static gboolean decidewindow(WebKitWebView *v, WebKitWebFrame *f, WebKitNetworkRequest *r, WebKitWebNavigationAction *n, WebKitWebPolicyDecision *p, Client *c);
74 static void destroyclient(Client *c);
75 static void destroywin(GtkWidget* w, Client *c);
76 static void die(char *str);
77 static void drawindicator(Client *c);
78 static gboolean exposeindicator(GtkWidget *w, GdkEventExpose *e, Client *c);
79 static void find(Client *c, const Arg *arg);
80 static const char *getatom(Client *c, int a);
81 static const char *getcookies(SoupURI *uri);
82 static char *geturi(Client *c);
83 void gotheaders(SoupMessage *msg, gpointer user_data);
84 static gboolean initdownload(WebKitWebView *v, WebKitDownload *o, Client *c);
85 static gboolean keypress(GtkWidget *w, GdkEventKey *ev, Client *c);
86 static void linkhover(WebKitWebView *v, const char* t, const char* l, Client *c);
87 static void loadstatuschange(WebKitWebView *view, GParamSpec *pspec, Client *c);
88 static void loaduri(Client *c, const Arg *arg);
89 static void navigate(Client *c, const Arg *arg);
90 static Client *newclient(void);
91 static void newwindow(Client *c, const Arg *arg);
92 static void newrequest(SoupSession *s, SoupMessage *msg, gpointer v);
93 static void pasteuri(GtkClipboard *clipboard, const char *text, gpointer d);
94 static void print(Client *c, const Arg *arg);
95 static GdkFilterReturn processx(GdkXEvent *xevent, GdkEvent *event, gpointer d);
96 static void progresschange(WebKitWebView *view, GParamSpec *pspec, Client *c);
97 static void reload(Client *c, const Arg *arg);
98 static void scroll_h(Client *c, const Arg *arg);
99 static void scroll_v(Client *c, const Arg *arg);
100 static void scroll(GtkAdjustment *a, const Arg *arg);
101 static void setatom(Client *c, int a, const char *v);
102 static void setcookie(SoupCookie *c);
103 static void setup(void);
104 static void sigchld(int unused);
105 static void source(Client *c, const Arg *arg);
106 static void spawn(Client *c, const Arg *arg);
107 static void eval(Client *c, const Arg *arg);
108 static void stop(Client *c, const Arg *arg);
109 static void titlechange(WebKitWebView *v, WebKitWebFrame* frame, const char* title, Client *c);
110 static void update(Client *c);
111 static void updatewinid(Client *c);
112 static void usage(void);
113 static void windowobjectcleared(GtkWidget *w, WebKitWebFrame *frame, JSContextRef js, JSObjectRef win, Client *c);
114 static void zoom(Client *c, const Arg *arg);
115
116 /* configuration, allows nested code to access above variables */
117 #include "config.h"
118
119 char *
120 buildpath(const char *path) {
121         char *apath, *p;
122         FILE *f;
123
124         /* creating directory */
125         if(path[0] == '/')
126                 apath = g_strdup(path);
127         else
128                 apath = g_strconcat(g_get_home_dir(), "/", path, NULL);
129         if((p = strrchr(apath, '/'))) {
130                 *p = '\0';
131                 g_mkdir_with_parents(apath, 0700);
132                 g_chmod(apath, 0700); /* in case it existed */
133                 *p = '/';
134         }
135         /* creating file (gives error when apath ends with "/") */
136         if((f = fopen(apath, "a"))) {
137                 g_chmod(apath, 0600); /* always */
138                 fclose(f);
139         }
140         return apath;
141 }
142
143 void
144 cleanup(void) {
145         while(clients)
146                 destroyclient(clients);
147         g_free(cookiefile);
148         g_free(scriptfile);
149         g_free(stylefile);
150 }
151
152 void
153 evalscript(JSContextRef js, char *script, char* scriptname) {
154         JSStringRef jsscript, jsscriptname;
155         JSValueRef exception = NULL;
156
157         jsscript = JSStringCreateWithUTF8CString(script);
158         jsscriptname = JSStringCreateWithUTF8CString(scriptname);
159         JSEvaluateScript(js, jsscript, JSContextGetGlobalObject(js), jsscriptname, 0, &exception);
160         JSStringRelease(jsscript);
161         JSStringRelease(jsscriptname);
162 }
163
164 void
165 runscript(WebKitWebFrame *frame) {
166         char *script;
167         GError *error;
168
169         if(g_file_get_contents(scriptfile, &script, NULL, &error)) {
170                 evalscript(webkit_web_frame_get_global_context(frame), script, scriptfile);
171         }
172 }
173
174 void
175 clipboard(Client *c, const Arg *arg) {
176         gboolean paste = *(gboolean *)arg;
177
178         if(paste)
179                 gtk_clipboard_request_text(gtk_clipboard_get(GDK_SELECTION_PRIMARY), pasteuri, c);
180         else
181                 gtk_clipboard_set_text(gtk_clipboard_get(GDK_SELECTION_PRIMARY), c->linkhover ? c->linkhover : geturi(c), -1);
182 }
183
184 char *
185 copystr(char **str, const char *src) {
186         char *tmp;
187         tmp = g_strdup(src);
188
189         if(str && *str) {
190                 g_free(*str);
191                 *str = tmp;
192         }
193         return tmp;
194 }
195
196 WebKitWebView *
197 createwindow(WebKitWebView  *v, WebKitWebFrame *f, Client *c) {
198         Client *n = newclient();
199         return n->view;
200 }
201
202 gboolean
203 decidedownload(WebKitWebView *v, WebKitWebFrame *f, WebKitNetworkRequest *r, gchar *m,  WebKitWebPolicyDecision *p, Client *c) {
204         if(!webkit_web_view_can_show_mime_type(v, m)) {
205                 webkit_web_policy_decision_download(p);
206                 return TRUE;
207         }
208         return FALSE;
209 }
210
211 gboolean
212 decidewindow(WebKitWebView *view, WebKitWebFrame *f, WebKitNetworkRequest *r, WebKitWebNavigationAction *n, WebKitWebPolicyDecision *p, Client *c) {
213         Arg arg;
214
215         if(webkit_web_navigation_action_get_reason(n) == WEBKIT_WEB_NAVIGATION_REASON_LINK_CLICKED) {
216                 webkit_web_policy_decision_ignore(p);
217                 arg.v = (void *)webkit_network_request_get_uri(r);
218                 newwindow(NULL, &arg);
219                 return TRUE;
220         }
221         return FALSE;
222 }
223
224 void
225 destroyclient(Client *c) {
226         Client *p;
227
228         webkit_web_view_stop_loading(c->view);
229         gtk_widget_destroy(c->indicator);
230         gtk_widget_destroy(GTK_WIDGET(c->view));
231         gtk_widget_destroy(c->scroll);
232         gtk_widget_destroy(c->vbox);
233         gtk_widget_destroy(c->win);
234
235         for(p = clients; p && p->next != c; p = p->next);
236         if(p)
237                 p->next = c->next;
238         else
239                 clients = c->next;
240         free(c);
241         if(clients == NULL)
242                 gtk_main_quit();
243 }
244
245 void
246 destroywin(GtkWidget* w, Client *c) {
247         destroyclient(c);
248 }
249
250 void
251 die(char *str) {
252         fputs(str, stderr);
253         exit(EXIT_FAILURE);
254 }
255
256 void
257 drawindicator(Client *c) {
258         gint width;
259         const char *uri;
260         GtkWidget *w;
261         GdkGC *gc;
262         GdkColor fg;
263
264         uri = geturi(c);
265         w = c->indicator;
266         width = c->progress * w->allocation.width / 100;
267         gc = gdk_gc_new(w->window);
268         if(strstr(uri, "https://") == uri)
269                 gdk_color_parse(c->sslfailed ?
270                                 progress_untrust : progress_trust, &fg);
271         else
272                 gdk_color_parse(progress, &fg);
273         gdk_gc_set_rgb_fg_color(gc, &fg);
274         gdk_draw_rectangle(w->window,
275                         w->style->bg_gc[GTK_WIDGET_STATE(w)],
276                         TRUE, 0, 0, w->allocation.width, w->allocation.height);
277         gdk_draw_rectangle(w->window, gc, TRUE, 0, 0, width,
278                         w->allocation.height);
279         g_object_unref(gc);
280 }
281
282 gboolean
283 exposeindicator(GtkWidget *w, GdkEventExpose *e, Client *c) {
284         drawindicator(c);
285         return TRUE;
286 }
287
288 void
289 find(Client *c, const Arg *arg) {
290         const char *s;
291
292         s = getatom(c, AtomFind);
293         gboolean forward = *(gboolean *)arg;
294         webkit_web_view_search_text(c->view, s, FALSE, forward, TRUE);
295 }
296
297 const char *
298 getcookies(SoupURI *uri) {
299         const char *c;
300         SoupCookieJar *j = soup_cookie_jar_text_new(cookiefile, TRUE);
301         c = soup_cookie_jar_get_cookies(j, uri, TRUE);
302         g_object_unref(j);
303         return c;
304 }
305
306 const char *
307 getatom(Client *c, int a) {
308         static char buf[BUFSIZ];
309         Atom adummy;
310         int idummy;
311         unsigned long ldummy;
312         unsigned char *p = NULL;
313
314         XGetWindowProperty(dpy, GDK_WINDOW_XID(GTK_WIDGET(c->win)->window),
315                         atoms[a], 0L, BUFSIZ, False, XA_STRING,
316                         &adummy, &idummy, &ldummy, &ldummy, &p);
317         if(p)
318                 strncpy(buf, (char *)p, LENGTH(buf)-1);
319         else
320                 buf[0] = '\0';
321         XFree(p);
322         return buf;
323 }
324
325 char *
326 geturi(Client *c) {
327         char *uri;
328
329         if(!(uri = (char *)webkit_web_view_get_uri(c->view)))
330                 uri = "about:blank";
331         return uri;
332 }
333
334 void
335 gotheaders(SoupMessage *msg, gpointer v) {
336         GSList *l, *p;
337
338         for(p = l = soup_cookies_from_response(msg); p;
339                 p = g_slist_next(p))  {
340                 setcookie((SoupCookie *)p->data);
341         }
342         soup_cookies_free(l);
343 }
344
345 gboolean
346 initdownload(WebKitWebView *view, WebKitDownload *o, Client *c) {
347         Arg arg;
348
349         updatewinid(c);
350         arg = (Arg)DOWNLOAD((char *)webkit_download_get_uri(o));
351         spawn(c, &arg);
352         return FALSE;
353 }
354
355 gboolean
356 keypress(GtkWidget* w, GdkEventKey *ev, Client *c) {
357         guint i;
358         gboolean processed = FALSE;
359
360         updatewinid(c);
361         for(i = 0; i < LENGTH(keys); i++) {
362                 if(gdk_keyval_to_lower(ev->keyval) == keys[i].keyval
363                                 && (ev->state & keys[i].mod) == keys[i].mod
364                                 && keys[i].func) {
365                         keys[i].func(c, &(keys[i].arg));
366                         processed = TRUE;
367                 }
368         }
369         return processed;
370 }
371
372 void
373 linkhover(WebKitWebView *v, const char* t, const char* l, Client *c) {
374         if(l) {
375                 c->linkhover = copystr(&c->linkhover, l);
376         }
377         else if(c->linkhover) {
378                 free(c->linkhover);
379                 c->linkhover = NULL;
380         }
381         update(c);
382 }
383
384 void
385 loadstatuschange(WebKitWebView *view, GParamSpec *pspec, Client *c) {
386         WebKitWebFrame *frame;
387         WebKitWebDataSource *src;
388         WebKitNetworkRequest *request;
389         SoupMessage *msg;
390         char *uri;
391
392         switch(webkit_web_view_get_load_status (c->view)) {
393         case WEBKIT_LOAD_COMMITTED:
394                 uri = geturi(c);
395                 if(strstr(uri, "https://") == uri) {
396                         frame = webkit_web_view_get_main_frame(c->view);
397                         src = webkit_web_frame_get_data_source(frame);
398                         request = webkit_web_data_source_get_request(src);
399                         msg = webkit_network_request_get_message(request);
400                         c->sslfailed = soup_message_get_flags(msg)
401                                        ^ SOUP_MESSAGE_CERTIFICATE_TRUSTED;
402                 }
403                 setatom(c, AtomUri, uri);
404                 break;
405         case WEBKIT_LOAD_FINISHED:
406                 c->progress = 0;
407                 update(c);
408                 break;
409         default:
410                 break;
411         }
412 }
413
414 void
415 loaduri(Client *c, const Arg *arg) {
416         char *u;
417         const char *uri = (char *)arg->v;
418         Arg a = { .b = FALSE };
419
420         if(strcmp(uri, "") == 0)
421                 return;
422         u = g_strrstr(uri, "://") ? g_strdup(uri)
423                 : g_strdup_printf("http://%s", uri);
424         /* prevents endless loop */
425         if(c->uri && strcmp(u, c->uri) == 0) {
426                 reload(c, &a);
427         }
428         else {
429                 webkit_web_view_load_uri(c->view, u);
430                 c->progress = 0;
431                 c->title = copystr(&c->title, u);
432                 g_free(u);
433                 update(c);
434         }
435 }
436
437 void
438 navigate(Client *c, const Arg *arg) {
439         int steps = *(int *)arg;
440         webkit_web_view_go_back_or_forward(c->view, steps);
441 }
442
443 Client *
444 newclient(void) {
445         Client *c;
446         WebKitWebSettings *settings;
447         WebKitWebFrame *frame;
448         GdkGeometry hints = { 1, 1 };
449         char *uri, *ua;
450
451         if(!(c = calloc(1, sizeof(Client))))
452                 die("Cannot malloc!\n");
453         /* Window */
454         if(embed) {
455                 c->win = gtk_plug_new(embed);
456         }
457         else {
458                 c->win = gtk_window_new(GTK_WINDOW_TOPLEVEL);
459                 /* TA:  20091214:  Despite what the GNOME docs say, the ICCCM
460                  * is always correct, so we should still call this function.
461                  * But when doing so, we *must* differentiate between a
462                  * WM_CLASS and a resource on the window.  By convention, the
463                  * window class (WM_CLASS) is capped, while the resource is in
464                  * lowercase.   Both these values come as a pair.
465                  */
466                 gtk_window_set_wmclass(GTK_WINDOW(c->win), "surf", "Surf");
467
468                 /* TA:  20091214:  And set the role here as well -- so that
469                  * sessions can pick this up.
470                  */
471                 gtk_window_set_role(GTK_WINDOW(c->win), "Surf");
472         }
473         gtk_window_set_default_size(GTK_WINDOW(c->win), 800, 600);
474         g_signal_connect(G_OBJECT(c->win), "destroy", G_CALLBACK(destroywin), c);
475         g_signal_connect(G_OBJECT(c->win), "key-press-event", G_CALLBACK(keypress), c);
476
477         /* VBox */
478         c->vbox = gtk_vbox_new(FALSE, 0);
479
480         /* Scrolled Window */
481         c->scroll = gtk_scrolled_window_new(NULL, NULL);
482         gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(c->scroll),
483                         GTK_POLICY_NEVER, GTK_POLICY_NEVER);
484
485         /* Webview */
486         c->view = WEBKIT_WEB_VIEW(webkit_web_view_new());
487         g_signal_connect(G_OBJECT(c->view), "title-changed", G_CALLBACK(titlechange), c);
488         g_signal_connect(G_OBJECT(c->view), "hovering-over-link", G_CALLBACK(linkhover), c);
489         g_signal_connect(G_OBJECT(c->view), "create-web-view", G_CALLBACK(createwindow), c);
490         g_signal_connect(G_OBJECT(c->view), "new-window-policy-decision-requested", G_CALLBACK(decidewindow), c);
491         g_signal_connect(G_OBJECT(c->view), "mime-type-policy-decision-requested", G_CALLBACK(decidedownload), c);
492         g_signal_connect(G_OBJECT(c->view), "window-object-cleared", G_CALLBACK(windowobjectcleared), c);
493         g_signal_connect(G_OBJECT(c->view), "notify::load-status", G_CALLBACK(loadstatuschange), c);
494         g_signal_connect(G_OBJECT(c->view), "notify::progress", G_CALLBACK(progresschange), c);
495         g_signal_connect(G_OBJECT(c->view), "download-requested", G_CALLBACK(initdownload), c);
496
497         /* Indicator */
498         c->indicator = gtk_drawing_area_new();
499         gtk_widget_set_size_request(c->indicator, 0, 2);
500         g_signal_connect (G_OBJECT (c->indicator), "expose_event",
501                         G_CALLBACK (exposeindicator), c);
502
503         /* Arranging */
504         gtk_container_add(GTK_CONTAINER(c->scroll), GTK_WIDGET(c->view));
505         gtk_container_add(GTK_CONTAINER(c->win), c->vbox);
506         gtk_container_add(GTK_CONTAINER(c->vbox), c->scroll);
507         gtk_container_add(GTK_CONTAINER(c->vbox), c->indicator);
508
509         /* Setup */
510         gtk_box_set_child_packing(GTK_BOX(c->vbox), c->indicator, FALSE, FALSE, 0, GTK_PACK_START);
511         gtk_box_set_child_packing(GTK_BOX(c->vbox), c->scroll, TRUE, TRUE, 0, GTK_PACK_START);
512         gtk_widget_grab_focus(GTK_WIDGET(c->view));
513         gtk_widget_show(c->vbox);
514         gtk_widget_show(c->indicator);
515         gtk_widget_show(c->scroll);
516         gtk_widget_show(GTK_WIDGET(c->view));
517         gtk_widget_show(c->win);
518         gtk_window_set_geometry_hints(GTK_WINDOW(c->win), NULL, &hints, GDK_HINT_MIN_SIZE);
519         gdk_window_set_events(GTK_WIDGET(c->win)->window, GDK_ALL_EVENTS_MASK);
520         gdk_window_add_filter(GTK_WIDGET(c->win)->window, processx, c);
521         webkit_web_view_set_full_content_zoom(c->view, TRUE);
522         frame = webkit_web_view_get_main_frame(c->view);
523         runscript(frame);
524         settings = webkit_web_view_get_settings(c->view);
525         if(!(ua = getenv("SURF_USERAGENT")))
526                 ua = useragent;
527         g_object_set(G_OBJECT(settings), "user-agent", ua, NULL);
528         uri = g_strconcat("file://", stylefile, NULL);
529         g_object_set(G_OBJECT(settings), "user-stylesheet-uri", uri, NULL);
530         g_object_set(G_OBJECT(settings), "auto-load-images", loadimage, NULL);
531         g_object_set(G_OBJECT(settings), "enable-plugins", plugin, NULL);
532         g_object_set(G_OBJECT(settings), "enable-scripts", script, NULL);
533         g_object_set(G_OBJECT(settings), "enable-spatial-navigation", SPATIAL_BROWSING, NULL);
534
535         g_free(uri);
536
537         setatom(c, AtomFind, "");
538         setatom(c, AtomUri, "about:blank");
539         if(HIDE_BACKGROUND)
540                 webkit_web_view_set_transparent(c->view, TRUE);
541
542         c->title = NULL;
543         c->next = clients;
544         clients = c;
545         if(showxid) {
546                 gdk_display_sync(gtk_widget_get_display(c->win));
547                 printf("%u\n", (guint)GDK_WINDOW_XID(GTK_WIDGET(c->win)->window));
548                 fflush(NULL);
549                 if (fclose(stdout) != 0) {
550                         die("Error closing stdout");
551                 }
552         }
553         return c;
554 }
555
556 void
557 newrequest(SoupSession *s, SoupMessage *msg, gpointer v) {
558         SoupMessageHeaders *h = msg->request_headers;
559         SoupURI *uri;
560         const char *c;
561
562         soup_message_headers_remove(h, "Cookie");
563         uri = soup_message_get_uri(msg);
564         if((c = getcookies(uri)))
565                 soup_message_headers_append(h, "Cookie", c);
566         g_signal_connect_after(G_OBJECT(msg), "got-headers", G_CALLBACK(gotheaders), NULL);
567 }
568
569 void
570 newwindow(Client *c, const Arg *arg) {
571         guint i = 0;
572         const char *cmd[10], *uri;
573         const Arg a = { .v = (void *)cmd };
574         char tmp[64];
575
576         cmd[i++] = progname;
577         if(embed) {
578                 cmd[i++] = "-e";
579                 snprintf(tmp, LENGTH(tmp), "%u\n", (int)embed);
580                 cmd[i++] = tmp;
581         }
582         if(!script)
583                 cmd[i++] = "-s";
584         if(!plugin)
585                 cmd[i++] = "-p";
586         if(!loadimage)
587                 cmd[i++] = "-i";
588         if(showxid)
589                 cmd[i++] = "-x";
590         cmd[i++] = "--";
591         uri = arg->v ? (char *)arg->v : c->linkhover;
592         if(uri)
593                 cmd[i++] = uri;
594         cmd[i++] = NULL;
595         spawn(NULL, &a);
596 }
597
598 void
599 pasteuri(GtkClipboard *clipboard, const char *text, gpointer d) {
600         Arg arg = {.v = text };
601         if(text != NULL)
602                 loaduri((Client *) d, &arg);
603 }
604
605 void
606 print(Client *c, const Arg *arg) {
607         webkit_web_frame_print(webkit_web_view_get_main_frame(c->view));
608 }
609
610 GdkFilterReturn
611 processx(GdkXEvent *e, GdkEvent *event, gpointer d) {
612         Client *c = (Client *)d;
613         XPropertyEvent *ev;
614         Arg arg;
615
616         if(((XEvent *)e)->type == PropertyNotify) {
617                 ev = &((XEvent *)e)->xproperty;
618                 if(ev->state == PropertyNewValue) {
619                         if(ev->atom == atoms[AtomFind]) {
620                                 arg.b = TRUE;
621                                 find(c, &arg);
622                                 return GDK_FILTER_REMOVE;
623                         }
624                         else if(ev->atom == atoms[AtomGo]) {
625                                 arg.v = getatom(c, AtomGo);
626                                 loaduri(c, &arg);
627                                 return GDK_FILTER_REMOVE;
628                         }
629                 }
630         }
631         return GDK_FILTER_CONTINUE;
632 }
633
634 void
635 progresschange(WebKitWebView *view, GParamSpec *pspec, Client *c) {
636         c->progress = webkit_web_view_get_progress(c->view) * 100;
637         update(c);
638 }
639
640 void
641 reload(Client *c, const Arg *arg) {
642         gboolean nocache = *(gboolean *)arg;
643         if(nocache)
644                  webkit_web_view_reload_bypass_cache(c->view);
645         else
646                  webkit_web_view_reload(c->view);
647 }
648
649 void
650 scroll_h(Client *c, const Arg *arg) {
651  scroll(gtk_scrolled_window_get_hadjustment(GTK_SCROLLED_WINDOW(c->scroll)), arg);
652 }
653
654 void
655 scroll_v(Client *c, const Arg *arg) {
656  scroll(gtk_scrolled_window_get_vadjustment(GTK_SCROLLED_WINDOW(c->scroll)), arg);
657 }
658
659 void
660 scroll(GtkAdjustment *a, const Arg *arg) {
661  gdouble v;
662
663  v = gtk_adjustment_get_value(a);
664  switch (arg->i){
665  case +10000:
666  case -10000:
667  v += gtk_adjustment_get_page_increment(a) * (arg->i / 10000); break;
668  case +20000:
669  case -20000:
670  default:
671  v += gtk_adjustment_get_step_increment(a) * arg->i;
672  }
673  v = MAX(v, 0.0);
674  v = MIN(v, gtk_adjustment_get_upper(a) - gtk_adjustment_get_page_size(a));
675  gtk_adjustment_set_value(a, v);
676 }
677
678 void
679 setcookie(SoupCookie *c) {
680         int lock;
681
682         lock = open(cookiefile, 0);
683         flock(lock, LOCK_EX);
684         SoupDate *e;
685         SoupCookieJar *j = soup_cookie_jar_text_new(cookiefile, FALSE);
686         c = soup_cookie_copy(c);
687         if(c->expires == NULL && sessiontime) {
688                 e = soup_date_new_from_time_t(time(NULL) + sessiontime);
689                 soup_cookie_set_expires(c, e);
690         }
691         soup_cookie_jar_add_cookie(j, c);
692         g_object_unref(j);
693         flock(lock, LOCK_UN);
694         close(lock);
695 }
696
697 void
698 setatom(Client *c, int a, const char *v) {
699         XSync(dpy, False);
700         XChangeProperty(dpy, GDK_WINDOW_XID(GTK_WIDGET(c->win)->window), atoms[a],
701                         XA_STRING, 8, PropModeReplace, (unsigned char *)v,
702                         strlen(v) + 1);
703 }
704
705 void
706 setup(void) {
707         char *proxy;
708         char *new_proxy;
709         SoupURI *puri;
710         SoupSession *s;
711
712         /* clean up any zombies immediately */
713         sigchld(0);
714         gtk_init(NULL, NULL);
715         if (!g_thread_supported())
716                 g_thread_init(NULL);
717
718         dpy = GDK_DISPLAY();
719         s = webkit_get_default_session();
720
721         /* atoms */
722         atoms[AtomFind] = XInternAtom(dpy, "_SURF_FIND", False);
723         atoms[AtomGo] = XInternAtom(dpy, "_SURF_GO", False);
724         atoms[AtomUri] = XInternAtom(dpy, "_SURF_URI", False);
725
726         /* dirs and files */
727         cookiefile = buildpath(cookiefile);
728         scriptfile = buildpath(scriptfile);
729         stylefile = buildpath(stylefile);
730
731         /* request handler */
732         s = webkit_get_default_session();
733         soup_session_remove_feature_by_type(s, soup_cookie_get_type());
734         soup_session_remove_feature_by_type(s, soup_cookie_jar_get_type());
735         g_signal_connect_after(G_OBJECT(s), "request-started", G_CALLBACK(newrequest), NULL);
736
737         /* ssl */
738         g_object_set(G_OBJECT(s), "ssl-ca-file", cafile, NULL);
739         g_object_set(G_OBJECT(s), "ssl-strict", strictssl, NULL);
740
741         /* proxy */
742         if((proxy = getenv("http_proxy")) && strcmp(proxy, "")) {
743                 new_proxy = g_strrstr(proxy, "http://") ? g_strdup(proxy) :
744                         g_strdup_printf("http://%s", proxy);
745                 puri = soup_uri_new(new_proxy);
746                 g_object_set(G_OBJECT(s), "proxy-uri", puri, NULL);
747                 soup_uri_free(puri);
748                 g_free(new_proxy);
749         }
750 }
751
752 void
753 sigchld(int unused) {
754         if(signal(SIGCHLD, sigchld) == SIG_ERR)
755                 die("Can't install SIGCHLD handler");
756         while(0 < waitpid(-1, NULL, WNOHANG));
757 }
758
759 void
760 source(Client *c, const Arg *arg) {
761         Arg a = { .b = FALSE };
762         gboolean s;
763
764         s = webkit_web_view_get_view_source_mode(c->view);
765         webkit_web_view_set_view_source_mode(c->view, !s);
766         reload(c, &a);
767 }
768
769 void
770 spawn(Client *c, const Arg *arg) {
771         if(fork() == 0) {
772                 if(dpy)
773                         close(ConnectionNumber(dpy));
774                 setsid();
775                 execvp(((char **)arg->v)[0], (char **)arg->v);
776                 fprintf(stderr, "surf: execvp %s", ((char **)arg->v)[0]);
777                 perror(" failed");
778                 exit(0);
779         }
780 }
781
782 void
783 eval(Client *c, const Arg *arg) {
784         WebKitWebFrame *frame = webkit_web_view_get_main_frame(c->view);
785         evalscript(webkit_web_frame_get_global_context(frame), ((char **)arg->v)[0], "");
786 }
787
788 void
789 stop(Client *c, const Arg *arg) {
790         webkit_web_view_stop_loading(c->view);
791 }
792
793 void
794 titlechange(WebKitWebView *v, WebKitWebFrame *f, const char *t, Client *c) {
795         c->title = copystr(&c->title, t);
796         update(c);
797 }
798
799 void
800 update(Client *c) {
801         char *t;
802
803         if(c->linkhover)
804                 t = g_strdup(c->linkhover);
805         else if(c->progress != 100)
806                 t = g_strdup_printf("[%i%%] %s", c->progress, c->title);
807         else
808                 t = g_strdup(c->title);
809         drawindicator(c);
810         gtk_window_set_title(GTK_WINDOW(c->win), t);
811         g_free(t);
812 }
813
814 void
815 updatewinid(Client *c) {
816         snprintf(winid, LENGTH(winid), "%u",
817                         (int)GDK_WINDOW_XID(GTK_WIDGET(c->win)->window));
818 }
819
820 void
821 usage(void) {
822         fputs("surf - simple browser\n", stderr);
823         die("usage: surf [-e xid] [-i] [-p] [-s] [-v] [-x] [uri]\n");
824 }
825
826 void
827 windowobjectcleared(GtkWidget *w, WebKitWebFrame *frame, JSContextRef js, JSObjectRef win, Client *c) {
828         runscript(frame);
829 }
830
831 void
832 zoom(Client *c, const Arg *arg) {
833         c->zoomed = TRUE;
834         if(arg->i < 0)          /* zoom out */
835                 webkit_web_view_zoom_out(c->view);
836         else if(arg->i > 0)     /* zoom in */
837                 webkit_web_view_zoom_in(c->view);
838         else {                  /* reset */
839                 c->zoomed = FALSE;
840                 webkit_web_view_set_zoom_level(c->view, 1.0);
841         }
842 }
843
844 int
845 main(int argc, char *argv[]) {
846         int i;
847         Arg arg;
848
849         progname = argv[0];
850         /* command line args */
851         for(i = 1, arg.v = NULL; i < argc && argv[i][0] == '-' &&
852                         argv[i][1] != '\0' && argv[i][2] == '\0'; i++) {
853                 if(!strcmp(argv[i], "--")) {
854                         i++;
855                         break;
856                 }
857                 switch(argv[i][1]) {
858                 case 'e':
859                         if(++i < argc)
860                                 embed = strtol(argv[i], NULL, 0);
861                         else
862                                 usage();
863                         break;
864                 case 'i':
865                         loadimage = 0;
866                         break;
867                 case 'p':
868                         plugin = 0;
869                         break;
870                 case 's':
871                         script = 0;
872                         break;
873                 case 'x':
874                         showxid = TRUE;
875                         break;
876                 case 'v':
877                         die("surf-"VERSION", ©2009-2012 surf engineers, see LICENSE for details\n");
878                 default:
879                         usage();
880                 }
881         }
882         if(i < argc)
883                 arg.v = argv[i];
884         setup();
885         newclient();
886         if(arg.v)
887                 loaduri(clients, &arg);
888         gtk_main();
889         cleanup();
890         return EXIT_SUCCESS;
891 }