Remove feedback for toggled proxy.
[vimprobable2.git] / main.c
blobfd9f619ba120704ba84be3027014ae82694dbbf7
1 /*
2 (c) 2009 by Leon Winter
3 (c) 2009-2012 by Hannes Schueller
4 (c) 2009-2010 by Matto Fransen
5 (c) 2010-2011 by Hans-Peter Deifel
6 (c) 2010-2011 by Thomas Adam
7 (c) 2011 by Albert Kim
8 (c) 2011 by Daniel Carl
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);
51 static gboolean blank_cb(void);
53 /* functions */
54 static gboolean bookmark(const Arg *arg);
55 static gboolean browser_settings(const Arg *arg);
56 static gboolean commandhistoryfetch(const Arg *arg);
57 static gboolean complete(const Arg *arg);
58 static gboolean descend(const Arg *arg);
59 gboolean echo(const Arg *arg);
60 static gboolean focus_input(const Arg *arg);
61 static gboolean input(const Arg *arg);
62 static gboolean navigate(const Arg *arg);
63 static gboolean number(const Arg *arg);
64 static gboolean open_arg(const Arg *arg);
65 static gboolean open_remembered(const Arg *arg);
66 static gboolean paste(const Arg *arg);
67 static gboolean quickmark(const Arg *arg);
68 static gboolean quit(const Arg *arg);
69 static gboolean revive(const Arg *arg);
70 static gboolean print_frame(const Arg *arg);
71 static gboolean search(const Arg *arg);
72 static gboolean set(const Arg *arg);
73 static gboolean script(const Arg *arg);
74 static gboolean scroll(const Arg *arg);
75 static gboolean search_tag(const Arg *arg);
76 static gboolean yank(const Arg *arg);
77 static gboolean view_source(const Arg * arg);
78 static gboolean zoom(const Arg *arg);
79 static gboolean fake_key_event(const Arg *arg);
81 static void update_url(const char *uri);
82 static void setup_modkeys(void);
83 static void setup_gui(void);
84 static void setup_settings(void);
85 static void setup_signals(void);
86 static void ascii_bar(int total, int state, char *string);
87 static gchar *jsapi_ref_to_string(JSContextRef context, JSValueRef ref);
88 static void jsapi_evaluate_script(const gchar *script, gchar **value, gchar **message);
89 static void download_progress(WebKitDownload *d, GParamSpec *pspec);
90 static void set_widget_font_and_color(GtkWidget *widget, const char *font_str,
91 const char *bg_color_str, const char *fg_color_str);
93 static gboolean history(void);
94 static gboolean process_set_line(char *line);
95 void save_command_history(char *line);
96 void toggle_proxy(gboolean onoff);
97 void toggle_scrollbars(gboolean onoff);
99 gboolean process_keypress(GdkEventKey *event);
100 void fill_suggline(char * suggline, const char * command, const char *fill_with);
101 GtkWidget * fill_eventbox(const char * completion_line);
102 static void mop_up(void);
104 #include "main.h"
106 /* variables */
107 static GtkWindow *window;
108 static GtkWidget *viewport;
109 static GtkBox *box;
110 static GtkScrollbar *scroll_h;
111 static GtkScrollbar *scroll_v;
112 static GtkAdjustment *adjust_h;
113 static GtkAdjustment *adjust_v;
114 static GtkWidget *inputbox;
115 static GtkWidget *eventbox;
116 static GtkBox *statusbar;
117 static GtkWidget *status_url;
118 static GtkWidget *status_state;
119 static WebKitWebView *webview;
120 static SoupSession *session;
121 static GtkClipboard *clipboards[2];
122 static GdkKeymap *keymap;
124 static char **args;
125 static unsigned int mode = ModeNormal;
126 static unsigned int count = 0;
127 static float zoomstep;
128 char *modkeys;
129 static char current_modkey;
130 static char *search_handle;
131 static gboolean search_direction;
132 static gboolean echo_active = TRUE;
133 WebKitWebInspector *inspector;
135 static GdkNativeWindow embed = 0;
136 static char *configfile = NULL;
137 static char *winid = NULL;
139 static char rememberedURI[1024] = "";
140 static char followTarget[8] = "";
141 char *error_msg = NULL;
142 char *config_base = NULL;
144 GList *activeDownloads;
146 #include "config.h"
147 #include "keymap.h"
149 GList *commandhistory = NULL;
150 int commandpointer = 0;
152 KeyList *keylistroot = NULL;
154 /* Cookie support. */
155 #ifdef ENABLE_COOKIE_SUPPORT
156 static SoupCookieJar *session_cookie_jar = NULL;
157 static SoupCookieJar *file_cookie_jar = NULL;
158 static time_t cookie_timeout = 4800;
159 static char *cookie_store;
160 static void setup_cookies(void);
161 static char *get_cookies(SoupURI *soup_uri);
162 static void load_all_cookies(void);
163 static void new_generic_request(SoupSession *soup_ses, SoupMessage *soup_msg, gpointer unused);
164 static void update_cookie_jar(SoupCookieJar *jar, SoupCookie *old, SoupCookie *new);
165 static void handle_cookie_request(SoupMessage *soup_msg, gpointer unused);
166 #endif
167 /* callbacks */
168 void
169 window_destroyed_cb(GtkWidget *window, gpointer func_data) {
170 quit(NULL);
173 void
174 webview_title_changed_cb(WebKitWebView *webview, WebKitWebFrame *frame, char *title, gpointer user_data) {
175 gtk_window_set_title(window, title);
178 void
179 webview_progress_changed_cb(WebKitWebView *webview, int progress, gpointer user_data) {
180 #ifdef ENABLE_GTK_PROGRESS_BAR
181 gtk_entry_set_progress_fraction(GTK_ENTRY(inputbox), progress == 100 ? 0 : (double)progress/100);
182 #endif
183 update_state();
186 #ifdef ENABLE_WGET_PROGRESS_BAR
187 void
188 ascii_bar(int total, int state, char *string) {
189 int i;
191 for (i = 0; i < state; i++)
192 string[i] = progressbartickchar;
193 string[i++] = progressbarcurrent;
194 for (; i < total; i++)
195 string[i] = progressbarspacer;
196 string[i] = '\0';
198 #endif
200 void
201 webview_load_committed_cb(WebKitWebView *webview, WebKitWebFrame *frame, gpointer user_data) {
202 Arg a = { .i = Silent, .s = g_strdup(JS_SETUP_HINTS) };
203 const char *uri = webkit_web_view_get_uri(webview);
205 update_url(uri);
206 script(&a);
207 g_free(a.s);
209 if (mode == ModeInsert) {
210 Arg a = { .i = ModeNormal };
211 set(&a);
215 void
216 webview_load_finished_cb(WebKitWebView *webview, WebKitWebFrame *frame, gpointer user_data) {
217 if (HISTORY_MAX_ENTRIES > 0)
218 history();
219 update_state();
222 static gboolean
223 webview_open_in_new_window_cb(WebKitWebView *webview, WebKitWebFrame *frame, gpointer user_data) {
224 Arg a = { .i = TargetNew, .s = (char*)webkit_web_view_get_uri(webview) };
225 if (strlen(rememberedURI) > 0) {
226 a.s = rememberedURI;
228 open_arg(&a);
229 return FALSE;
232 gboolean
233 webview_new_window_cb(WebKitWebView *webview, WebKitWebFrame *frame, WebKitNetworkRequest *request,
234 WebKitWebNavigationAction *action, WebKitWebPolicyDecision *decision, gpointer user_data) {
235 Arg a = { .i = TargetNew, .s = (char*)webkit_network_request_get_uri(request) };
236 open_arg(&a);
237 webkit_web_policy_decision_ignore(decision);
238 return TRUE;
241 gboolean
242 webview_mimetype_cb(WebKitWebView *webview, WebKitWebFrame *frame, WebKitNetworkRequest *request,
243 char *mime_type, WebKitWebPolicyDecision *decision, gpointer user_data) {
244 if (webkit_web_view_can_show_mime_type(webview, mime_type) == FALSE) {
245 webkit_web_policy_decision_download(decision);
246 return TRUE;
247 } else {
248 return FALSE;
252 static WebKitWebView*
253 inspector_inspect_web_view_cb(gpointer inspector, WebKitWebView* web_view) {
254 gchar* inspector_title;
255 GtkWidget* inspector_window;
256 GtkWidget* inspector_view;
258 /* just enough code to show the inspector - no signal handling etc. */
259 inspector_title = g_strdup_printf("Inspect page - %s - Vimprobable2", webkit_web_view_get_uri(web_view));
260 if (embed) {
261 inspector_window = gtk_plug_new(embed);
262 } else {
263 inspector_window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
264 gtk_window_set_wmclass(window, "vimprobable2", "Vimprobable2");
266 gtk_window_set_title(GTK_WINDOW(inspector_window), inspector_title);
267 g_free(inspector_title);
268 inspector_view = webkit_web_view_new();
269 gtk_container_add(GTK_CONTAINER(inspector_window), inspector_view);
270 gtk_widget_show_all(inspector_window);
271 return WEBKIT_WEB_VIEW(inspector_view);
274 gboolean
275 webview_download_cb(WebKitWebView *webview, WebKitDownload *download, gpointer user_data) {
276 const gchar *filename;
277 gchar *uri, *path;
278 uint32_t size;
279 Arg a;
280 WebKitDownloadStatus status;
282 filename = webkit_download_get_suggested_filename(download);
283 if (filename == NULL || strlen(filename) == 0) {
284 filename = "vimprobable_download";
286 path = g_build_filename(g_strdup_printf(DOWNLOADS_PATH), filename, NULL);
287 uri = g_strconcat("file://", path, NULL);
288 webkit_download_set_destination_uri(download, uri);
289 g_free(uri);
290 size = (uint32_t)webkit_download_get_total_size(download);
291 a.i = Info;
292 if (size > 0)
293 a.s = g_strdup_printf("Download %s started (expected size: %u bytes)...", filename, size);
294 else
295 a.s = g_strdup_printf("Download %s started (unknown size)...", filename);
296 echo(&a);
297 g_free(a.s);
298 activeDownloads = g_list_prepend(activeDownloads, download);
299 g_signal_connect(download, "notify::progress", G_CALLBACK(download_progress), NULL);
300 g_signal_connect(download, "notify::status", G_CALLBACK(download_progress), NULL);
301 status = webkit_download_get_status(download);
302 if (status == WEBKIT_DOWNLOAD_STATUS_CREATED)
303 webkit_download_start(download);
304 update_state();
305 return TRUE;
308 gboolean
309 blank_cb(void) {
310 return TRUE;
313 void
314 download_progress(WebKitDownload *d, GParamSpec *pspec) {
315 Arg a;
316 WebKitDownloadStatus status = webkit_download_get_status(d);
318 if (status != WEBKIT_DOWNLOAD_STATUS_STARTED && status != WEBKIT_DOWNLOAD_STATUS_CREATED) {
319 if (status != WEBKIT_DOWNLOAD_STATUS_FINISHED) {
320 a.i = Error;
321 a.s = g_strdup_printf("Error while downloading %s", webkit_download_get_suggested_filename(d));
322 echo(&a);
323 } else {
324 a.i = Info;
325 a.s = g_strdup_printf("Download %s finished", webkit_download_get_suggested_filename(d));
326 echo(&a);
328 g_free(a.s);
329 activeDownloads = g_list_remove(activeDownloads, d);
331 update_state();
335 gboolean
336 process_keypress(GdkEventKey *event) {
337 KeyList *current;
338 guint keyval;
339 GdkModifierType irrelevant;
341 /* Get a mask of modifiers that shouldn't be considered for this event.
342 * E.g.: It shouldn't matter whether ';' is shifted or not. */
343 gdk_keymap_translate_keyboard_state(keymap, event->hardware_keycode,
344 event->state, event->group, &keyval, NULL, NULL, &irrelevant);
346 current = keylistroot;
348 while (current != NULL) {
349 if (current->Element.mask == (CLEAN(event->state) & ~irrelevant)
350 && (current->Element.modkey == current_modkey
351 || (!current->Element.modkey && !current_modkey)
352 || current->Element.modkey == GDK_VoidSymbol ) /* wildcard */
353 && current->Element.key == keyval
354 && current->Element.func)
355 if (current->Element.func(&current->Element.arg)) {
356 current_modkey = count = 0;
357 update_state();
358 return TRUE;
360 current = current->next;
362 return FALSE;
365 gboolean
366 webview_keypress_cb(WebKitWebView *webview, GdkEventKey *event) {
367 Arg a = { .i = ModeNormal, .s = NULL };
368 guint keyval;
369 GdkModifierType irrelevant;
371 /* Get a mask of modifiers that shouldn't be considered for this event.
372 * E.g.: It shouldn't matter whether ';' is shifted or not. */
373 gdk_keymap_translate_keyboard_state(keymap, event->hardware_keycode,
374 event->state, event->group, &keyval, NULL, NULL, &irrelevant);
376 switch (mode) {
377 case ModeNormal:
378 if ((CLEAN(event->state) & ~irrelevant) == 0) {
379 if (IS_ESCAPE(event)) {
380 a.i = Info;
381 a.s = g_strdup("");
382 echo(&a);
383 g_free(a.s);
384 } else if (current_modkey == 0 && ((event->keyval >= GDK_1 && event->keyval <= GDK_9)
385 || (event->keyval == GDK_0 && count))) {
386 count = (count ? count * 10 : 0) + (event->keyval - GDK_0);
387 update_state();
388 return TRUE;
389 } else if (strchr(modkeys, event->keyval) && current_modkey != event->keyval) {
390 current_modkey = event->keyval;
391 update_state();
392 return TRUE;
395 /* keybindings */
396 if (process_keypress(event) == TRUE) return TRUE;
398 break;
399 case ModeInsert:
400 if (IS_ESCAPE(event)) {
401 a.i = Silent;
402 a.s = g_strdup("hints.clearFocus();");
403 script(&a);
404 g_free(a.s);
405 a.i = ModeNormal;
406 return set(&a);
408 case ModePassThrough:
409 if (IS_ESCAPE(event)) {
410 echo(&a);
411 set(&a);
412 return TRUE;
414 break;
415 case ModeSendKey:
416 echo(&a);
417 set(&a);
418 break;
420 return FALSE;
423 void
424 set_widget_font_and_color(GtkWidget *widget, const char *font_str, const char *bg_color_str,
425 const char *fg_color_str) {
426 GdkColor fg_color;
427 GdkColor bg_color;
428 PangoFontDescription *font;
430 font = pango_font_description_from_string(font_str);
431 gtk_widget_modify_font(widget, font);
432 pango_font_description_free(font);
434 if (fg_color_str)
435 gdk_color_parse(fg_color_str, &fg_color);
436 if (bg_color_str)
437 gdk_color_parse(bg_color_str, &bg_color);
439 gtk_widget_modify_text(widget, GTK_STATE_NORMAL, fg_color_str ? &fg_color : NULL);
440 gtk_widget_modify_base(widget, GTK_STATE_NORMAL, bg_color_str ? &bg_color : NULL);
442 return;
445 void
446 webview_hoverlink_cb(WebKitWebView *webview, char *title, char *link, gpointer data) {
447 const char *uri = webkit_web_view_get_uri(webview);
448 char *markup;
450 memset(rememberedURI, 0, 1024);
451 if (link) {
452 markup = g_markup_printf_escaped("<span font=\"%s\">Link: %s</span>", statusfont, link);
453 gtk_label_set_markup(GTK_LABEL(status_url), markup);
454 strncpy(rememberedURI, link, 1024);
455 g_free(markup);
456 } else
457 update_url(uri);
460 gboolean
461 webview_console_cb(WebKitWebView *webview, char *message, int line, char *source, gpointer user_data) {
462 Arg a;
464 /* Don't change internal mode if the browser doesn't have focus to prevent inconsistent states */
465 if (gtk_window_has_toplevel_focus(window)) {
466 if (!strcmp(message, "hintmode_off") || !strcmp(message, "insertmode_off")) {
467 a.i = ModeNormal;
468 return set(&a);
469 } else if (!strcmp(message, "insertmode_on")) {
470 a.i = ModeInsert;
471 return set(&a);
474 return FALSE;
477 void
478 inputbox_activate_cb(GtkEntry *entry, gpointer user_data) {
479 char *text;
480 guint16 length = gtk_entry_get_text_length(entry);
481 Arg a;
482 gboolean success = FALSE, forward = FALSE;
484 a.i = HideCompletion;
485 complete(&a);
486 if (length == 0)
487 return;
488 text = (char*)gtk_entry_get_text(entry);
489 if (length > 1 && text[0] == ':') {
490 success = process_line((text + 1));
491 } else if (length > 1 && ((forward = text[0] == '/') || text[0] == '?')) {
492 webkit_web_view_unmark_text_matches(webview);
493 #ifdef ENABLE_MATCH_HIGHLITING
494 webkit_web_view_mark_text_matches(webview, &text[1], FALSE, 0);
495 webkit_web_view_set_highlight_text_matches(webview, TRUE);
496 #endif
497 count = 0;
498 #ifndef ENABLE_INCREMENTAL_SEARCH
499 a.s =& text[1];
500 a.i = searchoptions | (forward ? DirectionForward : DirectionBackwards);
501 search(&a);
502 #else
503 search_direction = forward;
504 search_handle = g_strdup(&text[1]);
505 #endif
506 } else if (text[0] == '.' || text[0] == ',' || text[0] == ';') {
507 a.i = Silent;
508 a.s = g_strdup_printf("hints.fire();");
509 script(&a);
510 g_free(a.s);
511 update_state();
512 } else
513 return;
514 if (!echo_active)
515 gtk_entry_set_text(entry, "");
516 gtk_widget_grab_focus(GTK_WIDGET(webview));
519 gboolean
520 inputbox_keypress_cb(GtkEntry *entry, GdkEventKey *event) {
521 Arg a;
522 int numval;
524 if (mode == ModeHints) {
525 if (event->keyval == GDK_Tab) {
526 a.i = Silent;
527 a.s = g_strdup_printf("hints.focusNextHint();");
528 script(&a);
529 g_free(a.s);
530 update_state();
531 return TRUE;
533 if (event->keyval == GDK_ISO_Left_Tab) {
534 a.i = Silent;
535 a.s = g_strdup_printf("hints.focusPreviousHint();");
536 script(&a);
537 g_free(a.s);
538 update_state();
539 return TRUE;
541 if (event->keyval == GDK_Return) {
542 a.i = Silent;
543 a.s = g_strdup_printf("hints.fire();");
544 script(&a);
545 g_free(a.s);
546 update_state();
547 return TRUE;
550 switch (event->keyval) {
551 case GDK_bracketleft:
552 case GDK_Escape:
553 if (!IS_ESCAPE(event)) break;
554 a.i = HideCompletion;
555 complete(&a);
556 a.i = ModeNormal;
557 commandpointer = 0;
558 return set(&a);
559 break;
560 case GDK_Tab:
561 a.i = DirectionNext;
562 return complete(&a);
563 break;
564 case GDK_Up:
565 a.i = DirectionPrev;
566 return commandhistoryfetch(&a);
567 break;
568 case GDK_Down:
569 a.i = DirectionNext;
570 return commandhistoryfetch(&a);
571 break;
572 case GDK_ISO_Left_Tab:
573 a.i = DirectionPrev;
574 return complete(&a);
575 break;
578 if (mode == ModeHints) {
579 if ((CLEAN(event->state) & GDK_SHIFT_MASK) &&
580 (CLEAN(event->state) & GDK_CONTROL_MASK) &&
581 (event->keyval == GDK_BackSpace)) {
582 count /= 10;
583 a.i = Silent;
584 a.s = g_strdup_printf("hints.updateHints(%d);", count);
585 script(&a);
586 g_free(a.s);
587 update_state();
588 return TRUE;
591 numval = g_unichar_digit_value((gunichar) gdk_keyval_to_unicode(event->keyval));
592 if ((numval >= 1 && numval <= 9) || (numval == 0 && count)) {
593 /* allow a zero as non-first number */
594 count = (count ? count * 10 : 0) + numval;
595 a.i = Silent;
596 a.s = g_strdup_printf("hints.updateHints(%d);", count);
597 script(&a);
598 g_free(a.s);
599 update_state();
600 return TRUE;
604 return FALSE;
607 gboolean
608 notify_event_cb(GtkWidget *widget, GdkEvent *event, gpointer user_data) {
609 int i;
610 WebKitHitTestResult *result;
611 WebKitHitTestResultContext context;
612 if (mode == ModeNormal && event->type == GDK_BUTTON_RELEASE) {
613 /* handle mouse click events */
614 for (i = 0; i < LENGTH(mouse); i++) {
615 if (mouse[i].mask == CLEAN(event->button.state)
616 && (mouse[i].modkey == current_modkey
617 || (!mouse[i].modkey && !current_modkey)
618 || mouse[i].modkey == GDK_VoidSymbol) /* wildcard */
619 && mouse[i].button == event->button.button
620 && mouse[i].func) {
621 if (mouse[i].func(&mouse[i].arg)) {
622 current_modkey = count = 0;
623 update_state();
624 return TRUE;
628 result = webkit_web_view_get_hit_test_result(WEBKIT_WEB_VIEW(widget), (GdkEventButton*)event);
629 g_object_get(result, "context", &context, NULL);
630 if (context & WEBKIT_HIT_TEST_RESULT_CONTEXT_EDITABLE) {
631 Arg a = { .i = ModeInsert };
632 set(&a);
634 } else if (mode == ModeInsert && event->type == GDK_BUTTON_RELEASE) {
635 result = webkit_web_view_get_hit_test_result(WEBKIT_WEB_VIEW(widget), (GdkEventButton*)event);
636 g_object_get(result, "context", &context, NULL);
637 if (!(context & WEBKIT_HIT_TEST_RESULT_CONTEXT_EDITABLE)) {
638 Arg a = { .i = ModeNormal };
639 set(&a);
642 return FALSE;
645 static gboolean inputbox_keyrelease_cb(GtkEntry *entry, GdkEventKey *event) {
646 Arg a;
647 guint16 length = gtk_entry_get_text_length(entry);
649 if (!length) {
650 a.i = HideCompletion;
651 complete(&a);
652 a.i = ModeNormal;
653 return set(&a);
655 return FALSE;
658 static gboolean inputbox_changed_cb(GtkEditable *entry, gpointer user_data) {
659 Arg a;
660 char *text = (char*)gtk_entry_get_text(GTK_ENTRY(entry));
661 guint16 length = gtk_entry_get_text_length(GTK_ENTRY(entry));
662 gboolean forward = FALSE;
664 /* Update incremental search if the user changes the search text.
666 * Note: gtk_widget_is_focus() is a poor way to check if the change comes
667 * from the user. But if the entry is focused and the text is set
668 * through gtk_entry_set_text() in some asyncrounous operation,
669 * I would consider that a bug.
672 if (gtk_widget_is_focus(GTK_WIDGET(entry)) && length > 1 && ((forward = text[0] == '/') || text[0] == '?')) {
673 webkit_web_view_unmark_text_matches(webview);
674 webkit_web_view_search_text(webview, &text[1], searchoptions & CaseSensitive, forward, searchoptions & Wrapping);
675 return TRUE;
676 } else if (gtk_widget_is_focus(GTK_WIDGET(entry)) && length >= 1 &&
677 (text[0] == '.' || text[0] == ',' || text[0] == ';')) {
678 a.i = Silent;
679 switch (text[0]) {
680 case '.':
681 a.s = g_strconcat("hints.createHints('", text + 1, "', 'f');", NULL);
682 break;
684 case ',':
685 a.s = g_strconcat("hints.createHints('", text + 1, "', 'F');", NULL);
686 break;
688 case ';':
689 a.s = NULL;
690 switch (text[1]) {
691 case 's':
692 a.s = g_strconcat("hints.createHints('", text + 2, "', 's');", NULL);
693 break;
694 case 'y':
695 a.s = g_strconcat("hints.createHints('", text + 2, "', 'y');", NULL);
696 break;
697 case 'o':
698 a.s = g_strconcat("hints.createHints('", text + 2, "', 'f');", NULL);
699 break;
700 case 't': case 'w':
701 a.s = g_strconcat("hints.createHints('", text + 2, "', 'F');", NULL);
702 break;
703 case 'O': case 'T': case 'W':
704 a.s = g_strconcat("hints.createHints('", text + 2, "', 'O');", NULL);
705 break;
706 case 'i':
707 a.s = g_strconcat("hints.createHints('", text + 2, "', 'i');", NULL);
708 break;
709 case 'I':
710 a.s = g_strconcat("hints.createHints('", text + 2, "', 'I');", NULL);
711 break;
713 break;
715 count = 0;
716 if (a.s) {
717 script(&a);
718 g_free(a.s);
721 return TRUE;
722 } else if (length == 0 && followTarget[0]) {
723 mode = ModeNormal;
724 a.i = Silent;
725 a.s = g_strdup("hints.clearHints();");
726 script(&a);
727 g_free(a.s);
728 count = 0;
729 update_state();
732 return FALSE;
735 /* funcs here */
737 void fill_suggline(char * suggline, const char * command, const char *fill_with) {
738 memset(suggline, 0, 512);
739 strncpy(suggline, command, 512);
740 strncat(suggline, " ", 1);
741 strncat(suggline, fill_with, 512 - strlen(suggline) - 1);
744 GtkWidget * fill_eventbox(const char * completion_line) {
745 GtkBox * row;
746 GtkWidget *row_eventbox, *el;
747 GdkColor color;
748 char *markup, *markup_tmp;
750 row = GTK_BOX(gtk_hbox_new(FALSE, 0));
751 row_eventbox = gtk_event_box_new();
752 gdk_color_parse(completionbgcolor[0], &color);
753 gtk_widget_modify_bg(row_eventbox, GTK_STATE_NORMAL, &color);
754 el = gtk_label_new(NULL);
755 markup_tmp = g_markup_escape_text(completion_line, strlen(completion_line));
756 markup = g_strconcat("<span font=\"", completionfont[0], "\" color=\"", completioncolor[0], "\">",
757 markup_tmp, "</span>", NULL);
758 gtk_label_set_markup(GTK_LABEL(el), markup);
759 g_free(markup_tmp);
760 g_free(markup);
761 gtk_misc_set_alignment(GTK_MISC(el), 0, 0);
762 gtk_box_pack_start(row, el, TRUE, TRUE, 2);
763 gtk_container_add(GTK_CONTAINER(row_eventbox), GTK_WIDGET(row));
764 return row_eventbox;
767 gboolean
768 complete(const Arg *arg) {
769 char *str, *p, *s, *markup, *entry, *searchfor, command[32] = "", suggline[512] = "", **suggurls;
770 size_t listlen, len, cmdlen;
771 int i, spacepos;
772 Listelement *elementlist = NULL, *elementpointer;
773 gboolean highlight = FALSE;
774 GtkBox *row;
775 GtkWidget *row_eventbox, *el;
776 GtkBox *_table;
777 GdkColor color;
778 static GtkWidget *table, *top_border;
779 static char *prefix;
780 static char **suggestions;
781 static GtkWidget **widgets;
782 static int n = 0, m, current = -1;
784 str = (char*)gtk_entry_get_text(GTK_ENTRY(inputbox));
785 len = strlen(str);
787 /* Get the length of the list of commands for completion. We need this to
788 * malloc/realloc correctly.
790 listlen = LENGTH(commands);
792 if ((len == 0 || str[0] != ':') && arg->i != HideCompletion)
793 return TRUE;
794 if (prefix) {
795 if (arg->i != HideCompletion && widgets && current != -1 && !strcmp(&str[1], suggestions[current])) {
796 gdk_color_parse(completionbgcolor[0], &color);
797 gtk_widget_modify_bg(widgets[current], GTK_STATE_NORMAL, &color);
798 current = (n + current + (arg->i == DirectionPrev ? -1 : 1)) % n;
799 if ((arg->i == DirectionNext && current == 0)
800 || (arg->i == DirectionPrev && current == n - 1))
801 current = -1;
802 } else {
803 free(widgets);
804 free(suggestions);
805 free(prefix);
806 gtk_widget_destroy(GTK_WIDGET(table));
807 gtk_widget_destroy(GTK_WIDGET(top_border));
808 table = NULL;
809 widgets = NULL;
810 suggestions = NULL;
811 prefix = NULL;
812 n = 0;
813 current = -1;
814 if (arg->i == HideCompletion)
815 return TRUE;
817 } else if (arg->i == HideCompletion)
818 return TRUE;
819 if (!widgets) {
820 prefix = g_strdup(str);
821 widgets = malloc(sizeof(GtkWidget*) * listlen);
822 suggestions = malloc(sizeof(char*) * listlen);
823 top_border = gtk_event_box_new();
824 gtk_widget_set_size_request(GTK_WIDGET(top_border), 0, 1);
825 gdk_color_parse(completioncolor[2], &color);
826 gtk_widget_modify_bg(top_border, GTK_STATE_NORMAL, &color);
827 table = gtk_event_box_new();
828 gdk_color_parse(completionbgcolor[0], &color);
829 _table = GTK_BOX(gtk_vbox_new(FALSE, 0));
830 highlight = len > 1;
831 if (strchr(str, ' ') == NULL) {
832 /* command completion */
833 listlen = LENGTH(commands);
834 for (i = 0; i < listlen; i++) {
835 if (commands[i].cmd == NULL)
836 break;
837 cmdlen = strlen(commands[i].cmd);
838 if (!highlight || (n < MAX_LIST_SIZE && len - 1 <= cmdlen && !strncmp(&str[1], commands[i].cmd, len - 1))) {
839 p = s = malloc(sizeof(char*) * (highlight ? sizeof(COMPLETION_TAG_OPEN) + sizeof(COMPLETION_TAG_CLOSE) - 1 : 1) + cmdlen);
840 if (highlight) {
841 memcpy(p, COMPLETION_TAG_OPEN, sizeof(COMPLETION_TAG_OPEN) - 1);
842 memcpy((p += sizeof(COMPLETION_TAG_OPEN) - 1), &str[1], len - 1);
843 memcpy((p += len - 1), COMPLETION_TAG_CLOSE, sizeof(COMPLETION_TAG_CLOSE) - 1);
844 p += sizeof(COMPLETION_TAG_CLOSE) - 1;
846 memcpy(p, &commands[i].cmd[len - 1], cmdlen - len + 2);
847 row = GTK_BOX(gtk_hbox_new(FALSE, 0));
848 row_eventbox = gtk_event_box_new();
849 gtk_widget_modify_bg(row_eventbox, GTK_STATE_NORMAL, &color);
850 el = gtk_label_new(NULL);
851 markup = g_strconcat("<span font=\"", completionfont[0], "\" color=\"", completioncolor[0], "\">", s, "</span>", NULL);
852 free(s);
853 gtk_label_set_markup(GTK_LABEL(el), markup);
854 g_free(markup);
855 gtk_misc_set_alignment(GTK_MISC(el), 0, 0);
856 gtk_box_pack_start(row, el, TRUE, TRUE, 2);
857 gtk_container_add(GTK_CONTAINER(row_eventbox), GTK_WIDGET(row));
858 gtk_box_pack_start(_table, GTK_WIDGET(row_eventbox), FALSE, FALSE, 0);
859 suggestions[n] = commands[i].cmd;
860 widgets[n++] = row_eventbox;
863 } else {
864 entry = (char *)malloc(512 * sizeof(char));
865 if (entry == NULL) {
866 return FALSE;
868 memset(entry, 0, 512);
869 suggurls = malloc(sizeof(char*) * listlen);
870 if (suggurls == NULL) {
871 return FALSE;
873 spacepos = strcspn(str, " ");
874 searchfor = (str + spacepos + 1);
875 strncpy(command, (str + 1), spacepos - 1);
876 if (strlen(command) == 3 && strncmp(command, "set", 3) == 0) {
877 /* browser settings */
878 listlen = LENGTH(browsersettings);
879 for (i = 0; i < listlen; i++) {
880 if (n < MAX_LIST_SIZE && strstr(browsersettings[i].name, searchfor) != NULL) {
881 /* match */
882 fill_suggline(suggline, command, browsersettings[i].name);
883 /* FIXME(HP): This memory is never freed */
884 suggurls[n] = (char *)malloc(sizeof(char) * 512 + 1);
885 strncpy(suggurls[n], suggline, 512);
886 suggestions[n] = suggurls[n];
887 row_eventbox = fill_eventbox(suggline);
888 gtk_box_pack_start(_table, GTK_WIDGET(row_eventbox), FALSE, FALSE, 0);
889 widgets[n++] = row_eventbox;
893 } else if (strlen(command) == 2 && strncmp(command, "qt", 2) == 0) {
894 /* completion on tags */
895 spacepos = strcspn(str, " ");
896 searchfor = (str + spacepos + 1);
897 elementlist = complete_list(searchfor, 1, elementlist);
898 } else {
899 /* URL completion: bookmarks */
900 elementlist = complete_list(searchfor, 0, elementlist);
901 m = count_list(elementlist);
902 if (m < MAX_LIST_SIZE) {
903 /* URL completion: history */
904 elementlist = complete_list(searchfor, 2, elementlist);
907 elementpointer = elementlist;
908 while (elementpointer != NULL) {
909 fill_suggline(suggline, command, elementpointer->element);
910 /* FIXME(HP): This memory is never freed */
911 suggurls[n] = (char *)malloc(sizeof(char) * 512 + 1);
912 strncpy(suggurls[n], suggline, 512);
913 suggestions[n] = suggurls[n];
914 row_eventbox = fill_eventbox(suggline);
915 gtk_box_pack_start(_table, GTK_WIDGET(row_eventbox), FALSE, FALSE, 0);
916 widgets[n++] = row_eventbox;
917 elementpointer = elementpointer->next;
918 if (n >= MAX_LIST_SIZE)
919 break;
921 free_list(elementlist);
922 if (suggurls != NULL) {
923 free(suggurls);
924 suggurls = NULL;
926 if (entry != NULL) {
927 free(entry);
928 entry = NULL;
931 /* TA: FIXME - this needs rethinking entirely. */
933 GtkWidget **widgets_temp = realloc(widgets, sizeof(*widgets) * n);
934 if (widgets_temp == NULL && widgets == NULL) {
935 fprintf(stderr, "Couldn't realloc() widgets\n");
936 exit(1);
938 widgets = widgets_temp;
939 char **suggestions_temp = realloc(suggestions, sizeof(*suggestions) * n);
940 if (suggestions_temp == NULL && suggestions == NULL) {
941 fprintf(stderr, "Couldn't realloc() suggestions\n");
942 exit(1);
944 suggestions = suggestions_temp;
946 if (!n) {
947 gdk_color_parse(completionbgcolor[1], &color);
948 gtk_widget_modify_bg(table, GTK_STATE_NORMAL, &color);
949 el = gtk_label_new(NULL);
950 gtk_misc_set_alignment(GTK_MISC(el), 0, 0);
951 markup = g_strconcat("<span font=\"", completionfont[1], "\" color=\"", completioncolor[1], "\">No Completions</span>", NULL);
952 gtk_label_set_markup(GTK_LABEL(el), markup);
953 g_free(markup);
954 gtk_box_pack_start(_table, GTK_WIDGET(el), FALSE, FALSE, 0);
956 gtk_box_pack_start(box, GTK_WIDGET(top_border), FALSE, FALSE, 0);
957 gtk_container_add(GTK_CONTAINER(table), GTK_WIDGET(_table));
958 gtk_box_pack_start(box, GTK_WIDGET(table), FALSE, FALSE, 0);
959 gtk_widget_show_all(GTK_WIDGET(window));
960 if (!n)
961 return TRUE;
962 current = arg->i == DirectionPrev ? n - 1 : 0;
964 if (current != -1) {
965 gdk_color_parse(completionbgcolor[2], &color);
966 gtk_widget_modify_bg(GTK_WIDGET(widgets[current]), GTK_STATE_NORMAL, &color);
967 s = g_strconcat(":", suggestions[current], NULL);
968 gtk_entry_set_text(GTK_ENTRY(inputbox), s);
969 g_free(s);
970 } else
971 gtk_entry_set_text(GTK_ENTRY(inputbox), prefix);
972 gtk_editable_set_position(GTK_EDITABLE(inputbox), -1);
973 return TRUE;
976 gboolean
977 descend(const Arg *arg) {
978 char *source = (char*)webkit_web_view_get_uri(webview), *p = &source[0], *new;
979 int i, len;
980 count = count ? count : 1;
982 if (!source)
983 return TRUE;
984 if (arg->i == Rootdir) {
985 for (i = 0; i < 3; i++) /* get to the third slash */
986 if (!(p = strchr(++p, '/')))
987 return TRUE; /* if we cannot find it quit */
988 } else {
989 len = strlen(source);
990 if (!len) /* if string is empty quit */
991 return TRUE;
992 p = source + len; /* start at the end */
993 if (*(p - 1) == '/') /* /\/$/ is not an additional level */
994 ++count;
995 for (i = 0; i < count; i++)
996 while(*(p--) != '/' || *p == '/') /* count /\/+/ as one slash */
997 if (p == source) /* if we reach the first char pointer quit */
998 return TRUE;
999 ++p; /* since we do p-- in the while, we are pointing at
1000 the char before the slash, so +1 */
1002 len = p - source + 1; /* new length = end - start + 1 */
1003 new = malloc(len + 1);
1004 memcpy(new, source, len);
1005 new[len] = '\0';
1006 webkit_web_view_load_uri(webview, new);
1007 free(new);
1008 return TRUE;
1011 gboolean
1012 echo(const Arg *arg) {
1013 int index = !arg->s ? 0 : arg->i & (~NoAutoHide);
1015 if (index < Info || index > Error)
1016 return TRUE;
1018 set_widget_font_and_color(inputbox, urlboxfont[index], urlboxbgcolor[index], urlboxcolor[index]);
1019 gtk_entry_set_text(GTK_ENTRY(inputbox), !arg->s ? "" : arg->s);
1021 return TRUE;
1024 gboolean
1025 input(const Arg *arg) {
1026 int pos = 0;
1027 count = 0;
1028 const char *url;
1029 int index = Info;
1030 Arg a;
1032 /* if inputbox hidden, show it again */
1033 if (!gtk_widget_get_visible(inputbox))
1034 gtk_widget_set_visible(inputbox, TRUE);
1036 update_state();
1038 /* Set the colour and font back to the default, so that we don't still
1039 * maintain a red colour from a warning from an end of search indicator,
1040 * etc.
1042 set_widget_font_and_color(inputbox, urlboxfont[index], urlboxbgcolor[index], urlboxcolor[index]);
1044 /* to avoid things like :open URL :open URL2 or :open :open URL */
1045 gtk_entry_set_text(GTK_ENTRY(inputbox), "");
1046 gtk_editable_insert_text(GTK_EDITABLE(inputbox), arg->s, -1, &pos);
1047 if (arg->i & InsertCurrentURL && (url = webkit_web_view_get_uri(webview)))
1048 gtk_editable_insert_text(GTK_EDITABLE(inputbox), url, -1, &pos);
1050 gtk_widget_grab_focus(inputbox);
1051 gtk_editable_set_position(GTK_EDITABLE(inputbox), -1);
1053 if (arg->s[0] == '.' || arg->s[0] == ',' || arg->s[0] == ';') {
1054 mode = ModeHints;
1055 memset(followTarget, 0, 8);
1056 strncpy(followTarget, "current", 8);
1057 a.i = Silent;
1058 switch (arg->s[0]) {
1059 case '.':
1060 a.s = g_strdup("hints.createHints('', 'f');");
1061 break;
1063 case ',':
1064 a.s = g_strdup("hints.createHints('', 'F');");
1065 break;
1067 case ';':
1068 a.s = NULL;
1069 if (arg->s[1]) {
1070 switch (arg->s[1]) {
1071 case 's':
1072 a.s = g_strdup("hints.createHints('', 's');");
1073 break;
1074 case 'y':
1075 a.s = g_strdup("hints.createHints('', 'y');");
1076 break;
1077 case 'o':
1078 a.s = g_strdup("hints.createHints('', 'f');");
1079 break;
1080 case 't': case 'w':
1081 a.s = g_strdup("hints.createHints('', 'F');");
1082 break;
1083 case 'O': case 'T': case 'W':
1084 a.s = g_strdup("hints.createHints('', 'O');");
1085 break;
1086 case 'i':
1087 a.s = g_strdup("hints.createHints('', 'i');");
1088 break;
1089 case 'I':
1090 a.s = g_strdup("hints.createHints('', 'I');");
1091 break;
1094 break;
1096 count = 0;
1097 if (a.s) {
1098 script(&a);
1099 g_free(a.s);
1103 return TRUE;
1106 gboolean
1107 navigate(const Arg *arg) {
1108 if (arg->i & NavigationForwardBack)
1109 webkit_web_view_go_back_or_forward(webview, (arg->i == NavigationBack ? -1 : 1) * (count ? count : 1));
1110 else if (arg->i & NavigationReloadActions)
1111 (arg->i == NavigationReload ? webkit_web_view_reload : webkit_web_view_reload_bypass_cache)(webview);
1112 else
1113 webkit_web_view_stop_loading(webview);
1114 return TRUE;
1117 gboolean
1118 number(const Arg *arg) {
1119 const char *source = webkit_web_view_get_uri(webview);
1120 char *uri, *p, *new;
1121 int number, diff = (count ? count : 1) * (arg->i == Increment ? 1 : -1);
1123 if (!source)
1124 return TRUE;
1125 uri = g_strdup(source); /* copy string */
1126 p =& uri[0];
1127 while(*p != '\0') /* goto the end of the string */
1128 ++p;
1129 --p;
1130 while(*p >= '0' && *p <= '9') /* go back until non number char is reached */
1131 --p;
1132 if (*(++p) == '\0') { /* if no numbers were found abort */
1133 free(uri);
1134 return TRUE;
1136 number = atoi(p) + diff; /* apply diff on number */
1137 *p = '\0';
1138 new = g_strdup_printf("%s%d", uri, number); /* create new uri */
1139 webkit_web_view_load_uri(webview, new);
1140 g_free(new);
1141 free(uri);
1142 return TRUE;
1145 gboolean
1146 open_arg(const Arg *arg) {
1147 char *argv[64];
1148 char *s = arg->s, *p = NULL, *new;
1149 Arg a = { .i = NavigationReload };
1150 int len;
1151 char *search_uri, *search_term;
1153 if (embed) {
1154 argv[0] = *args;
1155 argv[1] = "-e";
1156 argv[2] = winid;
1157 argv[3] = arg->s;
1158 argv[4] = NULL;
1159 } else {
1160 argv[0] = *args;
1161 argv[1] = arg->s;
1162 argv[2] = NULL;
1165 if (!arg->s)
1166 navigate(&a);
1167 else if (arg->i == TargetCurrent) {
1168 while(*s == ' ') /* strip leading whitespace */
1169 ++s;
1170 p = (s + strlen(s) - 1);
1171 while(*p == ' ') /* strip trailing whitespace */
1172 --p;
1173 *(p + 1) = '\0';
1174 len = strlen(s);
1175 new = NULL;
1176 /* check for external handlers */
1177 if (open_handler(s))
1178 return TRUE;
1179 /* check for search engines */
1180 p = strchr(s, ' ');
1181 if (p) { /* check for search engines */
1182 *p = '\0';
1183 search_uri = find_uri_for_searchengine(s);
1184 if (search_uri != NULL) {
1185 search_term = soup_uri_encode(p+1, "&");
1186 new = g_strdup_printf(search_uri, search_term);
1187 g_free(search_term);
1189 *p = ' ';
1191 if (!new) {
1192 if (len > 3 && strstr(s, "://")) { /* valid url? */
1193 p = new = g_malloc(len + 1);
1194 while(*s != '\0') { /* strip whitespaces */
1195 if (*s != ' ')
1196 *(p++) = *s;
1197 ++s;
1199 *p = '\0';
1200 } else if (strcspn(s, "/") == 0 || strcspn(s, "./") == 0) { /* prepend "file://" */
1201 new = g_malloc(sizeof("file://") + len);
1202 strcpy(new, "file://");
1203 memcpy(&new[sizeof("file://") - 1], s, len + 1);
1204 } else if (p || !strchr(s, '.')) { /* whitespaces or no dot? */
1205 search_uri = find_uri_for_searchengine(defaultsearch);
1206 if (search_uri != NULL) {
1207 search_term = soup_uri_encode(s, "&");
1208 new = g_strdup_printf(search_uri, search_term);
1209 g_free(search_term);
1211 } else { /* prepend "http://" */
1212 new = g_malloc(sizeof("http://") + len);
1213 strcpy(new, "http://");
1214 memcpy(&new[sizeof("http://") - 1], s, len + 1);
1217 webkit_web_view_load_uri(webview, new);
1218 g_free(new);
1219 } else
1220 g_spawn_async(NULL, argv, NULL, G_SPAWN_SEARCH_PATH, NULL, NULL, NULL, NULL);
1221 return TRUE;
1224 gboolean
1225 open_remembered(const Arg *arg)
1227 Arg a = {arg->i, rememberedURI};
1229 if (strcmp(rememberedURI, "")) {
1230 open_arg(&a);
1232 return TRUE;
1235 gboolean
1236 yank(const Arg *arg) {
1237 const char *url, *feedback, *content;
1239 if (arg->i & SourceSelection) {
1240 webkit_web_view_copy_clipboard(webview);
1241 if (arg->i & ClipboardPrimary)
1242 content = gtk_clipboard_wait_for_text(clipboards[0]);
1243 if (!content && arg->i & ClipboardGTK)
1244 content = gtk_clipboard_wait_for_text(clipboards[1]);
1245 if (content) {
1246 feedback = g_strconcat("Yanked ", content, NULL);
1247 g_free((gpointer *)content);
1248 give_feedback(feedback);
1249 g_free((gpointer *)feedback);
1251 } else {
1252 if (arg->i & SourceURL) {
1253 url = webkit_web_view_get_uri(webview);
1254 } else {
1255 url = arg->s;
1257 if (!url)
1258 return TRUE;
1259 feedback = g_strconcat("Yanked ", url, NULL);
1260 give_feedback(feedback);
1261 if (arg->i & ClipboardPrimary)
1262 gtk_clipboard_set_text(clipboards[0], url, -1);
1263 if (arg->i & ClipboardGTK)
1264 gtk_clipboard_set_text(clipboards[1], url, -1);
1266 return TRUE;
1269 gboolean
1270 paste(const Arg *arg) {
1271 Arg a = { .i = arg->i & TargetNew, .s = NULL };
1273 /* If we're over a link, open it in a new target. */
1274 if (strlen(rememberedURI) > 0) {
1275 Arg new_target = { .i = TargetNew, .s = arg->s };
1276 open_arg(&new_target);
1277 return TRUE;
1280 if (arg->i & ClipboardPrimary)
1281 a.s = gtk_clipboard_wait_for_text(clipboards[0]);
1282 if (!a.s && arg->i & ClipboardGTK)
1283 a.s = gtk_clipboard_wait_for_text(clipboards[1]);
1284 if (a.s) {
1285 open_arg(&a);
1286 g_free(a.s);
1288 return TRUE;
1291 gboolean
1292 quit(const Arg *arg) {
1293 FILE *f;
1294 const char *filename;
1295 const char *uri = webkit_web_view_get_uri(webview);
1296 if (uri != NULL) {
1297 /* write last URL into status file for recreation with "u" */
1298 filename = g_strdup_printf(CLOSED_URL_FILENAME);
1299 f = fopen(filename, "w");
1300 g_free((gpointer *)filename);
1301 if (f != NULL) {
1302 fprintf(f, "%s", uri);
1303 fclose(f);
1306 gtk_main_quit();
1307 return TRUE;
1310 gboolean
1311 revive(const Arg *arg) {
1312 FILE *f;
1313 const char *filename;
1314 char buffer[512] = "";
1315 Arg a = { .i = TargetNew, .s = NULL };
1316 /* get the URL of the window which has been closed last */
1317 filename = g_strdup_printf(CLOSED_URL_FILENAME);
1318 f = fopen(filename, "r");
1319 g_free((gpointer *)filename);
1320 if (f != NULL) {
1321 fgets(buffer, 512, f);
1322 fclose(f);
1324 if (strlen(buffer) > 0) {
1325 a.s = buffer;
1326 open_arg(&a);
1327 return TRUE;
1329 return FALSE;
1332 static
1333 gboolean print_frame(const Arg *arg)
1335 WebKitWebFrame *frame = webkit_web_view_get_main_frame(webview);
1336 webkit_web_frame_print (frame);
1337 return TRUE;
1340 gboolean
1341 search(const Arg *arg) {
1342 count = count ? count : 1;
1343 gboolean success, direction = arg->i & DirectionPrev;
1344 Arg a;
1346 if (arg->s) {
1347 free(search_handle);
1348 search_handle = g_strdup(arg->s);
1350 if (!search_handle)
1351 return TRUE;
1352 if (arg->i & DirectionAbsolute)
1353 search_direction = direction;
1354 else
1355 direction ^= search_direction;
1356 do {
1357 success = webkit_web_view_search_text(webview, search_handle, arg->i & CaseSensitive, direction, FALSE);
1358 if (!success) {
1359 if (arg->i & Wrapping) {
1360 success = webkit_web_view_search_text(webview, search_handle, arg->i & CaseSensitive, direction, TRUE);
1361 if (success) {
1362 a.i = Warning;
1363 a.s = g_strdup_printf("search hit %s, continuing at %s",
1364 direction ? "BOTTOM" : "TOP",
1365 direction ? "TOP" : "BOTTOM");
1366 echo(&a);
1367 g_free(a.s);
1368 } else
1369 break;
1370 } else
1371 break;
1373 } while(--count);
1374 if (!success) {
1375 a.i = Error;
1376 a.s = g_strdup_printf("Pattern not found: %s", search_handle);
1377 echo(&a);
1378 g_free(a.s);
1380 return TRUE;
1383 gboolean
1384 set(const Arg *arg) {
1385 Arg a = { .i = Info | NoAutoHide };
1387 switch (arg->i) {
1388 case ModeNormal:
1389 if (search_handle) {
1390 search_handle = NULL;
1391 webkit_web_view_unmark_text_matches(webview);
1393 gtk_entry_set_text(GTK_ENTRY(inputbox), "");
1394 gtk_widget_grab_focus(GTK_WIDGET(webview));
1395 break;
1396 case ModePassThrough:
1397 a.s = g_strdup("-- PASS THROUGH --");
1398 echo(&a);
1399 g_free(a.s);
1400 break;
1401 case ModeSendKey:
1402 a.s = g_strdup("-- PASS TROUGH (next) --");
1403 echo(&a);
1404 g_free(a.s);
1405 break;
1406 case ModeInsert: /* should not be called manually but automatically */
1407 a.s = g_strdup("-- INSERT --");
1408 echo(&a);
1409 g_free(a.s);
1410 break;
1411 default:
1412 return TRUE;
1414 mode = arg->i;
1415 return TRUE;
1418 gchar*
1419 jsapi_ref_to_string(JSContextRef context, JSValueRef ref) {
1420 JSStringRef string_ref;
1421 gchar *string;
1422 size_t length;
1424 string_ref = JSValueToStringCopy(context, ref, NULL);
1425 length = JSStringGetMaximumUTF8CStringSize(string_ref);
1426 string = g_new(gchar, length);
1427 JSStringGetUTF8CString(string_ref, string, length);
1428 JSStringRelease(string_ref);
1429 return string;
1432 void
1433 jsapi_evaluate_script(const gchar *script, gchar **value, gchar **message) {
1434 WebKitWebFrame *frame = webkit_web_view_get_main_frame(webview);
1435 JSGlobalContextRef context = webkit_web_frame_get_global_context(frame);
1436 JSStringRef str;
1437 JSValueRef val, exception;
1439 str = JSStringCreateWithUTF8CString(script);
1440 val = JSEvaluateScript(context, str, JSContextGetGlobalObject(context), NULL, 0, &exception);
1441 JSStringRelease(str);
1442 if (!val)
1443 *message = jsapi_ref_to_string(context, exception);
1444 else
1445 *value = jsapi_ref_to_string(context, val);
1448 gboolean
1449 quickmark(const Arg *a) {
1450 int i, b;
1451 b = atoi(a->s);
1452 char *fn = g_strdup_printf(QUICKMARK_FILE);
1453 FILE *fp;
1454 fp = fopen(fn, "r");
1455 g_free(fn);
1456 fn = NULL;
1457 char buf[100];
1459 if (fp != NULL && b < 10) {
1460 for( i=0; i < b; ++i ) {
1461 if (feof(fp)) {
1462 break;
1464 fgets(buf, 100, fp);
1466 char *ptr = strrchr(buf, '\n');
1467 *ptr = '\0';
1468 Arg x = { .s = buf };
1469 if (strlen(buf))
1470 return open_arg(&x);
1471 else {
1472 x.i = Error;
1473 x.s = g_strdup_printf("Quickmark %d not defined", b);
1474 echo(&x);
1475 g_free(x.s);
1476 return false;
1478 } else { return false; }
1481 gboolean
1482 script(const Arg *arg) {
1483 gchar *value = NULL, *message = NULL;
1484 char text[1024] = "";
1485 Arg a;
1486 WebKitNetworkRequest *request;
1487 WebKitDownload *download;
1489 if (!arg->s) {
1490 set_error("Missing argument.");
1491 return FALSE;
1493 jsapi_evaluate_script(arg->s, &value, &message);
1494 if (message) {
1495 set_error(message);
1496 g_free(message);
1497 return FALSE;
1499 g_free(message);
1500 if (arg->i != Silent && value) {
1501 a.i = arg->i;
1502 a.s = g_strdup(value);
1503 echo(&a);
1504 g_free(a.s);
1506 /* switch mode according to scripts return value */
1507 if (value) {
1508 if (strncmp(value, "done;", 5) == 0) {
1509 a.i = ModeNormal;
1510 set(&a);
1511 } else if (strncmp(value, "insert;", 7) == 0) {
1512 a.i = ModeInsert;
1513 set(&a);
1514 } else if (strncmp(value, "save;", 5) == 0) {
1515 /* forced download */
1516 a.i = ModeNormal;
1517 set(&a);
1518 request = webkit_network_request_new((value + 5));
1519 download = webkit_download_new(request);
1520 webview_download_cb(webview, download, (gpointer *)NULL);
1521 } else if (strncmp(value, "yank;", 5) == 0) {
1522 /* yank link URL to clipboard */
1523 a.i = ModeNormal;
1524 set(&a);
1525 a.i = ClipboardPrimary | ClipboardGTK;
1526 a.s = (value + 5);
1527 yank(&a);
1528 } else if (strncmp(value, "colon;", 6) == 0) {
1529 /* use link URL for colon command */
1530 strncpy(text, (char *)gtk_entry_get_text(GTK_ENTRY(inputbox)), 1023);
1531 a.i = ModeNormal;
1532 set(&a);
1533 switch (text[1]) {
1534 case 'O':
1535 a.s = g_strconcat(":open ", (value + 6), NULL);
1536 break;
1537 case 'T': case 'W':
1538 a.s = g_strconcat(":tabopen ", (value + 6), NULL);
1539 break;
1541 if (a.s) {
1542 input(&a);
1543 g_free(a.s);
1545 } else if (strncmp(value, "error;", 6) == 0) {
1546 a.i = Error;
1547 set(&a);
1550 g_free(value);
1551 return TRUE;
1554 gboolean
1555 scroll(const Arg *arg) {
1556 GtkAdjustment *adjust = (arg->i & OrientationHoriz) ? adjust_h : adjust_v;
1557 int max = gtk_adjustment_get_upper(adjust) - gtk_adjustment_get_page_size(adjust);
1558 float val = gtk_adjustment_get_value(adjust) / max * 100;
1559 int direction = (arg->i & (1 << 2)) ? 1 : -1;
1561 if ((direction == 1 && val < 100) || (direction == -1 && val > 0)) {
1562 if (arg->i & ScrollMove)
1563 gtk_adjustment_set_value(adjust, gtk_adjustment_get_value(adjust) +
1564 direction * /* direction */
1565 ((arg->i & UnitLine || (arg->i & UnitBuffer && count)) ? (scrollstep * (count ? count : 1)) : (
1566 arg->i & UnitBuffer ? gtk_adjustment_get_page_size(adjust) / 2 :
1567 (count ? count : 1) * (gtk_adjustment_get_page_size(adjust) -
1568 (gtk_adjustment_get_page_size(adjust) > pagingkeep ? pagingkeep : 0)))));
1569 else
1570 gtk_adjustment_set_value(adjust,
1571 ((direction == 1) ? gtk_adjustment_get_upper : gtk_adjustment_get_lower)(adjust));
1572 update_state();
1574 return TRUE;
1577 gboolean
1578 zoom(const Arg *arg) {
1579 webkit_web_view_set_full_content_zoom(webview, (arg->i & ZoomFullContent) > 0);
1580 webkit_web_view_set_zoom_level(webview, (arg->i & ZoomOut) ?
1581 webkit_web_view_get_zoom_level(webview) +
1582 (((float)(count ? count : 1)) * (arg->i & (1 << 1) ? 1.0 : -1.0) * zoomstep) :
1583 (count ? (float)count / 100.0 : 1.0));
1584 return TRUE;
1587 gboolean
1588 fake_key_event(const Arg *a) {
1589 if(!embed) {
1590 return FALSE;
1592 Arg err;
1593 err.i = Error;
1594 Display *xdpy;
1595 if ( (xdpy = XOpenDisplay(NULL)) == NULL ) {
1596 err.s = g_strdup("Couldn't find the XDisplay.");
1597 echo(&err);
1598 g_free(err.s);
1599 return FALSE;
1602 XKeyEvent xk;
1603 xk.display = xdpy;
1604 xk.subwindow = None;
1605 xk.time = CurrentTime;
1606 xk.same_screen = True;
1607 xk.x = xk.y = xk.x_root = xk.y_root = 1;
1608 xk.window = embed;
1609 xk.state = a->i;
1611 if( ! a->s ) {
1612 err.s = g_strdup("Zero pointer as argument! Check your config.h");
1613 echo(&err);
1614 g_free(err.s);
1615 return FALSE;
1618 KeySym keysym;
1619 if( (keysym = XStringToKeysym(a->s)) == NoSymbol ) {
1620 err.s = g_strdup_printf("Couldn't translate %s to keysym", a->s );
1621 echo(&err);
1622 g_free(err.s);
1623 return FALSE;
1626 if( (xk.keycode = XKeysymToKeycode(xdpy, keysym)) == NoSymbol ) {
1627 err.s = g_strdup("Couldn't translate keysym to keycode");
1628 echo(&err);
1629 g_free(err.s);
1630 return FALSE;
1633 xk.type = KeyPress;
1634 if( !XSendEvent(xdpy, embed, True, KeyPressMask, (XEvent *)&xk) ) {
1635 err.s = g_strdup("XSendEvent failed");
1636 echo(&err);
1637 g_free(err.s);
1638 return FALSE;
1640 XFlush(xdpy);
1642 return TRUE;
1646 gboolean
1647 commandhistoryfetch(const Arg *arg) {
1648 const int length = g_list_length(commandhistory);
1650 if (length > 0) {
1651 if (arg->i == DirectionPrev) {
1652 commandpointer = (length + commandpointer - 1) % length;
1653 } else {
1654 commandpointer = (length + commandpointer + 1) % length;
1657 const char* command = (char *)g_list_nth_data(commandhistory, commandpointer);
1658 gtk_entry_set_text(GTK_ENTRY(inputbox), g_strconcat(":", command, NULL));
1659 gtk_editable_set_position(GTK_EDITABLE(inputbox), -1);
1660 return TRUE;
1663 return FALSE;
1666 gboolean
1667 bookmark(const Arg *arg) {
1668 FILE *f;
1669 const char *filename;
1670 const char *uri = webkit_web_view_get_uri(webview);
1671 const char *title = webkit_web_view_get_title(webview);
1672 filename = g_strdup_printf(BOOKMARKS_STORAGE_FILENAME);
1673 f = fopen(filename, "a");
1674 g_free((gpointer *)filename);
1675 if (uri == NULL || strlen(uri) == 0) {
1676 set_error("No URI found to bookmark.");
1677 return FALSE;
1679 if (f != NULL) {
1680 fprintf(f, "%s", uri);
1681 if (title != NULL) {
1682 fprintf(f, "%s", " ");
1683 fprintf(f, "%s", title);
1685 if (arg->s && strlen(arg->s)) {
1686 build_taglist(arg, f);
1688 fprintf(f, "%s", "\n");
1689 fclose(f);
1690 give_feedback( "Bookmark saved" );
1691 return TRUE;
1692 } else {
1693 set_error("Bookmarks file not found.");
1694 return FALSE;
1698 gboolean
1699 history() {
1700 FILE *f;
1701 const char *filename;
1702 const char *uri = webkit_web_view_get_uri(webview);
1703 const char *title = webkit_web_view_get_title(webview);
1704 char *entry, buffer[512], *new;
1705 int n, i = 0;
1706 gboolean finished = FALSE;
1707 if (uri != NULL) {
1708 if (title != NULL) {
1709 entry = malloc((strlen(uri) + strlen(title) + 2) * sizeof(char));
1710 memset(entry, 0, strlen(uri) + strlen(title) + 2);
1711 } else {
1712 entry = malloc((strlen(uri) + 1) * sizeof(char));
1713 memset(entry, 0, strlen(uri) + 1);
1715 if (entry != NULL) {
1716 strncpy(entry, uri, strlen(uri));
1717 if (title != NULL) {
1718 strncat(entry, " ", 1);
1719 strncat(entry, title, strlen(title));
1721 n = strlen(entry);
1722 filename = g_strdup_printf(HISTORY_STORAGE_FILENAME);
1723 f = fopen(filename, "r");
1724 if (f != NULL) {
1725 new = (char *)malloc(HISTORY_MAX_ENTRIES * 512 * sizeof(char) + 1);
1726 if (new != NULL) {
1727 memset(new, 0, HISTORY_MAX_ENTRIES * 512 * sizeof(char) + 1);
1728 /* newest entries go on top */
1729 strncpy(new, entry, strlen(entry));
1730 strncat(new, "\n", 1);
1731 /* retain at most HISTORY_MAX_ENTIRES - 1 old entries */
1732 while (finished != TRUE) {
1733 if ((char *)NULL == fgets(buffer, 512, f)) {
1734 /* check if end of file was reached / error occured */
1735 if (!feof(f)) {
1736 break;
1738 /* end of file reached */
1739 finished = TRUE;
1740 continue;
1742 /* compare line (-1 because of newline character) */
1743 if (n != strlen(buffer) - 1 || strncmp(entry, buffer, n) != 0) {
1744 /* if the URI is already in history; we put it on top and skip it here */
1745 strncat(new, buffer, 512);
1746 i++;
1748 if ((i + 1) >= HISTORY_MAX_ENTRIES) {
1749 break;
1752 fclose(f);
1754 f = fopen(filename, "w");
1755 g_free((gpointer *)filename);
1756 if (f != NULL) {
1757 fprintf(f, "%s", new);
1758 fclose(f);
1760 if (new != NULL) {
1761 free(new);
1762 new = NULL;
1766 if (entry != NULL) {
1767 free(entry);
1768 entry = NULL;
1771 return TRUE;
1774 static gboolean
1775 view_source(const Arg * arg) {
1776 gboolean current_mode = webkit_web_view_get_view_source_mode(webview);
1777 webkit_web_view_set_view_source_mode(webview, !current_mode);
1778 webkit_web_view_reload(webview);
1779 return TRUE;
1782 static gboolean
1783 focus_input(const Arg *arg) {
1784 static Arg a;
1786 a.s = g_strdup("hints.focusInput();");
1787 a.i = Silent;
1788 script(&a);
1789 g_free(a.s);
1790 update_state();
1791 return TRUE;
1794 static gboolean
1795 browser_settings(const Arg *arg) {
1796 char line[255];
1797 if (!arg->s) {
1798 set_error("Missing argument.");
1799 return FALSE;
1801 strncpy(line, arg->s, 254);
1802 if (process_set_line(line))
1803 return TRUE;
1804 else {
1805 set_error("Invalid setting.");
1806 return FALSE;
1810 char *
1811 search_word(int whichword) {
1812 int k = 0;
1813 static char word[240];
1814 char *c = my_pair.line;
1816 while (isspace(*c) && *c)
1817 c++;
1819 switch (whichword) {
1820 case 0:
1821 while (*c && !isspace (*c) && *c != '=' && k < 240) {
1822 word[k++] = *c;
1823 c++;
1825 word[k] = '\0';
1826 strncpy(my_pair.what, word, 20);
1827 break;
1828 case 1:
1829 while (*c && k < 240) {
1830 word[k++] = *c;
1831 c++;
1833 word[k] = '\0';
1834 strncpy(my_pair.value, word, 240);
1835 break;
1838 return c;
1841 static gboolean
1842 process_set_line(char *line) {
1843 char *c;
1844 int listlen, i;
1845 gboolean boolval;
1846 WebKitWebSettings *settings;
1848 settings = webkit_web_view_get_settings(webview);
1849 my_pair.line = line;
1850 c = search_word(0);
1851 if (!strlen(my_pair.what))
1852 return FALSE;
1854 while (isspace(*c) && *c)
1855 c++;
1857 if (*c == ':' || *c == '=')
1858 c++;
1860 my_pair.line = c;
1861 c = search_word(1);
1863 listlen = LENGTH(browsersettings);
1864 for (i = 0; i < listlen; i++) {
1865 if (strlen(browsersettings[i].name) == strlen(my_pair.what) && strncmp(browsersettings[i].name, my_pair.what, strlen(my_pair.what)) == 0) {
1866 /* mandatory argument not provided */
1867 if (strlen(my_pair.value) == 0)
1868 return FALSE;
1869 /* process qmark? */
1870 if (strlen(my_pair.what) == 5 && strncmp("qmark", my_pair.what, 5) == 0) {
1871 return (process_save_qmark(my_pair.value, webview));
1873 /* interpret boolean values */
1874 if (browsersettings[i].boolval) {
1875 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) {
1876 boolval = TRUE;
1877 } 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) {
1878 boolval = FALSE;
1879 } else {
1880 return FALSE;
1882 } else if (browsersettings[i].colourval) {
1883 /* interpret as hexadecimal colour */
1884 if (!parse_colour(my_pair.value)) {
1885 return FALSE;
1888 if (browsersettings[i].var != NULL) {
1889 /* write value into internal variable */
1890 /*if (browsersettings[i].intval) {
1891 browsersettings[i].var = atoi(my_pair.value);
1892 } else {*/
1893 strncpy(browsersettings[i].var, my_pair.value, MAX_SETTING_SIZE);
1894 if (strlen(my_pair.value) > MAX_SETTING_SIZE - 1) {
1895 /* in this case, \0 will not have been copied */
1896 browsersettings[i].var[MAX_SETTING_SIZE - 1] = '\0';
1897 /* in case this string is also used for a webkit setting, make sure it's consistent */
1898 my_pair.value[MAX_SETTING_SIZE - 1] = '\0';
1899 give_feedback("String too long; automatically truncated!");
1901 /*}*/
1903 if (strlen(browsersettings[i].webkit) > 0) {
1904 /* activate appropriate webkit setting */
1905 if (browsersettings[i].boolval) {
1906 g_object_set((GObject*)settings, browsersettings[i].webkit, boolval, NULL);
1907 } else if (browsersettings[i].intval) {
1908 g_object_set((GObject*)settings, browsersettings[i].webkit, atoi(my_pair.value), NULL);
1909 } else {
1910 g_object_set((GObject*)settings, browsersettings[i].webkit, my_pair.value, NULL);
1912 webkit_web_view_set_settings(webview, settings);
1915 if (strlen(my_pair.what) == 14) {
1916 if (strncmp("acceptlanguage", my_pair.what, 14) == 0) {
1917 g_object_set(G_OBJECT(session), "accept-language", acceptlanguage, NULL);
1918 } else if (strncmp("completioncase", my_pair.what, 14) == 0) {
1919 complete_case_sensitive = boolval;
1921 } else if (strlen(my_pair.what) == 5 && strncmp("proxy", my_pair.what, 5) == 0) {
1922 toggle_proxy(boolval);
1923 } else if (strlen(my_pair.what) == 10 && strncmp("scrollbars", my_pair.what, 10) == 0) {
1924 toggle_scrollbars(boolval);
1925 } else if (strlen(my_pair.what) == 9 && strncmp("statusbar", my_pair.what, 9) == 0) {
1926 gtk_widget_set_visible(GTK_WIDGET(statusbar), boolval);
1927 } else if (strlen(my_pair.what) == 8 && strncmp("inputbox", my_pair.what, 8) == 0) {
1928 gtk_widget_set_visible(inputbox, boolval);
1931 /* reload page? */
1932 if (browsersettings[i].reload)
1933 webkit_web_view_reload(webview);
1934 return TRUE;
1937 return FALSE;
1940 gboolean
1941 process_line(char *line) {
1942 char *c = line;
1943 int i;
1944 size_t len, length = strlen(line);
1945 gboolean found = FALSE, success = FALSE;
1946 Arg a;
1948 while (isspace(*c))
1949 c++;
1950 /* Ignore blank lines. */
1951 if (c[0] == '\0')
1952 return TRUE;
1953 for (i = 0; i < LENGTH(commands); i++) {
1954 if (commands[i].cmd == NULL)
1955 break;
1956 len = strlen(commands[i].cmd);
1957 if (length >= len && !strncmp(c, commands[i].cmd, len) && (c[len] == ' ' || !c[len])) {
1958 found = TRUE;
1959 a.i = commands[i].arg.i;
1960 a.s = g_strdup(length > len + 1 ? &c[len + 1] : commands[i].arg.s);
1961 success = commands[i].func(&a);
1962 g_free(a.s);
1963 break;
1966 save_command_history(c);
1967 if (!found) {
1968 a.i = Error;
1969 a.s = g_strdup_printf("Not a browser command: %s", c);
1970 echo(&a);
1971 g_free(a.s);
1972 } else if (!success) {
1973 a.i = Error;
1974 if (error_msg != NULL) {
1975 a.s = g_strdup_printf("%s", error_msg);
1976 g_free(error_msg);
1977 error_msg = NULL;
1978 } else {
1979 a.s = g_strdup_printf("Unknown error. Please file a bug report!");
1981 echo(&a);
1982 g_free(a.s);
1984 return success;
1987 static gboolean
1988 search_tag(const Arg * a) {
1989 FILE *f;
1990 const char *filename;
1991 const char *tag = a->s;
1992 char s[BUFFERSIZE], foundtag[40], url[BUFFERSIZE];
1993 int t, i, intag, k;
1995 if (!tag) {
1996 /* The user must give us something to load up. */
1997 set_error("Bookmark tag required with this option.");
1998 return FALSE;
2001 if (strlen(tag) > MAXTAGSIZE) {
2002 set_error("Tag too long.");
2003 return FALSE;
2006 filename = g_strdup_printf(BOOKMARKS_STORAGE_FILENAME);
2007 f = fopen(filename, "r");
2008 g_free((gpointer *)filename);
2009 if (f == NULL) {
2010 set_error("Couldn't open bookmarks file.");
2011 return FALSE;
2013 while (fgets(s, BUFFERSIZE-1, f)) {
2014 intag = 0;
2015 t = strlen(s) - 1;
2016 while (isspace(s[t]))
2017 t--;
2018 if (s[t] != ']') continue;
2019 while (t > 0) {
2020 if (s[t] == ']') {
2021 if (!intag)
2022 intag = t;
2023 else
2024 intag = 0;
2025 } else {
2026 if (s[t] == '[') {
2027 if (intag) {
2028 i = 0;
2029 k = t + 1;
2030 while (k < intag)
2031 foundtag[i++] = s[k++];
2032 foundtag[i] = '\0';
2033 /* foundtag now contains the tag */
2034 if (strlen(foundtag) < MAXTAGSIZE && strcmp(tag, foundtag) == 0) {
2035 i = 0;
2036 while (isspace(s[i])) i++;
2037 k = 0;
2038 while (s[i] && !isspace(s[i])) url[k++] = s[i++];
2039 url[k] = '\0';
2040 Arg x = { .i = TargetNew, .s = url };
2041 open_arg(&x);
2044 intag = 0;
2047 t--;
2050 return TRUE;
2053 void
2054 toggle_proxy(gboolean onoff) {
2055 SoupURI *proxy_uri;
2056 char *filename, *new;
2057 int len;
2059 if (onoff == FALSE) {
2060 g_object_set(session, "proxy-uri", NULL, NULL);
2061 } else {
2062 filename = (char *)g_getenv("http_proxy");
2064 /* Fallthrough to checking HTTP_PROXY as well, since this can also be
2065 * defined.
2067 if (filename == NULL)
2068 filename = (char *)g_getenv("HTTP_PROXY");
2070 if (filename != NULL && 0 < (len = strlen(filename))) {
2071 if (strstr(filename, "://") == NULL) {
2072 /* prepend http:// */
2073 new = g_malloc(sizeof("http://") + len);
2074 strcpy(new, "http://");
2075 memcpy(&new[sizeof("http://") - 1], filename, len + 1);
2076 proxy_uri = soup_uri_new(new);
2077 g_free(new);
2078 } else {
2079 proxy_uri = soup_uri_new(filename);
2081 g_object_set(session, "proxy-uri", proxy_uri, NULL);
2086 void
2087 toggle_scrollbars(gboolean onoff) {
2088 if (onoff == TRUE) {
2089 adjust_h = gtk_scrolled_window_get_hadjustment(GTK_SCROLLED_WINDOW(viewport));
2090 adjust_v = gtk_scrolled_window_get_vadjustment(GTK_SCROLLED_WINDOW(viewport));
2091 gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(viewport), GTK_POLICY_AUTOMATIC, GTK_POLICY_AUTOMATIC);
2092 } else {
2093 adjust_v = gtk_range_get_adjustment(GTK_RANGE(scroll_v));
2094 adjust_h = gtk_range_get_adjustment(GTK_RANGE(scroll_h));
2095 gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(viewport), GTK_POLICY_NEVER, GTK_POLICY_NEVER);
2097 gtk_widget_set_scroll_adjustments (GTK_WIDGET(webview), adjust_h, adjust_v);
2099 return;
2102 void
2103 update_url(const char *uri) {
2104 gboolean ssl = g_str_has_prefix(uri, "https://");
2105 GdkColor color;
2106 gchar *markup;
2107 #ifdef ENABLE_HISTORY_INDICATOR
2108 char before[] = " [";
2109 char after[] = "]";
2110 gboolean back = webkit_web_view_can_go_back(webview);
2111 gboolean fwd = webkit_web_view_can_go_forward(webview);
2113 if (!back && !fwd)
2114 before[0] = after[0] = '\0';
2115 #endif
2116 markup = g_markup_printf_escaped(
2117 #ifdef ENABLE_HISTORY_INDICATOR
2118 "<span font=\"%s\">%s%s%s%s%s</span>", statusfont, uri,
2119 before, back ? "+" : "", fwd ? "-" : "", after
2120 #else
2121 "<span font=\"%s\">%s</span>", statusfont, uri
2122 #endif
2124 gtk_label_set_markup(GTK_LABEL(status_url), markup);
2125 g_free(markup);
2126 gdk_color_parse(ssl ? sslbgcolor : statusbgcolor, &color);
2127 gtk_widget_modify_bg(eventbox, GTK_STATE_NORMAL, &color);
2128 gdk_color_parse(ssl ? sslcolor : statuscolor, &color);
2129 gtk_widget_modify_fg(GTK_WIDGET(status_url), GTK_STATE_NORMAL, &color);
2130 gtk_widget_modify_fg(GTK_WIDGET(status_state), GTK_STATE_NORMAL, &color);
2133 void
2134 update_state() {
2135 char *markup;
2136 int download_count = g_list_length(activeDownloads);
2137 GString *status = g_string_new("");
2139 /* construct the status line */
2141 /* count, modkey and input buffer */
2142 g_string_append_printf(status, "%.0d", count);
2143 if (current_modkey) g_string_append_c(status, current_modkey);
2145 /* the number of active downloads */
2146 if (activeDownloads) {
2147 g_string_append_printf(status, " %d active %s", download_count,
2148 (download_count == 1) ? "download" : "downloads");
2151 #ifdef ENABLE_WGET_PROGRESS_BAR
2152 /* the progressbar */
2154 int progress = -1;
2155 char progressbar[progressbartick + 1];
2157 if (activeDownloads) {
2158 progress = 0;
2159 GList *ptr;
2161 for (ptr = activeDownloads; ptr; ptr = g_list_next(ptr)) {
2162 progress += 100 * webkit_download_get_progress(ptr->data);
2165 progress /= download_count;
2167 } else if (webkit_web_view_get_load_status(webview) != WEBKIT_LOAD_FINISHED
2168 && webkit_web_view_get_load_status(webview) != WEBKIT_LOAD_FAILED) {
2170 progress = webkit_web_view_get_progress(webview) * 100;
2173 if (progress >= 0) {
2174 ascii_bar(progressbartick, progress * progressbartick / 100, progressbar);
2175 g_string_append_printf(status, " %c%s%c",
2176 progressborderleft, progressbar, progressborderright);
2179 #endif
2181 /* and the current scroll position */
2183 int max = gtk_adjustment_get_upper(adjust_v) - gtk_adjustment_get_page_size(adjust_v);
2184 int val = (int)(gtk_adjustment_get_value(adjust_v) / max * 100);
2186 if (max == 0)
2187 g_string_append(status, " All");
2188 else if (val == 0)
2189 g_string_append(status, " Top");
2190 else if (val == 100)
2191 g_string_append(status, " Bot");
2192 else
2193 g_string_append_printf(status, " %d%%", val);
2197 markup = g_markup_printf_escaped("<span font=\"%s\">%s</span>", statusfont, status->str);
2198 gtk_label_set_markup(GTK_LABEL(status_state), markup);
2199 g_free(markup);
2201 g_string_free(status, TRUE);
2204 void
2205 setup_modkeys() {
2206 unsigned int i;
2207 modkeys = calloc(LENGTH(keys) + 1, sizeof(char));
2208 char *ptr = modkeys;
2210 for (i = 0; i < LENGTH(keys); i++)
2211 if (keys[i].modkey && !strchr(modkeys, keys[i].modkey))
2212 *(ptr++) = keys[i].modkey;
2213 modkeys = realloc(modkeys, &ptr[0] - &modkeys[0] + 1);
2216 void
2217 setup_gui() {
2218 scroll_h = GTK_SCROLLBAR(gtk_hscrollbar_new(NULL));
2219 scroll_v = GTK_SCROLLBAR(gtk_vscrollbar_new(NULL));
2220 adjust_h = gtk_range_get_adjustment(GTK_RANGE(scroll_h));
2221 adjust_v = gtk_range_get_adjustment(GTK_RANGE(scroll_v));
2222 if (embed) {
2223 window = GTK_WINDOW(gtk_plug_new(embed));
2224 } else {
2225 window = GTK_WINDOW(gtk_window_new(GTK_WINDOW_TOPLEVEL));
2226 gtk_window_set_wmclass(GTK_WINDOW(window), "vimprobable2", "Vimprobable2");
2228 gtk_window_set_default_size(GTK_WINDOW(window), 640, 480);
2229 box = GTK_BOX(gtk_vbox_new(FALSE, 0));
2230 inputbox = gtk_entry_new();
2231 webview = (WebKitWebView*)webkit_web_view_new();
2232 statusbar = GTK_BOX(gtk_hbox_new(FALSE, 0));
2233 eventbox = gtk_event_box_new();
2234 status_url = gtk_label_new(NULL);
2235 status_state = gtk_label_new(NULL);
2236 GdkColor bg;
2237 PangoFontDescription *font;
2238 GdkGeometry hints = { 1, 1 };
2239 inspector = webkit_web_view_get_inspector(WEBKIT_WEB_VIEW(webview));
2241 clipboards[0] = gtk_clipboard_get(GDK_SELECTION_PRIMARY);
2242 clipboards[1] = gtk_clipboard_get(GDK_NONE);
2243 setup_settings();
2244 gdk_color_parse(statusbgcolor, &bg);
2245 gtk_widget_modify_bg(eventbox, GTK_STATE_NORMAL, &bg);
2246 gtk_widget_set_name(GTK_WIDGET(window), "Vimprobable2");
2247 gtk_window_set_geometry_hints(window, NULL, &hints, GDK_HINT_MIN_SIZE);
2249 keymap = gdk_keymap_get_default();
2251 #ifdef DISABLE_SCROLLBAR
2252 viewport = gtk_scrolled_window_new(NULL, NULL);
2253 gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(viewport), GTK_POLICY_NEVER, GTK_POLICY_NEVER);
2254 #else
2255 /* Ensure we still see scrollbars. */
2256 GtkWidget *viewport = gtk_scrolled_window_new(adjust_h, adjust_v);
2257 #endif
2259 setup_signals();
2260 gtk_container_add(GTK_CONTAINER(viewport), GTK_WIDGET(webview));
2262 /* Ensure we set the scroll adjustments now, so that if we're not drawing
2263 * titlebars, we can still scroll.
2265 gtk_widget_set_scroll_adjustments(GTK_WIDGET(webview), adjust_h, adjust_v);
2267 font = pango_font_description_from_string(urlboxfont[0]);
2268 gtk_widget_modify_font(GTK_WIDGET(inputbox), font);
2269 pango_font_description_free(font);
2270 gtk_entry_set_inner_border(GTK_ENTRY(inputbox), NULL);
2271 gtk_misc_set_alignment(GTK_MISC(status_url), 0.0, 0.0);
2272 gtk_misc_set_alignment(GTK_MISC(status_state), 1.0, 0.0);
2273 gtk_box_pack_start(statusbar, status_url, TRUE, TRUE, 2);
2274 gtk_box_pack_start(statusbar, status_state, FALSE, FALSE, 2);
2275 gtk_container_add(GTK_CONTAINER(eventbox), GTK_WIDGET(statusbar));
2276 gtk_box_pack_start(box, viewport, TRUE, TRUE, 0);
2277 gtk_box_pack_start(box, eventbox, FALSE, FALSE, 0);
2278 gtk_entry_set_has_frame(GTK_ENTRY(inputbox), FALSE);
2279 gtk_box_pack_end(box, inputbox, FALSE, FALSE, 0);
2280 gtk_container_add(GTK_CONTAINER(window), GTK_WIDGET(box));
2281 gtk_widget_grab_focus(GTK_WIDGET(webview));
2282 gtk_widget_show_all(GTK_WIDGET(window));
2283 set_widget_font_and_color(inputbox, urlboxfont[0], urlboxbgcolor[0], urlboxcolor[0]);
2284 g_object_set(gtk_widget_get_settings(inputbox), "gtk-entry-select-on-focus", FALSE, NULL);
2287 void
2288 setup_settings() {
2289 WebKitWebSettings *settings = (WebKitWebSettings*)webkit_web_settings_new();
2290 char *filename, *file_url;
2292 session = webkit_get_default_session();
2293 g_object_set(G_OBJECT(settings), "default-font-size", DEFAULT_FONT_SIZE, NULL);
2294 g_object_set(G_OBJECT(settings), "enable-scripts", enablePlugins, NULL);
2295 g_object_set(G_OBJECT(settings), "enable-plugins", enablePlugins, NULL);
2296 g_object_set(G_OBJECT(settings), "enable-java-applet", enableJava, NULL);
2297 g_object_set(G_OBJECT(settings), "enable-page-cache", enablePagecache, NULL);
2298 filename = g_strdup_printf(USER_STYLESHEET);
2299 file_url = g_strdup_printf("file://%s", filename);
2300 g_object_set(G_OBJECT(settings), "user-stylesheet-uri", file_url, NULL);
2301 g_free(file_url);
2302 g_free(filename);
2303 g_object_set(G_OBJECT(settings), "user-agent", useragent, NULL);
2304 g_object_get(G_OBJECT(settings), "zoom-step", &zoomstep, NULL);
2305 webkit_web_view_set_settings(webview, settings);
2307 /* proxy */
2308 toggle_proxy(use_proxy);
2311 void
2312 setup_signals() {
2313 WebKitWebFrame *frame = webkit_web_view_get_main_frame(webview);
2314 #ifdef ENABLE_COOKIE_SUPPORT
2315 /* Headers. */
2316 g_signal_connect_after(G_OBJECT(session), "request-started", G_CALLBACK(new_generic_request), NULL);
2317 #endif
2318 /* Accept-language header */
2319 g_object_set(G_OBJECT(session), "accept-language", acceptlanguage, NULL);
2320 /* window */
2321 g_object_connect(G_OBJECT(window),
2322 "signal::destroy", G_CALLBACK(window_destroyed_cb), NULL,
2323 NULL);
2324 /* frame */
2325 g_signal_connect(G_OBJECT(frame),
2326 "scrollbars-policy-changed", G_CALLBACK(blank_cb), NULL);
2327 /* webview */
2328 g_object_connect(G_OBJECT(webview),
2329 "signal::title-changed", G_CALLBACK(webview_title_changed_cb), NULL,
2330 "signal::load-progress-changed", G_CALLBACK(webview_progress_changed_cb), NULL,
2331 "signal::load-committed", G_CALLBACK(webview_load_committed_cb), NULL,
2332 "signal::load-finished", G_CALLBACK(webview_load_finished_cb), NULL,
2333 "signal::navigation-policy-decision-requested", G_CALLBACK(webview_navigation_cb), NULL,
2334 "signal::new-window-policy-decision-requested", G_CALLBACK(webview_new_window_cb), NULL,
2335 "signal::mime-type-policy-decision-requested", G_CALLBACK(webview_mimetype_cb), NULL,
2336 "signal::download-requested", G_CALLBACK(webview_download_cb), NULL,
2337 "signal::key-press-event", G_CALLBACK(webview_keypress_cb), NULL,
2338 "signal::hovering-over-link", G_CALLBACK(webview_hoverlink_cb), NULL,
2339 "signal::console-message", G_CALLBACK(webview_console_cb), NULL,
2340 "signal::create-web-view", G_CALLBACK(webview_open_in_new_window_cb), NULL,
2341 "signal::event", G_CALLBACK(notify_event_cb), NULL,
2342 NULL);
2343 /* webview adjustment */
2344 g_object_connect(G_OBJECT(adjust_v),
2345 "signal::value-changed", G_CALLBACK(webview_scroll_cb), NULL,
2346 NULL);
2347 /* inputbox */
2348 g_object_connect(G_OBJECT(inputbox),
2349 "signal::activate", G_CALLBACK(inputbox_activate_cb), NULL,
2350 "signal::key-press-event", G_CALLBACK(inputbox_keypress_cb), NULL,
2351 "signal::key-release-event", G_CALLBACK(inputbox_keyrelease_cb), NULL,
2352 #ifdef ENABLE_INCREMENTAL_SEARCH
2353 "signal::changed", G_CALLBACK(inputbox_changed_cb), NULL,
2354 #endif
2355 NULL);
2356 /* inspector */
2357 g_signal_connect(G_OBJECT(inspector),
2358 "inspect-web-view", G_CALLBACK(inspector_inspect_web_view_cb), NULL);
2361 #ifdef ENABLE_COOKIE_SUPPORT
2362 void
2363 setup_cookies()
2365 if (file_cookie_jar)
2366 g_object_unref(file_cookie_jar);
2368 if (session_cookie_jar)
2369 g_object_unref(session_cookie_jar);
2371 session_cookie_jar = soup_cookie_jar_new();
2373 cookie_store = g_strdup_printf(COOKIES_STORAGE_FILENAME);
2375 load_all_cookies();
2377 g_signal_connect(G_OBJECT(file_cookie_jar), "changed",
2378 G_CALLBACK(update_cookie_jar), NULL);
2380 return;
2383 /* TA: XXX - we should be using this callback for any header-requests we
2384 * receive (hence the name "new_generic_request" -- but for now, its use
2385 * is limited to handling cookies.
2387 void
2388 new_generic_request(SoupSession *session, SoupMessage *soup_msg, gpointer unused)
2390 SoupMessageHeaders *soup_msg_h;
2391 SoupURI *uri;
2392 char *cookie_str;
2394 soup_msg_h = soup_msg->request_headers;
2395 soup_message_headers_remove(soup_msg_h, "Cookie");
2396 uri = soup_message_get_uri(soup_msg);
2397 if ((cookie_str = get_cookies(uri))) {
2398 soup_message_headers_append(soup_msg_h, "Cookie", cookie_str);
2399 g_free(cookie_str);
2402 g_signal_connect_after(G_OBJECT(soup_msg), "got-headers", G_CALLBACK(handle_cookie_request), NULL);
2404 return;
2407 char *
2408 get_cookies(SoupURI *soup_uri) {
2409 char *cookie_str;
2411 cookie_str = soup_cookie_jar_get_cookies(file_cookie_jar, soup_uri, TRUE);
2413 return cookie_str;
2416 void
2417 handle_cookie_request(SoupMessage *soup_msg, gpointer unused)
2419 GSList *resp_cookie = NULL, *cookie_list;
2420 SoupCookie *cookie;
2422 cookie_list = soup_cookies_from_response(soup_msg);
2423 for(resp_cookie = cookie_list; resp_cookie; resp_cookie = g_slist_next(resp_cookie))
2425 SoupDate *soup_date;
2426 cookie = soup_cookie_copy((SoupCookie *)resp_cookie->data);
2428 if (cookie_timeout && cookie->expires == NULL) {
2429 soup_date = soup_date_new_from_time_t(time(NULL) + cookie_timeout * 10);
2430 soup_cookie_set_expires(cookie, soup_date);
2431 soup_date_free(soup_date);
2433 soup_cookie_jar_add_cookie(file_cookie_jar, cookie);
2436 soup_cookies_free(cookie_list);
2438 return;
2441 void
2442 update_cookie_jar(SoupCookieJar *jar, SoupCookie *old, SoupCookie *new)
2444 if (!new) {
2445 /* Nothing to do. */
2446 return;
2449 SoupCookie *copy;
2450 copy = soup_cookie_copy(new);
2452 soup_cookie_jar_add_cookie(session_cookie_jar, copy);
2454 return;
2457 void
2458 load_all_cookies(void)
2460 GSList *cookie_list;
2461 file_cookie_jar = soup_cookie_jar_text_new(cookie_store, COOKIES_STORAGE_READONLY);
2463 /* Put them back in the session store. */
2464 GSList *cookies_from_file = soup_cookie_jar_all_cookies(file_cookie_jar);
2465 cookie_list = cookies_from_file;
2467 for (; cookies_from_file;
2468 cookies_from_file = cookies_from_file->next)
2470 soup_cookie_jar_add_cookie(session_cookie_jar, cookies_from_file->data);
2473 soup_cookies_free(cookies_from_file);
2474 g_slist_free(cookie_list);
2476 return;
2479 #endif
2481 void
2482 mop_up(void) {
2483 /* Free up any nasty globals before exiting. */
2484 #ifdef ENABLE_COOKIE_SUPPORT
2485 if (cookie_store)
2486 g_free(cookie_store);
2487 #endif
2488 return;
2492 main(int argc, char *argv[]) {
2493 static Arg a;
2494 static char url[256] = "";
2495 static gboolean ver = false;
2496 static gboolean configfile_exists = FALSE;
2497 static const char *cfile = NULL;
2498 static GOptionEntry opts[] = {
2499 { "version", 'v', 0, G_OPTION_ARG_NONE, &ver, "print version", NULL },
2500 { "embed", 'e', 0, G_OPTION_ARG_STRING, &winid, "embedded", NULL },
2501 { "configfile", 'c', 0, G_OPTION_ARG_STRING, &cfile, "config file", NULL },
2502 { NULL }
2504 static GError *err;
2505 args = argv;
2507 /* command line argument: version */
2508 if (!gtk_init_with_args(&argc, &argv, "[<uri>]", opts, NULL, &err)) {
2509 g_printerr("can't init gtk: %s\n", err->message);
2510 g_error_free(err);
2511 return EXIT_FAILURE;
2514 if (ver) {
2515 printf("%s\n", INTERNAL_VERSION);
2516 return EXIT_SUCCESS;
2519 if( getenv("XDG_CONFIG_HOME") )
2520 config_base = g_strdup_printf("%s", getenv("XDG_CONFIG_HOME"));
2521 else
2522 config_base = g_strdup_printf("%s/.config/", getenv("HOME"));
2524 if (cfile)
2525 configfile = g_strdup(cfile);
2526 else
2527 configfile = g_strdup_printf(RCFILE);
2529 if (!g_thread_supported())
2530 g_thread_init(NULL);
2532 if (winid)
2533 embed = atoi(winid);
2535 setup_modkeys();
2536 make_keyslist();
2537 setup_gui();
2538 #ifdef ENABLE_COOKIE_SUPPORT
2539 setup_cookies();
2540 #endif
2542 make_searchengines_list(searchengines, LENGTH(searchengines));
2543 make_uri_handlers_list(uri_handlers, LENGTH(uri_handlers));
2545 /* Check if the specified file exists. */
2546 /* And only warn the user, if they explicitly asked for a config on the
2547 * command line.
2549 if (!(access(configfile, F_OK) == 0) && cfile) {
2550 char *feedback_str;
2552 feedback_str = g_strdup_printf("Config file '%s' doesn't exist", cfile);
2553 give_feedback(feedback_str);
2554 g_free(feedback_str);
2555 } else if ((access(configfile, F_OK) == 0))
2556 configfile_exists = true;
2558 /* read config file */
2559 /* But only report errors if we failed, and the file existed. */
2560 if ((SUCCESS != read_rcfile(configfile)) && configfile_exists) {
2561 a.i = Error;
2562 a.s = g_strdup_printf("Error in config file '%s'", configfile);
2563 echo(&a);
2564 g_free(a.s);
2565 g_free(configfile);
2568 /* command line argument: URL */
2569 if (argc > 1) {
2570 strncpy(url, argv[argc - 1], 255);
2571 } else {
2572 strncpy(url, startpage, 255);
2575 a.i = TargetCurrent;
2576 a.s = url;
2577 open_arg(&a);
2578 gtk_main();
2580 mop_up();
2582 return EXIT_SUCCESS;