support --config option + reorganize variables a bit in a clear hierachy
[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 #define GDK_Escape 0xff1b
34
35 #include <gtk/gtk.h>
36 #include <gdk/gdkx.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
46 /* housekeeping / internal variables */
47 static GtkWidget* main_window;
48 static GtkWidget* mainbar;
49 static WebKitWebView* web_view;
50 static gchar* main_title;
51 static gchar selected_url[500];
52 static gint load_progress;
53 static guint status_context_id;
54 static Window xwin = 0;
55 static char fifopath[64];
56
57 /* state variables (initial values coming from command line arguments but may be changed later) */
58 static gchar*   uri = NULL;
59 static gchar*   config_file = NULL;
60 static gboolean verbose = FALSE;
61
62 /* settings from config: group behaviour */
63 static gchar*   history_handler    = NULL;
64 static gchar*   fifodir            = NULL;
65 static gchar*   download_handler   = NULL;
66 static gboolean always_insert_mode = FALSE;
67 static gboolean show_status        = FALSE;
68 static gboolean insert_mode        = FALSE;
69 static gchar*   modkey             = NULL;
70
71
72 typedef struct
73 {
74     const char *binding;
75     const char *action;
76 } Binding;
77
78 /* settings from config: group bindings_internal */
79 static Binding internal_bindings[256];
80 static int     num_internal_bindings = 0;
81
82 /* settings from config: group bindings_external */
83 static Binding external_bindings[256];
84 static int     num_external_bindings = 0;
85
86 /* commandline arguments (set initial values for the state variables) */
87 static GOptionEntry entries[] =
88 {
89     { "uri",     'u', 0, G_OPTION_ARG_STRING, &uri,         "Uri to load", NULL },
90     { "verbose", 'v', 0, G_OPTION_ARG_NONE,   &verbose,     "Be verbose",  NULL },
91     { "config",  'c', 0, G_OPTION_ARG_STRING, &config_file, "Config file", NULL },
92     { NULL }
93 };
94
95 /* for internal list of commands */
96 typedef struct
97 {
98     const char *command;
99     void (*func_1_param)(WebKitWebView*);
100     void (*func_2_params)(WebKitWebView*, char *);
101 } Command;
102
103
104 static void
105 update_title (GtkWindow* window);
106
107 static gboolean
108 run_command(const char *command, const char *args);
109
110
111 /* --- CALLBACKS --- */
112 static void
113 go_back_cb (GtkWidget* widget, gpointer data) {
114     webkit_web_view_go_back (web_view);
115 }
116
117 static void
118 go_forward_cb (GtkWidget* widget, gpointer data) {
119     webkit_web_view_go_forward (web_view);
120 }
121
122
123 static void
124 link_hover_cb (WebKitWebView* page, const gchar* title, const gchar* link, gpointer data) {
125     /* underflow is allowed */
126     //gtk_statusbar_pop (main_statusbar, status_context_id);
127     //if (link)
128     //    gtk_statusbar_push (main_statusbar, status_context_id, link);
129     //TODO implementation roadmap pending..
130     
131     //ADD HOVER URL TO WINDOW TITLE
132     selected_url[0] = '\0';
133     if (link) {
134         strcpy (selected_url, link);
135     }
136     update_title (GTK_WINDOW (main_window));
137 }
138
139 static void
140 title_change_cb (WebKitWebView* web_view, WebKitWebFrame* web_frame, const gchar* title, gpointer data) {
141     if (main_title)
142         g_free (main_title);
143     main_title = g_strdup (title);
144     update_title (GTK_WINDOW (main_window));
145 }
146
147 static void
148 progress_change_cb (WebKitWebView* page, gint progress, gpointer data) {
149     load_progress = progress;
150     update_title (GTK_WINDOW (main_window));
151 }
152
153 static void
154 load_commit_cb (WebKitWebView* page, WebKitWebFrame* frame, gpointer data) {
155     strcpy (uri, webkit_web_frame_get_uri (frame));
156 }
157
158 static void
159 destroy_cb (GtkWidget* widget, gpointer data) {
160     gtk_main_quit ();
161 }
162
163 static void
164 log_history_cb () {
165    time_t rawtime;
166    struct tm * timeinfo;
167    char date [80];
168    time ( &rawtime );
169    timeinfo = localtime ( &rawtime );
170    strftime (date, 80, "%Y-%m-%d %H:%M:%S", timeinfo);
171    GString* args = g_string_new ("");
172    g_string_printf (args, "'%s' '%s' '%s'", uri, "TODO:page title here", date);
173    run_command(history_handler, args->str);
174 }
175
176 /* -- command to callback/function map for things we cannot attach to any signals */
177 // TODO: reload, home, quit
178 static Command commands[] =
179 {
180     { "back",     &go_back_cb,                    NULL },
181     { "forward",  &go_forward_cb,                 NULL },
182     { "refresh",  &webkit_web_view_reload,        NULL }, //Buggy
183     { "stop",     &webkit_web_view_stop_loading,  NULL },
184     { "zoom_in",  &webkit_web_view_zoom_in,       NULL }, //Can crash (when max zoom reached?).
185     { "zoom_out", &webkit_web_view_zoom_out,      NULL } ,
186     { "uri",      NULL, &webkit_web_view_load_uri      }
187 //{ "get uri",  &webkit_web_view_get_uri},
188 };
189
190 /* -- CORE FUNCTIONS -- */
191
192 // make sure to put '' around args, so that if there is whitespace we can still keep arguments together.
193 static gboolean
194 run_command(const char *command, const char *args) {
195    //command <uzbl conf> <uzbl pid> <uzbl win id> <uzbl fifo file> [args]
196     GString* to_execute = g_string_new ("");
197     gboolean result;
198     g_string_printf (to_execute, "%s '%s' '%i' '%i' '%s' %s", command, "./sampleconfig", (int) getpid() , (int) xwin, "/tmp/uzbl_25165827", args);
199     result = system(to_execute->str);
200     printf("Called %s.  Result: %s\n", to_execute->str, (result ? "FALSE" : "TRUE" ));
201     return result;
202 }
203
204 static void
205 parse_command(const char *command) {
206     int i;
207     Command *c;
208     char * command_name  = strtok (command, " ");
209     char * command_param = strtok (NULL,  " ,"); //dunno how this works, but it seems to work
210
211     Command *c_tmp;
212     for (i = 0; i < LENGTH (commands); i++) {
213         c_tmp = &commands[i];
214         if (strncmp (command_name, c_tmp->command, strlen (c_tmp->command)) == 0) {
215             c = c_tmp;
216         }
217     }
218     if (c != NULL) {
219         if (c->func_2_params != NULL) {
220             if (command_param != NULL) {
221                 printf ("command executing: \"%s %s\"\n", command_name, command_param);
222                 c->func_2_params (web_view, command_param);
223             } else {
224                 if (c->func_1_param != NULL) {
225                     printf ("command executing: \"%s\"\n", command_name);
226                     c->func_1_param (web_view);
227                 } else {
228                     fprintf (stderr, "command needs a parameter. \"%s\" is not complete\n", command_name);
229                 }
230             }
231         } else if (c->func_1_param != NULL) {
232             printf ("command executing: \"%s\"\n", command_name);
233             c->func_1_param (web_view);
234         }
235     } else {
236         fprintf (stderr, "command \"%s\" not understood. ignoring.\n", command);
237     }
238 }
239  
240 static void
241 *control_fifo() {
242     if (fifodir) {
243         sprintf (fifopath, "%s/uzbl_%d", fifodir, (int) xwin);
244     } else {
245         sprintf (fifopath, "/tmp/uzbl_%d", (int) xwin);
246     }
247  
248     if (mkfifo (fifopath, 0666) == -1) {
249         printf ("Possible error creating fifo\n");
250     }
251  
252     printf ("Control fifo opened in %s\n", fifopath);
253  
254     while (true) {
255         FILE *fifo = fopen (fifopath, "r");
256         if (!fifo) {
257             printf ("Could not open %s for reading\n", fifopath);
258             return NULL;
259         }
260         
261         char buffer[256];
262         memset (buffer, 0, sizeof (buffer));
263         while (!feof (fifo) && fgets (buffer, sizeof (buffer), fifo)) {
264             if (strcmp (buffer, "\n")) {
265                 buffer[strlen (buffer) - 1] = '\0'; // Remove newline
266                 parse_command (buffer);
267             }
268         }
269     }
270     
271     return NULL;
272
273  
274 static void
275 setup_threading () {
276     pthread_t control_thread;
277     pthread_create(&control_thread, NULL, control_fifo, NULL);
278 }
279
280 static void
281 update_title (GtkWindow* window) {
282     GString* string = g_string_new ("");
283     if (!always_insert_mode)
284         g_string_append (string, (insert_mode ? "[I] " : "[C] "));
285     g_string_append (string, main_title);
286     g_string_append (string, " - Uzbl browser");
287     if (load_progress < 100)
288         g_string_append_printf (string, " (%d%%)", load_progress);
289
290     if (selected_url[0]!=0) {
291         g_string_append_printf (string, " -> (%s)", selected_url);
292     }
293
294     gchar* title = g_string_free (string, FALSE);
295     gtk_window_set_title (window, title);
296     g_free (title);
297 }
298  
299 static gboolean
300 key_press_cb (WebKitWebView* page, GdkEventKey* event)
301 {
302     int i;
303     gboolean result=FALSE; //TRUE to stop other handlers from being invoked for the event. FALSE to propagate the event further.
304     if (event->type != GDK_KEY_PRESS) 
305         return result;
306
307     //TURN OFF INSERT MODE
308     if (insert_mode && (event->keyval == GDK_Escape)) {
309         insert_mode = FALSE;
310         update_title (GTK_WINDOW (main_window));
311         return TRUE;
312     }
313
314     //TURN ON INSERT MODE
315     if (!insert_mode && (event->string[0] == 'i')) {
316         insert_mode = TRUE;
317         update_title (GTK_WINDOW (main_window));
318         return TRUE;
319     }
320
321     //INTERNAL KEYS
322     if (always_insert_mode || !insert_mode) {
323         for (i = 0; i < num_internal_bindings; i++) {
324             if (event->string[0] == internal_bindings[i].binding[0]) {
325                 parse_command (internal_bindings[i].action);
326                 result = TRUE;
327             }   
328         }
329     }
330     if (!result)
331         result = (insert_mode ? FALSE : TRUE);      
332
333     return result;
334 }
335
336 static GtkWidget*
337 create_browser () {
338     GtkWidget* scrolled_window = gtk_scrolled_window_new (NULL, NULL);
339     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
340
341     web_view = WEBKIT_WEB_VIEW (webkit_web_view_new ());
342     gtk_container_add (GTK_CONTAINER (scrolled_window), GTK_WIDGET (web_view));
343
344     g_signal_connect (G_OBJECT (web_view), "title-changed", G_CALLBACK (title_change_cb), web_view);
345     g_signal_connect (G_OBJECT (web_view), "load-progress-changed", G_CALLBACK (progress_change_cb), web_view);
346     g_signal_connect (G_OBJECT (web_view), "load-committed", G_CALLBACK (load_commit_cb), web_view);
347     g_signal_connect (G_OBJECT (web_view), "load-committed", G_CALLBACK (log_history_cb), web_view);
348     g_signal_connect (G_OBJECT (web_view), "hovering-over-link", G_CALLBACK (link_hover_cb), web_view);
349     g_signal_connect (G_OBJECT (web_view), "key-press-event", G_CALLBACK (key_press_cb), web_view);
350
351     return scrolled_window;
352 }
353
354 static GtkWidget*
355 create_mainbar () {
356     mainbar = gtk_hbox_new (FALSE, 0);
357
358     //status_context_id = gtk_statusbar_get_context_id (main_statusbar, "Link Hover");
359
360     return mainbar;
361 }
362
363 static
364 GtkWidget* create_window () {
365     GtkWidget* window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
366     gtk_window_set_default_size (GTK_WINDOW (window), 800, 600);
367     gtk_widget_set_name (window, "Uzbl browser");
368     g_signal_connect (G_OBJECT (window), "destroy", G_CALLBACK (destroy_cb), NULL);
369
370     return window;
371 }
372
373 static void
374 add_binding (char *binding, char *action, bool internal) {
375     Binding bind = {binding, action};
376     if (internal) {
377         internal_bindings[num_internal_bindings] = bind;
378         num_internal_bindings ++;
379     } else {
380         external_bindings[num_external_bindings] = bind;
381         num_external_bindings ++;
382     }
383 }
384
385 static void
386 settings_init () {
387     GKeyFile* config = g_key_file_new ();
388     gboolean res = g_key_file_load_from_file (config, "./sampleconfig", G_KEY_FILE_NONE, NULL); //TODO: pass config file as argument
389     if (res) {
390         printf ("Config loaded\n");
391     } else {
392         fprintf (stderr, "Config loading failed\n"); //TODO: exit codes with gtk? 
393     }
394
395     history_handler = g_key_file_get_value (config, "behavior", "history_handler", NULL);
396     if (history_handler) {
397         printf ("History handler: %s\n", history_handler);
398     } else {
399         printf ("History handler disabled\n");
400     }
401
402     download_handler = g_key_file_get_value (config, "behavior", "download_handler", NULL);
403     if (download_handler) {
404         printf ("Download manager: %s\n", download_handler);
405     } else {
406         printf ("Download manager disabled\n");
407     }
408
409     if (! fifodir)
410         fifodir = g_key_file_get_value (config, "behavior", "fifodir", NULL);
411     if (fifodir) {
412         printf ("Fifo directory: %s\n", fifodir);
413     } else {
414         printf ("Fifo directory: /tmp\n");
415     }
416
417     always_insert_mode = g_key_file_get_boolean (config, "behavior", "always_insert_mode", NULL);
418     printf ("Always insert mode: %s\n", (always_insert_mode ? "TRUE" : "FALSE"));
419
420     show_status = g_key_file_get_boolean (config, "behavior", "show_status", NULL);
421     printf ("Show status: %s\n", (show_status ? "TRUE" : "FALSE"));
422
423     modkey = g_key_file_get_value (config, "behavior", "modkey", NULL);
424     if (modkey) {
425         printf ("Mod key: %s\n", modkey);
426     } else {
427         printf ("Mod key disabled/\n");
428     }
429
430     gchar **keysi = g_key_file_get_keys (config, "bindings_internal", NULL, NULL);
431     int i = 0;
432     for (i = 0; keysi[i]; i++)
433       {
434         gchar *binding = g_key_file_get_string(config, "bindings_internal", keysi[i], NULL);
435         printf("Action: %s, Binding: %s (internal)\n", g_strdup (keysi[i]), binding);
436         add_binding (binding, g_strdup (keysi[i]), true);
437       }
438
439     gchar **keyse = g_key_file_get_keys (config, "bindings_external", NULL, NULL);
440     for (i = 0; keyse[i]; i++)
441       {
442         gchar *binding = g_key_file_get_string(config, "bindings_external", keyse[i], NULL);
443         printf("Action: %s, Binding: %s (external)\n", g_strdup (keyse[i]), binding);
444         add_binding (binding, g_strdup (keyse[i]), false);
445       }
446 }
447
448 int
449 main (int argc, char* argv[]) {
450     gtk_init (&argc, &argv);
451     if (!g_thread_supported ())
452         g_thread_init (NULL);
453
454     settings_init ();
455     if (always_insert_mode)
456         insert_mode = TRUE;
457
458     GtkWidget* vbox = gtk_vbox_new (FALSE, 0);
459     gtk_box_pack_start (GTK_BOX (vbox), create_mainbar (), FALSE, TRUE, 0);
460     gtk_box_pack_start (GTK_BOX (vbox), create_browser (), TRUE, TRUE, 0);
461
462     main_window = create_window ();
463     gtk_container_add (GTK_CONTAINER (main_window), vbox);
464     GError *error = NULL;
465
466     GOptionContext* context = g_option_context_new ("- some stuff here maybe someday");
467     g_option_context_add_main_entries (context, entries, NULL);
468     g_option_context_add_group (context, gtk_get_option_group (TRUE));
469     g_option_context_parse (context, &argc, &argv, &error);
470
471     webkit_web_view_load_uri (web_view, uri);
472
473     gtk_widget_grab_focus (GTK_WIDGET (web_view));
474     gtk_widget_show_all (main_window);
475     xwin = GDK_WINDOW_XID (GTK_WIDGET (main_window)->window);
476     printf("window_id %i\n",(int) xwin);
477     printf("pid %i\n", getpid ());
478
479     setup_threading ();
480
481     gtk_main ();
482
483     unlink (fifopath);
484     return 0;
485 }