Initial commit
[uzbl-mobile] / uzbl.c
1 // Original code taken from the example webkit-gtk+ application. see notice below.
2 // Modified code is licensed under the GPL 3.  See LICENSE file.
3
4
5 /*
6  * Copyright (C) 2006, 2007 Apple Inc.
7  * Copyright (C) 2007 Alp Toker <alp@atoker.com>
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice, this list of conditions and the following disclaimer.
14  * 2. Redistributions in binary form must reproduce the above copyright
15  *    notice, this list of conditions and the following disclaimer in the
16  *    documentation and/or other materials provided with the distribution.
17  *
18  * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
19  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
21  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE COMPUTER, INC. OR
22  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
23  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
24  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
25  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
26  * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29  */
30
31
32 #define LENGTH(x) (sizeof x / sizeof x[0])
33
34 #include <gtk/gtk.h>
35 #include <gdk/gdkx.h>
36 #include <gdk/gdkkeysyms.h>
37 #include <webkit/webkit.h>
38 #include <pthread.h>
39 #include <stdio.h>
40 #include <string.h>
41 #include <sys/stat.h>
42 #include <sys/types.h>
43 #include <unistd.h>
44 #include <stdlib.h>
45 #include <errno.h>
46 #include <string.h>
47 #include <sys/types.h>
48 #include <fcntl.h>
49 #include <sys/socket.h>
50 #include <sys/un.h>
51
52 /* housekeeping / internal variables */
53 static GtkWidget* main_window;
54 static GtkWidget* mainbar;
55 static GtkWidget* mainbar_label;
56 static WebKitWebView* web_view;
57 static gchar* main_title;
58 static gchar selected_url[500] = "\0";
59 static gint load_progress;
60 static Window xwin = 0;
61 static char fifo_path[64];
62 static char socket_path[108];
63
64 /* state variables (initial values coming from command line arguments but may be changed later) */
65 static gchar*   uri         = NULL;
66 static gchar*   config_file = NULL;
67 static gchar    config_file_path[500];
68 static gboolean verbose     = FALSE;
69
70 /* settings from config: group behaviour */
71 static gchar*   history_handler    = NULL;
72 static gchar*   fifo_dir           = NULL;
73 static gchar*   socket_dir         = NULL;
74 static gchar*   download_handler   = NULL;
75 static gboolean always_insert_mode = FALSE;
76 static gboolean show_status        = FALSE;
77 static gboolean insert_mode        = FALSE;
78 static gboolean status_top         = FALSE;
79 static gchar*   modkey             = NULL;
80 static guint    modmask            = 0;
81 static gchar*   home_page          = NULL;
82
83 /* settings from config: group bindings_internal */
84 static GHashTable *internal_bindings;
85
86 /* settings from config: group bindings_external */
87 static GHashTable *external_bindings;
88
89 /* command list */
90 static GHashTable *commands;
91
92 /* commandline arguments (set initial values for the state variables) */
93 static GOptionEntry entries[] =
94 {
95     { "uri",     'u', 0, G_OPTION_ARG_STRING, &uri,         "Uri to load", NULL },
96     { "verbose", 'v', 0, G_OPTION_ARG_NONE,   &verbose,     "Be verbose",  NULL },
97     { "config",  'c', 0, G_OPTION_ARG_STRING, &config_file, "Config file", NULL },
98     { NULL,      0, 0, 0, NULL, NULL, NULL }
99 };
100
101 /* for internal list of commands */
102 typedef struct
103 {
104     gpointer command;
105     void (*func_1_param)(WebKitWebView*);
106     void (*func_2_params)(WebKitWebView*, const gchar *);
107 } Command;
108
109 /* XDG stuff */
110 char *XDG_CONFIG_HOME_default[256];
111 char *XDG_CONFIG_DIRS_default = "/etc/xdg";
112
113 static void
114 update_title (GtkWindow* window);
115
116 static void
117 load_uri ( WebKitWebView * web_view, const gchar * uri);
118
119 static void
120 new_window_load_uri (const gchar * uri);
121
122 static void
123 go_home ( WebKitWebView * web_view);
124
125 static void
126 close_uzbl ( WebKitWebView * web_view);
127
128 static gboolean
129 run_command(const char *command, const char *args);
130
131 /* --- UTILITY FUNCTIONS --- */
132 void
133 eprint(const char *errstr, ...) {
134         va_list ap;
135         vfprintf(stderr, errstr, ap);
136         va_end(ap);
137         exit(EXIT_FAILURE);
138 }
139
140 char *
141 estrdup(const char *str) {
142         void *res = strdup(str);
143         if(!res)
144             eprint("fatal: could not allocate %u bytes\n", strlen(str));
145         return res;
146 }
147
148 /* --- CALLBACKS --- */
149
150 static gboolean
151 new_window_cb (WebKitWebView *web_view, WebKitWebFrame *frame, WebKitNetworkRequest *request, WebKitWebNavigationAction *navigation_action, WebKitWebPolicyDecision *policy_decision, gpointer user_data) {
152     (void) web_view;
153     (void) frame;
154     (void) navigation_action;
155     (void) policy_decision;
156     (void) user_data;
157     const gchar* uri = webkit_network_request_get_uri (request);
158     printf("New window requested -> %s \n", uri);
159     new_window_load_uri(uri);
160     return (FALSE);
161 }
162
163 WebKitWebView*
164 create_web_view_cb (WebKitWebView  *web_view, WebKitWebFrame *frame, gpointer user_data) {
165     (void) web_view;
166     (void) frame;
167     (void) user_data;
168     if (selected_url[0]!=0) {
169         printf("\nNew web view -> %s\n",selected_url);
170         new_window_load_uri(selected_url);
171     } else {
172         printf("New web view -> %s\n","Nothing to open, exiting");
173     }
174     return (NULL);
175 }
176
177 static gboolean
178 download_cb (WebKitWebView *web_view, GObject *download, gpointer user_data) {
179     (void) web_view;
180     (void) user_data;
181     if (download_handler) {
182         const gchar* uri = webkit_download_get_uri ((WebKitDownload*)download);
183         printf("Download -> %s\n",uri);
184         run_command(download_handler, uri);
185     }
186     return (FALSE);
187 }
188
189 static void
190 go_back_cb (WebKitWebView* page) {
191     (void) page;
192     webkit_web_view_go_back (web_view);
193 }
194
195 static void
196 go_forward_cb (WebKitWebView* page) {
197     (void) page;
198     webkit_web_view_go_forward (web_view);
199 }
200
201 static void
202 toggle_status_cb (WebKitWebView* page) {
203     (void) page;
204     if (show_status) {
205         gtk_widget_hide(mainbar);
206     } else {
207         gtk_widget_show(mainbar);
208     }
209     show_status = !show_status;
210     update_title (GTK_WINDOW (main_window));
211 }
212
213 static void
214 link_hover_cb (WebKitWebView* page, const gchar* title, const gchar* link, gpointer data) {
215     (void) page;
216     (void) title;
217     (void) data;    
218     //ADD HOVER URL TO WINDOW TITLE
219     selected_url[0] = '\0';
220     if (link) {
221         strcpy (selected_url, link);
222     }
223     update_title (GTK_WINDOW (main_window));
224 }
225
226 static void
227 title_change_cb (WebKitWebView* web_view, WebKitWebFrame* web_frame, const gchar* title, gpointer data) {
228     (void) web_view;
229     (void) web_frame;
230     (void) data;
231     if (main_title)
232         g_free (main_title);
233     main_title = g_strdup (title);
234     update_title (GTK_WINDOW (main_window));
235 }
236
237 static void
238 progress_change_cb (WebKitWebView* page, gint progress, gpointer data) {
239     (void) page;
240     (void) data;
241     load_progress = progress;
242     update_title (GTK_WINDOW (main_window));
243 }
244
245 static void
246 load_commit_cb (WebKitWebView* page, WebKitWebFrame* frame, gpointer data) {
247     (void) page;
248     (void) data;
249     free (uri);
250     GString* newuri = g_string_new (webkit_web_frame_get_uri (frame));
251     uri = g_string_free (newuri, FALSE);
252 }
253
254 static void
255 destroy_cb (GtkWidget* widget, gpointer data) {
256     (void) widget;
257     (void) data;
258     gtk_main_quit ();
259 }
260
261 static void
262 log_history_cb () {
263    if (history_handler) {
264        time_t rawtime;
265        struct tm * timeinfo;
266        char date [80];
267        time ( &rawtime );
268        timeinfo = localtime ( &rawtime );
269        strftime (date, 80, "%Y-%m-%d %H:%M:%S", timeinfo);
270        GString* args = g_string_new ("");
271        g_string_printf (args, "'%s' '%s' '%s'", uri, "TODO:page title here", date);
272        run_command(history_handler, args->str);
273        g_string_free (args, TRUE);
274    }
275 }
276                                                                                                                                                              
277 /* -- command to callback/function map for things we cannot attach to any signals */
278 // TODO: reload, home, quit
279
280 static Command cmdlist[] =
281 {
282     { "back",          &go_back_cb,                    NULL },
283     { "forward",       &go_forward_cb,                 NULL },
284     { "refresh",       &webkit_web_view_reload,        NULL }, //Buggy
285     { "stop",          &webkit_web_view_stop_loading,  NULL },
286     { "zoom_in",       &webkit_web_view_zoom_in,       NULL }, //Can crash (when max zoom reached?).
287     { "zoom_out",      &webkit_web_view_zoom_out,      NULL },
288     { "uri",           (void *) NULL,             &load_uri },
289     { "toggle_status", &toggle_status_cb,              NULL },
290     { "home"         , &go_home,                       NULL },
291     { "exit"         , &close_uzbl,                    NULL },
292     { NULL,            NULL,                           NULL }
293 //{ "get uri",  &webkit_web_view_get_uri},
294 };
295
296 static void
297 commands_hash(void)
298 {
299   unsigned int i = 0;
300   commands = g_hash_table_new(g_str_hash, g_str_equal);
301   
302   while(cmdlist[i].command != NULL){
303     g_hash_table_insert(commands, cmdlist[i].command, &cmdlist[i]);
304     i++;
305   }
306 }
307
308 /* -- CORE FUNCTIONS -- */
309
310 static bool
311 file_exists (const char * filename) {
312     FILE *file = fopen (filename, "r");
313     if (file) {
314         fclose (file);
315         return true;
316     }
317     return false;
318 }
319
320 static void
321 load_uri (WebKitWebView * web_view, const gchar * uri) {
322     if (uri != NULL) {
323         GString* newuri = g_string_new (uri);
324         if (g_strrstr (uri, "://") == NULL)
325             g_string_prepend (newuri, "http://"); 
326         webkit_web_view_load_uri (web_view, newuri->str);
327         g_string_free (newuri, TRUE);
328     }
329 }
330
331 static void
332 new_window_load_uri (const gchar * uri) {
333     GString* to_execute = g_string_new ("");
334     if (!config_file) {
335         g_string_printf (to_execute, "uzbl --uri '%s'", uri);
336     } else {
337         g_string_printf (to_execute, "uzbl --uri '%s' --config '%s'", uri, config_file);
338     }
339     printf("Spawning %s\n",to_execute->str);
340     if (!g_spawn_command_line_async (to_execute->str, NULL)) {
341         if (!config_file) {
342             g_string_printf (to_execute, "./uzbl --uri '%s'", uri);
343         } else {
344             g_string_printf (to_execute, "./uzbl --uri '%s' --config '%s'", uri, config_file);
345         }
346         printf("Spawning %s\n",to_execute->str);
347         g_spawn_command_line_async (to_execute->str, NULL);
348     }
349     g_string_free (to_execute, TRUE);
350 }
351
352 static void
353 go_home (WebKitWebView * web_view) {
354     if (home_page)
355         webkit_web_view_load_uri (web_view, home_page);
356 }
357
358 static void
359 close_uzbl (WebKitWebView * web_view) {
360     (void) web_view;
361     gtk_main_quit ();
362 }
363
364 // make sure to put '' around args, so that if there is whitespace we can still keep arguments together.
365 static gboolean
366 run_command(const char *command, const char *args) {
367    //command <uzbl conf> <uzbl pid> <uzbl win id> <uzbl fifo file> <uzbl socket file> [args]
368     GString* to_execute = g_string_new ("");
369     gboolean result;
370     g_string_printf (to_execute, "%s '%s' '%i' '%i' '%s' '%s'", command, config_file, (int) getpid() , (int) xwin, fifo_path, socket_path);
371     if(args) {
372         g_string_append_printf (to_execute, " %s", args);
373     }
374     result = g_spawn_command_line_async (to_execute->str, NULL);
375     printf("Called %s.  Result: %s\n", to_execute->str, (result ? "TRUE" : "FALSE" ));
376     g_string_free (to_execute, TRUE);
377     return result;
378 }
379
380 static void
381 parse_command(const char *cmd) {
382     Command *c = NULL;
383     char buffer[512];
384     strcpy (buffer, cmd);
385     char * saveptr;
386     char * command_name  = strtok_r (buffer, " ", &saveptr);
387     gchar * command_param = strtok_r (NULL,  " ,", &saveptr);
388   
389     if((c = g_hash_table_lookup(commands, command_name)) != NULL){
390         if (c->func_2_params != NULL) {
391             if (command_param != NULL) {
392               printf ("command executing: \"%s %s\"\n", command_name, command_param);
393               c->func_2_params (web_view, command_param);
394             } else {
395                 if (c->func_1_param != NULL) {
396                   printf ("command executing: \"%s\"\n", command_name);
397                   c->func_1_param (web_view);
398                 } else 
399                     fprintf (stderr, "command needs a parameter. \"%s\" is not complete\n", command_name);
400             }
401         } else if (c->func_1_param != NULL) {
402             printf ("command executing: \"%s\"\n", command_name);
403             c->func_1_param (web_view);
404         }
405     } else
406         fprintf (stderr, "command \"%s\" not understood. ignoring.\n", cmd);
407
408     if(cmd)
409         free(cmd);
410 }
411
412 static void
413 control_fifo(GIOChannel *fd) {
414     gchar *ctl_line;
415     gsize ctl_line_length, term_pos;
416
417     if(!fd)
418        return;
419
420     g_io_channel_read_line(fd, &ctl_line, &ctl_line_length, &term_pos, NULL); //TODO: support partial writes
421     ctl_line[term_pos] ='\0';
422     parse_command(ctl_line);
423      
424     return;
425 }
426
427 static void
428 create_fifo() {
429     GIOChannel *chan = NULL;
430
431     if (fifo_dir) {
432         sprintf (fifo_path, "%s/uzbl_fifo_%d", fifo_dir, (int) xwin);
433     } else {
434         sprintf (fifo_path, "/tmp/uzbl_fifo_%d", (int) xwin);
435     }
436     printf ("Control fifo opened in %s\n", fifo_path);
437     if (mkfifo (fifo_path, 0666) == -1) {
438         printf ("Possible error creating fifo\n");
439     }
440
441     if( (chan = g_io_channel_new_file((gchar *) fifo_path, "r+", NULL)) )
442         g_io_add_watch(chan, G_IO_IN|G_IO_HUP, (GIOFunc) control_fifo, chan);
443     return;
444 }
445
446 static void
447 *control_socket() {
448     if (socket_dir) {
449         sprintf (socket_path, "%s/uzbl_socket_%d", socket_dir, (int) xwin);
450     } else {
451         sprintf (socket_path, "/tmp/uzbl_socket_%d", (int) xwin);
452     }
453  
454     int sock, clientsock, len;
455     unsigned int t;
456     struct sockaddr_un local, remote;
457
458     sock = socket (AF_UNIX, SOCK_STREAM, 0);
459
460     local.sun_family = AF_UNIX;
461     strcpy (local.sun_path, socket_path);
462     unlink (local.sun_path);
463
464     len = strlen (local.sun_path) + sizeof (local.sun_family);
465     bind (sock, (struct sockaddr *) &local, len);
466
467     if (errno == -1) {
468         printf ("A problem occurred when opening a socket in %s\n", socket_path);
469     } else {
470         printf ("Control socket opened in %s\n", socket_path);
471     }
472
473     listen (sock, 5);
474  
475     char buffer[512], *ctl_line;
476     char temp[128];
477     int done, n;
478     for(;;) {
479         memset (buffer, 0, sizeof (buffer));
480
481         t          = sizeof (remote);
482         clientsock = accept (sock, (struct sockaddr *) &remote, &t);
483         printf ("Connected to client\n");
484
485         done = 0;
486         do {
487             memset (temp, 0, sizeof (temp));
488             n = recv (clientsock, temp, 128, 0);
489             if (n == 0) {
490                 buffer[strlen (buffer)] = '\0';
491                 done = 1;
492             }
493
494             if (!done)
495                 strcat (buffer, temp);
496         } while (!done);
497
498         if (strcmp (buffer, "\n") < 0) {
499             buffer[strlen (buffer) - 1] = '\0';
500         } else {
501           buffer[strlen (buffer)] = '\0';
502         }
503
504         ctl_line = estrdup(buffer);
505         parse_command (ctl_line);
506         close (clientsock);
507     }
508     
509     return NULL;
510
511  
512 static void
513 setup_threading () {
514     pthread_t control_thread;
515     pthread_create(&control_thread, NULL, control_socket, NULL);
516 }
517
518 static void
519 update_title (GtkWindow* window) {
520     GString* string_long = g_string_new ("");
521     GString* string_short = g_string_new ("");
522     if (!always_insert_mode)
523         g_string_append (string_long, (insert_mode ? "[I] " : "[C] "));
524     g_string_append (string_long, main_title);
525     g_string_append (string_short, main_title);
526     g_string_append (string_long, " - Uzbl browser");
527     g_string_append (string_short, " - Uzbl browser");
528     if (load_progress < 100)
529         g_string_append_printf (string_long, " (%d%%)", load_progress);
530
531     if (selected_url[0]!=0) {
532         g_string_append_printf (string_long, " -> (%s)", selected_url);
533     }
534
535     gchar* title_long = g_string_free (string_long, FALSE);
536     gchar* title_short = g_string_free (string_short, FALSE);
537
538     if (show_status) {
539         gtk_window_set_title (window, title_short);
540         gtk_label_set_text(GTK_LABEL(mainbar_label), title_long);
541     } else {
542         gtk_window_set_title (window, title_long);
543     }
544
545     g_free (title_long);
546     g_free (title_short);
547 }
548  
549 static gboolean
550 key_press_cb (WebKitWebView* page, GdkEventKey* event)
551 {
552     (void) page;
553     gpointer act;
554     gboolean result=FALSE; //TRUE to stop other handlers from being invoked for the event. FALSE to propagate the event further.
555     if (event->type != GDK_KEY_PRESS || event->keyval == GDK_Page_Up || event->keyval == GDK_Page_Down
556         || event->keyval == GDK_Up || event->keyval == GDK_Down || event->keyval == GDK_Left || event->keyval == GDK_Right)
557         return result;
558
559     //TURN OFF/ON INSERT MODE
560     if (!always_insert_mode && ((insert_mode && (event->keyval == GDK_Escape)) || (!insert_mode && (event->string[0] == 'i')))) {
561         insert_mode = !insert_mode;
562         update_title (GTK_WINDOW (main_window));
563         return TRUE;
564     }
565
566     //INTERNAL BINDINGS
567     if((act = g_hash_table_lookup(internal_bindings, event->string)) != NULL)
568         if (!insert_mode || (event->state == modmask)) {
569             parse_command (act);
570             result = TRUE;
571         }
572     
573     //EXTERNAL BINDINGS
574     if((act = g_hash_table_lookup(external_bindings, event->string)) != NULL)
575         if (!insert_mode || (event->state == modmask)) {
576             run_command (act, NULL);
577             result = TRUE;
578         }
579     
580     if (!result)
581         result = (insert_mode ? FALSE : TRUE);      
582
583     return result;
584 }
585
586 static GtkWidget*
587 create_browser () {
588     GtkWidget* scrolled_window = gtk_scrolled_window_new (NULL, NULL);
589     gtk_scrolled_window_set_policy (GTK_SCROLLED_WINDOW (scrolled_window), GTK_POLICY_NEVER, GTK_POLICY_NEVER); //todo: some sort of display of position/total length. like what emacs does
590
591     web_view = WEBKIT_WEB_VIEW (webkit_web_view_new ());
592     gtk_container_add (GTK_CONTAINER (scrolled_window), GTK_WIDGET (web_view));
593
594     g_signal_connect (G_OBJECT (web_view), "title-changed", G_CALLBACK (title_change_cb), web_view);
595     g_signal_connect (G_OBJECT (web_view), "load-progress-changed", G_CALLBACK (progress_change_cb), web_view);
596     g_signal_connect (G_OBJECT (web_view), "load-committed", G_CALLBACK (load_commit_cb), web_view);
597     g_signal_connect (G_OBJECT (web_view), "load-committed", G_CALLBACK (log_history_cb), web_view);
598     g_signal_connect (G_OBJECT (web_view), "hovering-over-link", G_CALLBACK (link_hover_cb), web_view);
599     g_signal_connect (G_OBJECT (web_view), "key-press-event", G_CALLBACK (key_press_cb), web_view);
600     g_signal_connect (G_OBJECT (web_view), "new-window-policy-decision-requested", G_CALLBACK (new_window_cb), web_view); 
601     g_signal_connect (G_OBJECT (web_view), "download-requested", G_CALLBACK (download_cb), web_view); 
602     g_signal_connect (G_OBJECT (web_view), "create-web-view", G_CALLBACK (create_web_view_cb), web_view);  
603
604     return scrolled_window;
605 }
606
607 static GtkWidget*
608 create_mainbar () {
609     mainbar = gtk_hbox_new (FALSE, 0);
610     mainbar_label = gtk_label_new ("");  
611     gtk_misc_set_alignment (GTK_MISC(mainbar_label), 0, 0);
612     gtk_misc_set_padding (GTK_MISC(mainbar_label), 2, 2);
613     gtk_box_pack_start (GTK_BOX (mainbar), mainbar_label, TRUE, TRUE, 0);
614     return mainbar;
615 }
616
617 static
618 GtkWidget* create_window () {
619     GtkWidget* window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
620     gtk_window_set_default_size (GTK_WINDOW (window), 800, 600);
621     gtk_widget_set_name (window, "Uzbl browser");
622     g_signal_connect (G_OBJECT (window), "destroy", G_CALLBACK (destroy_cb), NULL);
623
624     return window;
625 }
626
627 static void
628 add_binding (char *binding, char *action, bool internal) {
629   g_hash_table_insert(internal ? internal_bindings : external_bindings,
630                       binding, action);
631 }
632
633 static void
634 settings_init () {
635     GKeyFile* config;
636     gboolean res  = FALSE;
637     gchar** keysi = NULL;
638     gchar** keyse = NULL;
639     char *saveptr;
640
641     if (!config_file) {
642         const char* XDG_CONFIG_HOME = getenv ("XDG_CONFIG_HOME");
643         if (! XDG_CONFIG_HOME || ! strcmp (XDG_CONFIG_HOME, "")) {
644           XDG_CONFIG_HOME = (char *)XDG_CONFIG_HOME_default;
645         }
646         printf("XDG_CONFIG_HOME: %s\n", XDG_CONFIG_HOME);
647     
648         strcpy (config_file_path, XDG_CONFIG_HOME);
649         strcat (config_file_path, "/uzbl/config");
650         if (file_exists (config_file_path)) {
651           printf ("Config file %s found.\n", config_file_path);
652           config_file = &config_file_path[0];
653         } else {
654             // Now we check $XDG_CONFIG_DIRS
655             char *XDG_CONFIG_DIRS = getenv ("XDG_CONFIG_DIRS");
656             if (! XDG_CONFIG_DIRS || ! strcmp (XDG_CONFIG_DIRS, ""))
657                 XDG_CONFIG_DIRS = XDG_CONFIG_DIRS_default;
658
659             printf("XDG_CONFIG_DIRS: %s\n", XDG_CONFIG_DIRS);
660
661             char buffer[512];
662             strcpy (buffer, XDG_CONFIG_DIRS);
663             const gchar* dir = (char *) strtok_r (buffer, ":", &saveptr);
664             while (dir && ! file_exists (config_file_path)) {
665                 strcpy (config_file_path, dir);
666                 strcat (config_file_path, "/uzbl/config_file_pathig");
667                 if (file_exists (config_file_path)) {
668                     printf ("Config file %s found.\n", config_file_path);
669                     config_file = &config_file_path[0];
670                 }
671                 dir = (char * ) strtok_r (NULL, ":", &saveptr);
672             }
673         }
674     }
675
676     if (config_file) {
677         config = g_key_file_new ();
678         res = g_key_file_load_from_file (config, config_file, G_KEY_FILE_NONE, NULL);
679           if(res) {
680             printf ("Config %s loaded\n", config_file);
681           } else {
682             fprintf (stderr, "Config %s loading failed\n", config_file);
683         }
684     } else {
685         printf ("No configuration.\n");
686     }
687
688     if (res) {
689         history_handler    = g_key_file_get_value   (config, "behavior", "history_handler",    NULL);
690         download_handler   = g_key_file_get_value   (config, "behavior", "download_handler",   NULL);
691         always_insert_mode = g_key_file_get_boolean (config, "behavior", "always_insert_mode", NULL);
692         show_status        = g_key_file_get_boolean (config, "behavior", "show_status",        NULL);
693         modkey             = g_key_file_get_value   (config, "behavior", "modkey",             NULL);
694         keysi              = g_key_file_get_keys    (config, "bindings_internal",        NULL, NULL);
695         keyse              = g_key_file_get_keys    (config, "bindings_external",        NULL, NULL);
696         status_top         = g_key_file_get_boolean (config, "behavior", "status_top",         NULL);
697         home_page          = g_key_file_get_value   (config, "behavior", "home_page",          NULL);
698         if (! fifo_dir)
699             fifo_dir       = g_key_file_get_value   (config, "behavior", "fifo_dir",           NULL);
700         if (! socket_dir)
701             socket_dir     = g_key_file_get_value   (config, "behavior", "socket_dir",         NULL);
702     }
703         
704     printf ("History handler: %s\n",    (history_handler    ? history_handler  : "disabled"));
705     printf ("Download manager: %s\n",   (download_handler   ? download_handler : "disabled"));
706     printf ("Fifo directory: %s\n",     (fifo_dir           ? fifo_dir         : "/tmp"));
707     printf ("Socket directory: %s\n",   (socket_dir         ? socket_dir       : "/tmp"));
708     printf ("Always insert mode: %s\n", (always_insert_mode ? "TRUE"           : "FALSE"));
709     printf ("Show status: %s\n",        (show_status        ? "TRUE"           : "FALSE"));
710     printf ("Status top: %s\n",         (status_top         ? "TRUE"           : "FALSE"));
711     printf ("Modkey: %s\n",             (modkey             ? modkey           : "disabled"));
712     printf ("Home page: %s\n",          (home_page          ? home_page        : "disabled"));
713
714     if (! modkey)
715         modkey = "";
716
717     //POSSIBLE MODKEY VALUES (COMBINATIONS CAN BE USED)
718     gchar* modkeyup = g_utf8_strup (modkey, -1);
719     if (g_strrstr (modkeyup,"SHIFT") != NULL)    modmask |= GDK_SHIFT_MASK;    //the Shift key.
720     if (g_strrstr (modkeyup,"LOCK") != NULL)     modmask |= GDK_LOCK_MASK;     //a Lock key (depending on the modifier mapping of the X server this may either be CapsLock or ShiftLock).
721     if (g_strrstr (modkeyup,"CONTROL") != NULL)  modmask |= GDK_CONTROL_MASK;  //the Control key.
722     if (g_strrstr (modkeyup,"MOD1") != NULL)     modmask |= GDK_MOD1_MASK;     //the fourth modifier key (it depends on the modifier mapping of the X server which key is interpreted as this modifier, but normally it is the Alt key).
723     if (g_strrstr (modkeyup,"MOD2") != NULL)     modmask |= GDK_MOD2_MASK;     //the fifth modifier key (it depends on the modifier mapping of the X server which key is interpreted as this modifier).
724     if (g_strrstr (modkeyup,"MOD3") != NULL)     modmask |= GDK_MOD3_MASK;     //the sixth modifier key (it depends on the modifier mapping of the X server which key is interpreted as this modifier).
725     if (g_strrstr (modkeyup,"MOD4") != NULL)     modmask |= GDK_MOD4_MASK;     //the seventh modifier key (it depends on the modifier mapping of the X server which key is interpreted as this modifier).
726     if (g_strrstr (modkeyup,"MOD5") != NULL)     modmask |= GDK_MOD5_MASK;     //the eighth modifier key (it depends on the modifier mapping of the X server which key is interpreted as this modifier).
727     if (g_strrstr (modkeyup,"BUTTON1") != NULL)  modmask |= GDK_BUTTON1_MASK;  //the first mouse button.
728     if (g_strrstr (modkeyup,"BUTTON2") != NULL)  modmask |= GDK_BUTTON2_MASK;  //the second mouse button.
729     if (g_strrstr (modkeyup,"BUTTON3") != NULL)  modmask |= GDK_BUTTON3_MASK;  //the third mouse button.
730     if (g_strrstr (modkeyup,"BUTTON4") != NULL)  modmask |= GDK_BUTTON4_MASK;  //the fourth mouse button.
731     if (g_strrstr (modkeyup,"BUTTON5") != NULL)  modmask |= GDK_BUTTON5_MASK;  //the fifth mouse button.
732     if (g_strrstr (modkeyup,"SUPER") != NULL)    modmask |= GDK_SUPER_MASK;    //the Super modifier. Since 2.10
733     if (g_strrstr (modkeyup,"HYPER") != NULL)    modmask |= GDK_HYPER_MASK;    //the Hyper modifier. Since 2.10
734     if (g_strrstr (modkeyup,"META") != NULL)     modmask |= GDK_META_MASK;     //the Meta modifier. Since 2.10  */
735     free (modkeyup);
736
737     if (keysi) {
738         int i = 0;
739         for (i = 0; keysi[i]; i++) {
740             gchar *binding = g_key_file_get_string (config, "bindings_internal", keysi[i], NULL);
741             printf ("Action: %s, Binding: %s (internal)\n", g_strdup (keysi[i]), binding);
742             add_binding (binding, g_strdup (keysi[i]), true);
743         }
744     }
745     if (keyse) {
746         int i = 0;
747         for (i = 0; keyse[i]; i++) {
748             gchar *binding = g_key_file_get_string (config, "bindings_external", keyse[i], NULL);
749             printf ("Action: %s, Binding: %s (external)\n", g_strdup (keyse[i]), binding);
750             add_binding (binding, g_strdup (keyse[i]), false);
751         }
752     }
753 }
754
755 int
756 main (int argc, char* argv[]) {
757     gtk_init (&argc, &argv);
758     if (!g_thread_supported ())
759         g_thread_init (NULL);
760
761     printf("Uzbl start location: %s\n", argv[0]);
762
763     strcat ((char *) XDG_CONFIG_HOME_default, getenv ("HOME"));
764     strcat ((char *) XDG_CONFIG_HOME_default, "/.config");
765
766     GError *error = NULL;
767     GOptionContext* context = g_option_context_new ("- some stuff here maybe someday");
768     g_option_context_add_main_entries (context, entries, NULL);
769     g_option_context_add_group (context, gtk_get_option_group (TRUE));
770     g_option_context_parse (context, &argc, &argv, &error);
771     /* initialize has tables */
772     internal_bindings = g_hash_table_new(g_str_hash, g_str_equal);
773     external_bindings = g_hash_table_new(g_str_hash, g_str_equal);
774
775     settings_init ();
776     commands_hash ();
777     
778     if (always_insert_mode)
779         insert_mode = TRUE;
780
781     GtkWidget* vbox = gtk_vbox_new (FALSE, 0);
782     if (status_top)
783         gtk_box_pack_start (GTK_BOX (vbox), create_mainbar (), FALSE, TRUE, 0);
784     gtk_box_pack_start (GTK_BOX (vbox), create_browser (), TRUE, TRUE, 0);
785     if (!status_top)
786         gtk_box_pack_start (GTK_BOX (vbox), create_mainbar (), FALSE, TRUE, 0);
787
788     main_window = create_window ();
789     gtk_container_add (GTK_CONTAINER (main_window), vbox);
790
791     load_uri (web_view, uri);
792
793     gtk_widget_grab_focus (GTK_WIDGET (web_view));
794     gtk_widget_show_all (main_window);
795     xwin = GDK_WINDOW_XID (GTK_WIDGET (main_window)->window);
796     printf("window_id %i\n",(int) xwin);
797     printf("pid %i\n", getpid ());
798
799     if (!show_status)
800         gtk_widget_hide(mainbar);
801
802     setup_threading ();
803     create_fifo ();
804
805     gtk_main ();
806
807     unlink (socket_path);
808     unlink (fifo_path);
809     return 0;
810 }
811
812 /* vi: set et ts=4: */