Adde early breakout to hinting.js.
[vimprobable2.git] / main.c
blob2269e9caccb8be4d45076c71b0b52740c4af3d40
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 (count && (text[0] == '.' || text[0] == ',')) {
474 a.i = Silent;
475 a.s = g_strdup_printf("hints.fire(%d);", count);
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 switch (event->keyval) {
491 case GDK_bracketleft:
492 case GDK_Escape:
493 if (!IS_ESCAPE(event)) break;
494 a.i = HideCompletion;
495 complete(&a);
496 a.i = ModeNormal;
497 return set(&a);
498 break;
499 case GDK_Tab:
500 a.i = DirectionNext;
501 return complete(&a);
502 break;
503 case GDK_Up:
504 a.i = DirectionPrev;
505 return commandhistoryfetch(&a);
506 break;
507 case GDK_Down:
508 a.i = DirectionNext;
509 return commandhistoryfetch(&a);
510 break;
511 case GDK_ISO_Left_Tab:
512 a.i = DirectionPrev;
513 return complete(&a);
514 break;
517 if (mode == ModeHints) {
518 if ((CLEAN(event->state) & GDK_SHIFT_MASK) &&
519 (CLEAN(event->state) & GDK_CONTROL_MASK) &&
520 (event->keyval == GDK_BackSpace)) {
521 count /= 10;
522 a.i = Silent;
523 a.s = g_strdup_printf("hints.updateHints(%d);", count);
524 script(&a);
525 update_state();
526 return TRUE;
529 numval = g_unichar_digit_value((gunichar) gdk_keyval_to_unicode(event->keyval));
530 if ((numval >= 1 && numval <= 9) || (numval == 0 && count)) {
531 /* allow a zero as non-first number */
532 count = (count ? count * 10 : 0) + numval;
533 a.i = Silent;
534 a.s = g_strdup_printf("hints.updateHints(%d);", count);
535 script(&a);
536 update_state();
537 return TRUE;
541 return FALSE;
544 gboolean
545 notify_event_cb(GtkWidget *widget, GdkEvent *event, gpointer user_data) {
546 int i;
547 if (mode == ModeNormal && event->type == GDK_BUTTON_RELEASE) {
548 /* handle mouse click events */
549 for (i = 0; i < LENGTH(mouse); i++) {
550 if (mouse[i].mask == CLEAN(event->button.state)
551 && (mouse[i].modkey == current_modkey
552 || (!mouse[i].modkey && !current_modkey)
553 || mouse[i].modkey == GDK_VoidSymbol) /* wildcard */
554 && mouse[i].button == event->button.button
555 && mouse[i].func) {
556 if (mouse[i].func(&mouse[i].arg)) {
557 current_modkey = count = 0;
558 update_state();
559 return TRUE;
564 return FALSE;
567 static gboolean inputbox_keyrelease_cb(GtkEntry *entry, GdkEventKey *event) {
568 Arg a;
569 guint16 length = gtk_entry_get_text_length(entry);
571 if (!length) {
572 a.i = HideCompletion;
573 complete(&a);
574 a.i = ModeNormal;
575 return set(&a);
577 return FALSE;
580 static gboolean inputbox_changed_cb(GtkEditable *entry, gpointer user_data) {
581 Arg a;
582 char *text = (char*)gtk_entry_get_text(GTK_ENTRY(entry));
583 guint16 length = gtk_entry_get_text_length(GTK_ENTRY(entry));
584 gboolean forward = FALSE;
586 /* Update incremental search if the user changes the search text.
588 * Note: gtk_widget_is_focus() is a poor way to check if the change comes
589 * from the user. But if the entry is focused and the text is set
590 * through gtk_entry_set_text() in some asyncrounous operation,
591 * I would consider that a bug.
594 if (gtk_widget_is_focus(GTK_WIDGET(entry)) && length > 1 && ((forward = text[0] == '/') || text[0] == '?')) {
595 webkit_web_view_unmark_text_matches(webview);
596 webkit_web_view_search_text(webview, &text[1], searchoptions & CaseSensitive, forward, searchoptions & Wrapping);
597 return TRUE;
598 } else if (gtk_widget_is_focus(GTK_WIDGET(entry)) && length >= 1 &&
599 (text[0] == '.' || text[0] == ',')) {
600 a.i = Silent;
601 a.s = g_strdup("hints.clearHints();");
602 script(&a);
604 a.i = Silent;
605 a.s = g_strconcat("hints.createHints('", text + 1, "');", NULL);
606 script(&a);
608 return TRUE;
609 } else if (length == 0 && followTarget[0]) {
610 mode = ModeNormal;
611 a.i = Silent;
612 a.s = g_strdup("hints.clearHints();");
613 script(&a);
614 count = 0;
615 update_state();
618 return FALSE;
621 /* funcs here */
623 void fill_suggline(char * suggline, const char * command, const char *fill_with) {
624 memset(suggline, 0, 512);
625 strncpy(suggline, command, 512);
626 strncat(suggline, " ", 1);
627 strncat(suggline, fill_with, 512 - strlen(suggline) - 1);
630 GtkWidget * fill_eventbox(const char * completion_line) {
631 GtkBox * row;
632 GtkWidget *row_eventbox, *el;
633 GdkColor color;
634 char * markup;
636 row = GTK_BOX(gtk_hbox_new(FALSE, 0));
637 row_eventbox = gtk_event_box_new();
638 gdk_color_parse(completionbgcolor[0], &color);
639 gtk_widget_modify_bg(row_eventbox, GTK_STATE_NORMAL, &color);
640 el = gtk_label_new(NULL);
641 markup = g_strconcat("<span font=\"", completionfont[0], "\" color=\"", completioncolor[0], "\">",
642 g_markup_escape_text(completion_line, strlen(completion_line)), "</span>", NULL);
643 gtk_label_set_markup(GTK_LABEL(el), markup);
644 g_free(markup);
645 gtk_misc_set_alignment(GTK_MISC(el), 0, 0);
646 gtk_box_pack_start(row, el, TRUE, TRUE, 2);
647 gtk_container_add(GTK_CONTAINER(row_eventbox), GTK_WIDGET(row));
648 return row_eventbox;
651 gboolean
652 complete(const Arg *arg) {
653 char *str, *p, *s, *markup, *entry, *searchfor, command[32] = "", suggline[512] = "", **suggurls;
654 size_t listlen, len, cmdlen;
655 int i, spacepos;
656 Listelement *elementlist = NULL, *elementpointer;
657 gboolean highlight = FALSE;
658 GtkBox *row;
659 GtkWidget *row_eventbox, *el;
660 GtkBox *_table;
661 GdkColor color;
662 static GtkWidget *table, *top_border;
663 static char *prefix;
664 static char **suggestions;
665 static GtkWidget **widgets;
666 static int n = 0, m, current = -1;
668 str = (char*)gtk_entry_get_text(GTK_ENTRY(inputbox));
669 len = strlen(str);
671 /* Get the length of the list of commands for completion. We need this to
672 * malloc/realloc correctly.
674 listlen = LENGTH(commands);
676 if ((len == 0 || str[0] != ':') && arg->i != HideCompletion)
677 return TRUE;
678 if (prefix) {
679 if (arg->i != HideCompletion && widgets && current != -1 && !strcmp(&str[1], suggestions[current])) {
680 gdk_color_parse(completionbgcolor[0], &color);
681 gtk_widget_modify_bg(widgets[current], GTK_STATE_NORMAL, &color);
682 current = (n + current + (arg->i == DirectionPrev ? -1 : 1)) % n;
683 if ((arg->i == DirectionNext && current == 0)
684 || (arg->i == DirectionPrev && current == n - 1))
685 current = -1;
686 } else {
687 free(widgets);
688 free(suggestions);
689 free(prefix);
690 gtk_widget_destroy(GTK_WIDGET(table));
691 gtk_widget_destroy(GTK_WIDGET(top_border));
692 table = NULL;
693 widgets = NULL;
694 suggestions = NULL;
695 prefix = NULL;
696 n = 0;
697 current = -1;
698 if (arg->i == HideCompletion)
699 return TRUE;
701 } else if (arg->i == HideCompletion)
702 return TRUE;
703 if (!widgets) {
704 prefix = g_strdup_printf(str);
705 widgets = malloc(sizeof(GtkWidget*) * listlen);
706 suggestions = malloc(sizeof(char*) * listlen);
707 top_border = gtk_event_box_new();
708 gtk_widget_set_size_request(GTK_WIDGET(top_border), 0, 1);
709 gdk_color_parse(completioncolor[2], &color);
710 gtk_widget_modify_bg(top_border, GTK_STATE_NORMAL, &color);
711 table = gtk_event_box_new();
712 gdk_color_parse(completionbgcolor[0], &color);
713 _table = GTK_BOX(gtk_vbox_new(FALSE, 0));
714 highlight = len > 1;
715 if (strchr(str, ' ') == NULL) {
716 /* command completion */
717 listlen = LENGTH(commands);
718 for (i = 0; i < listlen; i++) {
719 if (commands[i].cmd == NULL)
720 break;
721 cmdlen = strlen(commands[i].cmd);
722 if (!highlight || (n < MAX_LIST_SIZE && len - 1 <= cmdlen && !strncmp(&str[1], commands[i].cmd, len - 1))) {
723 p = s = malloc(sizeof(char*) * (highlight ? sizeof(COMPLETION_TAG_OPEN) + sizeof(COMPLETION_TAG_CLOSE) - 1 : 1) + cmdlen);
724 if (highlight) {
725 memcpy(p, COMPLETION_TAG_OPEN, sizeof(COMPLETION_TAG_OPEN) - 1);
726 memcpy((p += sizeof(COMPLETION_TAG_OPEN) - 1), &str[1], len - 1);
727 memcpy((p += len - 1), COMPLETION_TAG_CLOSE, sizeof(COMPLETION_TAG_CLOSE) - 1);
728 p += sizeof(COMPLETION_TAG_CLOSE) - 1;
730 memcpy(p, &commands[i].cmd[len - 1], cmdlen - len + 2);
731 row = GTK_BOX(gtk_hbox_new(FALSE, 0));
732 row_eventbox = gtk_event_box_new();
733 gtk_widget_modify_bg(row_eventbox, GTK_STATE_NORMAL, &color);
734 el = gtk_label_new(NULL);
735 markup = g_strconcat("<span font=\"", completionfont[0], "\" color=\"", completioncolor[0], "\">", s, "</span>", NULL);
736 free(s);
737 gtk_label_set_markup(GTK_LABEL(el), markup);
738 g_free(markup);
739 gtk_misc_set_alignment(GTK_MISC(el), 0, 0);
740 gtk_box_pack_start(row, el, TRUE, TRUE, 2);
741 gtk_container_add(GTK_CONTAINER(row_eventbox), GTK_WIDGET(row));
742 gtk_box_pack_start(_table, GTK_WIDGET(row_eventbox), FALSE, FALSE, 0);
743 suggestions[n] = commands[i].cmd;
744 widgets[n++] = row_eventbox;
747 } else {
748 entry = (char *)malloc(512 * sizeof(char));
749 if (entry == NULL) {
750 return FALSE;
752 memset(entry, 0, 512);
753 suggurls = malloc(sizeof(char*) * listlen);
754 if (suggurls == NULL) {
755 return FALSE;
757 spacepos = strcspn(str, " ");
758 searchfor = (str + spacepos + 1);
759 strncpy(command, (str + 1), spacepos - 1);
760 if (strlen(command) == 3 && strncmp(command, "set", 3) == 0) {
761 /* browser settings */
762 listlen = LENGTH(browsersettings);
763 for (i = 0; i < listlen; i++) {
764 if (n < MAX_LIST_SIZE && strstr(browsersettings[i].name, searchfor) != NULL) {
765 /* match */
766 fill_suggline(suggline, command, browsersettings[i].name);
767 suggurls[n] = (char *)malloc(sizeof(char) * 512 + 1);
768 strncpy(suggurls[n], suggline, 512);
769 suggestions[n] = suggurls[n];
770 row_eventbox = fill_eventbox(suggline);
771 gtk_box_pack_start(_table, GTK_WIDGET(row_eventbox), FALSE, FALSE, 0);
772 widgets[n++] = row_eventbox;
776 } else if (strlen(command) == 2 && strncmp(command, "qt", 2) == 0) {
777 /* completion on tags */
778 spacepos = strcspn(str, " ");
779 searchfor = (str + spacepos + 1);
780 elementlist = complete_list(searchfor, 1, elementlist);
781 } else {
782 /* URL completion: bookmarks */
783 elementlist = complete_list(searchfor, 0, elementlist);
784 m = count_list(elementlist);
785 if (m < MAX_LIST_SIZE) {
786 /* URL completion: history */
787 elementlist = complete_list(searchfor, 2, elementlist);
790 elementpointer = elementlist;
791 while (elementpointer != NULL) {
792 fill_suggline(suggline, command, elementpointer->element);
793 suggurls[n] = (char *)malloc(sizeof(char) * 512 + 1);
794 strncpy(suggurls[n], suggline, 512);
795 suggestions[n] = suggurls[n];
796 row_eventbox = fill_eventbox(suggline);
797 gtk_box_pack_start(_table, GTK_WIDGET(row_eventbox), FALSE, FALSE, 0);
798 widgets[n++] = row_eventbox;
799 elementpointer = elementpointer->next;
800 if (n >= MAX_LIST_SIZE)
801 break;
803 free_list(elementlist);
804 if (suggurls != NULL) {
805 free(suggurls);
806 suggurls = NULL;
808 if (entry != NULL) {
809 free(entry);
810 entry = NULL;
813 /* TA: FIXME - this needs rethinking entirely. */
815 GtkWidget **widgets_temp = realloc(widgets, sizeof(*widgets) * n);
816 if (widgets_temp == NULL && widgets == NULL) {
817 fprintf(stderr, "Couldn't realloc() widgets\n");
818 exit(1);
820 widgets = widgets_temp;
821 char **suggestions_temp = realloc(suggestions, sizeof(*suggestions) * n);
822 if (suggestions_temp == NULL && suggestions == NULL) {
823 fprintf(stderr, "Couldn't realloc() suggestions\n");
824 exit(1);
826 suggestions = suggestions_temp;
828 if (!n) {
829 gdk_color_parse(completionbgcolor[1], &color);
830 gtk_widget_modify_bg(table, GTK_STATE_NORMAL, &color);
831 el = gtk_label_new(NULL);
832 gtk_misc_set_alignment(GTK_MISC(el), 0, 0);
833 markup = g_strconcat("<span font=\"", completionfont[1], "\" color=\"", completioncolor[1], "\">No Completions</span>", NULL);
834 gtk_label_set_markup(GTK_LABEL(el), markup);
835 g_free(markup);
836 gtk_box_pack_start(_table, GTK_WIDGET(el), FALSE, FALSE, 0);
838 gtk_box_pack_start(box, GTK_WIDGET(top_border), FALSE, FALSE, 0);
839 gtk_container_add(GTK_CONTAINER(table), GTK_WIDGET(_table));
840 gtk_box_pack_start(box, GTK_WIDGET(table), FALSE, FALSE, 0);
841 gtk_widget_show_all(GTK_WIDGET(window));
842 if (!n)
843 return TRUE;
844 current = arg->i == DirectionPrev ? n - 1 : 0;
846 if (current != -1) {
847 gdk_color_parse(completionbgcolor[2], &color);
848 gtk_widget_modify_bg(GTK_WIDGET(widgets[current]), GTK_STATE_NORMAL, &color);
849 s = g_strconcat(":", suggestions[current], NULL);
850 gtk_entry_set_text(GTK_ENTRY(inputbox), s);
851 g_free(s);
852 } else
853 gtk_entry_set_text(GTK_ENTRY(inputbox), prefix);
854 gtk_editable_set_position(GTK_EDITABLE(inputbox), -1);
855 return TRUE;
858 gboolean
859 descend(const Arg *arg) {
860 char *source = (char*)webkit_web_view_get_uri(webview), *p = &source[0], *new;
861 int i, len;
862 count = count ? count : 1;
864 if (!source)
865 return TRUE;
866 if (arg->i == Rootdir) {
867 for (i = 0; i < 3; i++) /* get to the third slash */
868 if (!(p = strchr(++p, '/')))
869 return TRUE; /* if we cannot find it quit */
870 } else {
871 len = strlen(source);
872 if (!len) /* if string is empty quit */
873 return TRUE;
874 p = source + len; /* start at the end */
875 if (*(p - 1) == '/') /* /\/$/ is not an additional level */
876 ++count;
877 for (i = 0; i < count; i++)
878 while(*(p--) != '/' || *p == '/') /* count /\/+/ as one slash */
879 if (p == source) /* if we reach the first char pointer quit */
880 return TRUE;
881 ++p; /* since we do p-- in the while, we are pointing at
882 the char before the slash, so +1 */
884 len = p - source + 1; /* new length = end - start + 1 */
885 new = malloc(len + 1);
886 memcpy(new, source, len);
887 new[len] = '\0';
888 webkit_web_view_load_uri(webview, new);
889 free(new);
890 return TRUE;
893 gboolean
894 echo(const Arg *arg) {
895 int index = !arg->s ? 0 : arg->i & (~NoAutoHide);
897 if (index < Info || index > Error)
898 return TRUE;
900 set_widget_font_and_color(inputbox, urlboxfont[index], urlboxbgcolor[index], urlboxcolor[index]);
901 gtk_entry_set_text(GTK_ENTRY(inputbox), !arg->s ? "" : arg->s);
903 return TRUE;
906 gboolean
907 input(const Arg *arg) {
908 int pos = 0;
909 count = 0;
910 const char *url;
911 int index = Info;
912 Arg a;
914 /* if inputbox hidden, show it again */
915 if (!gtk_widget_get_visible(inputbox))
916 gtk_widget_set_visible(inputbox, TRUE);
918 update_state();
920 /* Set the colour and font back to the default, so that we don't still
921 * maintain a red colour from a warning from an end of search indicator,
922 * etc.
924 set_widget_font_and_color(inputbox, urlboxfont[index], urlboxbgcolor[index], urlboxcolor[index]);
926 if (arg->s[0] == '.' || arg->s[0] == ',') {
927 mode = ModeHints;
928 memset(followTarget, 0, 8);
929 strncpy(followTarget, arg->s[0] == '.' ? "current" : "new", 8);
930 a.i = Silent;
931 a.s = g_strdup("hints.createHints();");
932 script(&a);
935 /* to avoid things like :open URL :open URL2 or :open :open URL */
936 gtk_entry_set_text(GTK_ENTRY(inputbox), "");
937 gtk_editable_insert_text(GTK_EDITABLE(inputbox), arg->s, -1, &pos);
938 if (arg->i & InsertCurrentURL && (url = webkit_web_view_get_uri(webview)))
939 gtk_editable_insert_text(GTK_EDITABLE(inputbox), url, -1, &pos);
940 gtk_widget_grab_focus(inputbox);
941 gtk_editable_set_position(GTK_EDITABLE(inputbox), -1);
943 return TRUE;
946 gboolean
947 navigate(const Arg *arg) {
948 if (arg->i & NavigationForwardBack)
949 webkit_web_view_go_back_or_forward(webview, (arg->i == NavigationBack ? -1 : 1) * (count ? count : 1));
950 else if (arg->i & NavigationReloadActions)
951 (arg->i == NavigationReload ? webkit_web_view_reload : webkit_web_view_reload_bypass_cache)(webview);
952 else
953 webkit_web_view_stop_loading(webview);
954 return TRUE;
957 gboolean
958 number(const Arg *arg) {
959 const char *source = webkit_web_view_get_uri(webview);
960 char *uri, *p, *new;
961 int number, diff = (count ? count : 1) * (arg->i == Increment ? 1 : -1);
963 if (!source)
964 return TRUE;
965 uri = g_strdup_printf(source); /* copy string */
966 p =& uri[0];
967 while(*p != '\0') /* goto the end of the string */
968 ++p;
969 --p;
970 while(*p >= '0' && *p <= '9') /* go back until non number char is reached */
971 --p;
972 if (*(++p) == '\0') { /* if no numbers were found abort */
973 free(uri);
974 return TRUE;
976 number = atoi(p) + diff; /* apply diff on number */
977 *p = '\0';
978 new = g_strdup_printf("%s%d", uri, number); /* create new uri */
979 webkit_web_view_load_uri(webview, new);
980 g_free(new);
981 free(uri);
982 return TRUE;
985 gboolean
986 open_arg(const Arg *arg) {
987 char *argv[6];
988 char *s = arg->s, *p = NULL, *new;
989 Arg a = { .i = NavigationReload };
990 int len;
991 char *search_uri, *search_term;
993 if (embed) {
994 argv[0] = *args;
995 argv[1] = "-e";
996 argv[2] = winid;
997 argv[3] = arg->s;
998 argv[4] = NULL;
999 } else {
1000 argv[0] = *args;
1001 argv[1] = arg->s;
1002 argv[2] = NULL;
1005 if (!arg->s)
1006 navigate(&a);
1007 else if (arg->i == TargetCurrent) {
1008 while(*s == ' ') /* strip leading whitespace */
1009 ++s;
1010 p = (s + strlen(s) - 1);
1011 while(*p == ' ') /* strip trailing whitespace */
1012 --p;
1013 *(p + 1) = '\0';
1014 len = strlen(s);
1015 new = NULL, p = strchr(s, ' ');
1016 if (p) { /* check for search engines */
1017 *p = '\0';
1018 search_uri = find_uri_for_searchengine(s);
1019 if (search_uri != NULL) {
1020 search_term = soup_uri_encode(p+1, "&");
1021 new = g_strdup_printf(search_uri, search_term);
1022 g_free(search_term);
1024 *p = ' ';
1026 if (!new) {
1027 if (len > 3 && strstr(s, "://")) { /* valid url? */
1028 p = new = g_malloc(len + 1);
1029 while(*s != '\0') { /* strip whitespaces */
1030 if (*s != ' ')
1031 *(p++) = *s;
1032 ++s;
1034 *p = '\0';
1035 } else if (strcspn(s, "/") == 0 || strcspn(s, "./") == 0) { /* prepend "file://" */
1036 new = g_malloc(sizeof("file://") + len);
1037 strcpy(new, "file://");
1038 memcpy(&new[sizeof("file://") - 1], s, len + 1);
1039 } else if (p || !strchr(s, '.')) { /* whitespaces or no dot? */
1040 search_uri = find_uri_for_searchengine(defaultsearch);
1041 if (search_uri != NULL) {
1042 search_term = soup_uri_encode(s, "&");
1043 new = g_strdup_printf(search_uri, search_term);
1044 g_free(search_term);
1046 } else { /* prepend "http://" */
1047 new = g_malloc(sizeof("http://") + len);
1048 strcpy(new, "http://");
1049 memcpy(&new[sizeof("http://") - 1], s, len + 1);
1052 webkit_web_view_load_uri(webview, new);
1053 g_free(new);
1054 } else
1055 g_spawn_async(NULL, argv, NULL, G_SPAWN_SEARCH_PATH, NULL, NULL, NULL, NULL);
1056 return TRUE;
1059 gboolean
1060 open_remembered(const Arg *arg)
1062 Arg a = {arg->i, rememberedURI};
1064 if (strcmp(rememberedURI, "")) {
1065 open_arg(&a);
1067 return TRUE;
1070 gboolean
1071 yank(const Arg *arg) {
1072 const char *url, *feedback;
1074 if (arg->i & SourceURL) {
1075 url = webkit_web_view_get_uri(webview);
1076 if (!url)
1077 return TRUE;
1078 feedback = g_strconcat("Yanked ", url, NULL);
1079 give_feedback(feedback);
1080 if (arg->i & ClipboardPrimary)
1081 gtk_clipboard_set_text(clipboards[0], url, -1);
1082 if (arg->i & ClipboardGTK)
1083 gtk_clipboard_set_text(clipboards[1], url, -1);
1084 } else
1085 webkit_web_view_copy_clipboard(webview);
1086 return TRUE;
1089 gboolean
1090 paste(const Arg *arg) {
1091 Arg a = { .i = arg->i & TargetNew, .s = NULL };
1093 /* If we're over a link, open it in a new target. */
1094 if (strlen(rememberedURI) > 0) {
1095 Arg new_target = { .i = TargetNew, .s = arg->s };
1096 open_arg(&new_target);
1097 return TRUE;
1100 if (arg->i & ClipboardPrimary)
1101 a.s = gtk_clipboard_wait_for_text(clipboards[0]);
1102 if (!a.s && arg->i & ClipboardGTK)
1103 a.s = gtk_clipboard_wait_for_text(clipboards[1]);
1104 if (a.s)
1105 open_arg(&a);
1106 return TRUE;
1109 gboolean
1110 quit(const Arg *arg) {
1111 FILE *f;
1112 const char *filename;
1113 const char *uri = webkit_web_view_get_uri(webview);
1114 if (uri != NULL) {
1115 /* write last URL into status file for recreation with "u" */
1116 filename = g_strdup_printf(CLOSED_URL_FILENAME);
1117 f = fopen(filename, "w");
1118 if (f != NULL) {
1119 fprintf(f, "%s", uri);
1120 fclose(f);
1123 gtk_main_quit();
1124 return TRUE;
1127 gboolean
1128 revive(const Arg *arg) {
1129 FILE *f;
1130 const char *filename;
1131 char buffer[512] = "";
1132 Arg a = { .i = TargetNew, .s = NULL };
1133 /* get the URL of the window which has been closed last */
1134 filename = g_strdup_printf(CLOSED_URL_FILENAME);
1135 f = fopen(filename, "r");
1136 if (f != NULL) {
1137 fgets(buffer, 512, f);
1138 fclose(f);
1140 if (strlen(buffer) > 0) {
1141 a.s = buffer;
1142 open_arg(&a);
1143 return TRUE;
1145 return FALSE;
1148 static
1149 gboolean print_frame(const Arg *arg)
1151 WebKitWebFrame *frame = webkit_web_view_get_main_frame(webview);
1152 webkit_web_frame_print (frame);
1153 return TRUE;
1156 gboolean
1157 search(const Arg *arg) {
1158 count = count ? count : 1;
1159 gboolean success, direction = arg->i & DirectionPrev;
1160 Arg a;
1162 if (arg->s) {
1163 free(search_handle);
1164 search_handle = g_strdup_printf(arg->s);
1166 if (!search_handle)
1167 return TRUE;
1168 if (arg->i & DirectionAbsolute)
1169 search_direction = direction;
1170 else
1171 direction ^= search_direction;
1172 do {
1173 success = webkit_web_view_search_text(webview, search_handle, arg->i & CaseSensitive, direction, FALSE);
1174 if (!success) {
1175 if (arg->i & Wrapping) {
1176 success = webkit_web_view_search_text(webview, search_handle, arg->i & CaseSensitive, direction, TRUE);
1177 if (success) {
1178 a.i = Warning;
1179 a.s = g_strdup_printf("search hit %s, continuing at %s",
1180 direction ? "BOTTOM" : "TOP",
1181 direction ? "TOP" : "BOTTOM");
1182 echo(&a);
1183 g_free(a.s);
1184 } else
1185 break;
1186 } else
1187 break;
1189 } while(--count);
1190 if (!success) {
1191 a.i = Error;
1192 a.s = g_strdup_printf("Pattern not found: %s", search_handle);
1193 echo(&a);
1194 g_free(a.s);
1196 return TRUE;
1199 gboolean
1200 set(const Arg *arg) {
1201 Arg a = { .i = Info | NoAutoHide };
1203 switch (arg->i) {
1204 case ModeNormal:
1205 if (search_handle) {
1206 search_handle = NULL;
1207 webkit_web_view_unmark_text_matches(webview);
1209 gtk_entry_set_text(GTK_ENTRY(inputbox), "");
1210 gtk_widget_grab_focus(GTK_WIDGET(webview));
1211 break;
1212 case ModePassThrough:
1213 a.s = g_strdup("-- PASS THROUGH --");
1214 echo(&a);
1215 g_free(a.s);
1216 break;
1217 case ModeSendKey:
1218 a.s = g_strdup("-- PASS TROUGH (next) --");
1219 echo(&a);
1220 g_free(a.s);
1221 break;
1222 case ModeInsert: /* should not be called manually but automatically */
1223 a.s = g_strdup("-- INSERT --");
1224 echo(&a);
1225 g_free(a.s);
1226 break;
1227 default:
1228 return TRUE;
1230 mode = arg->i;
1231 return TRUE;
1234 gchar*
1235 jsapi_ref_to_string(JSContextRef context, JSValueRef ref) {
1236 JSStringRef string_ref;
1237 gchar *string;
1238 size_t length;
1240 string_ref = JSValueToStringCopy(context, ref, NULL);
1241 length = JSStringGetMaximumUTF8CStringSize(string_ref);
1242 string = g_new(gchar, length);
1243 JSStringGetUTF8CString(string_ref, string, length);
1244 JSStringRelease(string_ref);
1245 return string;
1248 void
1249 jsapi_evaluate_script(const gchar *script, gchar **value, gchar **message) {
1250 WebKitWebFrame *frame = webkit_web_view_get_main_frame(webview);
1251 JSGlobalContextRef context = webkit_web_frame_get_global_context(frame);
1252 JSStringRef str;
1253 JSValueRef val, exception;
1255 str = JSStringCreateWithUTF8CString(script);
1256 val = JSEvaluateScript(context, str, JSContextGetGlobalObject(context), NULL, 0, &exception);
1257 JSStringRelease(str);
1258 if (!val)
1259 *message = jsapi_ref_to_string(context, exception);
1260 else
1261 *value = jsapi_ref_to_string(context, val);
1264 gboolean
1265 quickmark(const Arg *a) {
1266 int i, b;
1267 b = atoi(a->s);
1268 char *fn = g_strdup_printf(QUICKMARK_FILE);
1269 FILE *fp;
1270 fp = fopen(fn, "r");
1271 char buf[100];
1273 if (fp != NULL && b < 10) {
1274 for( i=0; i < b; ++i ) {
1275 if (feof(fp)) {
1276 break;
1278 fgets(buf, 100, fp);
1280 char *ptr = strrchr(buf, '\n');
1281 *ptr = '\0';
1282 Arg x = { .s = buf };
1283 if (strlen(buf))
1284 return open_arg(&x);
1285 else {
1286 x.i = Error;
1287 x.s = g_strdup_printf("Quickmark %d not defined", b);
1288 echo(&x);
1289 g_free(x.s);
1290 return false;
1292 } else { return false; }
1295 gboolean
1296 script(const Arg *arg) {
1297 gchar *value = NULL, *message = NULL;
1298 Arg a;
1300 if (!arg->s) {
1301 set_error("Missing argument.");
1302 return FALSE;
1304 jsapi_evaluate_script(arg->s, &value, &message);
1305 if (message) {
1306 set_error(message);
1307 if (arg->s)
1308 g_free(arg->s);
1309 return FALSE;
1311 if (arg->i != Silent && value) {
1312 a.i = arg->i;
1313 a.s = g_strdup(value);
1314 echo(&a);
1315 g_free(a.s);
1317 if (value) {
1318 if (strncmp(value, "fire;", 5) == 0) {
1319 count = 0;
1320 a.s = g_strconcat("hints.fire(", (value + 5), ");", NULL);
1321 a.i = Silent;
1322 script(&a);
1323 } else if (strncmp(value, "open;", 5) == 0) {
1324 count = 0;
1325 a.i = ModeNormal;
1326 set(&a);
1327 if (strncmp(followTarget, "new", 3) == 0)
1328 a.i = TargetNew;
1329 else
1330 a.i = TargetCurrent;
1331 a.s = (value + 5);
1332 open_arg(&a);
1335 if (arg->s)
1336 g_free(arg->s);
1337 g_free(value);
1338 return TRUE;
1341 gboolean
1342 scroll(const Arg *arg) {
1343 GtkAdjustment *adjust = (arg->i & OrientationHoriz) ? adjust_h : adjust_v;
1344 int max = gtk_adjustment_get_upper(adjust) - gtk_adjustment_get_page_size(adjust);
1345 float val = gtk_adjustment_get_value(adjust) / max * 100;
1346 int direction = (arg->i & (1 << 2)) ? 1 : -1;
1348 if ((direction == 1 && val < 100) || (direction == -1 && val > 0)) {
1349 if (arg->i & ScrollMove)
1350 gtk_adjustment_set_value(adjust, gtk_adjustment_get_value(adjust) +
1351 direction * /* direction */
1352 ((arg->i & UnitLine || (arg->i & UnitBuffer && count)) ? (scrollstep * (count ? count : 1)) : (
1353 arg->i & UnitBuffer ? gtk_adjustment_get_page_size(adjust) / 2 :
1354 (count ? count : 1) * (gtk_adjustment_get_page_size(adjust) -
1355 (gtk_adjustment_get_page_size(adjust) > pagingkeep ? pagingkeep : 0)))));
1356 else
1357 gtk_adjustment_set_value(adjust,
1358 ((direction == 1) ? gtk_adjustment_get_upper : gtk_adjustment_get_lower)(adjust));
1359 update_state();
1361 return TRUE;
1364 gboolean
1365 zoom(const Arg *arg) {
1366 webkit_web_view_set_full_content_zoom(webview, (arg->i & ZoomFullContent) > 0);
1367 webkit_web_view_set_zoom_level(webview, (arg->i & ZoomOut) ?
1368 webkit_web_view_get_zoom_level(webview) +
1369 (((float)(count ? count : 1)) * (arg->i & (1 << 1) ? 1.0 : -1.0) * zoomstep) :
1370 (count ? (float)count / 100.0 : 1.0));
1371 return TRUE;
1374 gboolean
1375 fake_key_event(const Arg *a) {
1376 if(!embed) {
1377 return FALSE;
1379 Arg err;
1380 err.i = Error;
1381 Display *xdpy;
1382 if ( (xdpy = XOpenDisplay(NULL)) == NULL ) {
1383 err.s = g_strdup("Couldn't find the XDisplay.");
1384 echo(&err);
1385 g_free(err.s);
1386 return FALSE;
1389 XKeyEvent xk;
1390 xk.display = xdpy;
1391 xk.subwindow = None;
1392 xk.time = CurrentTime;
1393 xk.same_screen = True;
1394 xk.x = xk.y = xk.x_root = xk.y_root = 1;
1395 xk.window = embed;
1396 xk.state = a->i;
1398 if( ! a->s ) {
1399 err.s = g_strdup("Zero pointer as argument! Check your config.h");
1400 echo(&err);
1401 g_free(err.s);
1402 return FALSE;
1405 KeySym keysym;
1406 if( (keysym = XStringToKeysym(a->s)) == NoSymbol ) {
1407 err.s = g_strdup_printf("Couldn't translate %s to keysym", a->s );
1408 echo(&err);
1409 g_free(err.s);
1410 return FALSE;
1413 if( (xk.keycode = XKeysymToKeycode(xdpy, keysym)) == NoSymbol ) {
1414 err.s = g_strdup("Couldn't translate keysym to keycode");
1415 echo(&err);
1416 g_free(err.s);
1417 return FALSE;
1420 xk.type = KeyPress;
1421 if( !XSendEvent(xdpy, embed, True, KeyPressMask, (XEvent *)&xk) ) {
1422 err.s = g_strdup("XSendEvent failed");
1423 echo(&err);
1424 g_free(err.s);
1425 return FALSE;
1427 XFlush(xdpy);
1429 return TRUE;
1433 gboolean
1434 commandhistoryfetch(const Arg *arg) {
1435 if (arg->i == DirectionPrev) {
1436 commandpointer--;
1437 if (commandpointer < 0)
1438 commandpointer = maxcommands - 1;
1439 } else {
1440 commandpointer++;
1441 if (commandpointer == COMMANDHISTSIZE || commandpointer == maxcommands)
1442 commandpointer = 0;
1445 if (commandpointer < 0)
1446 return FALSE;
1448 gtk_entry_set_text(GTK_ENTRY(inputbox), commandhistory[commandpointer ]);
1449 gtk_editable_set_position(GTK_EDITABLE(inputbox), -1);
1450 return TRUE;
1454 gboolean
1455 bookmark(const Arg *arg) {
1456 FILE *f;
1457 const char *filename;
1458 const char *uri = webkit_web_view_get_uri(webview);
1459 const char *title = webkit_web_view_get_title(webview);
1460 filename = g_strdup_printf(BOOKMARKS_STORAGE_FILENAME);
1461 f = fopen(filename, "a");
1462 if (uri == NULL || strlen(uri) == 0) {
1463 set_error("No URI found to bookmark.");
1464 return FALSE;
1466 if (f != NULL) {
1467 fprintf(f, "%s", uri);
1468 if (title != NULL) {
1469 fprintf(f, "%s", " ");
1470 fprintf(f, "%s", title);
1472 if (arg->s && strlen(arg->s)) {
1473 build_taglist(arg, f);
1475 fprintf(f, "%s", "\n");
1476 fclose(f);
1477 give_feedback( "Bookmark saved" );
1478 return TRUE;
1479 } else {
1480 set_error("Bookmarks file not found.");
1481 return FALSE;
1485 gboolean
1486 history() {
1487 FILE *f;
1488 const char *filename;
1489 const char *uri = webkit_web_view_get_uri(webview);
1490 const char *title = webkit_web_view_get_title(webview);
1491 char *entry, buffer[512], *new;
1492 int n, i = 0;
1493 gboolean finished = FALSE;
1494 if (uri != NULL) {
1495 if (title != NULL) {
1496 entry = malloc((strlen(uri) + strlen(title) + 2) * sizeof(char));
1497 memset(entry, 0, strlen(uri) + strlen(title) + 2);
1498 } else {
1499 entry = malloc((strlen(uri) + 1) * sizeof(char));
1500 memset(entry, 0, strlen(uri) + 1);
1502 if (entry != NULL) {
1503 strncpy(entry, uri, strlen(uri));
1504 if (title != NULL) {
1505 strncat(entry, " ", 1);
1506 strncat(entry, title, strlen(title));
1508 n = strlen(entry);
1509 filename = g_strdup_printf(HISTORY_STORAGE_FILENAME);
1510 f = fopen(filename, "r");
1511 if (f != NULL) {
1512 new = (char *)malloc(HISTORY_MAX_ENTRIES * 512 * sizeof(char) + 1);
1513 if (new != NULL) {
1514 memset(new, 0, HISTORY_MAX_ENTRIES * 512 * sizeof(char) + 1);
1515 /* newest entries go on top */
1516 strncpy(new, entry, strlen(entry));
1517 strncat(new, "\n", 1);
1518 /* retain at most HISTORY_MAX_ENTIRES - 1 old entries */
1519 while (finished != TRUE) {
1520 if ((char *)NULL == fgets(buffer, 512, f)) {
1521 /* check if end of file was reached / error occured */
1522 if (!feof(f)) {
1523 break;
1525 /* end of file reached */
1526 finished = TRUE;
1527 continue;
1529 /* compare line (-1 because of newline character) */
1530 if (n != strlen(buffer) - 1 || strncmp(entry, buffer, n) != 0) {
1531 /* if the URI is already in history; we put it on top and skip it here */
1532 strncat(new, buffer, 512);
1533 i++;
1535 if ((i + 1) >= HISTORY_MAX_ENTRIES) {
1536 break;
1539 fclose(f);
1541 f = fopen(filename, "w");
1542 if (f != NULL) {
1543 fprintf(f, "%s", new);
1544 fclose(f);
1546 if (new != NULL) {
1547 free(new);
1548 new = NULL;
1552 if (entry != NULL) {
1553 free(entry);
1554 entry = NULL;
1557 return TRUE;
1560 static gboolean
1561 view_source(const Arg * arg) {
1562 gboolean current_mode = webkit_web_view_get_view_source_mode(webview);
1563 webkit_web_view_set_view_source_mode(webview, !current_mode);
1564 webkit_web_view_reload(webview);
1565 return TRUE;
1568 static gboolean
1569 focus_input(const Arg *arg) {
1570 static Arg a;
1572 a.s = g_strconcat("hints.focusInput();", NULL);
1573 a.i = Silent;
1574 script(&a);
1575 update_state();
1576 return TRUE;
1579 static gboolean
1580 browser_settings(const Arg *arg) {
1581 char line[255];
1582 if (!arg->s) {
1583 set_error("Missing argument.");
1584 return FALSE;
1586 strncpy(line, arg->s, 254);
1587 if (process_set_line(line))
1588 return TRUE;
1589 else {
1590 set_error("Invalid setting.");
1591 return FALSE;
1595 char *
1596 search_word(int whichword) {
1597 int k = 0;
1598 static char word[240];
1599 char *c = my_pair.line;
1601 while (isspace(*c) && *c)
1602 c++;
1604 switch (whichword) {
1605 case 0:
1606 while (*c && !isspace (*c) && *c != '=' && k < 240) {
1607 word[k++] = *c;
1608 c++;
1610 word[k] = '\0';
1611 strncpy(my_pair.what, word, 20);
1612 break;
1613 case 1:
1614 while (*c && k < 240) {
1615 word[k++] = *c;
1616 c++;
1618 word[k] = '\0';
1619 strncpy(my_pair.value, word, 240);
1620 break;
1623 return c;
1626 static gboolean
1627 process_set_line(char *line) {
1628 char *c;
1629 int listlen, i;
1630 gboolean boolval;
1631 WebKitWebSettings *settings;
1633 settings = webkit_web_view_get_settings(webview);
1634 my_pair.line = line;
1635 c = search_word(0);
1636 if (!strlen(my_pair.what))
1637 return FALSE;
1639 while (isspace(*c) && *c)
1640 c++;
1642 if (*c == ':' || *c == '=')
1643 c++;
1645 my_pair.line = c;
1646 c = search_word(1);
1648 listlen = LENGTH(browsersettings);
1649 for (i = 0; i < listlen; i++) {
1650 if (strlen(browsersettings[i].name) == strlen(my_pair.what) && strncmp(browsersettings[i].name, my_pair.what, strlen(my_pair.what)) == 0) {
1651 /* mandatory argument not provided */
1652 if (strlen(my_pair.value) == 0)
1653 return FALSE;
1654 /* process qmark? */
1655 if (strlen(my_pair.what) == 5 && strncmp("qmark", my_pair.what, 5) == 0) {
1656 return (process_save_qmark(my_pair.value, webview));
1658 /* interpret boolean values */
1659 if (browsersettings[i].boolval) {
1660 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) {
1661 boolval = TRUE;
1662 } 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) {
1663 boolval = FALSE;
1664 } else {
1665 return FALSE;
1667 } else if (browsersettings[i].colourval) {
1668 /* interpret as hexadecimal colour */
1669 if (!parse_colour(my_pair.value)) {
1670 return FALSE;
1673 if (browsersettings[i].var != NULL) {
1674 /* write value into internal variable */
1675 /*if (browsersettings[i].intval) {
1676 browsersettings[i].var = atoi(my_pair.value);
1677 } else {*/
1678 strncpy(browsersettings[i].var, my_pair.value, MAX_SETTING_SIZE);
1679 if (strlen(my_pair.value) > MAX_SETTING_SIZE - 1) {
1680 /* in this case, \0 will not have been copied */
1681 browsersettings[i].var[MAX_SETTING_SIZE - 1] = '\0';
1682 /* in case this string is also used for a webkit setting, make sure it's consistent */
1683 my_pair.value[MAX_SETTING_SIZE - 1] = '\0';
1684 give_feedback("String too long; automatically truncated!");
1686 /*}*/
1688 if (strlen(browsersettings[i].webkit) > 0) {
1689 /* activate appropriate webkit setting */
1690 if (browsersettings[i].boolval) {
1691 g_object_set((GObject*)settings, browsersettings[i].webkit, boolval, NULL);
1692 } else if (browsersettings[i].intval) {
1693 g_object_set((GObject*)settings, browsersettings[i].webkit, atoi(my_pair.value), NULL);
1694 } else {
1695 g_object_set((GObject*)settings, browsersettings[i].webkit, my_pair.value, NULL);
1697 webkit_web_view_set_settings(webview, settings);
1700 /* process acceptlanguage*/
1701 if (strlen(my_pair.what) == 14 && strncmp("acceptlanguage", my_pair.what, 14) == 0) {
1702 g_object_set(G_OBJECT(session), "accept-language", acceptlanguage, NULL);
1705 /* toggle proxy usage? */
1706 if (strlen(my_pair.what) == 5 && strncmp("proxy", my_pair.what, 5) == 0) {
1707 toggle_proxy(boolval);
1710 /* Toggle scrollbars. */
1711 if (strlen(my_pair.what) == 10 && strncmp("scrollbars", my_pair.what, 10) == 0)
1712 toggle_scrollbars(boolval);
1714 /* Toggle widgets */
1715 if (strlen(my_pair.what) == 9 && strncmp("statusbar", my_pair.what, 9) == 0)
1716 gtk_widget_set_visible(GTK_WIDGET(statusbar), boolval);
1717 if (strlen(my_pair.what) == 8 && strncmp("inputbox", my_pair.what, 8) == 0)
1718 gtk_widget_set_visible(inputbox, boolval);
1720 /* case sensitivity of completion */
1721 if (strlen(my_pair.what) == 14 && strncmp("completioncase", my_pair.what, 14) == 0)
1722 complete_case_sensitive = boolval;
1724 /* reload page? */
1725 if (browsersettings[i].reload)
1726 webkit_web_view_reload(webview);
1727 return TRUE;
1730 return FALSE;
1733 gboolean
1734 process_line(char *line) {
1735 char *c = line;
1736 int i;
1737 size_t len, length = strlen(line);
1738 gboolean found = FALSE, success = FALSE;
1739 Arg a;
1741 while (isspace(*c))
1742 c++;
1743 /* Ignore blank lines. */
1744 if (c[0] == '\0')
1745 return TRUE;
1746 for (i = 0; i < LENGTH(commands); i++) {
1747 if (commands[i].cmd == NULL)
1748 break;
1749 len = strlen(commands[i].cmd);
1750 if (length >= len && !strncmp(c, commands[i].cmd, len) && (c[len] == ' ' || !c[len])) {
1751 found = TRUE;
1752 a.i = commands[i].arg.i;
1753 a.s = length > len + 1 ? &c[len + 1] : commands[i].arg.s;
1754 success = commands[i].func(&a);
1755 break;
1758 save_command_history(c);
1759 if (!found) {
1760 a.i = Error;
1761 a.s = g_strdup_printf("Not a browser command: %s", c);
1762 echo(&a);
1763 } else if (!success) {
1764 a.i = Error;
1765 if (error_msg != NULL) {
1766 a.s = g_strdup_printf("%s", error_msg);
1767 g_free(error_msg);
1768 error_msg = NULL;
1769 } else {
1770 a.s = g_strdup_printf("Unknown error. Please file a bug report!");
1772 echo(&a);
1773 g_free(a.s);
1775 return success;
1778 static gboolean
1779 search_tag(const Arg * a) {
1780 FILE *f;
1781 const char *filename;
1782 const char *tag = a->s;
1783 char s[BUFFERSIZE], foundtag[40], url[BUFFERSIZE];
1784 int t, i, intag, k;
1786 if (!tag) {
1787 /* The user must give us something to load up. */
1788 set_error("Bookmark tag required with this option.");
1789 return FALSE;
1792 if (strlen(tag) > MAXTAGSIZE) {
1793 set_error("Tag too long.");
1794 return FALSE;
1797 filename = g_strdup_printf(BOOKMARKS_STORAGE_FILENAME);
1798 f = fopen(filename, "r");
1799 if (f == NULL) {
1800 set_error("Couldn't open bookmarks file.");
1801 return FALSE;
1803 while (fgets(s, BUFFERSIZE-1, f)) {
1804 intag = 0;
1805 t = strlen(s) - 1;
1806 while (isspace(s[t]))
1807 t--;
1808 if (s[t] != ']') continue;
1809 while (t > 0) {
1810 if (s[t] == ']') {
1811 if (!intag)
1812 intag = t;
1813 else
1814 intag = 0;
1815 } else {
1816 if (s[t] == '[') {
1817 if (intag) {
1818 i = 0;
1819 k = t + 1;
1820 while (k < intag)
1821 foundtag[i++] = s[k++];
1822 foundtag[i] = '\0';
1823 /* foundtag now contains the tag */
1824 if (strlen(foundtag) < MAXTAGSIZE && strcmp(tag, foundtag) == 0) {
1825 i = 0;
1826 while (isspace(s[i])) i++;
1827 k = 0;
1828 while (s[i] && !isspace(s[i])) url[k++] = s[i++];
1829 url[k] = '\0';
1830 Arg x = { .i = TargetNew, .s = url };
1831 open_arg(&x);
1834 intag = 0;
1837 t--;
1840 return TRUE;
1843 void
1844 toggle_proxy(gboolean onoff) {
1845 SoupURI *proxy_uri;
1846 char *filename, *new;
1847 int len;
1849 if (onoff == FALSE) {
1850 g_object_set(session, "proxy-uri", NULL, NULL);
1851 give_feedback("Proxy deactivated");
1852 } else {
1853 filename = (char *)g_getenv("http_proxy");
1855 /* Fallthrough to checking HTTP_PROXY as well, since this can also be
1856 * defined.
1858 if (filename == NULL)
1859 filename = (char *)g_getenv("HTTP_PROXY");
1861 if (filename != NULL && 0 < (len = strlen(filename))) {
1862 if (strstr(filename, "://") == NULL) {
1863 /* prepend http:// */
1864 new = g_malloc(sizeof("http://") + len);
1865 strcpy(new, "http://");
1866 memcpy(&new[sizeof("http://") - 1], filename, len + 1);
1867 proxy_uri = soup_uri_new(new);
1868 } else {
1869 proxy_uri = soup_uri_new(filename);
1871 g_object_set(session, "proxy-uri", proxy_uri, NULL);
1872 give_feedback("Proxy activated");
1877 void
1878 toggle_scrollbars(gboolean onoff) {
1879 if (onoff == TRUE) {
1880 adjust_h = gtk_scrolled_window_get_hadjustment(GTK_SCROLLED_WINDOW(viewport));
1881 adjust_v = gtk_scrolled_window_get_vadjustment(GTK_SCROLLED_WINDOW(viewport));
1883 else {
1884 adjust_v = gtk_range_get_adjustment(GTK_RANGE(scroll_v));
1885 adjust_h = gtk_range_get_adjustment(GTK_RANGE(scroll_h));
1887 gtk_widget_set_scroll_adjustments (GTK_WIDGET(webview), adjust_h, adjust_v);
1889 return;
1892 void
1893 update_url(const char *uri) {
1894 gboolean ssl = g_str_has_prefix(uri, "https://");
1895 GdkColor color;
1896 #ifdef ENABLE_HISTORY_INDICATOR
1897 char before[] = " [";
1898 char after[] = "]";
1899 gboolean back = webkit_web_view_can_go_back(webview);
1900 gboolean fwd = webkit_web_view_can_go_forward(webview);
1902 if (!back && !fwd)
1903 before[0] = after[0] = '\0';
1904 #endif
1905 gtk_label_set_markup(GTK_LABEL(status_url), g_markup_printf_escaped(
1906 #ifdef ENABLE_HISTORY_INDICATOR
1907 "<span font=\"%s\">%s%s%s%s%s</span>", statusfont, uri,
1908 before, back ? "+" : "", fwd ? "-" : "", after
1909 #else
1910 "<span font=\"%s\">%s</span>", statusfont, uri
1911 #endif
1913 gdk_color_parse(ssl ? sslbgcolor : statusbgcolor, &color);
1914 gtk_widget_modify_bg(eventbox, GTK_STATE_NORMAL, &color);
1915 gdk_color_parse(ssl ? sslcolor : statuscolor, &color);
1916 gtk_widget_modify_fg(GTK_WIDGET(status_url), GTK_STATE_NORMAL, &color);
1917 gtk_widget_modify_fg(GTK_WIDGET(status_state), GTK_STATE_NORMAL, &color);
1920 void
1921 update_state() {
1922 char *markup;
1923 int download_count = g_list_length(activeDownloads);
1924 GString *status = g_string_new("");
1926 /* construct the status line */
1928 /* count, modkey and input buffer */
1929 g_string_append_printf(status, "%.0d", count);
1930 if (current_modkey) g_string_append_c(status, current_modkey);
1932 /* the number of active downloads */
1933 if (activeDownloads) {
1934 g_string_append_printf(status, " %d active %s", download_count,
1935 (download_count == 1) ? "download" : "downloads");
1938 #ifdef ENABLE_WGET_PROGRESS_BAR
1939 /* the progressbar */
1941 int progress = -1;
1942 char progressbar[progressbartick + 1];
1944 if (activeDownloads) {
1945 progress = 0;
1946 GList *ptr;
1948 for (ptr = activeDownloads; ptr; ptr = g_list_next(ptr)) {
1949 progress += 100 * webkit_download_get_progress(ptr->data);
1952 progress /= download_count;
1954 } else if (webkit_web_view_get_load_status(webview) != WEBKIT_LOAD_FINISHED
1955 && webkit_web_view_get_load_status(webview) != WEBKIT_LOAD_FAILED) {
1957 progress = webkit_web_view_get_progress(webview) * 100;
1960 if (progress >= 0) {
1961 ascii_bar(progressbartick, progress * progressbartick / 100, progressbar);
1962 g_string_append_printf(status, " %c%s%c",
1963 progressborderleft, progressbar, progressborderright);
1966 #endif
1968 /* and the current scroll position */
1970 int max = gtk_adjustment_get_upper(adjust_v) - gtk_adjustment_get_page_size(adjust_v);
1971 int val = (int)(gtk_adjustment_get_value(adjust_v) / max * 100);
1973 if (max == 0)
1974 g_string_append(status, " All");
1975 else if (val == 0)
1976 g_string_append(status, " Top");
1977 else if (val == 100)
1978 g_string_append(status, " Bot");
1979 else
1980 g_string_append_printf(status, " %d%%", val);
1984 markup = g_markup_printf_escaped("<span font=\"%s\">%s</span>", statusfont, status->str);
1985 gtk_label_set_markup(GTK_LABEL(status_state), markup);
1987 g_string_free(status, TRUE);
1990 void
1991 setup_modkeys() {
1992 unsigned int i;
1993 modkeys = calloc(LENGTH(keys) + 1, sizeof(char));
1994 char *ptr = modkeys;
1996 for (i = 0; i < LENGTH(keys); i++)
1997 if (keys[i].modkey && !strchr(modkeys, keys[i].modkey))
1998 *(ptr++) = keys[i].modkey;
1999 modkeys = realloc(modkeys, &ptr[0] - &modkeys[0] + 1);
2002 void
2003 setup_gui() {
2004 scroll_h = GTK_SCROLLBAR(gtk_hscrollbar_new(NULL));
2005 scroll_v = GTK_SCROLLBAR(gtk_vscrollbar_new(NULL));
2006 adjust_h = gtk_range_get_adjustment(GTK_RANGE(scroll_h));
2007 adjust_v = gtk_range_get_adjustment(GTK_RANGE(scroll_v));
2008 if (embed) {
2009 window = GTK_WINDOW(gtk_plug_new(embed));
2010 } else {
2011 window = GTK_WINDOW(gtk_window_new(GTK_WINDOW_TOPLEVEL));
2012 gtk_window_set_wmclass(GTK_WINDOW(window), "vimprobable2", "Vimprobable2");
2014 gtk_window_set_default_size(GTK_WINDOW(window), 640, 480);
2015 box = GTK_BOX(gtk_vbox_new(FALSE, 0));
2016 inputbox = gtk_entry_new();
2017 webview = (WebKitWebView*)webkit_web_view_new();
2018 statusbar = GTK_BOX(gtk_hbox_new(FALSE, 0));
2019 eventbox = gtk_event_box_new();
2020 status_url = gtk_label_new(NULL);
2021 status_state = gtk_label_new(NULL);
2022 GdkColor bg;
2023 PangoFontDescription *font;
2024 GdkGeometry hints = { 1, 1 };
2025 inspector = webkit_web_view_get_inspector(WEBKIT_WEB_VIEW(webview));
2027 clipboards[0] = gtk_clipboard_get(GDK_SELECTION_PRIMARY);
2028 clipboards[1] = gtk_clipboard_get(GDK_NONE);
2029 setup_settings();
2030 gdk_color_parse(statusbgcolor, &bg);
2031 gtk_widget_modify_bg(eventbox, GTK_STATE_NORMAL, &bg);
2032 gtk_widget_set_name(GTK_WIDGET(window), "Vimprobable2");
2033 gtk_window_set_geometry_hints(window, NULL, &hints, GDK_HINT_MIN_SIZE);
2035 #ifdef DISABLE_SCROLLBAR
2036 viewport = gtk_scrolled_window_new(NULL, NULL);
2037 gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(viewport), GTK_POLICY_NEVER, GTK_POLICY_NEVER);
2038 #else
2039 /* Ensure we still see scrollbars. */
2040 GtkWidget *viewport = gtk_scrolled_window_new(adjust_h, adjust_v);
2041 #endif
2043 setup_signals();
2044 gtk_container_add(GTK_CONTAINER(viewport), GTK_WIDGET(webview));
2046 /* Ensure we set the scroll adjustments now, so that if we're not drawing
2047 * titlebars, we can still scroll.
2049 gtk_widget_set_scroll_adjustments(GTK_WIDGET(webview), adjust_h, adjust_v);
2051 font = pango_font_description_from_string(urlboxfont[0]);
2052 gtk_widget_modify_font(GTK_WIDGET(inputbox), font);
2053 pango_font_description_free(font);
2054 gtk_entry_set_inner_border(GTK_ENTRY(inputbox), NULL);
2055 gtk_misc_set_alignment(GTK_MISC(status_url), 0.0, 0.0);
2056 gtk_misc_set_alignment(GTK_MISC(status_state), 1.0, 0.0);
2057 gtk_box_pack_start(statusbar, status_url, TRUE, TRUE, 2);
2058 gtk_box_pack_start(statusbar, status_state, FALSE, FALSE, 2);
2059 gtk_container_add(GTK_CONTAINER(eventbox), GTK_WIDGET(statusbar));
2060 gtk_box_pack_start(box, viewport, TRUE, TRUE, 0);
2061 gtk_box_pack_start(box, eventbox, FALSE, FALSE, 0);
2062 gtk_entry_set_has_frame(GTK_ENTRY(inputbox), FALSE);
2063 gtk_box_pack_end(box, inputbox, FALSE, FALSE, 0);
2064 gtk_container_add(GTK_CONTAINER(window), GTK_WIDGET(box));
2065 gtk_widget_grab_focus(GTK_WIDGET(webview));
2066 gtk_widget_show_all(GTK_WIDGET(window));
2069 void
2070 setup_settings() {
2071 WebKitWebSettings *settings = (WebKitWebSettings*)webkit_web_settings_new();
2072 SoupURI *proxy_uri;
2073 char *filename, *new;
2074 int len;
2076 session = webkit_get_default_session();
2077 g_object_set(G_OBJECT(settings), "default-font-size", DEFAULT_FONT_SIZE, NULL);
2078 g_object_set(G_OBJECT(settings), "enable-scripts", enablePlugins, NULL);
2079 g_object_set(G_OBJECT(settings), "enable-plugins", enablePlugins, NULL);
2080 g_object_set(G_OBJECT(settings), "enable-java-applet", enableJava, NULL);
2081 g_object_set(G_OBJECT(settings), "enable-page-cache", enablePagecache, NULL);
2082 filename = g_strdup_printf(USER_STYLESHEET);
2083 filename = g_strdup_printf("file://%s", filename);
2084 g_object_set(G_OBJECT(settings), "user-stylesheet-uri", filename, NULL);
2085 g_object_set(G_OBJECT(settings), "user-agent", useragent, NULL);
2086 g_object_get(G_OBJECT(settings), "zoom-step", &zoomstep, NULL);
2087 webkit_web_view_set_settings(webview, settings);
2089 /* proxy */
2090 if (use_proxy == TRUE) {
2091 filename = (char *)g_getenv("http_proxy");
2092 if (filename != NULL && 0 < (len = strlen(filename))) {
2093 if (strstr(filename, "://") == NULL) {
2094 /* prepend http:// */
2095 new = g_malloc(sizeof("http://") + len);
2096 strcpy(new, "http://");
2097 memcpy(&new[sizeof("http://") - 1], filename, len + 1);
2098 proxy_uri = soup_uri_new(new);
2099 } else {
2100 proxy_uri = soup_uri_new(filename);
2102 g_object_set(session, "proxy-uri", proxy_uri, NULL);
2107 void
2108 setup_signals() {
2109 #ifdef ENABLE_COOKIE_SUPPORT
2110 /* Headers. */
2111 g_signal_connect_after(G_OBJECT(session), "request-started", G_CALLBACK(new_generic_request), NULL);
2112 #endif
2113 /* Accept-language header */
2114 g_object_set(G_OBJECT(session), "accept-language", acceptlanguage, NULL);
2115 /* window */
2116 g_object_connect(G_OBJECT(window),
2117 "signal::destroy", G_CALLBACK(window_destroyed_cb), NULL,
2118 NULL);
2119 /* webview */
2120 g_object_connect(G_OBJECT(webview),
2121 "signal::title-changed", G_CALLBACK(webview_title_changed_cb), NULL,
2122 "signal::load-progress-changed", G_CALLBACK(webview_progress_changed_cb), NULL,
2123 "signal::load-committed", G_CALLBACK(webview_load_committed_cb), NULL,
2124 "signal::load-finished", G_CALLBACK(webview_load_finished_cb), NULL,
2125 "signal::navigation-policy-decision-requested", G_CALLBACK(webview_navigation_cb), NULL,
2126 "signal::new-window-policy-decision-requested", G_CALLBACK(webview_new_window_cb), NULL,
2127 "signal::mime-type-policy-decision-requested", G_CALLBACK(webview_mimetype_cb), NULL,
2128 "signal::download-requested", G_CALLBACK(webview_download_cb), NULL,
2129 "signal::key-press-event", G_CALLBACK(webview_keypress_cb), NULL,
2130 "signal::hovering-over-link", G_CALLBACK(webview_hoverlink_cb), NULL,
2131 "signal::console-message", G_CALLBACK(webview_console_cb), NULL,
2132 "signal::create-web-view", G_CALLBACK(webview_open_in_new_window_cb), NULL,
2133 "signal::event", G_CALLBACK(notify_event_cb), NULL,
2134 NULL);
2135 /* webview adjustment */
2136 g_object_connect(G_OBJECT(adjust_v),
2137 "signal::value-changed", G_CALLBACK(webview_scroll_cb), NULL,
2138 NULL);
2139 /* inputbox */
2140 g_object_connect(G_OBJECT(inputbox),
2141 "signal::activate", G_CALLBACK(inputbox_activate_cb), NULL,
2142 "signal::key-press-event", G_CALLBACK(inputbox_keypress_cb), NULL,
2143 "signal::key-release-event", G_CALLBACK(inputbox_keyrelease_cb), NULL,
2144 #ifdef ENABLE_INCREMENTAL_SEARCH
2145 "signal::changed", G_CALLBACK(inputbox_changed_cb), NULL,
2146 #endif
2147 NULL);
2148 /* inspector */
2149 g_signal_connect(G_OBJECT(inspector),
2150 "inspect-web-view", G_CALLBACK(inspector_inspect_web_view_cb), NULL);
2153 #ifdef ENABLE_COOKIE_SUPPORT
2154 void
2155 setup_cookies()
2157 if (file_cookie_jar)
2158 g_object_unref(file_cookie_jar);
2160 if (session_cookie_jar)
2161 g_object_unref(session_cookie_jar);
2163 session_cookie_jar = soup_cookie_jar_new();
2165 cookie_store = g_strdup_printf(COOKIES_STORAGE_FILENAME);
2167 load_all_cookies();
2169 g_signal_connect(G_OBJECT(file_cookie_jar), "changed",
2170 G_CALLBACK(update_cookie_jar), NULL);
2172 return;
2175 /* TA: XXX - we should be using this callback for any header-requests we
2176 * receive (hence the name "new_generic_request" -- but for now, its use
2177 * is limited to handling cookies.
2179 void
2180 new_generic_request(SoupSession *session, SoupMessage *soup_msg, gpointer unused) {
2181 SoupMessageHeaders *soup_msg_h;
2182 SoupURI *uri;
2183 const char *cookie_str;
2185 soup_msg_h = soup_msg->request_headers;
2186 soup_message_headers_remove(soup_msg_h, "Cookie");
2187 uri = soup_message_get_uri(soup_msg);
2188 if( (cookie_str = get_cookies(uri)) )
2189 soup_message_headers_append(soup_msg_h, "Cookie", cookie_str);
2191 g_signal_connect_after(G_OBJECT(soup_msg), "got-headers", G_CALLBACK(handle_cookie_request), NULL);
2193 return;
2196 const char *
2197 get_cookies(SoupURI *soup_uri) {
2198 const char *cookie_str;
2200 cookie_str = soup_cookie_jar_get_cookies(file_cookie_jar, soup_uri, TRUE);
2202 return cookie_str;
2205 void
2206 handle_cookie_request(SoupMessage *soup_msg, gpointer unused)
2208 GSList *resp_cookie = NULL;
2209 SoupCookie *cookie;
2211 for(resp_cookie = soup_cookies_from_response(soup_msg);
2212 resp_cookie;
2213 resp_cookie = g_slist_next(resp_cookie))
2215 SoupDate *soup_date;
2216 cookie = soup_cookie_copy((SoupCookie *)resp_cookie->data);
2218 if (cookie_timeout && cookie->expires == NULL) {
2219 soup_date = soup_date_new_from_time_t(time(NULL) + cookie_timeout * 10);
2220 soup_cookie_set_expires(cookie, soup_date);
2222 soup_cookie_jar_add_cookie(file_cookie_jar, cookie);
2225 return;
2228 void
2229 update_cookie_jar(SoupCookieJar *jar, SoupCookie *old, SoupCookie *new)
2231 if (!new) {
2232 /* Nothing to do. */
2233 return;
2236 SoupCookie *copy;
2237 copy = soup_cookie_copy(new);
2239 soup_cookie_jar_add_cookie(session_cookie_jar, copy);
2241 return;
2244 void
2245 load_all_cookies(void)
2247 file_cookie_jar = soup_cookie_jar_text_new(cookie_store, COOKIES_STORAGE_READONLY);
2249 /* Put them back in the session store. */
2250 GSList *cookies_from_file = soup_cookie_jar_all_cookies(file_cookie_jar);
2252 for (; cookies_from_file;
2253 cookies_from_file = cookies_from_file->next)
2255 soup_cookie_jar_add_cookie(session_cookie_jar, cookies_from_file->data);
2258 soup_cookies_free(cookies_from_file);
2260 return;
2263 #endif
2265 void
2266 mop_up(void) {
2267 /* Free up any nasty globals before exiting. */
2268 #ifdef ENABLE_COOKIE_SUPPORT
2269 if (cookie_store)
2270 g_free(cookie_store);
2271 #endif
2272 return;
2276 main(int argc, char *argv[]) {
2277 static Arg a;
2278 static char url[256] = "";
2279 static gboolean ver = false;
2280 static gboolean configfile_exists = FALSE;
2281 static const char *cfile = NULL;
2282 char *searchengines_file;
2283 static GOptionEntry opts[] = {
2284 { "version", 'v', 0, G_OPTION_ARG_NONE, &ver, "print version", NULL },
2285 { "embed", 'e', 0, G_OPTION_ARG_STRING, &winid, "embedded", NULL },
2286 { "configfile", 'c', 0, G_OPTION_ARG_STRING, &cfile, "config file", NULL },
2287 { NULL }
2289 static GError *err;
2290 args = argv;
2292 /* command line argument: version */
2293 if (!gtk_init_with_args(&argc, &argv, "[<uri>]", opts, NULL, &err)) {
2294 g_printerr("can't init gtk: %s\n", err->message);
2295 g_error_free(err);
2296 return EXIT_FAILURE;
2299 if (ver) {
2300 printf("%s\n", INTERNAL_VERSION);
2301 return EXIT_SUCCESS;
2304 if (cfile)
2305 configfile = g_strdup_printf(cfile);
2306 else
2307 configfile = g_strdup_printf(RCFILE);
2309 if (!g_thread_supported())
2310 g_thread_init(NULL);
2312 if (winid)
2313 embed = atoi(winid);
2315 setup_modkeys();
2316 make_keyslist();
2317 setup_gui();
2318 #ifdef ENABLE_COOKIE_SUPPORT
2319 setup_cookies();
2320 #endif
2322 /* Check if the specified file exists. */
2323 /* And only warn the user, if they explicitly asked for a config on the
2324 * command line.
2326 if (!(access(configfile, F_OK) == 0) && cfile) {
2327 char *feedback_str;
2329 feedback_str = g_strdup_printf("Config file '%s' doesn't exist", cfile);
2330 give_feedback(feedback_str);
2331 } else if ((access(configfile, F_OK) == 0))
2332 configfile_exists = true;
2334 /* read config file */
2335 /* But only report errors if we failed, and the file existed. */
2336 if (!read_rcfile(configfile) && configfile_exists) {
2337 a.i = Error;
2338 a.s = g_strdup_printf("Error in config file '%s'", configfile);
2339 echo(&a);
2340 g_free(a.s);
2341 g_free(configfile);
2344 make_searchengines_list(searchengines, LENGTH(searchengines));
2346 /* read searchengines. */
2347 searchengines_file = g_strdup_printf(SEARCHENGINES_STORAGE_FILENAME);
2348 switch (read_searchengines(searchengines_file)) {
2349 case SYNTAX_ERROR:
2350 a.i = Error;
2351 a.s = g_strdup_printf("Syntax error in searchengines file '%s'", searchengines_file);
2352 echo(&a);
2353 break;
2354 case READING_FAILED:
2355 a.i = Error;
2356 a.s = g_strdup_printf("Could not read searchengines file '%s'", searchengines_file);
2357 echo(&a);
2358 break;
2359 default:
2360 break;
2362 g_free(searchengines_file);
2364 /* command line argument: URL */
2365 if (argc > 1) {
2366 strncpy(url, argv[argc - 1], 255);
2367 } else {
2368 strncpy(url, startpage, 255);
2371 a.i = TargetCurrent;
2372 a.s = url;
2373 open_arg(&a);
2374 gtk_main();
2376 mop_up();
2378 return EXIT_SUCCESS;