Fixed bug in cycling focused hints backwards.
[vimprobable/e.git] / main.c
blobd883f503b3e778254911677336aa63d57e50e370
2 /*
3 (c) 2009 by Leon Winter
4 (c) 2009-2011 by Hannes Schueller
5 (c) 2009-2010 by Matto Fransen
6 (c) 2010-2011 by Hans-Peter Deifel
7 (c) 2010-2011 by Thomas Adam
8 (c) 2011 by Albert Kim
9 see LICENSE file
12 #include <X11/Xlib.h>
13 #include "includes.h"
14 #include "vimprobable.h"
15 #include "utilities.h"
16 #include "callbacks.h"
17 #include "javascript.h"
19 /* the CLEAN_MOD_*_MASK defines have all the bits set that will be stripped from the modifier bit field */
20 #define CLEAN_MOD_NUMLOCK_MASK (GDK_MOD2_MASK)
21 #define CLEAN_MOD_BUTTON_MASK (GDK_BUTTON1_MASK|GDK_BUTTON2_MASK|GDK_BUTTON3_MASK|GDK_BUTTON4_MASK|GDK_BUTTON5_MASK)
23 /* remove unused bits, numlock symbol and buttons from keymask */
24 #define CLEAN(mask) (mask & (GDK_MODIFIER_MASK) & ~(CLEAN_MOD_NUMLOCK_MASK) & ~(CLEAN_MOD_BUTTON_MASK))
26 #define IS_ESCAPE(event) (IS_ESCAPE_KEY(CLEAN(event->state), event->keyval))
27 #define IS_ESCAPE_KEY(s, k) ((s == 0 && k == GDK_Escape) || \
28 (s == GDK_CONTROL_MASK && k == GDK_bracketleft))
30 /* callbacks here */
31 static void inputbox_activate_cb(GtkEntry *entry, gpointer user_data);
32 static gboolean inputbox_keypress_cb(GtkEntry *entry, GdkEventKey *event);
33 static gboolean inputbox_keyrelease_cb(GtkEntry *entry, GdkEventKey *event);
34 static gboolean inputbox_changed_cb(GtkEditable *entry, gpointer user_data);
35 static WebKitWebView* inspector_inspect_web_view_cb(gpointer inspector, WebKitWebView* web_view);
36 static gboolean notify_event_cb(GtkWidget *widget, GdkEvent *event, gpointer user_data);
37 static gboolean webview_console_cb(WebKitWebView *webview, char *message, int line, char *source, gpointer user_data);
38 static gboolean webview_download_cb(WebKitWebView *webview, WebKitDownload *download, gpointer user_data);
39 static void webview_hoverlink_cb(WebKitWebView *webview, char *title, char *link, gpointer data);
40 static gboolean webview_keypress_cb(WebKitWebView *webview, GdkEventKey *event);
41 static void webview_load_committed_cb(WebKitWebView *webview, WebKitWebFrame *frame, gpointer user_data);
42 static void webview_load_finished_cb(WebKitWebView *webview, WebKitWebFrame *frame, gpointer user_data);
43 static gboolean webview_mimetype_cb(WebKitWebView *webview, WebKitWebFrame *frame, WebKitNetworkRequest *request,
44 char *mime_type, WebKitWebPolicyDecision *decision, gpointer user_data);
45 static gboolean webview_new_window_cb(WebKitWebView *webview, WebKitWebFrame *frame, WebKitNetworkRequest *request,
46 WebKitWebNavigationAction *action, WebKitWebPolicyDecision *decision, gpointer user_data);
47 static gboolean webview_open_in_new_window_cb(WebKitWebView *webview, WebKitWebFrame *frame, gpointer user_data);
48 static void webview_progress_changed_cb(WebKitWebView *webview, int progress, gpointer user_data);
49 static void webview_title_changed_cb(WebKitWebView *webview, WebKitWebFrame *frame, char *title, gpointer user_data);
50 static void window_destroyed_cb(GtkWidget *window, gpointer func_data);
52 /* functions */
53 static gboolean bookmark(const Arg *arg);
54 static gboolean browser_settings(const Arg *arg);
55 static gboolean commandhistoryfetch(const Arg *arg);
56 static gboolean complete(const Arg *arg);
57 static gboolean descend(const Arg *arg);
58 gboolean echo(const Arg *arg);
59 static gboolean focus_input(const Arg *arg);
60 static gboolean input(const Arg *arg);
61 static gboolean navigate(const Arg *arg);
62 static gboolean number(const Arg *arg);
63 static gboolean open_arg(const Arg *arg);
64 static gboolean open_remembered(const Arg *arg);
65 static gboolean paste(const Arg *arg);
66 static gboolean quickmark(const Arg *arg);
67 static gboolean quit(const Arg *arg);
68 static gboolean revive(const Arg *arg);
69 static gboolean print_frame(const Arg *arg);
70 static gboolean search(const Arg *arg);
71 static gboolean set(const Arg *arg);
72 static gboolean script(const Arg *arg);
73 static gboolean scroll(const Arg *arg);
74 static gboolean search_tag(const Arg *arg);
75 static gboolean yank(const Arg *arg);
76 static gboolean view_source(const Arg * arg);
77 static gboolean zoom(const Arg *arg);
78 static gboolean fake_key_event(const Arg *arg);
80 static void update_url(const char *uri);
81 static void setup_modkeys(void);
82 static void setup_gui(void);
83 static void setup_settings(void);
84 static void setup_signals(void);
85 static void ascii_bar(int total, int state, char *string);
86 static gchar *jsapi_ref_to_string(JSContextRef context, JSValueRef ref);
87 static void jsapi_evaluate_script(const gchar *script, gchar **value, gchar **message);
88 static void download_progress(WebKitDownload *d, GParamSpec *pspec);
89 static void set_widget_font_and_color(GtkWidget *widget, const char *font_str,
90 const char *bg_color_str, const char *fg_color_str);
92 static gboolean history(void);
93 static gboolean process_set_line(char *line);
94 void save_command_history(char *line);
95 void toggle_proxy(gboolean onoff);
96 void toggle_scrollbars(gboolean onoff);
98 gboolean process_keypress(GdkEventKey *event);
99 void fill_suggline(char * suggline, const char * command, const char *fill_with);
100 GtkWidget * fill_eventbox(const char * completion_line);
101 static void mop_up(void);
103 #include "main.h"
105 /* variables */
106 static GtkWindow *window;
107 static GtkWidget *viewport;
108 static GtkBox *box;
109 static GtkScrollbar *scroll_h;
110 static GtkScrollbar *scroll_v;
111 static GtkAdjustment *adjust_h;
112 static GtkAdjustment *adjust_v;
113 static GtkWidget *inputbox;
114 static GtkWidget *eventbox;
115 static GtkBox *statusbar;
116 static GtkWidget *status_url;
117 static GtkWidget *status_state;
118 static WebKitWebView *webview;
119 static SoupSession *session;
120 static GtkClipboard *clipboards[2];
122 static char **args;
123 static unsigned int mode = ModeNormal;
124 static unsigned int count = 0;
125 static float zoomstep;
126 static char *modkeys;
127 static char current_modkey;
128 static char *search_handle;
129 static gboolean search_direction;
130 static gboolean echo_active = TRUE;
131 WebKitWebInspector *inspector;
133 static GdkNativeWindow embed = 0;
134 static char *configfile = NULL;
135 static char *winid = NULL;
137 static char rememberedURI[1024] = "";
138 static char followTarget[8] = "";
139 char *error_msg = NULL;
141 GList *activeDownloads;
143 #include "config.h"
144 #include "keymap.h"
146 char commandhistory[COMMANDHISTSIZE][255];
147 int lastcommand = 0;
148 int maxcommands = 0;
149 int commandpointer = 0;
150 KeyList *keylistroot = NULL;
152 /* Cookie support. */
153 #ifdef ENABLE_COOKIE_SUPPORT
154 static SoupCookieJar *session_cookie_jar = NULL;
155 static SoupCookieJar *file_cookie_jar = NULL;
156 static time_t cookie_timeout = 4800;
157 static char *cookie_store;
158 static void setup_cookies(void);
159 static const char *get_cookies(SoupURI *soup_uri);
160 static void load_all_cookies(void);
161 static void new_generic_request(SoupSession *soup_ses, SoupMessage *soup_msg, gpointer unused);
162 static void update_cookie_jar(SoupCookieJar *jar, SoupCookie *old, SoupCookie *new);
163 static void handle_cookie_request(SoupMessage *soup_msg, gpointer unused);
164 #endif
165 /* callbacks */
166 void
167 window_destroyed_cb(GtkWidget *window, gpointer func_data) {
168 quit(NULL);
171 void
172 webview_title_changed_cb(WebKitWebView *webview, WebKitWebFrame *frame, char *title, gpointer user_data) {
173 gtk_window_set_title(window, title);
176 void
177 webview_progress_changed_cb(WebKitWebView *webview, int progress, gpointer user_data) {
178 #ifdef ENABLE_GTK_PROGRESS_BAR
179 gtk_entry_set_progress_fraction(GTK_ENTRY(inputbox), progress == 100 ? 0 : (double)progress/100);
180 #endif
181 update_state();
184 #ifdef ENABLE_WGET_PROGRESS_BAR
185 void
186 ascii_bar(int total, int state, char *string) {
187 int i;
189 for (i = 0; i < state; i++)
190 string[i] = progressbartickchar;
191 string[i++] = progressbarcurrent;
192 for (; i < total; i++)
193 string[i] = progressbarspacer;
194 string[i] = '\0';
196 #endif
198 void
199 webview_load_committed_cb(WebKitWebView *webview, WebKitWebFrame *frame, gpointer user_data) {
200 Arg a = { .i = Silent, .s = g_strdup(JS_SETUP_HINTS) };
201 const char *uri = webkit_web_view_get_uri(webview);
203 update_url(uri);
204 script(&a);
207 void
208 webview_load_finished_cb(WebKitWebView *webview, WebKitWebFrame *frame, gpointer user_data) {
209 Arg a = { .i = Silent, .s = g_strdup(JS_SETUP_INPUT_FOCUS) };
211 if (HISTORY_MAX_ENTRIES > 0)
212 history();
213 update_state();
214 script(&a);
217 static gboolean
218 webview_open_in_new_window_cb(WebKitWebView *webview, WebKitWebFrame *frame, gpointer user_data) {
219 Arg a = { .i = TargetNew, .s = (char*)webkit_web_view_get_uri(webview) };
220 if (strlen(rememberedURI) > 0) {
221 a.s = rememberedURI;
223 open_arg(&a);
224 return FALSE;
227 gboolean
228 webview_new_window_cb(WebKitWebView *webview, WebKitWebFrame *frame, WebKitNetworkRequest *request,
229 WebKitWebNavigationAction *action, WebKitWebPolicyDecision *decision, gpointer user_data) {
230 Arg a = { .i = TargetNew, .s = (char*)webkit_network_request_get_uri(request) };
231 open_arg(&a);
232 webkit_web_policy_decision_ignore(decision);
233 return TRUE;
236 gboolean
237 webview_mimetype_cb(WebKitWebView *webview, WebKitWebFrame *frame, WebKitNetworkRequest *request,
238 char *mime_type, WebKitWebPolicyDecision *decision, gpointer user_data) {
239 if (webkit_web_view_can_show_mime_type(webview, mime_type) == FALSE) {
240 webkit_web_policy_decision_download(decision);
241 return TRUE;
242 } else {
243 return FALSE;
247 static WebKitWebView*
248 inspector_inspect_web_view_cb(gpointer inspector, WebKitWebView* web_view) {
249 gchar* inspector_title;
250 GtkWidget* inspector_window;
251 GtkWidget* inspector_view;
253 /* just enough code to show the inspector - no signal handling etc. */
254 inspector_title = g_strdup_printf("Inspect page - %s - Vimprobable2", webkit_web_view_get_uri(web_view));
255 if (embed) {
256 inspector_window = gtk_plug_new(embed);
257 } else {
258 inspector_window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
259 gtk_window_set_wmclass(window, "vimprobable2", "Vimprobable2");
261 gtk_window_set_title(GTK_WINDOW(inspector_window), inspector_title);
262 g_free(inspector_title);
263 inspector_view = webkit_web_view_new();
264 gtk_container_add(GTK_CONTAINER(inspector_window), inspector_view);
265 gtk_widget_show_all(inspector_window);
266 return WEBKIT_WEB_VIEW(inspector_view);
269 gboolean
270 webview_download_cb(WebKitWebView *webview, WebKitDownload *download, gpointer user_data) {
271 const gchar *filename;
272 gchar *uri, *path;
273 uint32_t size;
274 Arg a;
276 filename = webkit_download_get_suggested_filename(download);
277 if (filename == NULL || strlen(filename) == 0) {
278 filename = "vimprobable_download";
280 path = g_build_filename(g_strdup_printf(DOWNLOADS_PATH), filename, NULL);
281 uri = g_strconcat("file://", path, NULL);
282 webkit_download_set_destination_uri(download, uri);
283 g_free(uri);
284 size = (uint32_t)webkit_download_get_total_size(download);
285 a.i = Info;
286 if (size > 0)
287 a.s = g_strdup_printf("Download %s started (expected size: %u bytes)...", filename, size);
288 else
289 a.s = g_strdup_printf("Download %s started (unknown size)...", filename);
290 echo(&a);
291 g_free(a.s);
292 activeDownloads = g_list_prepend(activeDownloads, download);
293 g_signal_connect(download, "notify::progress", G_CALLBACK(download_progress), NULL);
294 g_signal_connect(download, "notify::status", G_CALLBACK(download_progress), NULL);
295 update_state();
296 return TRUE;
299 void
300 download_progress(WebKitDownload *d, GParamSpec *pspec) {
301 Arg a;
302 WebKitDownloadStatus status = webkit_download_get_status(d);
304 if (status != WEBKIT_DOWNLOAD_STATUS_STARTED && status != WEBKIT_DOWNLOAD_STATUS_CREATED) {
305 if (status != WEBKIT_DOWNLOAD_STATUS_FINISHED) {
306 a.i = Error;
307 a.s = g_strdup_printf("Error while downloading %s", webkit_download_get_suggested_filename(d));
308 echo(&a);
309 } else {
310 a.i = Info;
311 a.s = g_strdup_printf("Download %s finished", webkit_download_get_suggested_filename(d));
312 echo(&a);
314 g_free(a.s);
315 activeDownloads = g_list_remove(activeDownloads, d);
317 update_state();
321 gboolean
322 process_keypress(GdkEventKey *event) {
323 KeyList *current;
325 current = keylistroot;
326 while (current != NULL) {
327 if (current->Element.mask == CLEAN(event->state)
328 && (current->Element.modkey == current_modkey
329 || (!current->Element.modkey && !current_modkey)
330 || current->Element.modkey == GDK_VoidSymbol ) /* wildcard */
331 && current->Element.key == event->keyval
332 && current->Element.func)
333 if (current->Element.func(&current->Element.arg)) {
334 current_modkey = count = 0;
335 update_state();
336 return TRUE;
338 current = current->next;
340 return FALSE;
343 gboolean
344 webview_keypress_cb(WebKitWebView *webview, GdkEventKey *event) {
345 Arg a = { .i = ModeNormal, .s = NULL };
347 switch (mode) {
348 case ModeNormal:
349 if (CLEAN(event->state) == 0) {
350 if (IS_ESCAPE(event)) {
351 a.i = Info;
352 a.s = g_strdup("");
353 echo(&a);
354 g_free(a.s);
355 } else if (current_modkey == 0 && ((event->keyval >= GDK_1 && event->keyval <= GDK_9)
356 || (event->keyval == GDK_0 && count))) {
357 count = (count ? count * 10 : 0) + (event->keyval - GDK_0);
358 update_state();
359 return TRUE;
360 } else if (strchr(modkeys, event->keyval) && current_modkey != event->keyval) {
361 current_modkey = event->keyval;
362 update_state();
363 return TRUE;
366 /* keybindings */
367 if (process_keypress(event) == TRUE) return TRUE;
369 break;
370 case ModeInsert:
371 if (IS_ESCAPE(event)) {
372 a.i = Silent;
373 a.s = g_strdup("hints.clearFocus();");
374 script(&a);
375 a.i = ModeNormal;
376 return set(&a);
378 case ModePassThrough:
379 if (IS_ESCAPE(event)) {
380 echo(&a);
381 set(&a);
382 return TRUE;
384 break;
385 case ModeSendKey:
386 echo(&a);
387 set(&a);
388 break;
390 return FALSE;
393 void
394 set_widget_font_and_color(GtkWidget *widget, const char *font_str, const char *bg_color_str,
395 const char *fg_color_str) {
396 GdkColor fg_color;
397 GdkColor bg_color;
398 PangoFontDescription *font;
400 font = pango_font_description_from_string(font_str);
401 gtk_widget_modify_font(widget, font);
402 pango_font_description_free(font);
404 if (fg_color_str)
405 gdk_color_parse(fg_color_str, &fg_color);
406 if (bg_color_str)
407 gdk_color_parse(bg_color_str, &bg_color);
409 gtk_widget_modify_text(widget, GTK_STATE_NORMAL, fg_color_str ? &fg_color : NULL);
410 gtk_widget_modify_base(widget, GTK_STATE_NORMAL, bg_color_str ? &bg_color : NULL);
412 return;
415 void
416 webview_hoverlink_cb(WebKitWebView *webview, char *title, char *link, gpointer data) {
417 const char *uri = webkit_web_view_get_uri(webview);
419 memset(rememberedURI, 0, 1024);
420 if (link) {
421 gtk_label_set_markup(GTK_LABEL(status_url), g_markup_printf_escaped("<span font=\"%s\">Link: %s</span>", statusfont, link));
422 strncpy(rememberedURI, link, 1024);
423 } else
424 update_url(uri);
427 gboolean
428 webview_console_cb(WebKitWebView *webview, char *message, int line, char *source, gpointer user_data) {
429 Arg a;
431 /* Don't change internal mode if the browser doesn't have focus to prevent inconsistent states */
432 if (gtk_window_has_toplevel_focus(window)) {
433 if (!strcmp(message, "hintmode_off") || !strcmp(message, "insertmode_off")) {
434 a.i = ModeNormal;
435 return set(&a);
436 } else if (!strcmp(message, "insertmode_on")) {
437 a.i = ModeInsert;
438 return set(&a);
441 return FALSE;
444 void
445 inputbox_activate_cb(GtkEntry *entry, gpointer user_data) {
446 char *text;
447 guint16 length = gtk_entry_get_text_length(entry);
448 Arg a;
449 gboolean success = FALSE, forward = FALSE;
451 a.i = HideCompletion;
452 complete(&a);
453 if (length == 0)
454 return;
455 text = (char*)gtk_entry_get_text(entry);
456 if (length > 1 && text[0] == ':') {
457 success = process_line((text + 1));
458 } else if (length > 1 && ((forward = text[0] == '/') || text[0] == '?')) {
459 webkit_web_view_unmark_text_matches(webview);
460 #ifdef ENABLE_MATCH_HIGHLITING
461 webkit_web_view_mark_text_matches(webview, &text[1], FALSE, 0);
462 webkit_web_view_set_highlight_text_matches(webview, TRUE);
463 #endif
464 count = 0;
465 #ifndef ENABLE_INCREMENTAL_SEARCH
466 a.s =& text[1];
467 a.i = searchoptions | (forward ? DirectionForward : DirectionBackwards);
468 search(&a);
469 #else
470 search_direction = forward;
471 search_handle = g_strdup(&text[1]);
472 #endif
473 } else if (text[0] == '.' || text[0] == ',') {
474 a.i = Silent;
475 a.s = g_strdup_printf("hints.fire();");
476 script(&a);
477 update_state();
478 } else
479 return;
480 if (!echo_active)
481 gtk_entry_set_text(entry, "");
482 gtk_widget_grab_focus(GTK_WIDGET(webview));
485 gboolean
486 inputbox_keypress_cb(GtkEntry *entry, GdkEventKey *event) {
487 Arg a;
488 int numval;
490 if (mode == ModeHints) {
491 if (event->keyval == GDK_Tab) {
492 a.i = Silent;
493 a.s = g_strdup_printf("hints.focusNextHint();");
494 script(&a);
495 update_state();
496 return TRUE;
498 if (event->keyval == GDK_ISO_Left_Tab) {
499 a.i = Silent;
500 a.s = g_strdup_printf("hints.focusPreviousHint();");
501 script(&a);
502 update_state();
503 return TRUE;
505 if (event->keyval == GDK_Return) {
506 a.i = Silent;
507 a.s = g_strdup_printf("hints.fire();");
508 script(&a);
509 update_state();
510 return TRUE;
513 switch (event->keyval) {
514 case GDK_bracketleft:
515 case GDK_Escape:
516 if (!IS_ESCAPE(event)) break;
517 a.i = HideCompletion;
518 complete(&a);
519 a.i = ModeNormal;
520 return set(&a);
521 break;
522 case GDK_Tab:
523 a.i = DirectionNext;
524 return complete(&a);
525 break;
526 case GDK_Up:
527 a.i = DirectionPrev;
528 return commandhistoryfetch(&a);
529 break;
530 case GDK_Down:
531 a.i = DirectionNext;
532 return commandhistoryfetch(&a);
533 break;
534 case GDK_ISO_Left_Tab:
535 a.i = DirectionPrev;
536 return complete(&a);
537 break;
540 if (mode == ModeHints) {
541 if ((CLEAN(event->state) & GDK_SHIFT_MASK) &&
542 (CLEAN(event->state) & GDK_CONTROL_MASK) &&
543 (event->keyval == GDK_BackSpace)) {
544 count /= 10;
545 a.i = Silent;
546 a.s = g_strdup_printf("hints.updateHints(%d);", count);
547 script(&a);
548 update_state();
549 return TRUE;
552 numval = g_unichar_digit_value((gunichar) gdk_keyval_to_unicode(event->keyval));
553 if ((numval >= 1 && numval <= 9) || (numval == 0 && count)) {
554 /* allow a zero as non-first number */
555 count = (count ? count * 10 : 0) + numval;
556 a.i = Silent;
557 a.s = g_strdup_printf("hints.updateHints(%d);", count);
558 script(&a);
559 update_state();
560 return TRUE;
564 return FALSE;
567 gboolean
568 notify_event_cb(GtkWidget *widget, GdkEvent *event, gpointer user_data) {
569 int i;
570 if (mode == ModeNormal && event->type == GDK_BUTTON_RELEASE) {
571 /* handle mouse click events */
572 for (i = 0; i < LENGTH(mouse); i++) {
573 if (mouse[i].mask == CLEAN(event->button.state)
574 && (mouse[i].modkey == current_modkey
575 || (!mouse[i].modkey && !current_modkey)
576 || mouse[i].modkey == GDK_VoidSymbol) /* wildcard */
577 && mouse[i].button == event->button.button
578 && mouse[i].func) {
579 if (mouse[i].func(&mouse[i].arg)) {
580 current_modkey = count = 0;
581 update_state();
582 return TRUE;
587 return FALSE;
590 static gboolean inputbox_keyrelease_cb(GtkEntry *entry, GdkEventKey *event) {
591 Arg a;
592 guint16 length = gtk_entry_get_text_length(entry);
594 if (!length) {
595 a.i = HideCompletion;
596 complete(&a);
597 a.i = ModeNormal;
598 return set(&a);
600 return FALSE;
603 static gboolean inputbox_changed_cb(GtkEditable *entry, gpointer user_data) {
604 Arg a;
605 char *text = (char*)gtk_entry_get_text(GTK_ENTRY(entry));
606 guint16 length = gtk_entry_get_text_length(GTK_ENTRY(entry));
607 gboolean forward = FALSE;
609 /* Update incremental search if the user changes the search text.
611 * Note: gtk_widget_is_focus() is a poor way to check if the change comes
612 * from the user. But if the entry is focused and the text is set
613 * through gtk_entry_set_text() in some asyncrounous operation,
614 * I would consider that a bug.
617 if (gtk_widget_is_focus(GTK_WIDGET(entry)) && length > 1 && ((forward = text[0] == '/') || text[0] == '?')) {
618 webkit_web_view_unmark_text_matches(webview);
619 webkit_web_view_search_text(webview, &text[1], searchoptions & CaseSensitive, forward, searchoptions & Wrapping);
620 return TRUE;
621 } else if (gtk_widget_is_focus(GTK_WIDGET(entry)) && length >= 1 &&
622 (text[0] == '.' || text[0] == ',')) {
623 a.i = Silent;
624 a.s = g_strdup("hints.clearHints();");
625 script(&a);
627 a.i = Silent;
628 switch (text[0]) {
629 case '.':
630 a.s = g_strconcat("hints.createHints('", text + 1, "', 'f');", NULL);
631 count = 0;
632 break;
634 case ',':
635 a.s = g_strconcat("hints.createHints('", text + 1, "', 'F');", NULL);
636 count = 0;
637 break;
639 script(&a);
641 return TRUE;
642 } else if (length == 0 && followTarget[0]) {
643 mode = ModeNormal;
644 a.i = Silent;
645 a.s = g_strdup("hints.clearHints();");
646 script(&a);
647 count = 0;
648 update_state();
651 return FALSE;
654 /* funcs here */
656 void fill_suggline(char * suggline, const char * command, const char *fill_with) {
657 memset(suggline, 0, 512);
658 strncpy(suggline, command, 512);
659 strncat(suggline, " ", 1);
660 strncat(suggline, fill_with, 512 - strlen(suggline) - 1);
663 GtkWidget * fill_eventbox(const char * completion_line) {
664 GtkBox * row;
665 GtkWidget *row_eventbox, *el;
666 GdkColor color;
667 char * markup;
669 row = GTK_BOX(gtk_hbox_new(FALSE, 0));
670 row_eventbox = gtk_event_box_new();
671 gdk_color_parse(completionbgcolor[0], &color);
672 gtk_widget_modify_bg(row_eventbox, GTK_STATE_NORMAL, &color);
673 el = gtk_label_new(NULL);
674 markup = g_strconcat("<span font=\"", completionfont[0], "\" color=\"", completioncolor[0], "\">",
675 g_markup_escape_text(completion_line, strlen(completion_line)), "</span>", NULL);
676 gtk_label_set_markup(GTK_LABEL(el), markup);
677 g_free(markup);
678 gtk_misc_set_alignment(GTK_MISC(el), 0, 0);
679 gtk_box_pack_start(row, el, TRUE, TRUE, 2);
680 gtk_container_add(GTK_CONTAINER(row_eventbox), GTK_WIDGET(row));
681 return row_eventbox;
684 gboolean
685 complete(const Arg *arg) {
686 char *str, *p, *s, *markup, *entry, *searchfor, command[32] = "", suggline[512] = "", **suggurls;
687 size_t listlen, len, cmdlen;
688 int i, spacepos;
689 Listelement *elementlist = NULL, *elementpointer;
690 gboolean highlight = FALSE;
691 GtkBox *row;
692 GtkWidget *row_eventbox, *el;
693 GtkBox *_table;
694 GdkColor color;
695 static GtkWidget *table, *top_border;
696 static char *prefix;
697 static char **suggestions;
698 static GtkWidget **widgets;
699 static int n = 0, m, current = -1;
701 str = (char*)gtk_entry_get_text(GTK_ENTRY(inputbox));
702 len = strlen(str);
704 /* Get the length of the list of commands for completion. We need this to
705 * malloc/realloc correctly.
707 listlen = LENGTH(commands);
709 if ((len == 0 || str[0] != ':') && arg->i != HideCompletion)
710 return TRUE;
711 if (prefix) {
712 if (arg->i != HideCompletion && widgets && current != -1 && !strcmp(&str[1], suggestions[current])) {
713 gdk_color_parse(completionbgcolor[0], &color);
714 gtk_widget_modify_bg(widgets[current], GTK_STATE_NORMAL, &color);
715 current = (n + current + (arg->i == DirectionPrev ? -1 : 1)) % n;
716 if ((arg->i == DirectionNext && current == 0)
717 || (arg->i == DirectionPrev && current == n - 1))
718 current = -1;
719 } else {
720 free(widgets);
721 free(suggestions);
722 free(prefix);
723 gtk_widget_destroy(GTK_WIDGET(table));
724 gtk_widget_destroy(GTK_WIDGET(top_border));
725 table = NULL;
726 widgets = NULL;
727 suggestions = NULL;
728 prefix = NULL;
729 n = 0;
730 current = -1;
731 if (arg->i == HideCompletion)
732 return TRUE;
734 } else if (arg->i == HideCompletion)
735 return TRUE;
736 if (!widgets) {
737 prefix = g_strdup_printf(str);
738 widgets = malloc(sizeof(GtkWidget*) * listlen);
739 suggestions = malloc(sizeof(char*) * listlen);
740 top_border = gtk_event_box_new();
741 gtk_widget_set_size_request(GTK_WIDGET(top_border), 0, 1);
742 gdk_color_parse(completioncolor[2], &color);
743 gtk_widget_modify_bg(top_border, GTK_STATE_NORMAL, &color);
744 table = gtk_event_box_new();
745 gdk_color_parse(completionbgcolor[0], &color);
746 _table = GTK_BOX(gtk_vbox_new(FALSE, 0));
747 highlight = len > 1;
748 if (strchr(str, ' ') == NULL) {
749 /* command completion */
750 listlen = LENGTH(commands);
751 for (i = 0; i < listlen; i++) {
752 if (commands[i].cmd == NULL)
753 break;
754 cmdlen = strlen(commands[i].cmd);
755 if (!highlight || (n < MAX_LIST_SIZE && len - 1 <= cmdlen && !strncmp(&str[1], commands[i].cmd, len - 1))) {
756 p = s = malloc(sizeof(char*) * (highlight ? sizeof(COMPLETION_TAG_OPEN) + sizeof(COMPLETION_TAG_CLOSE) - 1 : 1) + cmdlen);
757 if (highlight) {
758 memcpy(p, COMPLETION_TAG_OPEN, sizeof(COMPLETION_TAG_OPEN) - 1);
759 memcpy((p += sizeof(COMPLETION_TAG_OPEN) - 1), &str[1], len - 1);
760 memcpy((p += len - 1), COMPLETION_TAG_CLOSE, sizeof(COMPLETION_TAG_CLOSE) - 1);
761 p += sizeof(COMPLETION_TAG_CLOSE) - 1;
763 memcpy(p, &commands[i].cmd[len - 1], cmdlen - len + 2);
764 row = GTK_BOX(gtk_hbox_new(FALSE, 0));
765 row_eventbox = gtk_event_box_new();
766 gtk_widget_modify_bg(row_eventbox, GTK_STATE_NORMAL, &color);
767 el = gtk_label_new(NULL);
768 markup = g_strconcat("<span font=\"", completionfont[0], "\" color=\"", completioncolor[0], "\">", s, "</span>", NULL);
769 free(s);
770 gtk_label_set_markup(GTK_LABEL(el), markup);
771 g_free(markup);
772 gtk_misc_set_alignment(GTK_MISC(el), 0, 0);
773 gtk_box_pack_start(row, el, TRUE, TRUE, 2);
774 gtk_container_add(GTK_CONTAINER(row_eventbox), GTK_WIDGET(row));
775 gtk_box_pack_start(_table, GTK_WIDGET(row_eventbox), FALSE, FALSE, 0);
776 suggestions[n] = commands[i].cmd;
777 widgets[n++] = row_eventbox;
780 } else {
781 entry = (char *)malloc(512 * sizeof(char));
782 if (entry == NULL) {
783 return FALSE;
785 memset(entry, 0, 512);
786 suggurls = malloc(sizeof(char*) * listlen);
787 if (suggurls == NULL) {
788 return FALSE;
790 spacepos = strcspn(str, " ");
791 searchfor = (str + spacepos + 1);
792 strncpy(command, (str + 1), spacepos - 1);
793 if (strlen(command) == 3 && strncmp(command, "set", 3) == 0) {
794 /* browser settings */
795 listlen = LENGTH(browsersettings);
796 for (i = 0; i < listlen; i++) {
797 if (n < MAX_LIST_SIZE && strstr(browsersettings[i].name, searchfor) != NULL) {
798 /* match */
799 fill_suggline(suggline, command, browsersettings[i].name);
800 suggurls[n] = (char *)malloc(sizeof(char) * 512 + 1);
801 strncpy(suggurls[n], suggline, 512);
802 suggestions[n] = suggurls[n];
803 row_eventbox = fill_eventbox(suggline);
804 gtk_box_pack_start(_table, GTK_WIDGET(row_eventbox), FALSE, FALSE, 0);
805 widgets[n++] = row_eventbox;
809 } else if (strlen(command) == 2 && strncmp(command, "qt", 2) == 0) {
810 /* completion on tags */
811 spacepos = strcspn(str, " ");
812 searchfor = (str + spacepos + 1);
813 elementlist = complete_list(searchfor, 1, elementlist);
814 } else {
815 /* URL completion: bookmarks */
816 elementlist = complete_list(searchfor, 0, elementlist);
817 m = count_list(elementlist);
818 if (m < MAX_LIST_SIZE) {
819 /* URL completion: history */
820 elementlist = complete_list(searchfor, 2, elementlist);
823 elementpointer = elementlist;
824 while (elementpointer != NULL) {
825 fill_suggline(suggline, command, elementpointer->element);
826 suggurls[n] = (char *)malloc(sizeof(char) * 512 + 1);
827 strncpy(suggurls[n], suggline, 512);
828 suggestions[n] = suggurls[n];
829 row_eventbox = fill_eventbox(suggline);
830 gtk_box_pack_start(_table, GTK_WIDGET(row_eventbox), FALSE, FALSE, 0);
831 widgets[n++] = row_eventbox;
832 elementpointer = elementpointer->next;
833 if (n >= MAX_LIST_SIZE)
834 break;
836 free_list(elementlist);
837 if (suggurls != NULL) {
838 free(suggurls);
839 suggurls = NULL;
841 if (entry != NULL) {
842 free(entry);
843 entry = NULL;
846 /* TA: FIXME - this needs rethinking entirely. */
848 GtkWidget **widgets_temp = realloc(widgets, sizeof(*widgets) * n);
849 if (widgets_temp == NULL && widgets == NULL) {
850 fprintf(stderr, "Couldn't realloc() widgets\n");
851 exit(1);
853 widgets = widgets_temp;
854 char **suggestions_temp = realloc(suggestions, sizeof(*suggestions) * n);
855 if (suggestions_temp == NULL && suggestions == NULL) {
856 fprintf(stderr, "Couldn't realloc() suggestions\n");
857 exit(1);
859 suggestions = suggestions_temp;
861 if (!n) {
862 gdk_color_parse(completionbgcolor[1], &color);
863 gtk_widget_modify_bg(table, GTK_STATE_NORMAL, &color);
864 el = gtk_label_new(NULL);
865 gtk_misc_set_alignment(GTK_MISC(el), 0, 0);
866 markup = g_strconcat("<span font=\"", completionfont[1], "\" color=\"", completioncolor[1], "\">No Completions</span>", NULL);
867 gtk_label_set_markup(GTK_LABEL(el), markup);
868 g_free(markup);
869 gtk_box_pack_start(_table, GTK_WIDGET(el), FALSE, FALSE, 0);
871 gtk_box_pack_start(box, GTK_WIDGET(top_border), FALSE, FALSE, 0);
872 gtk_container_add(GTK_CONTAINER(table), GTK_WIDGET(_table));
873 gtk_box_pack_start(box, GTK_WIDGET(table), FALSE, FALSE, 0);
874 gtk_widget_show_all(GTK_WIDGET(window));
875 if (!n)
876 return TRUE;
877 current = arg->i == DirectionPrev ? n - 1 : 0;
879 if (current != -1) {
880 gdk_color_parse(completionbgcolor[2], &color);
881 gtk_widget_modify_bg(GTK_WIDGET(widgets[current]), GTK_STATE_NORMAL, &color);
882 s = g_strconcat(":", suggestions[current], NULL);
883 gtk_entry_set_text(GTK_ENTRY(inputbox), s);
884 g_free(s);
885 } else
886 gtk_entry_set_text(GTK_ENTRY(inputbox), prefix);
887 gtk_editable_set_position(GTK_EDITABLE(inputbox), -1);
888 return TRUE;
891 gboolean
892 descend(const Arg *arg) {
893 char *source = (char*)webkit_web_view_get_uri(webview), *p = &source[0], *new;
894 int i, len;
895 count = count ? count : 1;
897 if (!source)
898 return TRUE;
899 if (arg->i == Rootdir) {
900 for (i = 0; i < 3; i++) /* get to the third slash */
901 if (!(p = strchr(++p, '/')))
902 return TRUE; /* if we cannot find it quit */
903 } else {
904 len = strlen(source);
905 if (!len) /* if string is empty quit */
906 return TRUE;
907 p = source + len; /* start at the end */
908 if (*(p - 1) == '/') /* /\/$/ is not an additional level */
909 ++count;
910 for (i = 0; i < count; i++)
911 while(*(p--) != '/' || *p == '/') /* count /\/+/ as one slash */
912 if (p == source) /* if we reach the first char pointer quit */
913 return TRUE;
914 ++p; /* since we do p-- in the while, we are pointing at
915 the char before the slash, so +1 */
917 len = p - source + 1; /* new length = end - start + 1 */
918 new = malloc(len + 1);
919 memcpy(new, source, len);
920 new[len] = '\0';
921 webkit_web_view_load_uri(webview, new);
922 free(new);
923 return TRUE;
926 gboolean
927 echo(const Arg *arg) {
928 int index = !arg->s ? 0 : arg->i & (~NoAutoHide);
930 if (index < Info || index > Error)
931 return TRUE;
933 set_widget_font_and_color(inputbox, urlboxfont[index], urlboxbgcolor[index], urlboxcolor[index]);
934 gtk_entry_set_text(GTK_ENTRY(inputbox), !arg->s ? "" : arg->s);
936 return TRUE;
939 gboolean
940 input(const Arg *arg) {
941 int pos = 0;
942 count = 0;
943 const char *url;
944 int index = Info;
945 Arg a;
947 /* if inputbox hidden, show it again */
948 if (!gtk_widget_get_visible(inputbox))
949 gtk_widget_set_visible(inputbox, TRUE);
951 update_state();
953 /* Set the colour and font back to the default, so that we don't still
954 * maintain a red colour from a warning from an end of search indicator,
955 * etc.
957 set_widget_font_and_color(inputbox, urlboxfont[index], urlboxbgcolor[index], urlboxcolor[index]);
959 if (arg->s[0] == '.' || arg->s[0] == ',') {
960 mode = ModeHints;
961 memset(followTarget, 0, 8);
962 strncpy(followTarget, "current", 8);
963 a.i = Silent;
964 switch (arg->s[0]) {
965 case '.':
966 a.s = g_strdup("hints.createHints('', 'f');");
967 count = 0;
968 break;
970 case ',':
971 a.s = g_strdup("hints.createHints('', 'F');");
972 count = 0;
973 break;
975 script(&a);
978 /* to avoid things like :open URL :open URL2 or :open :open URL */
979 gtk_entry_set_text(GTK_ENTRY(inputbox), "");
980 gtk_editable_insert_text(GTK_EDITABLE(inputbox), arg->s, -1, &pos);
981 if (arg->i & InsertCurrentURL && (url = webkit_web_view_get_uri(webview)))
982 gtk_editable_insert_text(GTK_EDITABLE(inputbox), url, -1, &pos);
983 gtk_widget_grab_focus(inputbox);
984 gtk_editable_set_position(GTK_EDITABLE(inputbox), -1);
986 return TRUE;
989 gboolean
990 navigate(const Arg *arg) {
991 if (arg->i & NavigationForwardBack)
992 webkit_web_view_go_back_or_forward(webview, (arg->i == NavigationBack ? -1 : 1) * (count ? count : 1));
993 else if (arg->i & NavigationReloadActions)
994 (arg->i == NavigationReload ? webkit_web_view_reload : webkit_web_view_reload_bypass_cache)(webview);
995 else
996 webkit_web_view_stop_loading(webview);
997 return TRUE;
1000 gboolean
1001 number(const Arg *arg) {
1002 const char *source = webkit_web_view_get_uri(webview);
1003 char *uri, *p, *new;
1004 int number, diff = (count ? count : 1) * (arg->i == Increment ? 1 : -1);
1006 if (!source)
1007 return TRUE;
1008 uri = g_strdup_printf(source); /* copy string */
1009 p =& uri[0];
1010 while(*p != '\0') /* goto the end of the string */
1011 ++p;
1012 --p;
1013 while(*p >= '0' && *p <= '9') /* go back until non number char is reached */
1014 --p;
1015 if (*(++p) == '\0') { /* if no numbers were found abort */
1016 free(uri);
1017 return TRUE;
1019 number = atoi(p) + diff; /* apply diff on number */
1020 *p = '\0';
1021 new = g_strdup_printf("%s%d", uri, number); /* create new uri */
1022 webkit_web_view_load_uri(webview, new);
1023 g_free(new);
1024 free(uri);
1025 return TRUE;
1028 gboolean
1029 open_arg(const Arg *arg) {
1030 char *argv[6];
1031 char *s = arg->s, *p = NULL, *new;
1032 Arg a = { .i = NavigationReload };
1033 int len;
1034 char *search_uri, *search_term;
1036 if (embed) {
1037 argv[0] = *args;
1038 argv[1] = "-e";
1039 argv[2] = winid;
1040 argv[3] = arg->s;
1041 argv[4] = NULL;
1042 } else {
1043 argv[0] = *args;
1044 argv[1] = arg->s;
1045 argv[2] = NULL;
1048 if (!arg->s)
1049 navigate(&a);
1050 else if (arg->i == TargetCurrent) {
1051 while(*s == ' ') /* strip leading whitespace */
1052 ++s;
1053 p = (s + strlen(s) - 1);
1054 while(*p == ' ') /* strip trailing whitespace */
1055 --p;
1056 *(p + 1) = '\0';
1057 len = strlen(s);
1058 new = NULL, p = strchr(s, ' ');
1059 if (p) { /* check for search engines */
1060 *p = '\0';
1061 search_uri = find_uri_for_searchengine(s);
1062 if (search_uri != NULL) {
1063 search_term = soup_uri_encode(p+1, "&");
1064 new = g_strdup_printf(search_uri, search_term);
1065 g_free(search_term);
1067 *p = ' ';
1069 if (!new) {
1070 if (len > 3 && strstr(s, "://")) { /* valid url? */
1071 p = new = g_malloc(len + 1);
1072 while(*s != '\0') { /* strip whitespaces */
1073 if (*s != ' ')
1074 *(p++) = *s;
1075 ++s;
1077 *p = '\0';
1078 } else if (strcspn(s, "/") == 0 || strcspn(s, "./") == 0) { /* prepend "file://" */
1079 new = g_malloc(sizeof("file://") + len);
1080 strcpy(new, "file://");
1081 memcpy(&new[sizeof("file://") - 1], s, len + 1);
1082 } else if (p || !strchr(s, '.')) { /* whitespaces or no dot? */
1083 search_uri = find_uri_for_searchengine(defaultsearch);
1084 if (search_uri != NULL) {
1085 search_term = soup_uri_encode(s, "&");
1086 new = g_strdup_printf(search_uri, search_term);
1087 g_free(search_term);
1089 } else { /* prepend "http://" */
1090 new = g_malloc(sizeof("http://") + len);
1091 strcpy(new, "http://");
1092 memcpy(&new[sizeof("http://") - 1], s, len + 1);
1095 webkit_web_view_load_uri(webview, new);
1096 g_free(new);
1097 } else
1098 g_spawn_async(NULL, argv, NULL, G_SPAWN_SEARCH_PATH, NULL, NULL, NULL, NULL);
1099 return TRUE;
1102 gboolean
1103 open_remembered(const Arg *arg)
1105 Arg a = {arg->i, rememberedURI};
1107 if (strcmp(rememberedURI, "")) {
1108 open_arg(&a);
1110 return TRUE;
1113 gboolean
1114 yank(const Arg *arg) {
1115 const char *url, *feedback;
1117 if (arg->i & SourceURL) {
1118 url = webkit_web_view_get_uri(webview);
1119 if (!url)
1120 return TRUE;
1121 feedback = g_strconcat("Yanked ", url, NULL);
1122 give_feedback(feedback);
1123 if (arg->i & ClipboardPrimary)
1124 gtk_clipboard_set_text(clipboards[0], url, -1);
1125 if (arg->i & ClipboardGTK)
1126 gtk_clipboard_set_text(clipboards[1], url, -1);
1127 } else
1128 webkit_web_view_copy_clipboard(webview);
1129 return TRUE;
1132 gboolean
1133 paste(const Arg *arg) {
1134 Arg a = { .i = arg->i & TargetNew, .s = NULL };
1136 /* If we're over a link, open it in a new target. */
1137 if (strlen(rememberedURI) > 0) {
1138 Arg new_target = { .i = TargetNew, .s = arg->s };
1139 open_arg(&new_target);
1140 return TRUE;
1143 if (arg->i & ClipboardPrimary)
1144 a.s = gtk_clipboard_wait_for_text(clipboards[0]);
1145 if (!a.s && arg->i & ClipboardGTK)
1146 a.s = gtk_clipboard_wait_for_text(clipboards[1]);
1147 if (a.s)
1148 open_arg(&a);
1149 return TRUE;
1152 gboolean
1153 quit(const Arg *arg) {
1154 FILE *f;
1155 const char *filename;
1156 const char *uri = webkit_web_view_get_uri(webview);
1157 if (uri != NULL) {
1158 /* write last URL into status file for recreation with "u" */
1159 filename = g_strdup_printf(CLOSED_URL_FILENAME);
1160 f = fopen(filename, "w");
1161 if (f != NULL) {
1162 fprintf(f, "%s", uri);
1163 fclose(f);
1166 gtk_main_quit();
1167 return TRUE;
1170 gboolean
1171 revive(const Arg *arg) {
1172 FILE *f;
1173 const char *filename;
1174 char buffer[512] = "";
1175 Arg a = { .i = TargetNew, .s = NULL };
1176 /* get the URL of the window which has been closed last */
1177 filename = g_strdup_printf(CLOSED_URL_FILENAME);
1178 f = fopen(filename, "r");
1179 if (f != NULL) {
1180 fgets(buffer, 512, f);
1181 fclose(f);
1183 if (strlen(buffer) > 0) {
1184 a.s = buffer;
1185 open_arg(&a);
1186 return TRUE;
1188 return FALSE;
1191 static
1192 gboolean print_frame(const Arg *arg)
1194 WebKitWebFrame *frame = webkit_web_view_get_main_frame(webview);
1195 webkit_web_frame_print (frame);
1196 return TRUE;
1199 gboolean
1200 search(const Arg *arg) {
1201 count = count ? count : 1;
1202 gboolean success, direction = arg->i & DirectionPrev;
1203 Arg a;
1205 if (arg->s) {
1206 free(search_handle);
1207 search_handle = g_strdup_printf(arg->s);
1209 if (!search_handle)
1210 return TRUE;
1211 if (arg->i & DirectionAbsolute)
1212 search_direction = direction;
1213 else
1214 direction ^= search_direction;
1215 do {
1216 success = webkit_web_view_search_text(webview, search_handle, arg->i & CaseSensitive, direction, FALSE);
1217 if (!success) {
1218 if (arg->i & Wrapping) {
1219 success = webkit_web_view_search_text(webview, search_handle, arg->i & CaseSensitive, direction, TRUE);
1220 if (success) {
1221 a.i = Warning;
1222 a.s = g_strdup_printf("search hit %s, continuing at %s",
1223 direction ? "BOTTOM" : "TOP",
1224 direction ? "TOP" : "BOTTOM");
1225 echo(&a);
1226 g_free(a.s);
1227 } else
1228 break;
1229 } else
1230 break;
1232 } while(--count);
1233 if (!success) {
1234 a.i = Error;
1235 a.s = g_strdup_printf("Pattern not found: %s", search_handle);
1236 echo(&a);
1237 g_free(a.s);
1239 return TRUE;
1242 gboolean
1243 set(const Arg *arg) {
1244 Arg a = { .i = Info | NoAutoHide };
1246 switch (arg->i) {
1247 case ModeNormal:
1248 if (search_handle) {
1249 search_handle = NULL;
1250 webkit_web_view_unmark_text_matches(webview);
1252 gtk_entry_set_text(GTK_ENTRY(inputbox), "");
1253 gtk_widget_grab_focus(GTK_WIDGET(webview));
1254 break;
1255 case ModePassThrough:
1256 a.s = g_strdup("-- PASS THROUGH --");
1257 echo(&a);
1258 g_free(a.s);
1259 break;
1260 case ModeSendKey:
1261 a.s = g_strdup("-- PASS TROUGH (next) --");
1262 echo(&a);
1263 g_free(a.s);
1264 break;
1265 case ModeInsert: /* should not be called manually but automatically */
1266 a.s = g_strdup("-- INSERT --");
1267 echo(&a);
1268 g_free(a.s);
1269 break;
1270 default:
1271 return TRUE;
1273 mode = arg->i;
1274 return TRUE;
1277 gchar*
1278 jsapi_ref_to_string(JSContextRef context, JSValueRef ref) {
1279 JSStringRef string_ref;
1280 gchar *string;
1281 size_t length;
1283 string_ref = JSValueToStringCopy(context, ref, NULL);
1284 length = JSStringGetMaximumUTF8CStringSize(string_ref);
1285 string = g_new(gchar, length);
1286 JSStringGetUTF8CString(string_ref, string, length);
1287 JSStringRelease(string_ref);
1288 return string;
1291 void
1292 jsapi_evaluate_script(const gchar *script, gchar **value, gchar **message) {
1293 WebKitWebFrame *frame = webkit_web_view_get_main_frame(webview);
1294 JSGlobalContextRef context = webkit_web_frame_get_global_context(frame);
1295 JSStringRef str;
1296 JSValueRef val, exception;
1298 str = JSStringCreateWithUTF8CString(script);
1299 val = JSEvaluateScript(context, str, JSContextGetGlobalObject(context), NULL, 0, &exception);
1300 JSStringRelease(str);
1301 if (!val)
1302 *message = jsapi_ref_to_string(context, exception);
1303 else
1304 *value = jsapi_ref_to_string(context, val);
1307 gboolean
1308 quickmark(const Arg *a) {
1309 int i, b;
1310 b = atoi(a->s);
1311 char *fn = g_strdup_printf(QUICKMARK_FILE);
1312 FILE *fp;
1313 fp = fopen(fn, "r");
1314 char buf[100];
1316 if (fp != NULL && b < 10) {
1317 for( i=0; i < b; ++i ) {
1318 if (feof(fp)) {
1319 break;
1321 fgets(buf, 100, fp);
1323 char *ptr = strrchr(buf, '\n');
1324 *ptr = '\0';
1325 Arg x = { .s = buf };
1326 if (strlen(buf))
1327 return open_arg(&x);
1328 else {
1329 x.i = Error;
1330 x.s = g_strdup_printf("Quickmark %d not defined", b);
1331 echo(&x);
1332 g_free(x.s);
1333 return false;
1335 } else { return false; }
1338 gboolean
1339 script(const Arg *arg) {
1340 gchar *value = NULL, *message = NULL;
1341 Arg a;
1343 if (!arg->s) {
1344 set_error("Missing argument.");
1345 return FALSE;
1347 jsapi_evaluate_script(arg->s, &value, &message);
1348 if (message) {
1349 set_error(message);
1350 if (arg->s)
1351 g_free(arg->s);
1352 return FALSE;
1354 if (arg->i != Silent && value) {
1355 a.i = arg->i;
1356 a.s = g_strdup(value);
1357 echo(&a);
1358 g_free(a.s);
1360 if (arg->s)
1361 g_free(arg->s);
1362 g_free(value);
1363 return TRUE;
1366 gboolean
1367 scroll(const Arg *arg) {
1368 GtkAdjustment *adjust = (arg->i & OrientationHoriz) ? adjust_h : adjust_v;
1369 int max = gtk_adjustment_get_upper(adjust) - gtk_adjustment_get_page_size(adjust);
1370 float val = gtk_adjustment_get_value(adjust) / max * 100;
1371 int direction = (arg->i & (1 << 2)) ? 1 : -1;
1373 if ((direction == 1 && val < 100) || (direction == -1 && val > 0)) {
1374 if (arg->i & ScrollMove)
1375 gtk_adjustment_set_value(adjust, gtk_adjustment_get_value(adjust) +
1376 direction * /* direction */
1377 ((arg->i & UnitLine || (arg->i & UnitBuffer && count)) ? (scrollstep * (count ? count : 1)) : (
1378 arg->i & UnitBuffer ? gtk_adjustment_get_page_size(adjust) / 2 :
1379 (count ? count : 1) * (gtk_adjustment_get_page_size(adjust) -
1380 (gtk_adjustment_get_page_size(adjust) > pagingkeep ? pagingkeep : 0)))));
1381 else
1382 gtk_adjustment_set_value(adjust,
1383 ((direction == 1) ? gtk_adjustment_get_upper : gtk_adjustment_get_lower)(adjust));
1384 update_state();
1386 return TRUE;
1389 gboolean
1390 zoom(const Arg *arg) {
1391 webkit_web_view_set_full_content_zoom(webview, (arg->i & ZoomFullContent) > 0);
1392 webkit_web_view_set_zoom_level(webview, (arg->i & ZoomOut) ?
1393 webkit_web_view_get_zoom_level(webview) +
1394 (((float)(count ? count : 1)) * (arg->i & (1 << 1) ? 1.0 : -1.0) * zoomstep) :
1395 (count ? (float)count / 100.0 : 1.0));
1396 return TRUE;
1399 gboolean
1400 fake_key_event(const Arg *a) {
1401 if(!embed) {
1402 return FALSE;
1404 Arg err;
1405 err.i = Error;
1406 Display *xdpy;
1407 if ( (xdpy = XOpenDisplay(NULL)) == NULL ) {
1408 err.s = g_strdup("Couldn't find the XDisplay.");
1409 echo(&err);
1410 g_free(err.s);
1411 return FALSE;
1414 XKeyEvent xk;
1415 xk.display = xdpy;
1416 xk.subwindow = None;
1417 xk.time = CurrentTime;
1418 xk.same_screen = True;
1419 xk.x = xk.y = xk.x_root = xk.y_root = 1;
1420 xk.window = embed;
1421 xk.state = a->i;
1423 if( ! a->s ) {
1424 err.s = g_strdup("Zero pointer as argument! Check your config.h");
1425 echo(&err);
1426 g_free(err.s);
1427 return FALSE;
1430 KeySym keysym;
1431 if( (keysym = XStringToKeysym(a->s)) == NoSymbol ) {
1432 err.s = g_strdup_printf("Couldn't translate %s to keysym", a->s );
1433 echo(&err);
1434 g_free(err.s);
1435 return FALSE;
1438 if( (xk.keycode = XKeysymToKeycode(xdpy, keysym)) == NoSymbol ) {
1439 err.s = g_strdup("Couldn't translate keysym to keycode");
1440 echo(&err);
1441 g_free(err.s);
1442 return FALSE;
1445 xk.type = KeyPress;
1446 if( !XSendEvent(xdpy, embed, True, KeyPressMask, (XEvent *)&xk) ) {
1447 err.s = g_strdup("XSendEvent failed");
1448 echo(&err);
1449 g_free(err.s);
1450 return FALSE;
1452 XFlush(xdpy);
1454 return TRUE;
1458 gboolean
1459 commandhistoryfetch(const Arg *arg) {
1460 if (arg->i == DirectionPrev) {
1461 commandpointer--;
1462 if (commandpointer < 0)
1463 commandpointer = maxcommands - 1;
1464 } else {
1465 commandpointer++;
1466 if (commandpointer == COMMANDHISTSIZE || commandpointer == maxcommands)
1467 commandpointer = 0;
1470 if (commandpointer < 0)
1471 return FALSE;
1473 gtk_entry_set_text(GTK_ENTRY(inputbox), commandhistory[commandpointer ]);
1474 gtk_editable_set_position(GTK_EDITABLE(inputbox), -1);
1475 return TRUE;
1479 gboolean
1480 bookmark(const Arg *arg) {
1481 FILE *f;
1482 const char *filename;
1483 const char *uri = webkit_web_view_get_uri(webview);
1484 const char *title = webkit_web_view_get_title(webview);
1485 filename = g_strdup_printf(BOOKMARKS_STORAGE_FILENAME);
1486 f = fopen(filename, "a");
1487 if (uri == NULL || strlen(uri) == 0) {
1488 set_error("No URI found to bookmark.");
1489 return FALSE;
1491 if (f != NULL) {
1492 fprintf(f, "%s", uri);
1493 if (title != NULL) {
1494 fprintf(f, "%s", " ");
1495 fprintf(f, "%s", title);
1497 if (arg->s && strlen(arg->s)) {
1498 build_taglist(arg, f);
1500 fprintf(f, "%s", "\n");
1501 fclose(f);
1502 give_feedback( "Bookmark saved" );
1503 return TRUE;
1504 } else {
1505 set_error("Bookmarks file not found.");
1506 return FALSE;
1510 gboolean
1511 history() {
1512 FILE *f;
1513 const char *filename;
1514 const char *uri = webkit_web_view_get_uri(webview);
1515 const char *title = webkit_web_view_get_title(webview);
1516 char *entry, buffer[512], *new;
1517 int n, i = 0;
1518 gboolean finished = FALSE;
1519 if (uri != NULL) {
1520 if (title != NULL) {
1521 entry = malloc((strlen(uri) + strlen(title) + 2) * sizeof(char));
1522 memset(entry, 0, strlen(uri) + strlen(title) + 2);
1523 } else {
1524 entry = malloc((strlen(uri) + 1) * sizeof(char));
1525 memset(entry, 0, strlen(uri) + 1);
1527 if (entry != NULL) {
1528 strncpy(entry, uri, strlen(uri));
1529 if (title != NULL) {
1530 strncat(entry, " ", 1);
1531 strncat(entry, title, strlen(title));
1533 n = strlen(entry);
1534 filename = g_strdup_printf(HISTORY_STORAGE_FILENAME);
1535 f = fopen(filename, "r");
1536 if (f != NULL) {
1537 new = (char *)malloc(HISTORY_MAX_ENTRIES * 512 * sizeof(char) + 1);
1538 if (new != NULL) {
1539 memset(new, 0, HISTORY_MAX_ENTRIES * 512 * sizeof(char) + 1);
1540 /* newest entries go on top */
1541 strncpy(new, entry, strlen(entry));
1542 strncat(new, "\n", 1);
1543 /* retain at most HISTORY_MAX_ENTIRES - 1 old entries */
1544 while (finished != TRUE) {
1545 if ((char *)NULL == fgets(buffer, 512, f)) {
1546 /* check if end of file was reached / error occured */
1547 if (!feof(f)) {
1548 break;
1550 /* end of file reached */
1551 finished = TRUE;
1552 continue;
1554 /* compare line (-1 because of newline character) */
1555 if (n != strlen(buffer) - 1 || strncmp(entry, buffer, n) != 0) {
1556 /* if the URI is already in history; we put it on top and skip it here */
1557 strncat(new, buffer, 512);
1558 i++;
1560 if ((i + 1) >= HISTORY_MAX_ENTRIES) {
1561 break;
1564 fclose(f);
1566 f = fopen(filename, "w");
1567 if (f != NULL) {
1568 fprintf(f, "%s", new);
1569 fclose(f);
1571 if (new != NULL) {
1572 free(new);
1573 new = NULL;
1577 if (entry != NULL) {
1578 free(entry);
1579 entry = NULL;
1582 return TRUE;
1585 static gboolean
1586 view_source(const Arg * arg) {
1587 gboolean current_mode = webkit_web_view_get_view_source_mode(webview);
1588 webkit_web_view_set_view_source_mode(webview, !current_mode);
1589 webkit_web_view_reload(webview);
1590 return TRUE;
1593 static gboolean
1594 focus_input(const Arg *arg) {
1595 static Arg a;
1597 a.s = g_strdup("hints.focusInput();");
1598 a.i = Silent;
1599 script(&a);
1600 update_state();
1601 return TRUE;
1604 static gboolean
1605 browser_settings(const Arg *arg) {
1606 char line[255];
1607 if (!arg->s) {
1608 set_error("Missing argument.");
1609 return FALSE;
1611 strncpy(line, arg->s, 254);
1612 if (process_set_line(line))
1613 return TRUE;
1614 else {
1615 set_error("Invalid setting.");
1616 return FALSE;
1620 char *
1621 search_word(int whichword) {
1622 int k = 0;
1623 static char word[240];
1624 char *c = my_pair.line;
1626 while (isspace(*c) && *c)
1627 c++;
1629 switch (whichword) {
1630 case 0:
1631 while (*c && !isspace (*c) && *c != '=' && k < 240) {
1632 word[k++] = *c;
1633 c++;
1635 word[k] = '\0';
1636 strncpy(my_pair.what, word, 20);
1637 break;
1638 case 1:
1639 while (*c && k < 240) {
1640 word[k++] = *c;
1641 c++;
1643 word[k] = '\0';
1644 strncpy(my_pair.value, word, 240);
1645 break;
1648 return c;
1651 static gboolean
1652 process_set_line(char *line) {
1653 char *c;
1654 int listlen, i;
1655 gboolean boolval;
1656 WebKitWebSettings *settings;
1658 settings = webkit_web_view_get_settings(webview);
1659 my_pair.line = line;
1660 c = search_word(0);
1661 if (!strlen(my_pair.what))
1662 return FALSE;
1664 while (isspace(*c) && *c)
1665 c++;
1667 if (*c == ':' || *c == '=')
1668 c++;
1670 my_pair.line = c;
1671 c = search_word(1);
1673 listlen = LENGTH(browsersettings);
1674 for (i = 0; i < listlen; i++) {
1675 if (strlen(browsersettings[i].name) == strlen(my_pair.what) && strncmp(browsersettings[i].name, my_pair.what, strlen(my_pair.what)) == 0) {
1676 /* mandatory argument not provided */
1677 if (strlen(my_pair.value) == 0)
1678 return FALSE;
1679 /* process qmark? */
1680 if (strlen(my_pair.what) == 5 && strncmp("qmark", my_pair.what, 5) == 0) {
1681 return (process_save_qmark(my_pair.value, webview));
1683 /* interpret boolean values */
1684 if (browsersettings[i].boolval) {
1685 if (strncmp(my_pair.value, "on", 2) == 0 || strncmp(my_pair.value, "true", 4) == 0 || strncmp(my_pair.value, "ON", 2) == 0 || strncmp(my_pair.value, "TRUE", 4) == 0) {
1686 boolval = TRUE;
1687 } else if (strncmp(my_pair.value, "off", 3) == 0 || strncmp(my_pair.value, "false", 5) == 0 || strncmp(my_pair.value, "OFF", 3) == 0 || strncmp(my_pair.value, "FALSE", 5) == 0) {
1688 boolval = FALSE;
1689 } else {
1690 return FALSE;
1692 } else if (browsersettings[i].colourval) {
1693 /* interpret as hexadecimal colour */
1694 if (!parse_colour(my_pair.value)) {
1695 return FALSE;
1698 if (browsersettings[i].var != NULL) {
1699 /* write value into internal variable */
1700 /*if (browsersettings[i].intval) {
1701 browsersettings[i].var = atoi(my_pair.value);
1702 } else {*/
1703 strncpy(browsersettings[i].var, my_pair.value, MAX_SETTING_SIZE);
1704 if (strlen(my_pair.value) > MAX_SETTING_SIZE - 1) {
1705 /* in this case, \0 will not have been copied */
1706 browsersettings[i].var[MAX_SETTING_SIZE - 1] = '\0';
1707 /* in case this string is also used for a webkit setting, make sure it's consistent */
1708 my_pair.value[MAX_SETTING_SIZE - 1] = '\0';
1709 give_feedback("String too long; automatically truncated!");
1711 /*}*/
1713 if (strlen(browsersettings[i].webkit) > 0) {
1714 /* activate appropriate webkit setting */
1715 if (browsersettings[i].boolval) {
1716 g_object_set((GObject*)settings, browsersettings[i].webkit, boolval, NULL);
1717 } else if (browsersettings[i].intval) {
1718 g_object_set((GObject*)settings, browsersettings[i].webkit, atoi(my_pair.value), NULL);
1719 } else {
1720 g_object_set((GObject*)settings, browsersettings[i].webkit, my_pair.value, NULL);
1722 webkit_web_view_set_settings(webview, settings);
1725 /* process acceptlanguage*/
1726 if (strlen(my_pair.what) == 14 && strncmp("acceptlanguage", my_pair.what, 14) == 0) {
1727 g_object_set(G_OBJECT(session), "accept-language", acceptlanguage, NULL);
1730 /* toggle proxy usage? */
1731 if (strlen(my_pair.what) == 5 && strncmp("proxy", my_pair.what, 5) == 0) {
1732 toggle_proxy(boolval);
1735 /* Toggle scrollbars. */
1736 if (strlen(my_pair.what) == 10 && strncmp("scrollbars", my_pair.what, 10) == 0)
1737 toggle_scrollbars(boolval);
1739 /* Toggle widgets */
1740 if (strlen(my_pair.what) == 9 && strncmp("statusbar", my_pair.what, 9) == 0)
1741 gtk_widget_set_visible(GTK_WIDGET(statusbar), boolval);
1742 if (strlen(my_pair.what) == 8 && strncmp("inputbox", my_pair.what, 8) == 0)
1743 gtk_widget_set_visible(inputbox, boolval);
1745 /* case sensitivity of completion */
1746 if (strlen(my_pair.what) == 14 && strncmp("completioncase", my_pair.what, 14) == 0)
1747 complete_case_sensitive = boolval;
1749 /* reload page? */
1750 if (browsersettings[i].reload)
1751 webkit_web_view_reload(webview);
1752 return TRUE;
1755 return FALSE;
1758 gboolean
1759 process_line(char *line) {
1760 char *c = line;
1761 int i;
1762 size_t len, length = strlen(line);
1763 gboolean found = FALSE, success = FALSE;
1764 Arg a;
1766 while (isspace(*c))
1767 c++;
1768 /* Ignore blank lines. */
1769 if (c[0] == '\0')
1770 return TRUE;
1771 for (i = 0; i < LENGTH(commands); i++) {
1772 if (commands[i].cmd == NULL)
1773 break;
1774 len = strlen(commands[i].cmd);
1775 if (length >= len && !strncmp(c, commands[i].cmd, len) && (c[len] == ' ' || !c[len])) {
1776 found = TRUE;
1777 a.i = commands[i].arg.i;
1778 a.s = length > len + 1 ? &c[len + 1] : commands[i].arg.s;
1779 success = commands[i].func(&a);
1780 break;
1783 save_command_history(c);
1784 if (!found) {
1785 a.i = Error;
1786 a.s = g_strdup_printf("Not a browser command: %s", c);
1787 echo(&a);
1788 } else if (!success) {
1789 a.i = Error;
1790 if (error_msg != NULL) {
1791 a.s = g_strdup_printf("%s", error_msg);
1792 g_free(error_msg);
1793 error_msg = NULL;
1794 } else {
1795 a.s = g_strdup_printf("Unknown error. Please file a bug report!");
1797 echo(&a);
1798 g_free(a.s);
1800 return success;
1803 static gboolean
1804 search_tag(const Arg * a) {
1805 FILE *f;
1806 const char *filename;
1807 const char *tag = a->s;
1808 char s[BUFFERSIZE], foundtag[40], url[BUFFERSIZE];
1809 int t, i, intag, k;
1811 if (!tag) {
1812 /* The user must give us something to load up. */
1813 set_error("Bookmark tag required with this option.");
1814 return FALSE;
1817 if (strlen(tag) > MAXTAGSIZE) {
1818 set_error("Tag too long.");
1819 return FALSE;
1822 filename = g_strdup_printf(BOOKMARKS_STORAGE_FILENAME);
1823 f = fopen(filename, "r");
1824 if (f == NULL) {
1825 set_error("Couldn't open bookmarks file.");
1826 return FALSE;
1828 while (fgets(s, BUFFERSIZE-1, f)) {
1829 intag = 0;
1830 t = strlen(s) - 1;
1831 while (isspace(s[t]))
1832 t--;
1833 if (s[t] != ']') continue;
1834 while (t > 0) {
1835 if (s[t] == ']') {
1836 if (!intag)
1837 intag = t;
1838 else
1839 intag = 0;
1840 } else {
1841 if (s[t] == '[') {
1842 if (intag) {
1843 i = 0;
1844 k = t + 1;
1845 while (k < intag)
1846 foundtag[i++] = s[k++];
1847 foundtag[i] = '\0';
1848 /* foundtag now contains the tag */
1849 if (strlen(foundtag) < MAXTAGSIZE && strcmp(tag, foundtag) == 0) {
1850 i = 0;
1851 while (isspace(s[i])) i++;
1852 k = 0;
1853 while (s[i] && !isspace(s[i])) url[k++] = s[i++];
1854 url[k] = '\0';
1855 Arg x = { .i = TargetNew, .s = url };
1856 open_arg(&x);
1859 intag = 0;
1862 t--;
1865 return TRUE;
1868 void
1869 toggle_proxy(gboolean onoff) {
1870 SoupURI *proxy_uri;
1871 char *filename, *new;
1872 int len;
1874 if (onoff == FALSE) {
1875 g_object_set(session, "proxy-uri", NULL, NULL);
1876 give_feedback("Proxy deactivated");
1877 } else {
1878 filename = (char *)g_getenv("http_proxy");
1880 /* Fallthrough to checking HTTP_PROXY as well, since this can also be
1881 * defined.
1883 if (filename == NULL)
1884 filename = (char *)g_getenv("HTTP_PROXY");
1886 if (filename != NULL && 0 < (len = strlen(filename))) {
1887 if (strstr(filename, "://") == NULL) {
1888 /* prepend http:// */
1889 new = g_malloc(sizeof("http://") + len);
1890 strcpy(new, "http://");
1891 memcpy(&new[sizeof("http://") - 1], filename, len + 1);
1892 proxy_uri = soup_uri_new(new);
1893 } else {
1894 proxy_uri = soup_uri_new(filename);
1896 g_object_set(session, "proxy-uri", proxy_uri, NULL);
1897 give_feedback("Proxy activated");
1902 void
1903 toggle_scrollbars(gboolean onoff) {
1904 if (onoff == TRUE) {
1905 adjust_h = gtk_scrolled_window_get_hadjustment(GTK_SCROLLED_WINDOW(viewport));
1906 adjust_v = gtk_scrolled_window_get_vadjustment(GTK_SCROLLED_WINDOW(viewport));
1908 else {
1909 adjust_v = gtk_range_get_adjustment(GTK_RANGE(scroll_v));
1910 adjust_h = gtk_range_get_adjustment(GTK_RANGE(scroll_h));
1912 gtk_widget_set_scroll_adjustments (GTK_WIDGET(webview), adjust_h, adjust_v);
1914 return;
1917 void
1918 update_url(const char *uri) {
1919 gboolean ssl = g_str_has_prefix(uri, "https://");
1920 GdkColor color;
1921 #ifdef ENABLE_HISTORY_INDICATOR
1922 char before[] = " [";
1923 char after[] = "]";
1924 gboolean back = webkit_web_view_can_go_back(webview);
1925 gboolean fwd = webkit_web_view_can_go_forward(webview);
1927 if (!back && !fwd)
1928 before[0] = after[0] = '\0';
1929 #endif
1930 gtk_label_set_markup(GTK_LABEL(status_url), g_markup_printf_escaped(
1931 #ifdef ENABLE_HISTORY_INDICATOR
1932 "<span font=\"%s\">%s%s%s%s%s</span>", statusfont, uri,
1933 before, back ? "+" : "", fwd ? "-" : "", after
1934 #else
1935 "<span font=\"%s\">%s</span>", statusfont, uri
1936 #endif
1938 gdk_color_parse(ssl ? sslbgcolor : statusbgcolor, &color);
1939 gtk_widget_modify_bg(eventbox, GTK_STATE_NORMAL, &color);
1940 gdk_color_parse(ssl ? sslcolor : statuscolor, &color);
1941 gtk_widget_modify_fg(GTK_WIDGET(status_url), GTK_STATE_NORMAL, &color);
1942 gtk_widget_modify_fg(GTK_WIDGET(status_state), GTK_STATE_NORMAL, &color);
1945 void
1946 update_state() {
1947 char *markup;
1948 int download_count = g_list_length(activeDownloads);
1949 GString *status = g_string_new("");
1951 /* construct the status line */
1953 /* count, modkey and input buffer */
1954 g_string_append_printf(status, "%.0d", count);
1955 if (current_modkey) g_string_append_c(status, current_modkey);
1957 /* the number of active downloads */
1958 if (activeDownloads) {
1959 g_string_append_printf(status, " %d active %s", download_count,
1960 (download_count == 1) ? "download" : "downloads");
1963 #ifdef ENABLE_WGET_PROGRESS_BAR
1964 /* the progressbar */
1966 int progress = -1;
1967 char progressbar[progressbartick + 1];
1969 if (activeDownloads) {
1970 progress = 0;
1971 GList *ptr;
1973 for (ptr = activeDownloads; ptr; ptr = g_list_next(ptr)) {
1974 progress += 100 * webkit_download_get_progress(ptr->data);
1977 progress /= download_count;
1979 } else if (webkit_web_view_get_load_status(webview) != WEBKIT_LOAD_FINISHED
1980 && webkit_web_view_get_load_status(webview) != WEBKIT_LOAD_FAILED) {
1982 progress = webkit_web_view_get_progress(webview) * 100;
1985 if (progress >= 0) {
1986 ascii_bar(progressbartick, progress * progressbartick / 100, progressbar);
1987 g_string_append_printf(status, " %c%s%c",
1988 progressborderleft, progressbar, progressborderright);
1991 #endif
1993 /* and the current scroll position */
1995 int max = gtk_adjustment_get_upper(adjust_v) - gtk_adjustment_get_page_size(adjust_v);
1996 int val = (int)(gtk_adjustment_get_value(adjust_v) / max * 100);
1998 if (max == 0)
1999 g_string_append(status, " All");
2000 else if (val == 0)
2001 g_string_append(status, " Top");
2002 else if (val == 100)
2003 g_string_append(status, " Bot");
2004 else
2005 g_string_append_printf(status, " %d%%", val);
2009 markup = g_markup_printf_escaped("<span font=\"%s\">%s</span>", statusfont, status->str);
2010 gtk_label_set_markup(GTK_LABEL(status_state), markup);
2012 g_string_free(status, TRUE);
2015 void
2016 setup_modkeys() {
2017 unsigned int i;
2018 modkeys = calloc(LENGTH(keys) + 1, sizeof(char));
2019 char *ptr = modkeys;
2021 for (i = 0; i < LENGTH(keys); i++)
2022 if (keys[i].modkey && !strchr(modkeys, keys[i].modkey))
2023 *(ptr++) = keys[i].modkey;
2024 modkeys = realloc(modkeys, &ptr[0] - &modkeys[0] + 1);
2027 void
2028 setup_gui() {
2029 scroll_h = GTK_SCROLLBAR(gtk_hscrollbar_new(NULL));
2030 scroll_v = GTK_SCROLLBAR(gtk_vscrollbar_new(NULL));
2031 adjust_h = gtk_range_get_adjustment(GTK_RANGE(scroll_h));
2032 adjust_v = gtk_range_get_adjustment(GTK_RANGE(scroll_v));
2033 if (embed) {
2034 window = GTK_WINDOW(gtk_plug_new(embed));
2035 } else {
2036 window = GTK_WINDOW(gtk_window_new(GTK_WINDOW_TOPLEVEL));
2037 gtk_window_set_wmclass(GTK_WINDOW(window), "vimprobable2", "Vimprobable2");
2039 gtk_window_set_default_size(GTK_WINDOW(window), 640, 480);
2040 box = GTK_BOX(gtk_vbox_new(FALSE, 0));
2041 inputbox = gtk_entry_new();
2042 webview = (WebKitWebView*)webkit_web_view_new();
2043 statusbar = GTK_BOX(gtk_hbox_new(FALSE, 0));
2044 eventbox = gtk_event_box_new();
2045 status_url = gtk_label_new(NULL);
2046 status_state = gtk_label_new(NULL);
2047 GdkColor bg;
2048 PangoFontDescription *font;
2049 GdkGeometry hints = { 1, 1 };
2050 inspector = webkit_web_view_get_inspector(WEBKIT_WEB_VIEW(webview));
2052 clipboards[0] = gtk_clipboard_get(GDK_SELECTION_PRIMARY);
2053 clipboards[1] = gtk_clipboard_get(GDK_NONE);
2054 setup_settings();
2055 gdk_color_parse(statusbgcolor, &bg);
2056 gtk_widget_modify_bg(eventbox, GTK_STATE_NORMAL, &bg);
2057 gtk_widget_set_name(GTK_WIDGET(window), "Vimprobable2");
2058 gtk_window_set_geometry_hints(window, NULL, &hints, GDK_HINT_MIN_SIZE);
2060 #ifdef DISABLE_SCROLLBAR
2061 viewport = gtk_scrolled_window_new(NULL, NULL);
2062 gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(viewport), GTK_POLICY_NEVER, GTK_POLICY_NEVER);
2063 #else
2064 /* Ensure we still see scrollbars. */
2065 GtkWidget *viewport = gtk_scrolled_window_new(adjust_h, adjust_v);
2066 #endif
2068 setup_signals();
2069 gtk_container_add(GTK_CONTAINER(viewport), GTK_WIDGET(webview));
2071 /* Ensure we set the scroll adjustments now, so that if we're not drawing
2072 * titlebars, we can still scroll.
2074 gtk_widget_set_scroll_adjustments(GTK_WIDGET(webview), adjust_h, adjust_v);
2076 font = pango_font_description_from_string(urlboxfont[0]);
2077 gtk_widget_modify_font(GTK_WIDGET(inputbox), font);
2078 pango_font_description_free(font);
2079 gtk_entry_set_inner_border(GTK_ENTRY(inputbox), NULL);
2080 gtk_misc_set_alignment(GTK_MISC(status_url), 0.0, 0.0);
2081 gtk_misc_set_alignment(GTK_MISC(status_state), 1.0, 0.0);
2082 gtk_box_pack_start(statusbar, status_url, TRUE, TRUE, 2);
2083 gtk_box_pack_start(statusbar, status_state, FALSE, FALSE, 2);
2084 gtk_container_add(GTK_CONTAINER(eventbox), GTK_WIDGET(statusbar));
2085 gtk_box_pack_start(box, viewport, TRUE, TRUE, 0);
2086 gtk_box_pack_start(box, eventbox, FALSE, FALSE, 0);
2087 gtk_entry_set_has_frame(GTK_ENTRY(inputbox), FALSE);
2088 gtk_box_pack_end(box, inputbox, FALSE, FALSE, 0);
2089 gtk_container_add(GTK_CONTAINER(window), GTK_WIDGET(box));
2090 gtk_widget_grab_focus(GTK_WIDGET(webview));
2091 gtk_widget_show_all(GTK_WIDGET(window));
2094 void
2095 setup_settings() {
2096 WebKitWebSettings *settings = (WebKitWebSettings*)webkit_web_settings_new();
2097 SoupURI *proxy_uri;
2098 char *filename, *new;
2099 int len;
2101 session = webkit_get_default_session();
2102 g_object_set(G_OBJECT(settings), "default-font-size", DEFAULT_FONT_SIZE, NULL);
2103 g_object_set(G_OBJECT(settings), "enable-scripts", enablePlugins, NULL);
2104 g_object_set(G_OBJECT(settings), "enable-plugins", enablePlugins, NULL);
2105 g_object_set(G_OBJECT(settings), "enable-java-applet", enableJava, NULL);
2106 g_object_set(G_OBJECT(settings), "enable-page-cache", enablePagecache, NULL);
2107 filename = g_strdup_printf(USER_STYLESHEET);
2108 filename = g_strdup_printf("file://%s", filename);
2109 g_object_set(G_OBJECT(settings), "user-stylesheet-uri", filename, NULL);
2110 g_object_set(G_OBJECT(settings), "user-agent", useragent, NULL);
2111 g_object_get(G_OBJECT(settings), "zoom-step", &zoomstep, NULL);
2112 webkit_web_view_set_settings(webview, settings);
2114 /* proxy */
2115 if (use_proxy == TRUE) {
2116 filename = (char *)g_getenv("http_proxy");
2117 if (filename != NULL && 0 < (len = strlen(filename))) {
2118 if (strstr(filename, "://") == NULL) {
2119 /* prepend http:// */
2120 new = g_malloc(sizeof("http://") + len);
2121 strcpy(new, "http://");
2122 memcpy(&new[sizeof("http://") - 1], filename, len + 1);
2123 proxy_uri = soup_uri_new(new);
2124 } else {
2125 proxy_uri = soup_uri_new(filename);
2127 g_object_set(session, "proxy-uri", proxy_uri, NULL);
2132 void
2133 setup_signals() {
2134 #ifdef ENABLE_COOKIE_SUPPORT
2135 /* Headers. */
2136 g_signal_connect_after(G_OBJECT(session), "request-started", G_CALLBACK(new_generic_request), NULL);
2137 #endif
2138 /* Accept-language header */
2139 g_object_set(G_OBJECT(session), "accept-language", acceptlanguage, NULL);
2140 /* window */
2141 g_object_connect(G_OBJECT(window),
2142 "signal::destroy", G_CALLBACK(window_destroyed_cb), NULL,
2143 NULL);
2144 /* webview */
2145 g_object_connect(G_OBJECT(webview),
2146 "signal::title-changed", G_CALLBACK(webview_title_changed_cb), NULL,
2147 "signal::load-progress-changed", G_CALLBACK(webview_progress_changed_cb), NULL,
2148 "signal::load-committed", G_CALLBACK(webview_load_committed_cb), NULL,
2149 "signal::load-finished", G_CALLBACK(webview_load_finished_cb), NULL,
2150 "signal::navigation-policy-decision-requested", G_CALLBACK(webview_navigation_cb), NULL,
2151 "signal::new-window-policy-decision-requested", G_CALLBACK(webview_new_window_cb), NULL,
2152 "signal::mime-type-policy-decision-requested", G_CALLBACK(webview_mimetype_cb), NULL,
2153 "signal::download-requested", G_CALLBACK(webview_download_cb), NULL,
2154 "signal::key-press-event", G_CALLBACK(webview_keypress_cb), NULL,
2155 "signal::hovering-over-link", G_CALLBACK(webview_hoverlink_cb), NULL,
2156 "signal::console-message", G_CALLBACK(webview_console_cb), NULL,
2157 "signal::create-web-view", G_CALLBACK(webview_open_in_new_window_cb), NULL,
2158 "signal::event", G_CALLBACK(notify_event_cb), NULL,
2159 NULL);
2160 /* webview adjustment */
2161 g_object_connect(G_OBJECT(adjust_v),
2162 "signal::value-changed", G_CALLBACK(webview_scroll_cb), NULL,
2163 NULL);
2164 /* inputbox */
2165 g_object_connect(G_OBJECT(inputbox),
2166 "signal::activate", G_CALLBACK(inputbox_activate_cb), NULL,
2167 "signal::key-press-event", G_CALLBACK(inputbox_keypress_cb), NULL,
2168 "signal::key-release-event", G_CALLBACK(inputbox_keyrelease_cb), NULL,
2169 #ifdef ENABLE_INCREMENTAL_SEARCH
2170 "signal::changed", G_CALLBACK(inputbox_changed_cb), NULL,
2171 #endif
2172 NULL);
2173 /* inspector */
2174 g_signal_connect(G_OBJECT(inspector),
2175 "inspect-web-view", G_CALLBACK(inspector_inspect_web_view_cb), NULL);
2178 #ifdef ENABLE_COOKIE_SUPPORT
2179 void
2180 setup_cookies()
2182 if (file_cookie_jar)
2183 g_object_unref(file_cookie_jar);
2185 if (session_cookie_jar)
2186 g_object_unref(session_cookie_jar);
2188 session_cookie_jar = soup_cookie_jar_new();
2190 cookie_store = g_strdup_printf(COOKIES_STORAGE_FILENAME);
2192 load_all_cookies();
2194 g_signal_connect(G_OBJECT(file_cookie_jar), "changed",
2195 G_CALLBACK(update_cookie_jar), NULL);
2197 return;
2200 /* TA: XXX - we should be using this callback for any header-requests we
2201 * receive (hence the name "new_generic_request" -- but for now, its use
2202 * is limited to handling cookies.
2204 void
2205 new_generic_request(SoupSession *session, SoupMessage *soup_msg, gpointer unused) {
2206 SoupMessageHeaders *soup_msg_h;
2207 SoupURI *uri;
2208 const char *cookie_str;
2210 soup_msg_h = soup_msg->request_headers;
2211 soup_message_headers_remove(soup_msg_h, "Cookie");
2212 uri = soup_message_get_uri(soup_msg);
2213 if( (cookie_str = get_cookies(uri)) )
2214 soup_message_headers_append(soup_msg_h, "Cookie", cookie_str);
2216 g_signal_connect_after(G_OBJECT(soup_msg), "got-headers", G_CALLBACK(handle_cookie_request), NULL);
2218 return;
2221 const char *
2222 get_cookies(SoupURI *soup_uri) {
2223 const char *cookie_str;
2225 cookie_str = soup_cookie_jar_get_cookies(file_cookie_jar, soup_uri, TRUE);
2227 return cookie_str;
2230 void
2231 handle_cookie_request(SoupMessage *soup_msg, gpointer unused)
2233 GSList *resp_cookie = NULL;
2234 SoupCookie *cookie;
2236 for(resp_cookie = soup_cookies_from_response(soup_msg);
2237 resp_cookie;
2238 resp_cookie = g_slist_next(resp_cookie))
2240 SoupDate *soup_date;
2241 cookie = soup_cookie_copy((SoupCookie *)resp_cookie->data);
2243 if (cookie_timeout && cookie->expires == NULL) {
2244 soup_date = soup_date_new_from_time_t(time(NULL) + cookie_timeout * 10);
2245 soup_cookie_set_expires(cookie, soup_date);
2247 soup_cookie_jar_add_cookie(file_cookie_jar, cookie);
2250 return;
2253 void
2254 update_cookie_jar(SoupCookieJar *jar, SoupCookie *old, SoupCookie *new)
2256 if (!new) {
2257 /* Nothing to do. */
2258 return;
2261 SoupCookie *copy;
2262 copy = soup_cookie_copy(new);
2264 soup_cookie_jar_add_cookie(session_cookie_jar, copy);
2266 return;
2269 void
2270 load_all_cookies(void)
2272 file_cookie_jar = soup_cookie_jar_text_new(cookie_store, COOKIES_STORAGE_READONLY);
2274 /* Put them back in the session store. */
2275 GSList *cookies_from_file = soup_cookie_jar_all_cookies(file_cookie_jar);
2277 for (; cookies_from_file;
2278 cookies_from_file = cookies_from_file->next)
2280 soup_cookie_jar_add_cookie(session_cookie_jar, cookies_from_file->data);
2283 soup_cookies_free(cookies_from_file);
2285 return;
2288 #endif
2290 void
2291 mop_up(void) {
2292 /* Free up any nasty globals before exiting. */
2293 #ifdef ENABLE_COOKIE_SUPPORT
2294 if (cookie_store)
2295 g_free(cookie_store);
2296 #endif
2297 return;
2301 main(int argc, char *argv[]) {
2302 static Arg a;
2303 static char url[256] = "";
2304 static gboolean ver = false;
2305 static gboolean configfile_exists = FALSE;
2306 static const char *cfile = NULL;
2307 char *searchengines_file;
2308 static GOptionEntry opts[] = {
2309 { "version", 'v', 0, G_OPTION_ARG_NONE, &ver, "print version", NULL },
2310 { "embed", 'e', 0, G_OPTION_ARG_STRING, &winid, "embedded", NULL },
2311 { "configfile", 'c', 0, G_OPTION_ARG_STRING, &cfile, "config file", NULL },
2312 { NULL }
2314 static GError *err;
2315 args = argv;
2317 /* command line argument: version */
2318 if (!gtk_init_with_args(&argc, &argv, "[<uri>]", opts, NULL, &err)) {
2319 g_printerr("can't init gtk: %s\n", err->message);
2320 g_error_free(err);
2321 return EXIT_FAILURE;
2324 if (ver) {
2325 printf("%s\n", INTERNAL_VERSION);
2326 return EXIT_SUCCESS;
2329 if (cfile)
2330 configfile = g_strdup_printf(cfile);
2331 else
2332 configfile = g_strdup_printf(RCFILE);
2334 if (!g_thread_supported())
2335 g_thread_init(NULL);
2337 if (winid)
2338 embed = atoi(winid);
2340 setup_modkeys();
2341 make_keyslist();
2342 setup_gui();
2343 #ifdef ENABLE_COOKIE_SUPPORT
2344 setup_cookies();
2345 #endif
2347 /* Check if the specified file exists. */
2348 /* And only warn the user, if they explicitly asked for a config on the
2349 * command line.
2351 if (!(access(configfile, F_OK) == 0) && cfile) {
2352 char *feedback_str;
2354 feedback_str = g_strdup_printf("Config file '%s' doesn't exist", cfile);
2355 give_feedback(feedback_str);
2356 } else if ((access(configfile, F_OK) == 0))
2357 configfile_exists = true;
2359 /* read config file */
2360 /* But only report errors if we failed, and the file existed. */
2361 if (!read_rcfile(configfile) && configfile_exists) {
2362 a.i = Error;
2363 a.s = g_strdup_printf("Error in config file '%s'", configfile);
2364 echo(&a);
2365 g_free(a.s);
2366 g_free(configfile);
2369 make_searchengines_list(searchengines, LENGTH(searchengines));
2371 /* read searchengines. */
2372 searchengines_file = g_strdup_printf(SEARCHENGINES_STORAGE_FILENAME);
2373 switch (read_searchengines(searchengines_file)) {
2374 case SYNTAX_ERROR:
2375 a.i = Error;
2376 a.s = g_strdup_printf("Syntax error in searchengines file '%s'", searchengines_file);
2377 echo(&a);
2378 break;
2379 case READING_FAILED:
2380 a.i = Error;
2381 a.s = g_strdup_printf("Could not read searchengines file '%s'", searchengines_file);
2382 echo(&a);
2383 break;
2384 default:
2385 break;
2387 g_free(searchengines_file);
2389 /* command line argument: URL */
2390 if (argc > 1) {
2391 strncpy(url, argv[argc - 1], 255);
2392 } else {
2393 strncpy(url, startpage, 255);
2396 a.i = TargetCurrent;
2397 a.s = url;
2398 open_arg(&a);
2399 gtk_main();
2401 mop_up();
2403 return EXIT_SUCCESS;