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