fix icon apearing when http_proxy is set
[xombrero.git] / xombrero.c
bloba88c94804ae9667cf09f8a019b3ec133af7c1dd6
1 /*
2 * Copyright (c) 2010, 2011 Marco Peereboom <marco@peereboom.us>
3 * Copyright (c) 2011 Stevan Andjelkovic <stevan@student.chalmers.se>
4 * Copyright (c) 2010, 2011, 2012 Edd Barrett <vext01@gmail.com>
5 * Copyright (c) 2011 Todd T. Fries <todd@fries.net>
6 * Copyright (c) 2011 Raphael Graf <r@undefined.ch>
7 * Copyright (c) 2011 Michal Mazurek <akfaew@jasminek.net>
8 * Copyright (c) 2012 Josh Rickmar <jrick@devio.us>
10 * Permission to use, copy, modify, and distribute this software for any
11 * purpose with or without fee is hereby granted, provided that the above
12 * copyright notice and this permission notice appear in all copies.
14 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
15 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
16 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
17 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
18 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
19 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
20 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
23 #include <xombrero.h>
24 #include "version.h"
26 char *version = XOMBRERO_VERSION;
28 #ifdef XT_DEBUG
29 uint32_t swm_debug = 0
30 | XT_D_MOVE
31 | XT_D_KEY
32 | XT_D_TAB
33 | XT_D_URL
34 | XT_D_CMD
35 | XT_D_NAV
36 | XT_D_DOWNLOAD
37 | XT_D_CONFIG
38 | XT_D_JS
39 | XT_D_FAVORITE
40 | XT_D_PRINTING
41 | XT_D_COOKIE
42 | XT_D_KEYBINDING
43 | XT_D_CLIP
44 | XT_D_BUFFERCMD
45 | XT_D_INSPECTOR
46 | XT_D_VISITED
47 | XT_D_HISTORY
49 #endif
51 #ifdef USE_THREADS
52 GCRY_THREAD_OPTION_PTHREAD_IMPL;
53 #endif
55 char *icons[] = {
56 "xombreroicon16.png",
57 "xombreroicon32.png",
58 "xombreroicon48.png",
59 "xombreroicon64.png",
60 "xombreroicon128.png"
63 struct session {
64 TAILQ_ENTRY(session) entry;
65 const gchar *name;
67 TAILQ_HEAD(session_list, session);
69 struct undo {
70 TAILQ_ENTRY(undo) entry;
71 gchar *uri;
72 GList *history;
73 int back; /* Keeps track of how many back
74 * history items there are. */
76 TAILQ_HEAD(undo_tailq, undo);
78 struct command_entry {
79 char *line;
80 TAILQ_ENTRY(command_entry) entry;
82 TAILQ_HEAD(command_list, command_entry);
84 /* defines */
85 #define XT_CACHE_DIR ("cache")
86 #define XT_CERT_DIR ("certs")
87 #define XT_CERT_CACHE_DIR ("certs_cache")
88 #define XT_JS_DIR ("js")
89 #define XT_SESSIONS_DIR ("sessions")
90 #define XT_TEMP_DIR ("tmp")
91 #define XT_QMARKS_FILE ("quickmarks")
92 #define XT_SAVED_TABS_FILE ("main_session")
93 #define XT_RESTART_TABS_FILE ("restart_tabs")
94 #define XT_SOCKET_FILE ("socket")
95 #define XT_SAVE_SESSION_ID ("SESSION_NAME=")
96 #define XT_SEARCH_FILE ("search_history")
97 #define XT_COMMAND_FILE ("command_history")
98 #define XT_DLMAN_REFRESH "10"
99 #define XT_MAX_URL_LENGTH (4096) /* 1 page is atomic, don't make bigger */
100 #define XT_MAX_UNDO_CLOSE_TAB (32)
101 #define XT_PRINT_EXTRA_MARGIN 10
102 #define XT_URL_REGEX ("^[[:blank:]]*[^[:blank:]]*([[:alnum:]-]+\\.)+[[:alnum:]-][^[:blank:]]*[[:blank:]]*$")
103 #define XT_INVALID_MARK (-1) /* XXX this is a double, maybe use something else, like a nan */
105 /* colors */
106 #define XT_COLOR_RED "#cc0000"
107 #define XT_COLOR_YELLOW "#ffff66"
108 #define XT_COLOR_BLUE "lightblue"
109 #define XT_COLOR_GREEN "#99ff66"
110 #define XT_COLOR_WHITE "white"
111 #define XT_COLOR_BLACK "black"
113 #define XT_COLOR_CT_BACKGROUND "#000000"
114 #define XT_COLOR_CT_INACTIVE "#dddddd"
115 #define XT_COLOR_CT_ACTIVE "#bbbb00"
116 #define XT_COLOR_CT_SEPARATOR "#555555"
118 #define XT_COLOR_SB_SEPARATOR "#555555"
120 /* CSS element names */
121 #define XT_CSS_NORMAL ""
122 #define XT_CSS_RED "red"
123 #define XT_CSS_YELLOW "yellow"
124 #define XT_CSS_GREEN "green"
125 #define XT_CSS_BLUE "blue"
126 #define XT_CSS_HIDDEN "hidden"
127 #define XT_CSS_ACTIVE "active"
129 #define XT_PROTO_DELIM "://"
131 /* actions */
132 #define XT_MOVE_INVALID (0)
133 #define XT_MOVE_DOWN (1)
134 #define XT_MOVE_UP (2)
135 #define XT_MOVE_BOTTOM (3)
136 #define XT_MOVE_TOP (4)
137 #define XT_MOVE_PAGEDOWN (5)
138 #define XT_MOVE_PAGEUP (6)
139 #define XT_MOVE_HALFDOWN (7)
140 #define XT_MOVE_HALFUP (8)
141 #define XT_MOVE_LEFT (9)
142 #define XT_MOVE_FARLEFT (10)
143 #define XT_MOVE_RIGHT (11)
144 #define XT_MOVE_FARRIGHT (12)
145 #define XT_MOVE_PERCENT (13)
146 #define XT_MOVE_CENTER (14)
148 #define XT_QMARK_SET (0)
149 #define XT_QMARK_OPEN (1)
150 #define XT_QMARK_TAB (2)
152 #define XT_MARK_SET (0)
153 #define XT_MARK_GOTO (1)
155 #define XT_GO_UP_ROOT (999)
157 #define XT_NAV_INVALID (0)
158 #define XT_NAV_BACK (1)
159 #define XT_NAV_FORWARD (2)
160 #define XT_NAV_RELOAD (3)
161 #define XT_NAV_STOP (4)
163 #define XT_FOCUS_INVALID (0)
164 #define XT_FOCUS_URI (1)
165 #define XT_FOCUS_SEARCH (2)
167 #define XT_SEARCH_INVALID (0)
168 #define XT_SEARCH_NEXT (1)
169 #define XT_SEARCH_PREV (2)
171 #define XT_PASTE_CURRENT_TAB (0)
172 #define XT_PASTE_NEW_TAB (1)
174 #define XT_ZOOM_IN (-1)
175 #define XT_ZOOM_OUT (-2)
176 #define XT_ZOOM_NORMAL (100)
178 #define XT_SES_DONOTHING (0)
179 #define XT_SES_CLOSETABS (1)
181 #define XT_PREFIX (1<<0)
182 #define XT_USERARG (1<<1)
183 #define XT_URLARG (1<<2)
184 #define XT_INTARG (1<<3)
185 #define XT_SESSARG (1<<4)
186 #define XT_SETARG (1<<5)
188 #define XT_HINT_NEWTAB (1<<0)
190 #define XT_BUFCMD_SZ (8)
192 #define XT_EJS_SHOW (1<<0)
194 GtkWidget * create_button(char *, char *, int);
196 void recalc_tabs(void);
197 void recolor_compact_tabs(void);
198 void set_current_tab(int page_num);
199 gboolean update_statusbar_position(GtkAdjustment*, gpointer);
200 void marks_clear(struct tab *t);
202 /* globals */
203 extern char *__progname;
204 char * const *start_argv;
205 struct passwd *pwd;
206 GtkWidget *main_window;
207 GtkNotebook *notebook;
208 GtkWidget *tab_bar;
209 GtkWidget *tab_bar_box;
210 GtkWidget *arrow, *abtn;
211 GdkEvent *fevent = NULL;
212 struct tab_list tabs;
213 struct history_list hl;
214 int hl_purge_count = 0;
215 struct session_list sessions;
216 struct wl_list c_wl;
217 struct wl_list js_wl;
218 struct wl_list pl_wl;
219 struct wl_list force_https;
220 struct wl_list svil;
221 struct strict_transport_tree st_tree;
222 struct undo_tailq undos;
223 struct keybinding_list kbl;
224 struct sp_list spl;
225 struct user_agent_list ua_list;
226 struct http_accept_list ha_list;
227 struct domain_id_list di_list;
228 struct cmd_alias_list cal;
229 struct custom_uri_list cul;
230 struct command_list chl;
231 struct command_list shl;
232 struct command_entry *history_at;
233 struct command_entry *search_at;
234 struct secviolation_list svl;
235 struct set_reject_list srl;
236 int undo_count;
237 int cmd_history_count = 0;
238 int search_history_count = 0;
239 char *global_search;
240 uint64_t blocked_cookies = 0;
241 char named_session[PATH_MAX];
242 GtkListStore *completion_model;
243 GtkListStore *buffers_store;
244 char *stylesheet;
246 char *qmarks[XT_NOQMARKS];
247 int btn_down; /* M1 down in any wv */
248 regex_t url_re; /* guess_search regex */
250 /* starts from 1 to catch atoi() failures when calling xtp_handle_dl() */
251 int next_download_id = 1;
253 void xxx_dir(char *);
254 int icon_size_map(int);
255 void activate_uri_entry_cb(GtkWidget*, struct tab *);
257 void
258 history_delete(struct command_list *l, int *counter)
260 struct command_entry *c;
262 if (l == NULL || counter == NULL)
263 return;
265 c = TAILQ_LAST(l, command_list);
266 if (c == NULL)
267 return;
269 TAILQ_REMOVE(l, c, entry);
270 *counter -= 1;
271 g_free(c->line);
272 g_free(c);
275 void
276 history_add(struct command_list *list, char *file, char *l, int *counter)
278 struct command_entry *c;
279 FILE *f;
281 if (list == NULL || l == NULL || counter == NULL)
282 return;
284 /* don't add the same line */
285 c = TAILQ_FIRST(list);
286 if (c)
287 if (!strcmp(c->line + 1 /* skip space */, l))
288 return;
290 c = g_malloc0(sizeof *c);
291 c->line = g_strdup_printf(" %s", l);
293 *counter += 1;
294 TAILQ_INSERT_HEAD(list, c, entry);
296 if (*counter > 1000)
297 history_delete(list, counter);
299 if (history_autosave && file) {
300 f = fopen(file, "w");
301 if (f == NULL) {
302 show_oops(NULL, "couldn't write history %s", file);
303 return;
306 TAILQ_FOREACH_REVERSE(c, list, command_list, entry) {
307 c->line[0] = ' ';
308 fprintf(f, "%s\n", c->line);
311 fclose(f);
316 history_read(struct command_list *list, char *file, int *counter)
318 FILE *f;
319 char *s, line[65536];
321 if (list == NULL || file == NULL)
322 return (1);
324 f = fopen(file, "r");
325 if (f == NULL) {
326 startpage_add("couldn't open history file %s", file);
327 return (1);
330 for (;;) {
331 s = fgets(line, sizeof line, f);
332 if (s == NULL || feof(f) || ferror(f))
333 break;
334 if ((s = strchr(line, '\n')) == NULL) {
335 startpage_add("invalid history file %s", file);
336 fclose(f);
337 return (1);
339 *s = '\0';
341 history_add(list, NULL, line + 1, counter);
344 fclose(f);
346 return (0);
349 /* marks array storage. */
350 char
351 indextomark(int i)
353 if (i < 0 || i >= XT_NOMARKS)
354 return (0);
356 return XT_MARKS[i];
360 marktoindex(char m)
362 char *ret;
364 if ((ret = strchr(XT_MARKS, m)) != NULL)
365 return ret - XT_MARKS;
367 return (-1);
370 /* quickmarks array storage. */
371 char
372 indextoqmark(int i)
374 if (i < 0 || i >= XT_NOQMARKS)
375 return (0);
377 return XT_QMARKS[i];
381 qmarktoindex(char m)
383 char *ret;
385 if ((ret = strchr(XT_QMARKS, m)) != NULL)
386 return ret - XT_QMARKS;
388 return (-1);
392 is_g_object_setting(GObject *o, char *str)
394 guint n_props = 0, i;
395 GParamSpec **proplist;
396 int rv = 0;
398 if (!G_IS_OBJECT(o))
399 return (0);
401 proplist = g_object_class_list_properties(G_OBJECT_GET_CLASS(o),
402 &n_props);
404 for (i = 0; i < n_props; i++) {
405 if (! strcmp(proplist[i]->name, str)) {
406 rv = 1;
407 break;
411 g_free(proplist);
412 return (rv);
415 struct tab *
416 get_current_tab(void)
418 struct tab *t;
420 TAILQ_FOREACH(t, &tabs, entry) {
421 if (t->tab_id == gtk_notebook_get_current_page(notebook))
422 return (t);
425 warnx("%s: no current tab", __func__);
427 return (NULL);
431 set_ssl_ca_file(struct settings *s, char *file)
433 struct stat sb;
435 if (file == NULL || strlen(file) == 0)
436 return (-1);
437 if (stat(file, &sb)) {
438 warnx("no CA file: %s", file);
439 return (-1);
441 expand_tilde(ssl_ca_file, sizeof ssl_ca_file, file);
442 g_object_set(session,
443 SOUP_SESSION_SSL_CA_FILE, ssl_ca_file,
444 SOUP_SESSION_SSL_STRICT, ssl_strict_certs,
445 (void *)NULL);
446 return (0);
449 void
450 set_status(struct tab *t, gchar *fmt, ...)
452 va_list ap;
453 gchar *status;
455 va_start(ap, fmt);
457 status = g_strdup_vprintf(fmt, ap);
459 gtk_entry_set_text(GTK_ENTRY(t->sbe.uri), status);
461 if (!t->status)
462 t->status = status;
463 else if (strcmp(t->status, status)) {
464 /* set new status */
465 g_free(t->status);
466 t->status = status;
467 } else
468 g_free(status);
470 va_end(ap);
473 void
474 hide_cmd(struct tab *t)
476 DNPRINTF(XT_D_CMD, "%s: tab %d\n", __func__, t->tab_id);
478 history_at = NULL; /* just in case */
479 search_at = NULL; /* just in case */
480 gtk_widget_set_can_focus(t->cmd, FALSE);
481 gtk_widget_hide(t->cmd);
484 void
485 show_cmd(struct tab *t, const char *s)
487 DNPRINTF(XT_D_CMD, "%s: tab %d\n", __func__, t->tab_id);
489 /* without this you can't middle click in t->cmd to paste */
490 gtk_entry_set_text(GTK_ENTRY(t->cmd), "");
492 history_at = NULL;
493 search_at = NULL;
494 gtk_widget_hide(t->oops);
495 gtk_widget_set_can_focus(t->cmd, TRUE);
496 gtk_widget_show(t->cmd);
498 gtk_widget_grab_focus(GTK_WIDGET(t->cmd));
499 #if GTK_CHECK_VERSION(3, 0, 0)
500 gtk_widget_set_name(t->cmd, XT_CSS_NORMAL);
501 #else
502 gtk_widget_modify_base(t->cmd, GTK_STATE_NORMAL,
503 &t->default_style->base[GTK_STATE_NORMAL]);
504 #endif
505 gtk_entry_set_text(GTK_ENTRY(t->cmd), s);
506 gtk_editable_set_position(GTK_EDITABLE(t->cmd), -1);
509 void
510 hide_buffers(struct tab *t)
512 gtk_widget_hide(t->buffers);
513 gtk_widget_set_can_focus(t->buffers, FALSE);
514 gtk_list_store_clear(buffers_store);
517 enum {
518 COL_ID = 0,
519 COL_FAVICON,
520 COL_TITLE,
521 NUM_COLS
525 sort_tabs_by_page_num(struct tab ***stabs)
527 int num_tabs = 0;
528 struct tab *t;
530 num_tabs = gtk_notebook_get_n_pages(notebook);
532 *stabs = g_malloc0(num_tabs * sizeof(struct tab *));
534 TAILQ_FOREACH(t, &tabs, entry)
535 (*stabs)[gtk_notebook_page_num(notebook, t->vbox)] = t;
537 return (num_tabs);
540 void
541 buffers_make_list(void)
543 int i, num_tabs;
544 const gchar *title = NULL;
545 GtkTreeIter iter;
546 struct tab **stabs = NULL;
548 num_tabs = sort_tabs_by_page_num(&stabs);
550 for (i = 0; i < num_tabs; i++)
551 if (stabs[i]) {
552 gtk_list_store_append(buffers_store, &iter);
553 title = get_title(stabs[i], FALSE);
554 gtk_list_store_set(buffers_store, &iter,
555 COL_ID, i + 1, /* Enumerate the tabs starting from 1
556 * rather than 0. */
557 COL_FAVICON, gtk_image_get_pixbuf
558 (GTK_IMAGE(stabs[i]->tab_elems.favicon)),
559 COL_TITLE, title,
560 -1);
563 g_free(stabs);
566 void
567 show_buffers(struct tab *t)
569 GtkTreeIter iter;
570 GtkTreeSelection *sel;
571 GtkTreePath *path;
572 int index;
574 if (gtk_widget_get_visible(GTK_WIDGET(t->buffers)))
575 return;
577 buffers_make_list();
579 sel = gtk_tree_view_get_selection(GTK_TREE_VIEW(t->buffers));
580 index = gtk_notebook_get_current_page(notebook);
581 path = gtk_tree_path_new_from_indices(index, -1);
582 if (gtk_tree_model_get_iter(GTK_TREE_MODEL(buffers_store), &iter, path))
583 gtk_tree_selection_select_iter(sel, &iter);
584 gtk_tree_path_free(path);
586 gtk_widget_show(t->buffers);
587 gtk_widget_set_can_focus(t->buffers, TRUE);
588 gtk_widget_grab_focus(GTK_WIDGET(t->buffers));
591 void
592 toggle_buffers(struct tab *t)
594 if (gtk_widget_get_visible(t->buffers))
595 hide_buffers(t);
596 else
597 show_buffers(t);
601 buffers(struct tab *t, struct karg *args)
603 show_buffers(t);
605 return (0);
609 set_scrollbar_visibility(struct tab *t, int visible)
611 #if GTK_CHECK_VERSION(3, 0, 0)
612 GtkWidget *h_scrollbar, *v_scrollbar;
614 h_scrollbar = gtk_scrolled_window_get_hscrollbar(
615 GTK_SCROLLED_WINDOW(t->browser_win));
616 v_scrollbar = gtk_scrolled_window_get_vscrollbar(
617 GTK_SCROLLED_WINDOW(t->browser_win));
619 if (visible == 0) {
620 gtk_widget_set_name(h_scrollbar, XT_CSS_HIDDEN);
621 gtk_widget_set_name(v_scrollbar, XT_CSS_HIDDEN);
622 } else {
623 gtk_widget_set_name(h_scrollbar, "");
624 gtk_widget_set_name(v_scrollbar, "");
627 return (0);
628 #else
629 return (visible == 0);
630 #endif
633 void
634 hide_oops(struct tab *t)
636 gtk_widget_hide(t->oops);
639 void
640 show_oops(struct tab *at, const char *fmt, ...)
642 va_list ap;
643 char *msg = NULL;
644 struct tab *t = NULL;
646 if (fmt == NULL)
647 return;
649 if (at == NULL) {
650 if ((t = get_current_tab()) == NULL)
651 return;
652 } else
653 t = at;
655 va_start(ap, fmt);
656 if ((msg = g_strdup_vprintf(fmt, ap)) == NULL)
657 errx(1, "show_oops failed");
658 va_end(ap);
660 gtk_entry_set_text(GTK_ENTRY(t->oops), msg);
661 gtk_widget_hide(t->cmd);
662 gtk_widget_show(t->oops);
664 if (msg)
665 g_free(msg);
668 char work_dir[PATH_MAX];
669 char certs_dir[PATH_MAX];
670 char certs_cache_dir[PATH_MAX];
671 char js_dir[PATH_MAX];
672 char cache_dir[PATH_MAX];
673 char sessions_dir[PATH_MAX];
674 char temp_dir[PATH_MAX];
675 char cookie_file[PATH_MAX];
676 char *strict_transport_file = NULL;
677 SoupSession *session;
678 SoupCookieJar *s_cookiejar;
679 SoupCookieJar *p_cookiejar;
680 char rc_fname[PATH_MAX];
682 struct mime_type_list mtl;
683 struct alias_list aliases;
685 /* protos */
686 struct tab *create_new_tab(char *, struct undo *, int, int);
687 void delete_tab(struct tab *);
688 void setzoom_webkit(struct tab *, int);
689 int download_rb_cmp(struct download *, struct download *);
690 gboolean cmd_execute(struct tab *t, char *str);
693 history_rb_cmp(struct history *h1, struct history *h2)
695 return (strcmp(h1->uri, h2->uri));
697 RB_GENERATE(history_list, history, entry, history_rb_cmp);
700 download_rb_cmp(struct download *e1, struct download *e2)
702 return (e1->id < e2->id ? -1 : e1->id > e2->id);
704 RB_GENERATE(download_list, download, entry, download_rb_cmp);
707 secviolation_rb_cmp(struct secviolation *s1, struct secviolation *s2)
709 return (s1->xtp_arg < s2->xtp_arg ? -1 : s1->xtp_arg > s2->xtp_arg);
711 RB_GENERATE(secviolation_list, secviolation, entry, secviolation_rb_cmp);
714 user_agent_rb_cmp(struct user_agent *ua1, struct user_agent *ua2)
716 return (ua1->id < ua2->id ? -1 : ua1->id > ua2->id);
718 RB_GENERATE(user_agent_list, user_agent, entry, user_agent_rb_cmp);
721 http_accept_rb_cmp(struct http_accept *ha1, struct http_accept *ha2)
723 return (ha1->id < ha2->id ? -1 : ha1->id > ha2->id);
725 RB_GENERATE(http_accept_list, http_accept, entry, http_accept_rb_cmp);
728 domain_id_rb_cmp(struct domain_id *d1, struct domain_id *d2)
730 return (strcmp(d1->domain, d2->domain));
732 RB_GENERATE(domain_id_list, domain_id, entry, domain_id_rb_cmp);
734 struct valid_url_types {
735 char *type;
736 } vut[] = {
737 { "http://" },
738 { "https://" },
739 { "ftp://" },
740 { "file://" },
741 { XT_URI_ABOUT },
742 { XT_XTP_STR },
746 valid_url_type(char *url)
748 int i;
750 for (i = 0; i < LENGTH(vut); i++)
751 if (!strncasecmp(vut[i].type, url, strlen(vut[i].type)))
752 return (0);
754 return (1);
757 char *
758 match_alias(char *url_in)
760 struct alias *a;
761 char *arg;
762 char *url_out = NULL, *search, *enc_arg;
763 char **sv;
765 search = g_strdup(url_in);
766 arg = search;
767 if (strsep(&arg, " \t") == NULL) {
768 show_oops(NULL, "match_alias: NULL URL");
769 goto done;
772 TAILQ_FOREACH(a, &aliases, entry) {
773 if (!strcmp(search, a->a_name))
774 break;
777 if (a != NULL) {
778 DNPRINTF(XT_D_URL, "match_alias: matched alias %s\n",
779 a->a_name);
780 if (arg == NULL)
781 arg = "";
782 enc_arg = soup_uri_encode(arg, XT_RESERVED_CHARS);
783 sv = g_strsplit(a->a_uri, "%s", 2);
784 if (arg != NULL)
785 url_out = g_strjoinv(enc_arg, sv);
786 else
787 url_out = g_strjoinv("", sv);
788 g_free(enc_arg);
789 g_strfreev(sv);
791 done:
792 g_free(search);
793 return (url_out);
796 char *
797 guess_url_type(char *url_in)
799 struct stat sb;
800 char cwd[PATH_MAX] = {0};
801 char *url_out = NULL, *enc_search = NULL;
802 char *path = NULL;
803 char **sv = NULL;
804 int i;
807 /* substitute aliases */
808 url_out = match_alias(url_in);
809 if (url_out != NULL)
810 return (url_out);
812 /* see if we are an about page */
813 if (!strncmp(url_in, XT_URI_ABOUT, XT_URI_ABOUT_LEN))
814 for (i = 0; i < about_list_size(); i++)
815 if (!strcmp(&url_in[XT_URI_ABOUT_LEN],
816 about_list[i].name)) {
817 url_out = g_strdup(url_in);
818 goto done;
821 if (guess_search && url_regex &&
822 !(g_str_has_prefix(url_in, "http://") ||
823 g_str_has_prefix(url_in, "https://"))) {
824 if (regexec(&url_re, url_in, 0, NULL, 0)) {
825 /* invalid URI so search instead */
826 enc_search = soup_uri_encode(url_in, XT_RESERVED_CHARS);
827 sv = g_strsplit(search_string, "%s", 2);
828 url_out = g_strjoinv(enc_search, sv);
829 g_free(enc_search);
830 g_strfreev(sv);
831 goto done;
835 /* XXX not sure about this heuristic */
836 if (stat(url_in, &sb) == 0) {
837 if (url_in[0] == '/')
838 url_out = g_filename_to_uri(url_in, NULL, NULL);
839 else {
840 if (getcwd(cwd, PATH_MAX) != NULL) {
841 path = g_strdup_printf("%s" PS "%s", cwd,
842 url_in);
843 url_out = g_filename_to_uri(path, NULL, NULL);
844 g_free(path);
847 } else
848 url_out = g_strdup_printf("http://%s", url_in); /* guess http */
849 done:
850 DNPRINTF(XT_D_URL, "guess_url_type: guessed %s\n", url_out);
852 return (url_out);
855 void
856 set_normal_tab_meaning(struct tab *t)
858 if (t == NULL)
859 return;
861 t->xtp_meaning = XT_XTP_TAB_MEANING_NORMAL;
862 if (t->session_key != NULL) {
863 g_free(t->session_key);
864 t->session_key = NULL;
868 void
869 load_uri(struct tab *t, gchar *uri)
871 struct karg args;
872 gchar *newuri = NULL;
873 int i;
875 if (uri == NULL)
876 return;
878 /* Strip leading spaces. */
879 while (*uri && isspace(*uri))
880 uri++;
882 if (strlen(uri) == 0) {
883 blank(t, NULL);
884 return;
887 set_normal_tab_meaning(t);
889 if (valid_url_type(uri)) {
890 newuri = guess_url_type(uri);
891 uri = newuri;
894 if (!strncmp(uri, XT_URI_ABOUT, XT_URI_ABOUT_LEN)) {
895 for (i = 0; i < about_list_size(); i++)
896 if (!strcmp(&uri[XT_URI_ABOUT_LEN], about_list[i].name) &&
897 about_list[i].func != NULL) {
898 bzero(&args, sizeof args);
899 about_list[i].func(t, &args);
900 gtk_widget_set_sensitive(GTK_WIDGET(t->stop),
901 FALSE);
902 goto done;
904 show_oops(t, "invalid about page");
905 goto done;
908 set_status(t, "Loading: %s", (char *)uri);
909 marks_clear(t);
910 webkit_web_view_load_uri(t->wv, uri);
911 done:
912 if (newuri)
913 g_free(newuri);
916 const gchar *
917 get_uri(struct tab *t)
919 const gchar *uri = NULL;
921 if (webkit_web_view_get_load_status(t->wv) == WEBKIT_LOAD_FAILED &&
922 !t->download_requested)
923 return (NULL);
924 if (t->xtp_meaning == XT_XTP_TAB_MEANING_NORMAL)
925 uri = webkit_web_view_get_uri(t->wv);
926 else {
927 /* use tmp_uri to make sure it is g_freed */
928 if (t->tmp_uri)
929 g_free(t->tmp_uri);
930 t->tmp_uri = g_strdup_printf("%s%s", XT_URI_ABOUT,
931 about_list[t->xtp_meaning].name);
932 uri = t->tmp_uri;
934 return (uri);
937 const gchar *
938 get_title(struct tab *t, bool window)
940 const gchar *set = NULL, *title = NULL;
941 WebKitLoadStatus status = webkit_web_view_get_load_status(t->wv);
943 if (status == WEBKIT_LOAD_PROVISIONAL ||
944 (status == WEBKIT_LOAD_FAILED && !t->download_requested) ||
945 t->xtp_meaning == XT_XTP_TAB_MEANING_BL)
946 goto notitle;
948 title = webkit_web_view_get_title(t->wv);
949 if ((set = title ? title : get_uri(t)))
950 return set;
952 notitle:
953 set = window ? XT_NAME : "(untitled)";
955 return set;
958 struct mime_type *
959 find_mime_type(char *mime_type)
961 struct mime_type *m, *def = NULL, *rv = NULL;
963 TAILQ_FOREACH(m, &mtl, entry) {
964 if (m->mt_default &&
965 !strncmp(mime_type, m->mt_type, strlen(m->mt_type)))
966 def = m;
968 if (m->mt_default == 0 && !strcmp(mime_type, m->mt_type)) {
969 rv = m;
970 break;
974 if (rv == NULL)
975 rv = def;
977 return (rv);
981 * This only escapes the & and < characters, as per the discussion found here:
982 * http://lists.apple.com/archives/Webkitsdk-dev/2007/May/msg00056.html
984 char *
985 html_escape(const char *val)
987 char *s, *sp;
988 char **sv;
990 if (val == NULL)
991 return NULL;
993 sv = g_strsplit(val, "&", -1);
994 s = g_strjoinv("&amp;", sv);
995 g_strfreev(sv);
996 sp = s;
997 sv = g_strsplit(val, "<", -1);
998 s = g_strjoinv("&lt;", sv);
999 g_strfreev(sv);
1000 g_free(sp);
1001 return (s);
1004 struct wl_entry *
1005 wl_find_uri(const gchar *s, struct wl_list *wl)
1007 int i;
1008 char *ss;
1009 struct wl_entry *w;
1011 if (s == NULL || wl == NULL)
1012 return (NULL);
1014 if (!strncmp(s, "http://", strlen("http://")))
1015 s = &s[strlen("http://")];
1016 else if (!strncmp(s, "https://", strlen("https://")))
1017 s = &s[strlen("https://")];
1019 if (strlen(s) < 2)
1020 return (NULL);
1022 for (i = 0; i < strlen(s) + 1 /* yes er need this */; i++)
1023 /* chop string at first slash */
1024 if (s[i] == '/' || s[i] == ':' || s[i] == '\0') {
1025 ss = g_strdup(s);
1026 ss[i] = '\0';
1027 w = wl_find(ss, wl);
1028 g_free(ss);
1029 return (w);
1032 return (NULL);
1035 char *
1036 js_ref_to_string(JSContextRef context, JSValueRef ref)
1038 char *s = NULL;
1039 size_t l;
1040 JSStringRef jsref;
1042 jsref = JSValueToStringCopy(context, ref, NULL);
1043 if (jsref == NULL)
1044 return (NULL);
1046 l = JSStringGetMaximumUTF8CStringSize(jsref);
1047 s = g_malloc(l);
1048 if (s)
1049 JSStringGetUTF8CString(jsref, s, l);
1050 JSStringRelease(jsref);
1052 return (s);
1055 #define XT_JS_DONE ("done;")
1056 #define XT_JS_DONE_LEN (strlen(XT_JS_DONE))
1057 #define XT_JS_INSERT ("insert;")
1058 #define XT_JS_INSERT_LEN (strlen(XT_JS_INSERT))
1061 run_script(struct tab *t, char *s)
1063 JSGlobalContextRef ctx;
1064 WebKitWebFrame *frame;
1065 JSStringRef str;
1066 JSValueRef val, exception;
1067 char *es;
1069 DNPRINTF(XT_D_JS, "%s: tab %d %s\n", __func__,
1070 t->tab_id, s == (char *)JS_HINTING ? "JS_HINTING" : s);
1072 frame = webkit_web_view_get_main_frame(t->wv);
1073 ctx = webkit_web_frame_get_global_context(frame);
1075 str = JSStringCreateWithUTF8CString(s);
1076 val = JSEvaluateScript(ctx, str, JSContextGetGlobalObject(ctx),
1077 NULL, 0, &exception);
1078 JSStringRelease(str);
1080 DNPRINTF(XT_D_JS, "%s: val %p\n", __func__, val);
1081 if (val == NULL) {
1082 es = js_ref_to_string(ctx, exception);
1083 if (es) {
1084 DNPRINTF(XT_D_JS, "%s: exception %s\n", __func__, es);
1085 g_free(es);
1087 return (1);
1088 } else {
1089 es = js_ref_to_string(ctx, val);
1090 #if 0
1091 /* return values */
1092 if (!strncmp(es, XT_JS_DONE, XT_JS_DONE_LEN))
1093 ; /* do nothing */
1094 if (!strncmp(es, XT_JS_INSERT, XT_JS_INSERT_LEN))
1095 ; /* do nothing */
1096 #endif
1097 if (es) {
1098 DNPRINTF(XT_D_JS, "%s: val %s\n", __func__, es);
1099 g_free(es);
1103 return (0);
1107 run_script_locked(struct tab *t, char *s)
1109 int rv;
1110 #ifdef USE_THREADS
1111 gdk_threads_enter();
1112 #endif
1113 rv = run_script(t, s);
1114 #ifdef USE_THREADS
1115 GDK_FLUSH();
1116 gdk_threads_leave();
1117 #endif
1118 return (rv);
1121 void
1122 enable_hints(struct tab *t)
1124 DNPRINTF(XT_D_JS, "%s: tab %d\n", __func__, t->tab_id);
1126 if (t->new_tab)
1127 run_script(t, "hints.createHints('', 'F');");
1128 else
1129 run_script(t, "hints.createHints('', 'f');");
1130 t->mode = XT_MODE_HINT;
1133 void
1134 disable_hints(struct tab *t)
1136 DNPRINTF(XT_D_JS, "%s: tab %d\n", __func__, t->tab_id);
1138 run_script(t, "hints.clearHints();");
1139 t->mode = XT_MODE_COMMAND;
1140 t->new_tab = 0;
1144 passthrough(struct tab *t, struct karg *args)
1146 t->mode = XT_MODE_PASSTHROUGH;
1147 return (0);
1151 modurl(struct tab *t, struct karg *args)
1153 const gchar *uri = NULL;
1154 char *u = NULL;
1156 /* XXX kind of a bad hack, but oh well */
1157 if (gtk_widget_has_focus(t->uri_entry)) {
1158 if ((uri = gtk_entry_get_text(GTK_ENTRY(t->uri_entry))) &&
1159 (strlen(uri))) {
1160 u = g_strdup_printf("www.%s.com", uri);
1161 gtk_entry_set_text(GTK_ENTRY(t->uri_entry), u);
1162 g_free(u);
1163 activate_uri_entry_cb(t->uri_entry, t);
1166 return (0);
1170 hint(struct tab *t, struct karg *args)
1173 DNPRINTF(XT_D_JS, "hint: tab %d args %d\n", t->tab_id, args->i);
1175 if (t->mode == XT_MODE_HINT) {
1176 if (args->i == XT_HINT_NEWTAB)
1177 t->new_tab = 1;
1178 enable_hints(t);
1179 } else
1180 disable_hints(t);
1182 return (0);
1185 void
1186 apply_style(struct tab *t)
1188 t->styled = 1;
1189 g_object_set(G_OBJECT(t->settings),
1190 "user-stylesheet-uri", t->stylesheet, (char *)NULL);
1193 void
1194 remove_style(struct tab *t)
1196 t->styled = 0;
1197 g_object_set(G_OBJECT(t->settings),
1198 "user-stylesheet-uri", NULL, (char *)NULL);
1202 userstyle_cmd(struct tab *t, struct karg *args)
1204 char script[PATH_MAX] = {'\0'};
1205 char *script_uri;
1206 struct tab *tt;
1208 DNPRINTF(XT_D_JS, "userstyle_cmd: tab %d\n", t->tab_id);
1210 if (args->s != NULL && strlen(args->s)) {
1211 expand_tilde(script, sizeof script, args->s);
1212 script_uri = g_filename_to_uri(script, NULL, NULL);
1213 } else
1214 script_uri = g_strdup(userstyle);
1216 if (script_uri == NULL)
1217 return (1);
1219 switch (args->i) {
1220 case XT_STYLE_CURRENT_TAB:
1221 if (t->styled && !strcmp(script_uri, t->stylesheet))
1222 remove_style(t);
1223 else {
1224 if (t->stylesheet)
1225 g_free(t->stylesheet);
1226 t->stylesheet = g_strdup(script_uri);
1227 apply_style(t);
1229 break;
1230 case XT_STYLE_GLOBAL:
1231 if (userstyle_global && !strcmp(script_uri, t->stylesheet)) {
1232 userstyle_global = 0;
1233 TAILQ_FOREACH(tt, &tabs, entry)
1234 remove_style(tt);
1235 } else {
1236 userstyle_global = 1;
1238 /* need to save this stylesheet for new tabs */
1239 if (stylesheet)
1240 g_free(stylesheet);
1241 stylesheet = g_strdup(script_uri);
1243 TAILQ_FOREACH(tt, &tabs, entry) {
1244 if (tt->stylesheet)
1245 g_free(tt->stylesheet);
1246 tt->stylesheet = g_strdup(script_uri);
1247 apply_style(tt);
1250 break;
1253 g_free(script_uri);
1255 return (0);
1259 quit(struct tab *t, struct karg *args)
1261 if (save_global_history)
1262 save_global_history_to_disk(t);
1264 gtk_main_quit();
1266 return (1);
1269 void
1270 restore_sessions_list(void)
1272 DIR *sdir = NULL;
1273 struct dirent *dp = NULL;
1274 struct session *s;
1275 int reg;
1277 sdir = opendir(sessions_dir);
1278 if (sdir) {
1279 while ((dp = readdir(sdir)) != NULL) {
1280 #if defined __MINGW32__
1281 reg = 1; /* windows only has regular files */
1282 #else
1283 reg = dp->d_type == DT_REG;
1284 #endif
1285 if (dp && reg) {
1286 s = g_malloc(sizeof(struct session));
1287 s->name = g_strdup(dp->d_name);
1288 TAILQ_INSERT_TAIL(&sessions, s, entry);
1291 closedir(sdir);
1296 open_tabs(struct tab *t, struct karg *a)
1298 char file[PATH_MAX];
1299 FILE *f = NULL;
1300 char *uri = NULL;
1301 int rv = 1;
1302 struct tab *ti, *tt;
1304 if (a == NULL)
1305 goto done;
1307 ti = TAILQ_LAST(&tabs, tab_list);
1309 snprintf(file, sizeof file, "%s" PS "%s", sessions_dir, a->s);
1310 if ((f = fopen(file, "r")) == NULL)
1311 goto done;
1313 for (;;) {
1314 if ((uri = fparseln(f, NULL, NULL, "\0\0\0", 0)) == NULL)
1315 if (feof(f) || ferror(f))
1316 break;
1318 /* retrieve session name */
1319 if (uri && g_str_has_prefix(uri, XT_SAVE_SESSION_ID)) {
1320 strlcpy(named_session,
1321 &uri[strlen(XT_SAVE_SESSION_ID)],
1322 sizeof named_session);
1323 continue;
1326 if (uri && strlen(uri))
1327 create_new_tab(uri, NULL, 1, -1);
1329 free(uri);
1330 uri = NULL;
1333 /* close open tabs */
1334 if (a->i == XT_SES_CLOSETABS && ti != NULL) {
1335 for (;;) {
1336 tt = TAILQ_FIRST(&tabs);
1337 if (tt == NULL)
1338 break;
1339 if (tt != ti) {
1340 delete_tab(tt);
1341 continue;
1343 delete_tab(tt);
1344 break;
1348 rv = 0;
1349 done:
1350 if (f)
1351 fclose(f);
1353 return (rv);
1357 restore_saved_tabs(void)
1359 char file[PATH_MAX];
1360 int unlink_file = 0;
1361 struct stat sb;
1362 struct karg a;
1363 int rv = 0;
1365 snprintf(file, sizeof file, "%s" PS "%s",
1366 sessions_dir, XT_RESTART_TABS_FILE);
1367 if (stat(file, &sb) == -1)
1368 a.s = XT_SAVED_TABS_FILE;
1369 else {
1370 unlink_file = 1;
1371 a.s = XT_RESTART_TABS_FILE;
1374 a.i = XT_SES_DONOTHING;
1375 rv = open_tabs(NULL, &a);
1377 if (unlink_file)
1378 unlink(file);
1380 return (rv);
1384 save_tabs(struct tab *t, struct karg *a)
1386 char file[PATH_MAX];
1387 FILE *f;
1388 int num_tabs = 0, i;
1389 struct tab **stabs = NULL;
1391 /* tab may be null here */
1393 if (a == NULL)
1394 return (1);
1395 if (a->s == NULL)
1396 snprintf(file, sizeof file, "%s" PS "%s",
1397 sessions_dir, named_session);
1398 else
1399 snprintf(file, sizeof file, "%s" PS "%s", sessions_dir, a->s);
1401 if ((f = fopen(file, "w")) == NULL) {
1402 show_oops(t, "Can't open save_tabs file: %s", strerror(errno));
1403 return (1);
1406 /* save session name */
1407 fprintf(f, "%s%s\n", XT_SAVE_SESSION_ID, named_session);
1409 /* Save tabs, in the order they are arranged in the notebook. */
1410 num_tabs = sort_tabs_by_page_num(&stabs);
1412 for (i = 0; i < num_tabs; i++)
1413 if (stabs[i]) {
1414 if (get_uri(stabs[i]) != NULL)
1415 fprintf(f, "%s\n", get_uri(stabs[i]));
1416 else if (gtk_entry_get_text(GTK_ENTRY(
1417 stabs[i]->uri_entry)))
1418 fprintf(f, "%s\n", gtk_entry_get_text(GTK_ENTRY(
1419 stabs[i]->uri_entry)));
1422 g_free(stabs);
1424 /* try and make sure this gets to disk NOW. XXX Backup first? */
1425 if (fflush(f) != 0 || fsync(fileno(f)) != 0) {
1426 show_oops(t, "May not have managed to save session: %s",
1427 strerror(errno));
1430 fclose(f);
1432 return (0);
1436 save_tabs_and_quit(struct tab *t, struct karg *args)
1438 struct karg a;
1440 a.s = NULL;
1441 save_tabs(t, &a);
1442 quit(t, NULL);
1444 return (1);
1447 void
1448 expand_tilde(char *path, size_t len, const char *s)
1450 struct passwd *pwd;
1451 int i;
1452 char user[LOGIN_NAME_MAX];
1453 const char *sc = s;
1455 if (path == NULL || s == NULL)
1456 errx(1, "expand_tilde");
1458 if (s[0] != '~') {
1459 strlcpy(path, sc, len);
1460 return;
1463 ++s;
1464 for (i = 0; s[i] != PSC && s[i] != '\0'; ++i)
1465 user[i] = s[i];
1466 user[i] = '\0';
1467 s = &s[i];
1469 pwd = strlen(user) == 0 ? getpwuid(getuid()) : getpwnam(user);
1470 if (pwd == NULL)
1471 strlcpy(path, sc, len);
1472 else
1473 snprintf(path, len, "%s%s", pwd->pw_dir, s);
1477 run_page_script(struct tab *t, struct karg *args)
1479 const gchar *uri;
1480 char *tmp, script[PATH_MAX];
1481 char *sv[3];
1483 tmp = args->s != NULL && strlen(args->s) > 0 ? args->s : default_script;
1484 if (tmp[0] == '\0') {
1485 show_oops(t, "no script specified");
1486 return (1);
1489 if ((uri = get_uri(t)) == NULL) {
1490 show_oops(t, "tab is empty, not running script");
1491 return (1);
1494 expand_tilde(script, sizeof script, tmp);
1496 sv[0] = script;
1497 sv[1] = (char *)uri;
1498 sv[2] = NULL;
1499 if (!g_spawn_async(NULL, sv, NULL, G_SPAWN_SEARCH_PATH, NULL, NULL,
1500 NULL, NULL)) {
1501 show_oops(t, "%s: could not spawn process: %s %s", __func__,
1502 sv[0], sv[1]);
1503 return (1);
1504 } else
1505 show_oops(t, "running: %s %s", sv[0], sv[1]);
1507 return (0);
1511 yank_uri(struct tab *t, struct karg *args)
1513 const gchar *uri;
1514 GtkClipboard *clipboard, *primary;
1516 if ((uri = get_uri(t)) == NULL)
1517 return (1);
1519 primary = gtk_clipboard_get(GDK_SELECTION_PRIMARY);
1520 clipboard = gtk_clipboard_get(GDK_SELECTION_CLIPBOARD);
1521 gtk_clipboard_set_text(primary, uri, -1);
1522 gtk_clipboard_set_text(clipboard, uri, -1);
1524 return (0);
1528 paste_uri(struct tab *t, struct karg *args)
1530 GtkClipboard *clipboard, *primary;
1531 gchar *c = NULL, *p = NULL, *uri;
1532 int i;
1534 clipboard = gtk_clipboard_get(GDK_SELECTION_CLIPBOARD);
1535 primary = gtk_clipboard_get(GDK_SELECTION_PRIMARY);
1536 c = gtk_clipboard_wait_for_text(clipboard);
1537 p = gtk_clipboard_wait_for_text(primary);
1539 if (c || p) {
1540 #ifdef __MINGW32__
1541 /* Windows try clipboard first */
1542 uri = c ? c : p;
1543 #else
1544 /* UNIX try primary first */
1545 uri = p ? p : c;
1546 #endif
1547 /* replace all newlines with spaces */
1548 for (i = 0; uri[i] != '\0'; ++i)
1549 if (uri[i] == '\n')
1550 uri[i] = ' ';
1552 while (*uri && isspace(*uri))
1553 uri++;
1554 if (strlen(uri) == 0) {
1555 show_oops(t, "empty paste buffer");
1556 goto done;
1558 if (guess_search == 0 && valid_url_type(uri)) {
1559 /* we can be clever and paste this in search box */
1560 show_oops(t, "not a valid URL");
1561 goto done;
1564 if (args->i == XT_PASTE_CURRENT_TAB)
1565 load_uri(t, uri);
1566 else if (args->i == XT_PASTE_NEW_TAB)
1567 create_new_tab(uri, NULL, 1, -1);
1570 done:
1571 if (c)
1572 g_free(c);
1573 if (p)
1574 g_free(p);
1576 return (0);
1579 void
1580 js_toggle_cb(GtkWidget *w, struct tab *t)
1582 struct karg a;
1583 int es, set;
1585 g_object_get(G_OBJECT(t->settings),
1586 "enable-scripts", &es, (char *)NULL);
1587 es = !es;
1588 if (es)
1589 set = XT_WL_ENABLE;
1590 else
1591 set = XT_WL_DISABLE;
1593 a.i = set | XT_WL_TOPLEVEL;
1594 toggle_pl(t, &a);
1596 a.i = set | XT_WL_TOPLEVEL;
1597 toggle_cwl(t, &a);
1599 a.i = XT_WL_TOGGLE | XT_WL_TOPLEVEL | XT_WL_RELOAD;
1600 toggle_js(t, &a);
1603 void
1604 proxy_toggle_cb(GtkWidget *w, struct tab *t)
1606 struct karg args = {0};
1608 args.i = XT_PRXY_TOGGLE;
1609 proxy_cmd(t, &args);
1613 toggle_src(struct tab *t, struct karg *args)
1615 gboolean mode;
1617 if (t == NULL)
1618 return (0);
1620 mode = webkit_web_view_get_view_source_mode(t->wv);
1621 webkit_web_view_set_view_source_mode(t->wv, !mode);
1622 webkit_web_view_reload(t->wv);
1624 return (0);
1627 void
1628 focus_webview(struct tab *t)
1630 if (t == NULL)
1631 return;
1633 /* only grab focus if we are visible */
1634 if (gtk_notebook_get_current_page(notebook) == t->tab_id)
1635 gtk_widget_grab_focus(GTK_WIDGET(t->wv));
1639 focus(struct tab *t, struct karg *args)
1641 if (t == NULL || args == NULL)
1642 return (1);
1644 if (show_url == 0)
1645 return (0);
1647 if (args->i == XT_FOCUS_URI)
1648 gtk_widget_grab_focus(GTK_WIDGET(t->uri_entry));
1649 else if (args->i == XT_FOCUS_SEARCH)
1650 gtk_widget_grab_focus(GTK_WIDGET(t->search_entry));
1652 return (0);
1656 connect_socket_from_uri(const gchar *uri, const gchar **error_str, char *domain,
1657 size_t domain_sz)
1659 SoupURI *su = NULL;
1660 struct addrinfo hints, *res = NULL, *ai;
1661 int rv = -1, s = -1, on, error;
1662 char port[8];
1663 static gchar myerror[256]; /* this is not thread safe */
1665 myerror[0] = '\0';
1666 *error_str = myerror;
1667 if (uri && !g_str_has_prefix(uri, "https://")) {
1668 *error_str = "invalid URI";
1669 goto done;
1672 su = soup_uri_new(uri);
1673 if (su == NULL) {
1674 *error_str = "invalid soup URI";
1675 goto done;
1677 if (!SOUP_URI_VALID_FOR_HTTP(su)) {
1678 *error_str = "invalid HTTPS URI";
1679 goto done;
1682 snprintf(port, sizeof port, "%d", su->port);
1683 bzero(&hints, sizeof(struct addrinfo));
1684 hints.ai_flags = AI_CANONNAME;
1685 hints.ai_family = AF_UNSPEC;
1686 hints.ai_socktype = SOCK_STREAM;
1688 if ((error = getaddrinfo(su->host, port, &hints, &res))) {
1689 snprintf(myerror, sizeof myerror, "getaddrinfo failed: %s",
1690 gai_strerror(errno));
1691 goto done;
1694 for (ai = res; ai; ai = ai->ai_next) {
1695 if (s != -1) {
1696 close(s);
1697 s = -1;
1700 if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6)
1701 continue;
1702 s = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
1703 if (s == -1)
1704 continue;
1705 if (setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &on,
1706 sizeof(on)) == -1)
1707 continue;
1708 if (connect(s, ai->ai_addr, ai->ai_addrlen) == 0)
1709 break;
1711 if (s == -1) {
1712 snprintf(myerror, sizeof myerror,
1713 "could not obtain certificates from: %s",
1714 su->host);
1715 goto done;
1718 if (domain)
1719 strlcpy(domain, su->host, domain_sz);
1720 rv = s;
1721 done:
1722 if (su)
1723 soup_uri_free(su);
1724 if (res)
1725 freeaddrinfo(res);
1726 if (rv == -1 && s != -1)
1727 close(s);
1729 return (rv);
1732 #ifdef __MINGW32__
1733 static ssize_t
1734 custom_gnutls_push(void *s, const void *buf, size_t len)
1736 return send((size_t)s, buf, len, 0);
1739 static ssize_t
1740 custom_gnutls_pull(void *s, void *buf, size_t len)
1742 return recv((size_t)s, buf, len, 0);
1744 #endif
1747 stop_tls(gnutls_session_t gsession, gnutls_certificate_credentials_t xcred)
1749 if (gsession)
1750 gnutls_deinit(gsession);
1751 if (xcred)
1752 gnutls_certificate_free_credentials(xcred);
1754 return (0);
1758 start_tls(const gchar **error_str, int s, gnutls_session_t *gs,
1759 gnutls_certificate_credentials_t *xc)
1761 gnutls_certificate_credentials_t xcred;
1762 gnutls_session_t gsession;
1763 int rv = 1;
1764 static gchar myerror[1024]; /* this is not thread safe */
1766 if (gs == NULL || xc == NULL)
1767 goto done;
1769 myerror[0] = '\0';
1770 *gs = NULL;
1771 *xc = NULL;
1773 gnutls_certificate_allocate_credentials(&xcred);
1774 gnutls_certificate_set_x509_trust_file(xcred, ssl_ca_file,
1775 GNUTLS_X509_FMT_PEM);
1777 gnutls_init(&gsession, GNUTLS_CLIENT);
1778 gnutls_priority_set_direct(gsession, "PERFORMANCE", NULL);
1779 gnutls_credentials_set(gsession, GNUTLS_CRD_CERTIFICATE, xcred);
1780 gnutls_transport_set_ptr(gsession, (gnutls_transport_ptr_t)(long)s);
1781 #ifdef __MINGW32__
1782 /* sockets on windows don't use file descriptors */
1783 gnutls_transport_set_push_function(gsession, custom_gnutls_push);
1784 gnutls_transport_set_pull_function(gsession, custom_gnutls_pull);
1785 #endif
1786 if ((rv = gnutls_handshake(gsession)) < 0) {
1787 snprintf(myerror, sizeof myerror,
1788 "gnutls_handshake failed %d fatal %d %s",
1790 gnutls_error_is_fatal(rv),
1791 #if LIBGNUTLS_VERSION_MAJOR >= 2 && LIBGNUTLS_VERSION_MINOR >= 6
1792 gnutls_strerror_name(rv));
1793 #else
1794 "GNUTLS version is too old to provide human readable error");
1795 #endif
1796 stop_tls(gsession, xcred);
1797 goto done;
1800 gnutls_credentials_type_t cred;
1801 cred = gnutls_auth_get_type(gsession);
1802 if (cred != GNUTLS_CRD_CERTIFICATE) {
1803 snprintf(myerror, sizeof myerror,
1804 "gnutls_auth_get_type failed %d",
1805 (int)cred);
1806 stop_tls(gsession, xcred);
1807 goto done;
1810 *gs = gsession;
1811 *xc = xcred;
1812 rv = 0;
1813 done:
1814 *error_str = myerror;
1815 return (rv);
1819 get_connection_certs(gnutls_session_t gsession, gnutls_x509_crt_t **certs,
1820 size_t *cert_count)
1822 unsigned int len;
1823 const gnutls_datum_t *cl;
1824 gnutls_x509_crt_t *all_certs;
1825 int i, rv = 1;
1827 if (certs == NULL || cert_count == NULL)
1828 goto done;
1829 if (gnutls_certificate_type_get(gsession) != GNUTLS_CRT_X509)
1830 goto done;
1831 cl = gnutls_certificate_get_peers(gsession, &len);
1832 if (len == 0)
1833 goto done;
1835 all_certs = g_malloc(sizeof(gnutls_x509_crt_t) * len);
1836 for (i = 0; i < len; i++) {
1837 gnutls_x509_crt_init(&all_certs[i]);
1838 if (gnutls_x509_crt_import(all_certs[i], &cl[i],
1839 GNUTLS_X509_FMT_PEM < 0)) {
1840 g_free(all_certs);
1841 goto done;
1845 *certs = all_certs;
1846 *cert_count = len;
1847 rv = 0;
1848 done:
1849 return (rv);
1852 void
1853 free_connection_certs(gnutls_x509_crt_t *certs, size_t cert_count)
1855 int i;
1857 for (i = 0; i < cert_count; i++)
1858 gnutls_x509_crt_deinit(certs[i]);
1859 g_free(certs);
1862 #if GTK_CHECK_VERSION(3, 0, 0)
1863 void
1864 statusbar_modify_attr(struct tab *t, const char *css_name)
1866 gtk_widget_set_name(t->sbe.ebox, css_name);
1868 #else
1869 void
1870 statusbar_modify_attr(struct tab *t, const char *text, const char *base)
1872 GdkColor c_text, c_base;
1874 gdk_color_parse(text, &c_text);
1875 gdk_color_parse(base, &c_base);
1877 gtk_widget_modify_bg(t->sbe.ebox, GTK_STATE_NORMAL, &c_base);
1878 gtk_widget_modify_base(t->sbe.uri, GTK_STATE_NORMAL, &c_base);
1879 gtk_widget_modify_text(t->sbe.uri, GTK_STATE_NORMAL, &c_text);
1881 #endif
1883 void
1884 save_certs(struct tab *t, gnutls_x509_crt_t *certs,
1885 size_t cert_count, const char *domain, const char *dir)
1887 size_t cert_buf_sz;
1888 char cert_buf[64 * 1024], file[PATH_MAX];
1889 int i;
1890 FILE *f;
1892 if (t == NULL || certs == NULL || cert_count <= 0 || domain == NULL)
1893 return;
1895 snprintf(file, sizeof file, "%s" PS "%s", dir, domain);
1896 if ((f = fopen(file, "w")) == NULL) {
1897 show_oops(t, "Can't create cert file %s %s",
1898 file, strerror(errno));
1899 return;
1902 for (i = 0; i < cert_count; i++) {
1903 cert_buf_sz = sizeof cert_buf;
1904 if (gnutls_x509_crt_export(certs[i], GNUTLS_X509_FMT_PEM,
1905 cert_buf, &cert_buf_sz)) {
1906 show_oops(t, "gnutls_x509_crt_export failed");
1907 goto done;
1909 if (fwrite(cert_buf, cert_buf_sz, 1, f) != 1) {
1910 show_oops(t, "Can't write certs: %s", strerror(errno));
1911 goto done;
1915 done:
1916 fclose(f);
1919 enum cert_trust {
1920 CERT_LOCAL,
1921 CERT_TRUSTED,
1922 CERT_UNTRUSTED,
1923 CERT_BAD
1926 enum cert_trust
1927 load_compare_cert(const gchar *uri, const gchar **error_str, const char *dir)
1929 char domain[8182], file[PATH_MAX];
1930 char cert_buf[64 * 1024], r_cert_buf[64 * 1024];
1931 int s = -1, i;
1932 unsigned int error = 0;
1933 FILE *f = NULL;
1934 size_t cert_buf_sz, cert_count;
1935 enum cert_trust rv = CERT_UNTRUSTED;
1936 static gchar serr[80]; /* this isn't thread safe */
1937 gnutls_session_t gsession;
1938 gnutls_x509_crt_t *certs;
1939 gnutls_certificate_credentials_t xcred;
1941 DNPRINTF(XT_D_URL, "%s: %s\n", __func__, uri);
1943 serr[0] = '\0';
1944 *error_str = serr;
1945 if ((s = connect_socket_from_uri(uri, error_str, domain,
1946 sizeof domain)) == -1)
1947 return (rv);
1949 DNPRINTF(XT_D_URL, "%s: fd %d\n", __func__, s);
1951 /* go ssl/tls */
1952 if (start_tls(error_str, s, &gsession, &xcred))
1953 goto done;
1954 DNPRINTF(XT_D_URL, "%s: got tls\n", __func__);
1956 /* verify certs in case cert file doesn't exist */
1957 if (gnutls_certificate_verify_peers2(gsession, &error) !=
1958 GNUTLS_E_SUCCESS) {
1959 *error_str = "Invalid certificates";
1960 goto done;
1963 /* get certs */
1964 if (get_connection_certs(gsession, &certs, &cert_count)) {
1965 *error_str = "Can't get connection certificates";
1966 goto done;
1969 snprintf(file, sizeof file, "%s" PS "%s", dir, domain);
1970 if ((f = fopen(file, "r")) == NULL) {
1971 if (!error)
1972 rv = CERT_TRUSTED;
1973 goto freeit;
1976 for (i = 0; i < cert_count; i++) {
1977 cert_buf_sz = sizeof cert_buf;
1978 if (gnutls_x509_crt_export(certs[i], GNUTLS_X509_FMT_PEM,
1979 cert_buf, &cert_buf_sz)) {
1980 goto freeit;
1982 if (fread(r_cert_buf, cert_buf_sz, 1, f) != 1 && !feof(f)) {
1983 rv = CERT_BAD; /* critical */
1984 goto freeit;
1986 if (bcmp(r_cert_buf, cert_buf, cert_buf_sz)) {
1987 rv = CERT_BAD; /* critical */
1988 goto freeit;
1990 rv = CERT_LOCAL;
1993 freeit:
1994 if (f)
1995 fclose(f);
1996 free_connection_certs(certs, cert_count);
1997 done:
1998 /* we close the socket first for speed */
1999 if (s != -1)
2000 close(s);
2002 /* only complain if we didn't save it locally */
2003 if (strlen(ssl_ca_file) != 0 && error && rv != CERT_LOCAL) {
2004 strlcpy(serr, "Certificate exception(s): ", sizeof serr);
2005 if (error & GNUTLS_CERT_INVALID)
2006 strlcat(serr, "invalid, ", sizeof serr);
2007 if (error & GNUTLS_CERT_REVOKED)
2008 strlcat(serr, "revoked, ", sizeof serr);
2009 if (error & GNUTLS_CERT_SIGNER_NOT_FOUND)
2010 strlcat(serr, "signer not found, ", sizeof serr);
2011 if (error & GNUTLS_CERT_SIGNER_NOT_CA)
2012 strlcat(serr, "not signed by CA, ", sizeof serr);
2013 if (error & GNUTLS_CERT_INSECURE_ALGORITHM)
2014 strlcat(serr, "insecure algorithm, ", sizeof serr);
2015 #if LIBGNUTLS_VERSION_MAJOR >= 2 && LIBGNUTLS_VERSION_MINOR >= 6
2016 if (error & GNUTLS_CERT_NOT_ACTIVATED)
2017 strlcat(serr, "not activated, ", sizeof serr);
2018 if (error & GNUTLS_CERT_EXPIRED)
2019 strlcat(serr, "expired, ", sizeof serr);
2020 #endif
2021 for (i = strlen(serr) - 1; i > 0; i--)
2022 if (serr[i] == ',') {
2023 serr[i] = '\0';
2024 break;
2026 *error_str = serr;
2029 stop_tls(gsession, xcred);
2031 return (rv);
2034 gnutls_x509_crt_t *
2035 get_local_cert_chain(const char *uri, size_t *ncerts, const char **error_str,
2036 const char *dir)
2038 SoupURI *su;
2039 unsigned char cert_buf[64 * 1024] = {0};
2040 gnutls_datum_t data;
2041 unsigned int len = UINT_MAX;
2042 int bytes_read;
2043 char file[PATH_MAX];
2044 FILE *f;
2045 gnutls_x509_crt_t *certs;
2047 if ((su = soup_uri_new(uri)) == NULL) {
2048 *error_str = "Invalid URI";
2049 return (NULL);
2052 snprintf(file, sizeof file, "%s" PS "%s", dir, su->host);
2053 if ((f = fopen(file, "r")) == NULL) {
2054 *error_str = "Could not read local cert";
2055 return (NULL);
2058 bytes_read = fread(cert_buf, sizeof *cert_buf, sizeof cert_buf, f);
2059 if (bytes_read == 0) {
2060 *error_str = "Could not read local cert";
2061 return (NULL);
2064 data.data = cert_buf;
2065 data.size = bytes_read;
2066 certs = g_malloc(sizeof *certs);
2067 *ncerts = INT_MAX;
2068 if (gnutls_x509_crt_list_import(certs, &len, &data,
2069 GNUTLS_X509_FMT_PEM, 0) < 0) {
2070 *error_str = "Error reading local cert chain";
2071 return (NULL);
2074 *ncerts = len;
2075 return (certs);
2080 cert_cmd(struct tab *t, struct karg *args)
2082 const gchar *uri, *error_str = NULL;
2083 char domain[8182];
2084 int s = -1;
2085 size_t cert_count;
2086 gnutls_session_t gsession;
2087 gnutls_x509_crt_t *certs;
2088 gnutls_certificate_credentials_t xcred;
2089 #if !GTK_CHECK_VERSION(3, 0, 0)
2090 GdkColor color;
2091 #endif
2093 if (t == NULL)
2094 return (1);
2096 if (args->s != NULL)
2097 uri = args->s;
2098 else if ((uri = get_uri(t)) == NULL) {
2099 show_oops(t, "Invalid URI");
2100 return (1);
2104 * if we're only showing the local certs, don't open a socket and get
2105 * the remote certs
2107 if (args->i & XT_SHOW && args->i & XT_CACHE) {
2108 certs = get_local_cert_chain(uri, &cert_count, &error_str,
2109 certs_cache_dir);
2110 if (error_str == NULL) {
2111 show_certs(t, certs, cert_count, "Certificate Chain");
2112 free_connection_certs(certs, cert_count);
2113 } else {
2114 show_oops(t, "%s", error_str);
2115 return (1);
2117 return (0);
2120 if ((s = connect_socket_from_uri(uri, &error_str, domain,
2121 sizeof domain)) == -1) {
2122 show_oops(t, "%s", error_str);
2123 return (1);
2126 /* go ssl/tls */
2127 if (start_tls(&error_str, s, &gsession, &xcred))
2128 goto done;
2130 /* get certs */
2131 if (get_connection_certs(gsession, &certs, &cert_count)) {
2132 show_oops(t, "get_connection_certs failed");
2133 goto done;
2136 if (args->i & XT_SHOW)
2137 show_certs(t, certs, cert_count, "Certificate Chain");
2138 else if (args->i & XT_SAVE) {
2139 save_certs(t, certs, cert_count, domain, certs_dir);
2140 #if GTK_CHECK_VERSION(3, 0, 0)
2141 gtk_widget_set_name(t->uri_entry, XT_CSS_BLUE);
2142 statusbar_modify_attr(t, XT_CSS_BLUE);
2143 #else
2144 gdk_color_parse(XT_COLOR_BLUE, &color);
2145 gtk_widget_modify_base(t->uri_entry, GTK_STATE_NORMAL, &color);
2146 statusbar_modify_attr(t, XT_COLOR_BLACK, XT_COLOR_BLUE);
2147 #endif
2148 } else if (args->i & XT_CACHE)
2149 save_certs(t, certs, cert_count, domain, certs_cache_dir);
2151 free_connection_certs(certs, cert_count);
2152 done:
2153 /* we close the socket first for speed */
2154 if (s != -1)
2155 close(s);
2156 stop_tls(gsession, xcred);
2157 if (error_str && strlen(error_str))
2158 show_oops(t, "%s", error_str);
2159 return (0);
2163 * args must be allocated dynamically as the thread that added this function
2164 * to the idle loop no longer exists
2166 gboolean
2167 warn_cert_cache_differs_idle(struct karg *args)
2169 if (args == NULL) {
2170 show_oops(NULL, "%s: invalid parameters", __func__);
2171 /* return 0 to not re-add function to the idle loop */
2172 return (0);
2174 xtp_page_sv((struct tab *)args->ptr, args);
2175 g_free(args);
2176 return (0);
2180 check_cert_changes(struct tab *t, const char *uri)
2182 SoupURI *soupuri = NULL;
2183 struct karg args = {0};
2184 struct wl_entry *w = NULL;
2185 const char *errstr = NULL;
2186 struct karg *argsp;
2188 if (!(warn_cert_changes && g_str_has_prefix(uri, "https://")))
2189 return (0);
2191 switch (load_compare_cert(uri, &errstr, certs_cache_dir)) {
2192 case CERT_LOCAL:
2193 /* The cached certificate is identical */
2194 break;
2195 case CERT_TRUSTED: /* FALLTHROUGH */
2196 case CERT_UNTRUSTED:
2197 /* cache new certificate */
2198 args.i = XT_CACHE;
2199 cert_cmd(t, &args);
2200 break;
2201 case CERT_BAD:
2202 if ((soupuri = soup_uri_new(uri)) == NULL ||
2203 soupuri->host == NULL)
2204 break;
2205 if ((w = wl_find(soupuri->host, &svil)) != NULL)
2206 break;
2207 t->xtp_meaning = XT_XTP_TAB_MEANING_SV;
2208 argsp = g_malloc0(sizeof(struct karg));
2209 argsp->s = g_strdup((char *)uri);
2210 argsp->ptr = (void *)t;
2211 g_idle_add((GSourceFunc)warn_cert_cache_differs_idle, argsp);
2212 break;
2215 if (soupuri)
2216 soup_uri_free(soupuri);
2217 return (0);
2221 remove_cookie(int index)
2223 int i, rv = 1;
2224 GSList *cf;
2225 SoupCookie *c;
2227 DNPRINTF(XT_D_COOKIE, "remove_cookie: %d\n", index);
2229 cf = soup_cookie_jar_all_cookies(s_cookiejar);
2231 for (i = 1; cf; cf = cf->next, i++) {
2232 if (i != index)
2233 continue;
2234 c = cf->data;
2235 print_cookie("remove cookie", c);
2236 soup_cookie_jar_delete_cookie(s_cookiejar, c);
2237 rv = 0;
2238 break;
2241 soup_cookies_free(cf);
2243 return (rv);
2247 remove_cookie_domain(int domain_id)
2249 int domain_count, rv = 1;
2250 GSList *cf;
2251 SoupCookie *c;
2252 char *last_domain;
2254 DNPRINTF(XT_D_COOKIE, "remove_cookie_domain: %d\n", domain_id);
2256 last_domain = "";
2257 cf = soup_cookie_jar_all_cookies(s_cookiejar);
2259 for (domain_count = 0; cf; cf = cf->next) {
2260 c = cf->data;
2262 if (strcmp(last_domain, c->domain) != 0) {
2263 domain_count++;
2264 last_domain = c->domain;
2267 if (domain_count < domain_id)
2268 continue;
2269 else if (domain_count > domain_id)
2270 break;
2272 print_cookie("remove cookie", c);
2273 soup_cookie_jar_delete_cookie(s_cookiejar, c);
2274 rv = 0;
2277 soup_cookies_free(cf);
2279 return (rv);
2283 remove_cookie_all()
2285 int rv = 1;
2286 GSList *cf;
2287 SoupCookie *c;
2289 DNPRINTF(XT_D_COOKIE, "remove_cookie_all\n");
2291 cf = soup_cookie_jar_all_cookies(s_cookiejar);
2293 for (; cf; cf = cf->next) {
2294 c = cf->data;
2296 print_cookie("remove cookie", c);
2297 soup_cookie_jar_delete_cookie(s_cookiejar, c);
2298 rv = 0;
2301 soup_cookies_free(cf);
2303 return (rv);
2307 toplevel_cmd(struct tab *t, struct karg *args)
2309 js_toggle_cb(t->js_toggle, t);
2311 return (0);
2315 can_go_back_for_real(struct tab *t)
2317 int i;
2318 WebKitWebHistoryItem *item;
2319 const gchar *uri;
2321 if (t == NULL)
2322 return (FALSE);
2324 if (t->item != NULL)
2325 return (TRUE);
2327 /* rely on webkit to make sure we can go backward when on an about page */
2328 uri = get_uri(t);
2329 if (uri == NULL || g_str_has_prefix(uri, "about:") ||
2330 g_str_has_prefix(uri, "xxxt://"))
2331 return (webkit_web_view_can_go_back(t->wv));
2333 /* the back/forward list is stupid so help determine if we can go back */
2334 for (i = 0, item = webkit_web_back_forward_list_get_current_item(t->bfl);
2335 item != NULL;
2336 i--, item = webkit_web_back_forward_list_get_nth_item(t->bfl, i)) {
2337 if (strcmp(webkit_web_history_item_get_uri(item), uri))
2338 return (TRUE);
2341 return (FALSE);
2345 can_go_forward_for_real(struct tab *t)
2347 int i;
2348 WebKitWebHistoryItem *item;
2349 const gchar *uri;
2351 if (t == NULL)
2352 return (FALSE);
2354 /* rely on webkit to make sure we can go forward when on an about page */
2355 uri = get_uri(t);
2356 if (uri == NULL || g_str_has_prefix(uri, "about:") ||
2357 g_str_has_prefix(uri, "xxxt://"))
2358 return (webkit_web_view_can_go_forward(t->wv));
2360 /* the back/forwars list is stupid so help selecting a different item */
2361 for (i = 0, item = webkit_web_back_forward_list_get_current_item(t->bfl);
2362 item != NULL;
2363 i++, item = webkit_web_back_forward_list_get_nth_item(t->bfl, i)) {
2364 if (strcmp(webkit_web_history_item_get_uri(item), uri))
2365 return (TRUE);
2368 return (FALSE);
2371 void
2372 go_back_for_real(struct tab *t)
2374 int i;
2375 WebKitWebHistoryItem *item;
2376 const gchar *uri;
2378 if (t == NULL)
2379 return;
2381 uri = get_uri(t);
2382 if (uri == NULL || g_str_has_prefix(uri, "about:") ||
2383 g_str_has_prefix(uri, "xxxt://")) {
2384 webkit_web_view_go_back(t->wv);
2385 return;
2387 /* the back/forwars list is stupid so help selecting a different item */
2388 for (i = 0, item = webkit_web_back_forward_list_get_current_item(t->bfl);
2389 item != NULL;
2390 i--, item = webkit_web_back_forward_list_get_nth_item(t->bfl, i)) {
2391 if (strcmp(webkit_web_history_item_get_uri(item), uri)) {
2392 webkit_web_view_go_to_back_forward_item(t->wv, item);
2393 break;
2398 void
2399 go_forward_for_real(struct tab *t)
2401 int i;
2402 WebKitWebHistoryItem *item;
2403 const gchar *uri;
2405 if (t == NULL)
2406 return;
2408 uri = get_uri(t);
2409 if (uri == NULL || g_str_has_prefix(uri, "about:") ||
2410 g_str_has_prefix(uri, "xxxt://")) {
2411 webkit_web_view_go_forward(t->wv);
2412 return;
2414 /* the back/forwars list is stupid so help selecting a different item */
2415 for (i = 0, item = webkit_web_back_forward_list_get_current_item(t->bfl);
2416 item != NULL;
2417 i++, item = webkit_web_back_forward_list_get_nth_item(t->bfl, i)) {
2418 if (strcmp(webkit_web_history_item_get_uri(item), uri)) {
2419 webkit_web_view_go_to_back_forward_item(t->wv, item);
2420 break;
2426 navaction(struct tab *t, struct karg *args)
2428 WebKitWebHistoryItem *item = NULL;
2429 WebKitWebFrame *frame;
2431 DNPRINTF(XT_D_NAV, "navaction: tab %d opcode %d\n",
2432 t->tab_id, args->i);
2434 hide_oops(t);
2435 set_normal_tab_meaning(t);
2436 if (t->item) {
2437 if (args->i == XT_NAV_BACK)
2438 item = webkit_web_back_forward_list_get_current_item(t->bfl);
2439 else
2440 item = webkit_web_back_forward_list_get_forward_item(t->bfl);
2443 switch (args->i) {
2444 case XT_NAV_BACK:
2445 if (t->item) {
2446 if (item == NULL)
2447 return (XT_CB_PASSTHROUGH);
2448 webkit_web_view_go_to_back_forward_item(t->wv, item);
2449 t->item = NULL;
2450 return (XT_CB_PASSTHROUGH);
2452 marks_clear(t);
2453 go_back_for_real(t);
2454 break;
2455 case XT_NAV_FORWARD:
2456 if (t->item) {
2457 if (item == NULL)
2458 return (XT_CB_PASSTHROUGH);
2459 webkit_web_view_go_to_back_forward_item(t->wv, item);
2460 t->item = NULL;
2461 return (XT_CB_PASSTHROUGH);
2463 marks_clear(t);
2464 go_forward_for_real(t);
2465 break;
2466 case XT_NAV_RELOAD:
2467 frame = webkit_web_view_get_main_frame(t->wv);
2468 webkit_web_frame_reload(frame);
2469 break;
2470 case XT_NAV_STOP:
2471 frame = webkit_web_view_get_main_frame(t->wv);
2472 webkit_web_frame_stop_loading(frame);
2473 break;
2475 return (XT_CB_PASSTHROUGH);
2479 move(struct tab *t, struct karg *args)
2481 GtkAdjustment *adjust;
2482 double pi, si, pos, ps, upper, lower, max;
2483 double percent;
2485 switch (args->i) {
2486 case XT_MOVE_DOWN:
2487 case XT_MOVE_UP:
2488 case XT_MOVE_BOTTOM:
2489 case XT_MOVE_TOP:
2490 case XT_MOVE_PAGEDOWN:
2491 case XT_MOVE_PAGEUP:
2492 case XT_MOVE_HALFDOWN:
2493 case XT_MOVE_HALFUP:
2494 case XT_MOVE_PERCENT:
2495 case XT_MOVE_CENTER:
2496 adjust = t->adjust_v;
2497 break;
2498 default:
2499 adjust = t->adjust_h;
2500 break;
2503 pos = gtk_adjustment_get_value(adjust);
2504 ps = gtk_adjustment_get_page_size(adjust);
2505 upper = gtk_adjustment_get_upper(adjust);
2506 lower = gtk_adjustment_get_lower(adjust);
2507 si = gtk_adjustment_get_step_increment(adjust);
2508 pi = gtk_adjustment_get_page_increment(adjust);
2509 max = upper - ps;
2511 DNPRINTF(XT_D_MOVE, "move: opcode %d %s pos %f ps %f upper %f lower %f "
2512 "max %f si %f pi %f\n",
2513 args->i, adjust == t->adjust_h ? "horizontal" : "vertical",
2514 pos, ps, upper, lower, max, si, pi);
2516 switch (args->i) {
2517 case XT_MOVE_DOWN:
2518 case XT_MOVE_RIGHT:
2519 pos += si;
2520 gtk_adjustment_set_value(adjust, MIN(pos, max));
2521 break;
2522 case XT_MOVE_UP:
2523 case XT_MOVE_LEFT:
2524 pos -= si;
2525 gtk_adjustment_set_value(adjust, MAX(pos, lower));
2526 break;
2527 case XT_MOVE_BOTTOM:
2528 case XT_MOVE_FARRIGHT:
2529 t->mark[marktoindex('\'')] = gtk_adjustment_get_value(t->adjust_v);
2530 gtk_adjustment_set_value(adjust, max);
2531 break;
2532 case XT_MOVE_TOP:
2533 case XT_MOVE_FARLEFT:
2534 t->mark[marktoindex('\'')] = gtk_adjustment_get_value(t->adjust_v);
2535 gtk_adjustment_set_value(adjust, lower);
2536 break;
2537 case XT_MOVE_PAGEDOWN:
2538 pos += pi;
2539 gtk_adjustment_set_value(adjust, MIN(pos, max));
2540 break;
2541 case XT_MOVE_PAGEUP:
2542 pos -= pi;
2543 gtk_adjustment_set_value(adjust, MAX(pos, lower));
2544 break;
2545 case XT_MOVE_HALFDOWN:
2546 pos += pi / 2;
2547 gtk_adjustment_set_value(adjust, MIN(pos, max));
2548 break;
2549 case XT_MOVE_HALFUP:
2550 pos -= pi / 2;
2551 gtk_adjustment_set_value(adjust, MAX(pos, lower));
2552 break;
2553 case XT_MOVE_CENTER:
2554 t->mark[marktoindex('\'')] = gtk_adjustment_get_value(t->adjust_v);
2555 args->s = g_strdup("50.0");
2556 /* FALLTHROUGH */
2557 case XT_MOVE_PERCENT:
2558 t->mark[marktoindex('\'')] = gtk_adjustment_get_value(t->adjust_v);
2559 percent = atoi(args->s) / 100.0;
2560 pos = max * percent;
2561 if (pos < 0.0 || pos > max)
2562 break;
2563 gtk_adjustment_set_value(adjust, pos);
2564 break;
2565 default:
2566 return (XT_CB_PASSTHROUGH);
2569 DNPRINTF(XT_D_MOVE, "move: new pos %f %f\n", pos, MIN(pos, max));
2571 return (XT_CB_HANDLED);
2574 void
2575 url_set_visibility(void)
2577 struct tab *t;
2579 TAILQ_FOREACH(t, &tabs, entry)
2580 if (show_url == 0) {
2581 gtk_widget_hide(t->toolbar);
2582 focus_webview(t);
2583 } else
2584 gtk_widget_show(t->toolbar);
2587 void
2588 notebook_tab_set_visibility(void)
2590 if (show_tabs == 0) {
2591 gtk_widget_hide(tab_bar);
2592 gtk_notebook_set_show_tabs(notebook, FALSE);
2593 } else {
2594 if (tab_style == XT_TABS_NORMAL) {
2595 gtk_widget_hide(tab_bar);
2596 gtk_notebook_set_show_tabs(notebook, TRUE);
2597 } else if (tab_style == XT_TABS_COMPACT) {
2598 gtk_widget_show(tab_bar);
2599 gtk_notebook_set_show_tabs(notebook, FALSE);
2604 void
2605 statusbar_set_visibility(void)
2607 struct tab *t;
2609 TAILQ_FOREACH(t, &tabs, entry){
2610 if (show_statusbar == 0)
2611 gtk_widget_hide(t->statusbar);
2612 else
2613 gtk_widget_show(t->statusbar);
2615 focus_webview(t);
2619 void
2620 url_set(struct tab *t, int enable_url_entry)
2622 GdkPixbuf *pixbuf;
2623 int progress;
2625 show_url = enable_url_entry;
2627 if (enable_url_entry) {
2628 gtk_entry_set_icon_from_icon_name(GTK_ENTRY(t->sbe.uri),
2629 GTK_ENTRY_ICON_PRIMARY, NULL);
2630 gtk_entry_set_progress_fraction(GTK_ENTRY(t->sbe.uri), 0);
2631 } else {
2632 pixbuf = gtk_entry_get_icon_pixbuf(GTK_ENTRY(t->uri_entry),
2633 GTK_ENTRY_ICON_PRIMARY);
2634 progress =
2635 gtk_entry_get_progress_fraction(GTK_ENTRY(t->uri_entry));
2636 gtk_entry_set_icon_from_pixbuf(GTK_ENTRY(t->sbe.uri),
2637 GTK_ENTRY_ICON_PRIMARY, pixbuf);
2638 gtk_entry_set_progress_fraction(GTK_ENTRY(t->sbe.uri),
2639 progress);
2644 fullscreen(struct tab *t, struct karg *args)
2646 DNPRINTF(XT_D_TAB, "%s: %p %d\n", __func__, t, args->i);
2648 if (t == NULL)
2649 return (XT_CB_PASSTHROUGH);
2651 if (show_url == 0) {
2652 url_set(t, 1);
2653 show_tabs = 1;
2654 } else {
2655 url_set(t, 0);
2656 show_tabs = 0;
2659 url_set_visibility();
2660 notebook_tab_set_visibility();
2662 return (XT_CB_HANDLED);
2666 statustoggle(struct tab *t, struct karg *args)
2668 DNPRINTF(XT_D_TAB, "%s: %p %d\n", __func__, t, args->i);
2670 if (show_statusbar == 1) {
2671 show_statusbar = 0;
2672 statusbar_set_visibility();
2673 } else if (show_statusbar == 0) {
2674 show_statusbar = 1;
2675 statusbar_set_visibility();
2677 return (XT_CB_HANDLED);
2681 urlaction(struct tab *t, struct karg *args)
2683 int rv = XT_CB_HANDLED;
2685 DNPRINTF(XT_D_TAB, "%s: %p %d\n", __func__, t, args->i);
2687 if (t == NULL)
2688 return (XT_CB_PASSTHROUGH);
2690 switch (args->i) {
2691 case XT_URL_SHOW:
2692 if (show_url == 0) {
2693 url_set(t, 1);
2694 url_set_visibility();
2696 break;
2697 case XT_URL_HIDE:
2698 if (show_url == 1) {
2699 url_set(t, 0);
2700 url_set_visibility();
2702 break;
2704 return (rv);
2708 tabaction(struct tab *t, struct karg *args)
2710 int rv = XT_CB_HANDLED;
2711 char *url = args->s;
2712 struct undo *u;
2713 struct tab *tt, *tv;
2715 DNPRINTF(XT_D_TAB, "tabaction: %p %d\n", t, args->i);
2717 if (t == NULL)
2718 return (XT_CB_PASSTHROUGH);
2720 switch (args->i) {
2721 case XT_TAB_NEW:
2722 if (strlen(url) > 0)
2723 create_new_tab(url, NULL, 1, args->precount);
2724 else
2725 create_new_tab(NULL, NULL, 1, args->precount);
2726 break;
2727 case XT_TAB_DELETE:
2728 if (args->precount < 0)
2729 delete_tab(t);
2730 else
2731 TAILQ_FOREACH(tt, &tabs, entry)
2732 if (tt->tab_id == args->precount - 1) {
2733 delete_tab(tt);
2734 break;
2736 break;
2737 case XT_TAB_DELQUIT:
2738 if (gtk_notebook_get_n_pages(notebook) > 1)
2739 delete_tab(t);
2740 else
2741 quit(t, args);
2742 break;
2743 case XT_TAB_ONLY:
2744 TAILQ_FOREACH_SAFE(tt, &tabs, entry, tv)
2745 if (t != tt)
2746 delete_tab(tt);
2747 break;
2748 case XT_TAB_OPEN:
2749 if (strlen(url) > 0)
2751 else {
2752 rv = XT_CB_PASSTHROUGH;
2753 goto done;
2755 load_uri(t, url);
2756 break;
2757 case XT_TAB_SHOW:
2758 if (show_tabs == 0) {
2759 show_tabs = 1;
2760 notebook_tab_set_visibility();
2762 break;
2763 case XT_TAB_HIDE:
2764 if (show_tabs == 1) {
2765 show_tabs = 0;
2766 notebook_tab_set_visibility();
2768 break;
2769 case XT_TAB_NEXTSTYLE:
2770 if (tab_style == XT_TABS_NORMAL) {
2771 tab_style = XT_TABS_COMPACT;
2772 recolor_compact_tabs();
2774 else
2775 tab_style = XT_TABS_NORMAL;
2776 notebook_tab_set_visibility();
2777 break;
2778 case XT_TAB_UNDO_CLOSE:
2779 if (undo_count == 0) {
2780 DNPRINTF(XT_D_TAB, "%s: no tabs to undo close",
2781 __func__);
2782 goto done;
2783 } else {
2784 undo_count--;
2785 u = TAILQ_FIRST(&undos);
2786 create_new_tab(u->uri, u, 1, -1);
2788 TAILQ_REMOVE(&undos, u, entry);
2789 g_free(u->uri);
2790 /* u->history is freed in create_new_tab() */
2791 g_free(u);
2793 break;
2794 case XT_TAB_LOAD_IMAGES:
2796 if (!auto_load_images) {
2798 /* Enable auto-load images (this will load all
2799 * previously unloaded images). */
2800 g_object_set(G_OBJECT(t->settings),
2801 "auto-load-images", TRUE, (char *)NULL);
2802 webkit_web_view_set_settings(t->wv, t->settings);
2804 webkit_web_view_reload(t->wv);
2806 /* Webkit triggers an event when we change the setting,
2807 * so we can't disable the auto-loading at once.
2809 * Unfortunately, webkit does not tell us when it's done.
2810 * Instead, we wait until the next request, and then
2811 * disable autoloading again.
2813 t->load_images = TRUE;
2815 break;
2816 default:
2817 rv = XT_CB_PASSTHROUGH;
2818 goto done;
2821 done:
2822 if (args->s) {
2823 g_free(args->s);
2824 args->s = NULL;
2827 return (rv);
2831 resizetab(struct tab *t, struct karg *args)
2833 if (t == NULL || args == NULL) {
2834 show_oops(NULL, "resizetab invalid parameters");
2835 return (XT_CB_PASSTHROUGH);
2838 DNPRINTF(XT_D_TAB, "resizetab: tab %d %d\n",
2839 t->tab_id, args->i);
2841 setzoom_webkit(t, args->i);
2843 return (XT_CB_HANDLED);
2847 movetab(struct tab *t, struct karg *args)
2849 int n, dest;
2851 if (t == NULL || args == NULL) {
2852 show_oops(NULL, "movetab invalid parameters");
2853 return (XT_CB_PASSTHROUGH);
2856 DNPRINTF(XT_D_TAB, "movetab: tab %d opcode %d\n",
2857 t->tab_id, args->i);
2859 if (args->i >= XT_TAB_INVALID)
2860 return (XT_CB_PASSTHROUGH);
2862 if (TAILQ_EMPTY(&tabs))
2863 return (XT_CB_PASSTHROUGH);
2865 n = gtk_notebook_get_n_pages(notebook);
2866 dest = gtk_notebook_get_current_page(notebook);
2868 switch (args->i) {
2869 case XT_TAB_NEXT:
2870 if (args->precount < 0)
2871 dest = dest == n - 1 ? 0 : dest + 1;
2872 else
2873 dest = args->precount - 1;
2875 break;
2876 case XT_TAB_PREV:
2877 if (args->precount < 0)
2878 dest -= 1;
2879 else
2880 dest -= args->precount % n;
2882 if (dest < 0)
2883 dest += n;
2885 break;
2886 case XT_TAB_FIRST:
2887 dest = 0;
2888 break;
2889 case XT_TAB_LAST:
2890 dest = n - 1;
2891 break;
2892 default:
2893 return (XT_CB_PASSTHROUGH);
2896 if (dest < 0 || dest >= n)
2897 return (XT_CB_PASSTHROUGH);
2898 if (t->tab_id == dest) {
2899 DNPRINTF(XT_D_TAB, "movetab: do nothing\n");
2900 return (XT_CB_HANDLED);
2903 set_current_tab(dest);
2905 return (XT_CB_HANDLED);
2908 int cmd_prefix = 0;
2910 struct prompt_sub {
2911 const char *s;
2912 const char *(*f)(struct tab *);
2913 } subs[] = {
2914 { "<uri>", get_uri },
2918 command(struct tab *t, struct karg *args)
2920 struct karg a = {0};
2921 int i, cmd_setup = 0;
2922 char *s = NULL, *sp = NULL, *sl = NULL;
2923 gchar **sv;
2925 if (t == NULL || args == NULL) {
2926 show_oops(NULL, "command invalid parameters");
2927 return (XT_CB_PASSTHROUGH);
2930 switch (args->i) {
2931 case '/':
2932 s = "/";
2933 break;
2934 case '?':
2935 s = "?";
2936 break;
2937 case ':':
2938 if (cmd_prefix == 0) {
2939 if (args->s != NULL && strlen(args->s) != 0) {
2940 sp = g_strdup_printf(":%s", args->s);
2941 s = sp;
2942 } else
2943 s = ":";
2944 } else {
2945 sp = g_strdup_printf(":%d", cmd_prefix);
2946 s = sp;
2947 cmd_prefix = 0;
2949 sl = g_strdup(s);
2950 if (sp) {
2951 g_free(sp);
2952 sp = NULL;
2954 s = sl;
2955 for (i = 0; i < LENGTH(subs); ++i) {
2956 sv = g_strsplit(sl, subs[i].s, -1);
2957 if (sl)
2958 g_free(sl);
2959 sl = g_strjoinv(subs[i].f(t), sv);
2960 g_strfreev(sv);
2961 s = sl;
2963 break;
2964 case '.':
2965 t->mode = XT_MODE_HINT;
2966 a.i = 0;
2967 s = ".";
2969 * js code will auto fire() if a single link is visible,
2970 * causing the focus-out-event cb function to be called. Setup
2971 * the cmd _before_ triggering hinting code so the cmd can get
2972 * killed by the cb in this case.
2974 show_cmd(t, s);
2975 cmd_setup = 1;
2976 hint(t, &a);
2977 break;
2978 case ',':
2979 t->mode = XT_MODE_HINT;
2980 a.i = XT_HINT_NEWTAB;
2981 s = ",";
2982 show_cmd(t, s);
2983 cmd_setup = 1;
2984 hint(t, &a);
2985 break;
2986 default:
2987 show_oops(t, "command: invalid opcode %d", args->i);
2988 return (XT_CB_PASSTHROUGH);
2991 DNPRINTF(XT_D_CMD, "%s: tab %d type %s\n", __func__, t->tab_id, s);
2993 if (!cmd_setup)
2994 show_cmd(t, s);
2996 if (sp)
2997 g_free(sp);
2998 if (sl)
2999 g_free(sl);
3001 return (XT_CB_HANDLED);
3005 search(struct tab *t, struct karg *args)
3007 gboolean d;
3009 if (t == NULL || args == NULL) {
3010 show_oops(NULL, "search invalid parameters");
3011 return (1);
3014 switch (args->i) {
3015 case XT_SEARCH_NEXT:
3016 d = t->search_forward;
3017 break;
3018 case XT_SEARCH_PREV:
3019 d = !t->search_forward;
3020 break;
3021 default:
3022 return (XT_CB_PASSTHROUGH);
3025 if (t->search_text == NULL) {
3026 if (global_search == NULL)
3027 return (XT_CB_PASSTHROUGH);
3028 else {
3029 d = t->search_forward = TRUE;
3030 t->search_text = g_strdup(global_search);
3031 webkit_web_view_mark_text_matches(t->wv, global_search, FALSE, 0);
3032 webkit_web_view_set_highlight_text_matches(t->wv, TRUE);
3036 DNPRINTF(XT_D_CMD, "search: tab %d opc %d forw %d text %s\n",
3037 t->tab_id, args->i, t->search_forward, t->search_text);
3039 webkit_web_view_search_text(t->wv, t->search_text, FALSE, d, TRUE);
3041 return (XT_CB_HANDLED);
3045 session_save(struct tab *t, char *filename)
3047 struct karg a;
3048 int rv = 1;
3049 struct session *s;
3051 if (strlen(filename) == 0)
3052 goto done;
3054 if (filename[0] == '.' || filename[0] == '/')
3055 goto done;
3057 a.s = filename;
3058 if (save_tabs(t, &a))
3059 goto done;
3060 strlcpy(named_session, filename, sizeof named_session);
3062 /* add the new session to the list of sessions */
3063 s = g_malloc(sizeof(struct session));
3064 s->name = g_strdup(filename);
3065 TAILQ_INSERT_TAIL(&sessions, s, entry);
3067 rv = 0;
3068 done:
3069 return (rv);
3073 session_open(struct tab *t, char *filename)
3075 struct karg a;
3076 int rv = 1;
3078 if (strlen(filename) == 0)
3079 goto done;
3081 if (filename[0] == '.' || filename[0] == '/')
3082 goto done;
3084 a.s = filename;
3085 a.i = XT_SES_CLOSETABS;
3086 if (open_tabs(t, &a))
3087 goto done;
3089 strlcpy(named_session, filename, sizeof named_session);
3091 rv = 0;
3092 done:
3093 return (rv);
3097 session_delete(struct tab *t, char *filename)
3099 char file[PATH_MAX];
3100 int rv = 1;
3101 struct session *s;
3103 if (strlen(filename) == 0)
3104 goto done;
3106 if (filename[0] == '.' || filename[0] == '/')
3107 goto done;
3109 snprintf(file, sizeof file, "%s" PS "%s", sessions_dir, filename);
3110 if (unlink(file))
3111 goto done;
3113 if (!strcmp(filename, named_session))
3114 strlcpy(named_session, XT_SAVED_TABS_FILE,
3115 sizeof named_session);
3117 /* remove session from sessions list */
3118 TAILQ_FOREACH(s, &sessions, entry) {
3119 if (!strcmp(s->name, filename))
3120 break;
3122 if (s == NULL)
3123 goto done;
3124 TAILQ_REMOVE(&sessions, s, entry);
3125 g_free((gpointer) s->name);
3126 g_free(s);
3128 rv = 0;
3129 done:
3130 return (rv);
3134 session_cmd(struct tab *t, struct karg *args)
3136 char *filename = args->s;
3138 if (t == NULL)
3139 return (1);
3141 if (args->i & XT_SHOW)
3142 show_oops(t, "Current session: %s", named_session[0] == '\0' ?
3143 XT_SAVED_TABS_FILE : named_session);
3144 else if (args->i & XT_SAVE) {
3145 if (session_save(t, filename)) {
3146 show_oops(t, "Can't save session: %s",
3147 filename ? filename : "INVALID");
3148 goto done;
3150 } else if (args->i & XT_OPEN) {
3151 if (session_open(t, filename)) {
3152 show_oops(t, "Can't open session: %s",
3153 filename ? filename : "INVALID");
3154 goto done;
3156 } else if (args->i & XT_DELETE) {
3157 if (session_delete(t, filename)) {
3158 show_oops(t, "Can't delete session: %s",
3159 filename ? filename : "INVALID");
3160 goto done;
3163 done:
3164 return (XT_CB_PASSTHROUGH);
3168 script_cmd(struct tab *t, struct karg *args)
3170 struct stat sb;
3171 FILE *f = NULL;
3172 char *buf = NULL;
3174 if (t == NULL)
3175 goto done;
3177 if ((f = fopen(args->s, "r")) == NULL) {
3178 show_oops(t, "Can't open script file: %s", args->s);
3179 goto done;
3182 if (fstat(fileno(f), &sb) == -1) {
3183 show_oops(t, "Can't stat script file: %s", args->s);
3184 goto done;
3187 buf = g_malloc0(sb.st_size + 1);
3188 if (fread(buf, 1, sb.st_size, f) != sb.st_size) {
3189 show_oops(t, "Can't read script file: %s", args->s);
3190 goto done;
3193 DNPRINTF(XT_D_JS, "%s: about to run script\n", __func__);
3194 run_script(t, buf);
3196 done:
3197 if (f)
3198 fclose(f);
3199 if (buf)
3200 g_free(buf);
3202 return (XT_CB_PASSTHROUGH);
3206 * Make a hardcopy of the page
3209 print_page(struct tab *t, struct karg *args)
3211 WebKitWebFrame *frame;
3212 GtkPageSetup *ps;
3213 GtkPrintOperation *op;
3214 GtkPrintOperationAction action;
3215 GtkPrintOperationResult print_res;
3216 GError *g_err = NULL;
3217 int marg_l, marg_r, marg_t, marg_b;
3219 DNPRINTF(XT_D_PRINTING, "%s:", __func__);
3221 ps = gtk_page_setup_new();
3222 op = gtk_print_operation_new();
3223 action = GTK_PRINT_OPERATION_ACTION_PRINT_DIALOG;
3224 frame = webkit_web_view_get_main_frame(t->wv);
3226 /* the default margins are too small, so we will bump them */
3227 marg_l = gtk_page_setup_get_left_margin(ps, GTK_UNIT_MM) +
3228 XT_PRINT_EXTRA_MARGIN;
3229 marg_r = gtk_page_setup_get_right_margin(ps, GTK_UNIT_MM) +
3230 XT_PRINT_EXTRA_MARGIN;
3231 marg_t = gtk_page_setup_get_top_margin(ps, GTK_UNIT_MM) +
3232 XT_PRINT_EXTRA_MARGIN;
3233 marg_b = gtk_page_setup_get_bottom_margin(ps, GTK_UNIT_MM) +
3234 XT_PRINT_EXTRA_MARGIN;
3236 /* set margins */
3237 gtk_page_setup_set_left_margin(ps, marg_l, GTK_UNIT_MM);
3238 gtk_page_setup_set_right_margin(ps, marg_r, GTK_UNIT_MM);
3239 gtk_page_setup_set_top_margin(ps, marg_t, GTK_UNIT_MM);
3240 gtk_page_setup_set_bottom_margin(ps, marg_b, GTK_UNIT_MM);
3242 gtk_print_operation_set_default_page_setup(op, ps);
3244 /* this appears to free 'op' and 'ps' */
3245 print_res = webkit_web_frame_print_full(frame, op, action, &g_err);
3247 /* check it worked */
3248 if (print_res == GTK_PRINT_OPERATION_RESULT_ERROR) {
3249 show_oops(NULL, "can't print: %s", g_err->message);
3250 g_error_free (g_err);
3251 return (1);
3254 return (0);
3258 go_home(struct tab *t, struct karg *args)
3260 load_uri(t, home);
3261 return (0);
3265 set_encoding(struct tab *t, struct karg *args)
3267 const gchar *e;
3269 if (args->s && strlen(g_strstrip(args->s)) == 0) {
3270 e = webkit_web_view_get_custom_encoding(t->wv);
3271 if (e == NULL)
3272 e = webkit_web_view_get_encoding(t->wv);
3273 show_oops(t, "encoding: %s", e ? e : "N/A");
3274 } else
3275 webkit_web_view_set_custom_encoding(t->wv, args->s);
3277 return (0);
3281 restart(struct tab *t, struct karg *args)
3283 struct karg a;
3285 a.s = XT_RESTART_TABS_FILE;
3286 save_tabs(t, &a);
3287 execvp(start_argv[0], start_argv);
3288 /* NOTREACHED */
3290 return (0);
3293 char *http_proxy_save; /* not a setting, used to toggle */
3296 proxy_cmd(struct tab *t, struct karg *args)
3298 struct tab *tt;
3300 DNPRINTF(XT_D_CMD, "%s: tab %d\n", __func__, t->tab_id);
3302 if (t == NULL)
3303 return (1);
3305 /* setup */
3306 if (http_proxy) {
3307 TAILQ_FOREACH(tt, &tabs, entry)
3308 gtk_widget_show(t->proxy_toggle);
3309 if (http_proxy_save)
3310 g_free(http_proxy_save);
3311 http_proxy_save = g_strdup(http_proxy);
3314 if (args->i & XT_PRXY_SHOW) {
3315 if (http_proxy)
3316 show_oops(t, "http_proxy = %s", http_proxy);
3317 else
3318 show_oops(t, "proxy is currently disabled");
3319 } else if (args->i & XT_PRXY_TOGGLE) {
3320 if (http_proxy_save == NULL && http_proxy == NULL) {
3321 show_oops(t, "can't toggle proxy");
3322 goto done;
3324 TAILQ_FOREACH(tt, &tabs, entry)
3325 gtk_widget_show(t->proxy_toggle);
3326 if (http_proxy) {
3327 setup_proxy(NULL);
3328 button_set_file(t->proxy_toggle, "tordisabled.ico");
3329 show_oops(t, "http proxy disabled");
3330 } else {
3331 setup_proxy(http_proxy_save);
3332 button_set_file(t->proxy_toggle, "torenabled.ico");
3333 show_oops(t, "http_proxy = %s", http_proxy);
3336 done:
3337 return (XT_CB_PASSTHROUGH);
3339 struct cmd {
3340 char *cmd;
3341 int level;
3342 int (*func)(struct tab *, struct karg *);
3343 int arg;
3344 int type;
3345 } cmds[] = {
3346 { "command_mode", 0, command_mode, XT_MODE_COMMAND, 0 },
3347 { "insert_mode", 0, command_mode, XT_MODE_INSERT, 0 },
3348 { "command", 0, command, ':', 0 },
3349 { "search", 0, command, '/', 0 },
3350 { "searchb", 0, command, '?', 0 },
3351 { "hinting", 0, command, '.', 0 },
3352 { "hinting_newtab", 0, command, ',', 0 },
3353 { "togglesrc", 0, toggle_src, 0, 0 },
3354 { "editsrc", 0, edit_src, 0, 0 },
3355 { "editelement", 0, edit_element, 0, 0 },
3356 { "passthrough", 0, passthrough, 0, 0 },
3357 { "modurl", 0, modurl, 0, 0 },
3359 /* yanking and pasting */
3360 { "yankuri", 0, yank_uri, 0, 0 },
3361 { "pasteuricur", 0, paste_uri, XT_PASTE_CURRENT_TAB, 0 },
3362 { "pasteurinew", 0, paste_uri, XT_PASTE_NEW_TAB, 0 },
3364 /* search */
3365 { "searchnext", 0, search, XT_SEARCH_NEXT, 0 },
3366 { "searchprevious", 0, search, XT_SEARCH_PREV, 0 },
3368 /* focus */
3369 { "focusaddress", 0, focus, XT_FOCUS_URI, 0 },
3370 { "focussearch", 0, focus, XT_FOCUS_SEARCH, 0 },
3372 /* hinting */
3373 { "hinting", 0, hint, 0, 0 },
3374 { "hinting_newtab", 0, hint, XT_HINT_NEWTAB, 0 },
3376 /* custom stylesheet */
3377 { "userstyle", 0, userstyle_cmd, XT_STYLE_CURRENT_TAB, XT_USERARG },
3378 { "userstyle_global", 0, userstyle_cmd, XT_STYLE_GLOBAL, XT_USERARG },
3380 /* navigation */
3381 { "goback", 0, navaction, XT_NAV_BACK, 0 },
3382 { "goforward", 0, navaction, XT_NAV_FORWARD, 0 },
3383 { "reload", 0, navaction, XT_NAV_RELOAD, 0 },
3384 { "stop", 0, navaction, XT_NAV_STOP, 0 },
3386 /* vertical movement */
3387 { "scrolldown", 0, move, XT_MOVE_DOWN, 0 },
3388 { "scrollup", 0, move, XT_MOVE_UP, 0 },
3389 { "scrollbottom", 0, move, XT_MOVE_BOTTOM, 0 },
3390 { "scrolltop", 0, move, XT_MOVE_TOP, 0 },
3391 { "1", 0, move, XT_MOVE_TOP, 0 },
3392 { "scrollhalfdown", 0, move, XT_MOVE_HALFDOWN, 0 },
3393 { "scrollhalfup", 0, move, XT_MOVE_HALFUP, 0 },
3394 { "scrollpagedown", 0, move, XT_MOVE_PAGEDOWN, 0 },
3395 { "scrollpageup", 0, move, XT_MOVE_PAGEUP, 0 },
3396 /* horizontal movement */
3397 { "scrollright", 0, move, XT_MOVE_RIGHT, 0 },
3398 { "scrollleft", 0, move, XT_MOVE_LEFT, 0 },
3399 { "scrollfarright", 0, move, XT_MOVE_FARRIGHT, 0 },
3400 { "scrollfarleft", 0, move, XT_MOVE_FARLEFT, 0 },
3402 { "favorites", 0, xtp_page_fl, XT_SHOW, 0 },
3403 { "fav", 0, xtp_page_fl, XT_SHOW, 0 },
3404 { "favedit", 0, xtp_page_fl, XT_SHOW|XT_DELETE, 0 },
3405 { "favadd", 0, add_favorite, 0, 0 },
3407 { "qall", 0, quit, 0, 0 },
3408 { "quitall", 0, quit, 0, 0 },
3409 { "w", 0, save_tabs, 0, 0 },
3410 { "wq", 0, save_tabs_and_quit, 0, 0 },
3411 { "help", 0, help, 0, 0 },
3412 { "about", 0, xtp_page_ab, 0, 0 },
3413 { "stats", 0, stats, 0, 0 },
3414 { "version", 0, xtp_page_ab, 0, 0 },
3416 /* js command */
3417 { "js", 0, js_cmd, XT_SHOW | XT_WL_PERSISTENT | XT_WL_SESSION, 0 },
3418 { "save", 1, js_cmd, XT_SAVE | XT_WL_FQDN, 0 },
3419 { "domain", 2, js_cmd, XT_SAVE | XT_WL_TOPLEVEL, 0 },
3420 { "fqdn", 2, js_cmd, XT_SAVE | XT_WL_FQDN, 0 },
3421 { "show", 1, js_cmd, XT_SHOW | XT_WL_PERSISTENT | XT_WL_SESSION, 0 },
3422 { "all", 2, js_cmd, XT_SHOW | XT_WL_PERSISTENT | XT_WL_SESSION, 0 },
3423 { "persistent", 2, js_cmd, XT_SHOW | XT_WL_PERSISTENT, 0 },
3424 { "session", 2, js_cmd, XT_SHOW | XT_WL_SESSION, 0 },
3425 { "toggle", 1, js_cmd, XT_WL_TOGGLE | XT_WL_FQDN, 0 },
3426 { "domain", 2, js_cmd, XT_WL_TOGGLE | XT_WL_TOPLEVEL, 0 },
3427 { "fqdn", 2, js_cmd, XT_WL_TOGGLE | XT_WL_FQDN, 0 },
3429 /* cookie command */
3430 { "cookie", 0, cookie_cmd, XT_SHOW | XT_WL_PERSISTENT | XT_WL_SESSION, 0 },
3431 { "save", 1, cookie_cmd, XT_SAVE | XT_WL_FQDN, 0 },
3432 { "domain", 2, cookie_cmd, XT_SAVE | XT_WL_TOPLEVEL, 0 },
3433 { "fqdn", 2, cookie_cmd, XT_SAVE | XT_WL_FQDN, 0 },
3434 { "show", 1, cookie_cmd, XT_SHOW | XT_WL_PERSISTENT | XT_WL_SESSION, 0 },
3435 { "all", 2, cookie_cmd, XT_SHOW | XT_WL_PERSISTENT | XT_WL_SESSION, 0 },
3436 { "persistent", 2, cookie_cmd, XT_SHOW | XT_WL_PERSISTENT, 0 },
3437 { "session", 2, cookie_cmd, XT_SHOW | XT_WL_SESSION, 0 },
3438 { "toggle", 1, cookie_cmd, XT_WL_TOGGLE | XT_WL_FQDN, 0 },
3439 { "domain", 2, cookie_cmd, XT_WL_TOGGLE | XT_WL_TOPLEVEL, 0 },
3440 { "fqdn", 2, cookie_cmd, XT_WL_TOGGLE | XT_WL_FQDN, 0 },
3441 { "purge", 1, cookie_cmd, XT_DELETE, 0 },
3443 /* plugin command */
3444 { "plugin", 0, pl_cmd, XT_SHOW | XT_WL_PERSISTENT | XT_WL_SESSION, 0 },
3445 { "save", 1, pl_cmd, XT_SAVE | XT_WL_FQDN, 0 },
3446 { "domain", 2, pl_cmd, XT_SAVE | XT_WL_TOPLEVEL, 0 },
3447 { "fqdn", 2, pl_cmd, XT_SAVE | XT_WL_FQDN, 0 },
3448 { "show", 1, pl_cmd, XT_SHOW | XT_WL_PERSISTENT | XT_WL_SESSION, 0 },
3449 { "all", 2, pl_cmd, XT_SHOW | XT_WL_PERSISTENT | XT_WL_SESSION, 0 },
3450 { "persistent", 2, pl_cmd, XT_SHOW | XT_WL_PERSISTENT, 0 },
3451 { "session", 2, pl_cmd, XT_SHOW | XT_WL_SESSION, 0 },
3452 { "toggle", 1, pl_cmd, XT_WL_TOGGLE | XT_WL_FQDN, 0 },
3453 { "domain", 2, pl_cmd, XT_WL_TOGGLE | XT_WL_TOPLEVEL, 0 },
3454 { "fqdn", 2, pl_cmd, XT_WL_TOGGLE | XT_WL_FQDN, 0 },
3456 /* https command */
3457 { "https", 0, https_cmd, XT_SHOW | XT_WL_PERSISTENT | XT_WL_SESSION, 0 },
3458 { "save", 1, https_cmd, XT_SAVE | XT_WL_FQDN, 0 },
3459 { "domain", 2, https_cmd, XT_SAVE | XT_WL_TOPLEVEL, 0 },
3460 { "fqdn", 2, https_cmd, XT_SAVE | XT_WL_FQDN, 0 },
3461 { "show", 1, https_cmd, XT_SHOW | XT_WL_PERSISTENT | XT_WL_SESSION, 0 },
3462 { "all", 2, https_cmd, XT_SHOW | XT_WL_PERSISTENT | XT_WL_SESSION, 0 },
3463 { "persistent", 2, https_cmd, XT_SHOW | XT_WL_PERSISTENT, 0 },
3464 { "session", 2, https_cmd, XT_SHOW | XT_WL_SESSION, 0 },
3465 { "toggle", 1, https_cmd, XT_WL_TOGGLE | XT_WL_FQDN, 0 },
3466 { "domain", 2, https_cmd, XT_WL_TOGGLE | XT_WL_TOPLEVEL, 0 },
3467 { "fqdn", 2, https_cmd, XT_WL_TOGGLE | XT_WL_FQDN, 0 },
3469 /* toplevel (domain) command */
3470 { "toplevel", 0, toplevel_cmd, XT_WL_TOGGLE | XT_WL_TOPLEVEL | XT_WL_RELOAD, 0 },
3471 { "toggle", 1, toplevel_cmd, XT_WL_TOGGLE | XT_WL_TOPLEVEL | XT_WL_RELOAD, 0 },
3473 /* cookie jar */
3474 { "cookiejar", 0, xtp_page_cl, 0, 0 },
3476 /* cert command */
3477 { "cert", 0, cert_cmd, XT_SHOW, 0 },
3478 { "save", 1, cert_cmd, XT_SAVE, 0 },
3479 { "show", 1, cert_cmd, XT_SHOW, 0 },
3481 { "ca", 0, ca_cmd, 0, 0 },
3482 { "downloadmgr", 0, xtp_page_dl, 0, 0 },
3483 { "dl", 0, xtp_page_dl, 0, 0 },
3484 { "h", 0, xtp_page_hl, 0, 0 },
3485 { "history", 0, xtp_page_hl, 0, 0 },
3486 { "home", 0, go_home, 0, 0 },
3487 { "restart", 0, restart, 0, 0 },
3488 { "urlhide", 0, urlaction, XT_URL_HIDE, 0 },
3489 { "urlshow", 0, urlaction, XT_URL_SHOW, 0 },
3490 { "statustoggle", 0, statustoggle, 0, 0 },
3491 { "run_script", 0, run_page_script, 0, XT_USERARG },
3493 { "print", 0, print_page, 0, 0 },
3495 /* tabs */
3496 { "focusin", 0, resizetab, XT_ZOOM_IN, 0 },
3497 { "focusout", 0, resizetab, XT_ZOOM_OUT, 0 },
3498 { "focusreset", 0, resizetab, XT_ZOOM_NORMAL, 0 },
3499 { "q", 0, tabaction, XT_TAB_DELQUIT, 0 },
3500 { "quit", 0, tabaction, XT_TAB_DELQUIT, 0 },
3501 { "open", 0, tabaction, XT_TAB_OPEN, XT_URLARG },
3502 { "tabclose", 0, tabaction, XT_TAB_DELETE, XT_PREFIX | XT_INTARG},
3503 { "tabedit", 0, tabaction, XT_TAB_NEW, XT_PREFIX | XT_URLARG },
3504 { "tabfirst", 0, movetab, XT_TAB_FIRST, 0 },
3505 { "tabhide", 0, tabaction, XT_TAB_HIDE, 0 },
3506 { "tablast", 0, movetab, XT_TAB_LAST, 0 },
3507 { "tabnew", 0, tabaction, XT_TAB_NEW, XT_PREFIX | XT_URLARG },
3508 { "tabnext", 0, movetab, XT_TAB_NEXT, XT_PREFIX | XT_INTARG},
3509 { "tabnextstyle", 0, tabaction, XT_TAB_NEXTSTYLE, 0 },
3510 { "tabonly", 0, tabaction, XT_TAB_ONLY, 0 },
3511 { "tabprevious", 0, movetab, XT_TAB_PREV, XT_PREFIX | XT_INTARG},
3512 { "tabrewind", 0, movetab, XT_TAB_FIRST, 0 },
3513 { "tabshow", 0, tabaction, XT_TAB_SHOW, 0 },
3514 { "tabs", 0, buffers, 0, 0 },
3515 { "tabundoclose", 0, tabaction, XT_TAB_UNDO_CLOSE, 0 },
3516 { "buffers", 0, buffers, 0, 0 },
3517 { "ls", 0, buffers, 0, 0 },
3518 { "encoding", 0, set_encoding, 0, XT_USERARG },
3519 { "loadimages", 0, tabaction, XT_TAB_LOAD_IMAGES, 0 },
3521 /* settings */
3522 { "set", 0, set, 0, XT_SETARG },
3523 { "runtime", 0, xtp_page_rt, 0, 0 },
3525 { "fullscreen", 0, fullscreen, 0, 0 },
3526 { "f", 0, fullscreen, 0, 0 },
3528 /* sessions */
3529 { "session", 0, session_cmd, XT_SHOW, 0 },
3530 { "delete", 1, session_cmd, XT_DELETE, XT_SESSARG },
3531 { "open", 1, session_cmd, XT_OPEN, XT_SESSARG },
3532 { "save", 1, session_cmd, XT_SAVE, XT_USERARG },
3533 { "show", 1, session_cmd, XT_SHOW, 0 },
3535 /* external javascript */
3536 { "script", 0, script_cmd, XT_EJS_SHOW, XT_USERARG },
3538 /* inspector */
3539 { "inspector", 0, inspector_cmd, XT_INS_SHOW, 0 },
3540 { "show", 1, inspector_cmd, XT_INS_SHOW, 0 },
3541 { "hide", 1, inspector_cmd, XT_INS_HIDE, 0 },
3543 /* proxy */
3544 { "proxy", 0, proxy_cmd, XT_PRXY_SHOW, 0 },
3545 { "show", 1, proxy_cmd, XT_PRXY_SHOW, 0 },
3546 { "toggle", 1, proxy_cmd, XT_PRXY_TOGGLE, 0 },
3549 struct {
3550 int index;
3551 int len;
3552 gchar *list[256];
3553 } cmd_status = {-1, 0};
3555 gboolean
3556 wv_release_button_cb(GtkWidget *btn, GdkEventButton *e, struct tab *t)
3559 if (e->type == GDK_BUTTON_RELEASE && e->button == 1)
3560 btn_down = 0;
3562 return (FALSE);
3565 gboolean
3566 wv_button_cb(GtkWidget *btn, GdkEventButton *e, struct tab *t)
3568 struct karg a;
3569 WebKitHitTestResult *hit_test_result;
3570 guint context;
3572 hit_test_result = webkit_web_view_get_hit_test_result(t->wv, e);
3573 g_object_get(hit_test_result, "context", &context, NULL);
3575 hide_oops(t);
3576 hide_buffers(t);
3578 if (context & WEBKIT_HIT_TEST_RESULT_CONTEXT_EDITABLE)
3579 t->mode = XT_MODE_INSERT;
3580 else
3581 t->mode = XT_MODE_COMMAND;
3583 if (e->type == GDK_BUTTON_PRESS && e->button == 1)
3584 btn_down = 1;
3585 else if (e->type == GDK_BUTTON_PRESS && e->button == 8 /* btn 4 */) {
3586 /* go backward */
3587 a.i = XT_NAV_BACK;
3588 navaction(t, &a);
3590 return (TRUE);
3591 } else if (e->type == GDK_BUTTON_PRESS && e->button == 9 /* btn 5 */) {
3592 /* go forward */
3593 a.i = XT_NAV_FORWARD;
3594 navaction(t, &a);
3596 return (TRUE);
3599 return (FALSE);
3602 gboolean
3603 tab_close_cb(GtkWidget *btn, GdkEventButton *e, struct tab *t)
3605 DNPRINTF(XT_D_TAB, "tab_close_cb: tab %d\n", t->tab_id);
3607 if (e->type == GDK_BUTTON_PRESS && e->button == 1)
3608 delete_tab(t);
3610 return (FALSE);
3614 parse_custom_uri(struct tab *t, const char *uri)
3616 struct custom_uri *u;
3617 int handled = 0;
3618 char *sv[3];
3620 TAILQ_FOREACH(u, &cul, entry) {
3621 if (strncmp(uri, u->uri, strlen(u->uri)))
3622 continue;
3624 handled = 1;
3625 sv[0] = u->cmd;
3626 sv[1] = (char *)uri;
3627 sv[2] = NULL;
3628 if (!g_spawn_async(NULL, sv, NULL, G_SPAWN_SEARCH_PATH, NULL,
3629 NULL, NULL, NULL))
3630 show_oops(t, "%s: could not spawn process", __func__);
3633 return (handled);
3636 void
3637 activate_uri_entry_cb(GtkWidget* entry, struct tab *t)
3639 const gchar *uri = gtk_entry_get_text(GTK_ENTRY(entry));
3641 DNPRINTF(XT_D_URL, "activate_uri_entry_cb: %s\n", uri);
3643 if (t == NULL) {
3644 show_oops(NULL, "activate_uri_entry_cb invalid parameters");
3645 return;
3648 if (uri == NULL) {
3649 show_oops(t, "activate_uri_entry_cb no uri");
3650 return;
3653 uri += strspn(uri, "\t ");
3655 if (parse_custom_uri(t, uri))
3656 return;
3658 /* otherwise continue to load page normally */
3659 load_uri(t, (gchar *)uri);
3660 focus_webview(t);
3663 void
3664 activate_search_entry_cb(GtkWidget* entry, struct tab *t)
3666 const gchar *search = gtk_entry_get_text(GTK_ENTRY(entry));
3667 char *newuri = NULL;
3668 gchar *enc_search;
3669 char **sv;
3671 DNPRINTF(XT_D_URL, "activate_search_entry_cb: %s\n", search);
3673 if (t == NULL) {
3674 show_oops(NULL, "activate_search_entry_cb invalid parameters");
3675 return;
3678 if (search_string == NULL || strlen(search_string) == 0) {
3679 show_oops(t, "no search_string");
3680 return;
3683 set_normal_tab_meaning(t);
3685 enc_search = soup_uri_encode(search, XT_RESERVED_CHARS);
3686 sv = g_strsplit(search_string, "%s", 2);
3687 newuri = g_strjoinv(enc_search, sv);
3688 g_free(enc_search);
3689 g_strfreev(sv);
3691 marks_clear(t);
3692 load_uri(t, newuri);
3693 focus_webview(t);
3695 if (newuri)
3696 g_free(newuri);
3699 void
3700 check_and_set_cookie(const gchar *uri, struct tab *t)
3702 struct wl_entry *w = NULL;
3703 int es = 0;
3705 if (uri == NULL || t == NULL)
3706 return;
3708 if ((w = wl_find_uri(uri, &c_wl)) == NULL)
3709 es = 0;
3710 else
3711 es = 1;
3713 DNPRINTF(XT_D_COOKIE, "check_and_set_cookie: %s %s\n",
3714 es ? "enable" : "disable", uri);
3716 g_object_set(G_OBJECT(t->settings),
3717 "enable-html5-local-storage", es, (char *)NULL);
3718 webkit_web_view_set_settings(t->wv, t->settings);
3721 void
3722 check_and_set_js(const gchar *uri, struct tab *t)
3724 struct wl_entry *w = NULL;
3725 int es = 0;
3727 if (uri == NULL || t == NULL)
3728 return;
3730 if ((w = wl_find_uri(uri, &js_wl)) == NULL)
3731 es = 0;
3732 else
3733 es = 1;
3735 DNPRINTF(XT_D_JS, "check_and_set_js: %s %s\n",
3736 es ? "enable" : "disable", uri);
3738 g_object_set(G_OBJECT(t->settings),
3739 "enable-scripts", es, (char *)NULL);
3740 g_object_set(G_OBJECT(t->settings),
3741 "javascript-can-open-windows-automatically", es, (char *)NULL);
3742 webkit_web_view_set_settings(t->wv, t->settings);
3744 button_set_stockid(t->js_toggle,
3745 es ? GTK_STOCK_MEDIA_PLAY : GTK_STOCK_MEDIA_PAUSE);
3748 void
3749 check_and_set_pl(const gchar *uri, struct tab *t)
3751 struct wl_entry *w = NULL;
3752 int es = 0;
3754 if (uri == NULL || t == NULL)
3755 return;
3757 if ((w = wl_find_uri(uri, &pl_wl)) == NULL)
3758 es = 0;
3759 else
3760 es = 1;
3762 DNPRINTF(XT_D_JS, "check_and_set_pl: %s %s\n",
3763 es ? "enable" : "disable", uri);
3765 g_object_set(G_OBJECT(t->settings),
3766 "enable-plugins", es, (char *)NULL);
3767 webkit_web_view_set_settings(t->wv, t->settings);
3770 #if GTK_CHECK_VERSION(3, 0, 0)
3771 /* A lot of this can be removed when gtk2 is dropped on the floor */
3772 char *
3773 get_css_name(const char *col_str)
3775 char *name = NULL;
3777 if (!strcmp(col_str, XT_COLOR_WHITE))
3778 name = g_strdup(XT_CSS_NORMAL);
3779 else if (!strcmp(col_str, XT_COLOR_RED))
3780 name = g_strdup(XT_CSS_RED);
3781 else if (!strcmp(col_str, XT_COLOR_YELLOW))
3782 name = g_strdup(XT_CSS_YELLOW);
3783 else if (!strcmp(col_str, XT_COLOR_GREEN))
3784 name = g_strdup(XT_CSS_GREEN);
3785 else if (!strcmp(col_str, XT_COLOR_BLUE))
3786 name = g_strdup(XT_CSS_BLUE);
3787 return (name);
3789 #endif
3791 void
3792 check_certs(gpointer p)
3794 struct tab *tt, *t = p;
3795 gchar *col_str = XT_COLOR_WHITE;
3796 const gchar *uri, *u = NULL, *error_str = NULL;
3797 #if GTK_CHECK_VERSION(3, 0, 0)
3798 char *name;
3799 #else
3800 GdkColor color;
3801 gchar *text, *base;
3802 #endif
3804 #ifdef USE_THREADS
3805 gdk_threads_enter();
3806 #endif
3807 DNPRINTF(XT_D_URL, "%s:\n", __func__);
3809 /* make sure t still exists */
3810 if (t == NULL)
3811 goto done;
3812 TAILQ_FOREACH(tt, &tabs, entry)
3813 if (t == tt)
3814 break;
3815 if (t != tt)
3816 goto done;
3818 if ((uri = get_uri(t)) == NULL)
3819 goto white;
3820 u = g_strdup(uri);
3822 #ifdef USE_THREADS
3823 GDK_FLUSH();
3824 gdk_threads_leave();
3825 #endif
3827 col_str = XT_COLOR_YELLOW;
3828 switch (load_compare_cert(u, &error_str, certs_dir)) {
3829 case CERT_LOCAL:
3830 col_str = XT_COLOR_BLUE;
3831 break;
3832 case CERT_TRUSTED:
3833 col_str = (strlen(ssl_ca_file) == 0) ? XT_COLOR_RED
3834 : XT_COLOR_GREEN;
3835 break;
3836 case CERT_UNTRUSTED:
3837 col_str = (strlen(ssl_ca_file) == 0) ? XT_COLOR_RED
3838 : XT_COLOR_YELLOW;
3839 break;
3840 case CERT_BAD:
3841 col_str = XT_COLOR_RED;
3842 break;
3845 #ifdef USE_THREADS
3846 gdk_threads_enter();
3847 #endif
3848 /* make sure t isn't deleted */
3849 TAILQ_FOREACH(tt, &tabs, entry)
3850 if (t == tt)
3851 break;
3852 if (t != tt)
3853 goto done;
3855 #ifdef USE_THREADS
3856 /* test to see if the user navigated away and canceled the thread */
3857 if (t->thread != g_thread_self())
3858 goto done;
3859 if ((uri = get_uri(t)) == NULL) {
3860 t->thread = NULL;
3861 goto done;
3863 if (strcmp(uri, u)) {
3864 /* make sure we are still the same url */
3865 t->thread = NULL;
3866 goto done;
3868 #endif
3869 white:
3871 if (!strcmp(col_str, XT_COLOR_WHITE)) {
3872 #if GTK_CHECK_VERSION(3, 0, 0)
3873 gtk_widget_set_name(t->uri_entry, XT_CSS_NORMAL);
3874 statusbar_modify_attr(t, XT_CSS_NORMAL);
3875 #else
3876 text = gdk_color_to_string(
3877 &t->default_style->text[GTK_STATE_NORMAL]);
3878 base = gdk_color_to_string(
3879 &t->default_style->base[GTK_STATE_NORMAL]);
3880 gtk_widget_modify_base(t->uri_entry, GTK_STATE_NORMAL,
3881 &t->default_style->base[GTK_STATE_NORMAL]);
3882 statusbar_modify_attr(t, text, base);
3883 g_free(text);
3884 g_free(base);
3885 #endif
3886 } else {
3887 #if GTK_CHECK_VERSION(3, 0, 0)
3888 name = get_css_name(col_str);
3889 gtk_widget_set_name(t->uri_entry, name);
3890 statusbar_modify_attr(t, name);
3891 g_free(name);
3892 #else
3893 gdk_color_parse(col_str, &color);
3894 gtk_widget_modify_base(t->uri_entry, GTK_STATE_NORMAL, &color);
3895 statusbar_modify_attr(t, XT_COLOR_BLACK, col_str);
3896 #endif
3899 if (error_str && error_str[0] != '\0')
3900 show_oops(t, "%s", error_str);
3902 check_cert_changes(t, u);
3904 #ifdef USE_THREADS
3905 t->thread = NULL;
3906 #endif
3907 done:
3908 /* t is invalid at this point */
3909 if (u)
3910 g_free((gpointer)u);
3911 #ifdef USE_THREADS
3912 GDK_FLUSH();
3913 gdk_threads_leave();
3914 #endif
3917 void
3918 show_ca_status(struct tab *t, const char *uri)
3920 gchar *col_str = XT_COLOR_WHITE;
3921 #if GTK_CHECK_VERSION(3, 0, 0)
3922 char *name;
3923 #else
3924 GdkColor color;
3925 gchar *text, *base;
3926 #endif
3928 DNPRINTF(XT_D_URL, "show_ca_status: %d %s %s\n",
3929 ssl_strict_certs, ssl_ca_file, uri);
3931 if (t == NULL)
3932 return;
3934 if (uri == NULL || g_str_has_prefix(uri, "http://") ||
3935 !g_str_has_prefix(uri, "https://"))
3936 goto done;
3938 #ifdef USE_THREADS
3940 * It is not necessary to see if the thread is already running.
3941 * If the thread is in progress setting it to something else aborts it
3942 * on the way out.
3945 /* thread the coloring of the address bar */
3946 t->thread = g_thread_create((GThreadFunc)check_certs, t, TRUE, NULL);
3947 #else
3948 check_certs(t);
3949 #endif
3950 return;
3952 done:
3953 if (col_str) {
3954 if (!strcmp(col_str, XT_COLOR_WHITE)) {
3955 #if GTK_CHECK_VERSION(3, 0, 0)
3956 gtk_widget_set_name(t->uri_entry, XT_CSS_NORMAL);
3957 statusbar_modify_attr(t, XT_CSS_NORMAL);
3958 #else
3959 text = gdk_color_to_string(
3960 &t->default_style->text[GTK_STATE_NORMAL]);
3961 base = gdk_color_to_string(
3962 &t->default_style->base[GTK_STATE_NORMAL]);
3963 gtk_widget_modify_base(t->uri_entry, GTK_STATE_NORMAL,
3964 &t->default_style->base[GTK_STATE_NORMAL]);
3965 statusbar_modify_attr(t, text, base);
3966 g_free(text);
3967 g_free(base);
3968 #endif
3969 } else {
3970 #if GTK_CHECK_VERSION(3, 0, 0)
3971 name = get_css_name(col_str);
3972 gtk_widget_set_name(t->uri_entry, name);
3973 statusbar_modify_attr(t, name);
3974 g_free(name);
3975 #else
3976 gdk_color_parse(col_str, &color);
3977 gtk_widget_modify_base(t->uri_entry, GTK_STATE_NORMAL, &color);
3978 statusbar_modify_attr(t, XT_COLOR_BLACK, col_str);
3979 #endif
3984 void
3985 free_favicon(struct tab *t)
3987 DNPRINTF(XT_D_DOWNLOAD, "%s: down %p req %p\n",
3988 __func__, t->icon_download, t->icon_request);
3990 if (t->icon_request)
3991 g_object_unref(t->icon_request);
3992 if (t->icon_dest_uri)
3993 g_free(t->icon_dest_uri);
3995 t->icon_request = NULL;
3996 t->icon_dest_uri = NULL;
3999 void
4000 xt_icon_from_name(struct tab *t, gchar *name)
4002 if (!enable_favicon_entry)
4003 return;
4005 gtk_entry_set_icon_from_icon_name(GTK_ENTRY(t->uri_entry),
4006 GTK_ENTRY_ICON_PRIMARY, "text-html");
4007 if (show_url == 0)
4008 gtk_entry_set_icon_from_icon_name(GTK_ENTRY(t->sbe.uri),
4009 GTK_ENTRY_ICON_PRIMARY, "text-html");
4010 else
4011 gtk_entry_set_icon_from_icon_name(GTK_ENTRY(t->sbe.uri),
4012 GTK_ENTRY_ICON_PRIMARY, NULL);
4015 void
4016 xt_icon_from_pixbuf(struct tab *t, GdkPixbuf *pb)
4018 GdkPixbuf *pb_scaled;
4020 if (gdk_pixbuf_get_width(pb) > 16 || gdk_pixbuf_get_height(pb) > 16)
4021 pb_scaled = gdk_pixbuf_scale_simple(pb, 16, 16,
4022 GDK_INTERP_BILINEAR);
4023 else
4024 pb_scaled = pb;
4026 if (enable_favicon_entry) {
4028 /* Classic tabs. */
4029 gtk_entry_set_icon_from_pixbuf(GTK_ENTRY(t->uri_entry),
4030 GTK_ENTRY_ICON_PRIMARY, pb_scaled);
4032 /* Minimal tabs. */
4033 if (show_url == 0) {
4034 gtk_entry_set_icon_from_pixbuf(GTK_ENTRY(t->sbe.uri),
4035 GTK_ENTRY_ICON_PRIMARY, pb_scaled);
4036 } else
4037 gtk_entry_set_icon_from_icon_name(GTK_ENTRY(t->sbe.uri),
4038 GTK_ENTRY_ICON_PRIMARY, NULL);
4041 /* XXX: Only supports the minimal tabs atm. */
4042 if (enable_favicon_tabs)
4043 gtk_image_set_from_pixbuf(GTK_IMAGE(t->tab_elems.favicon),
4044 pb_scaled);
4046 if (pb_scaled != pb)
4047 g_object_unref(pb_scaled);
4050 void
4051 xt_icon_from_file(struct tab *t, char *uri)
4053 GdkPixbuf *pb;
4054 char *file;
4056 if (g_str_has_prefix(uri, "file://"))
4057 file = g_filename_from_uri(uri, NULL, NULL);
4058 else
4059 file = g_strdup(uri);
4061 if (file == NULL)
4062 return;
4064 pb = gdk_pixbuf_new_from_file(file, NULL);
4065 if (pb) {
4066 xt_icon_from_pixbuf(t, pb);
4067 g_object_unref(pb);
4068 } else
4069 xt_icon_from_name(t, "text-html");
4071 g_free(file);
4074 gboolean
4075 is_valid_icon(char *file)
4077 gboolean valid = 0;
4078 const char *mime_type;
4079 GFileInfo *fi;
4080 GFile *gf;
4082 gf = g_file_new_for_path(file);
4083 fi = g_file_query_info(gf, G_FILE_ATTRIBUTE_STANDARD_CONTENT_TYPE, 0,
4084 NULL, NULL);
4085 mime_type = g_file_info_get_content_type(fi);
4086 valid = g_strcmp0(mime_type, "image/x-ico") == 0 ||
4087 g_strcmp0(mime_type, "image/vnd.microsoft.icon") == 0 ||
4088 g_strcmp0(mime_type, "image/png") == 0 ||
4089 g_strcmp0(mime_type, "image/gif") == 0 ||
4090 g_strcmp0(mime_type, "application/octet-stream") == 0;
4091 g_object_unref(fi);
4092 g_object_unref(gf);
4094 return (valid);
4097 void
4098 set_favicon_from_file(struct tab *t, char *uri)
4100 struct stat sb;
4101 char *file;
4103 if (t == NULL || uri == NULL)
4104 return;
4106 if (g_str_has_prefix(uri, "file://"))
4107 file = g_filename_from_uri(uri, NULL, NULL);
4108 else
4109 file = g_strdup(uri);
4111 if (file == NULL)
4112 return;
4114 DNPRINTF(XT_D_DOWNLOAD, "%s: loading %s\n", __func__, file);
4116 if (!stat(file, &sb)) {
4117 if (sb.st_size == 0 || !is_valid_icon(file)) {
4118 /* corrupt icon so trash it */
4119 DNPRINTF(XT_D_DOWNLOAD, "%s: corrupt icon %s\n",
4120 __func__, file);
4121 unlink(file);
4122 /* no need to set icon to default here */
4123 goto done;
4126 xt_icon_from_file(t, file);
4127 done:
4128 g_free(file);
4131 void
4132 favicon_download_status_changed_cb(WebKitDownload *download, GParamSpec *spec,
4133 WebKitWebView *wv)
4135 WebKitDownloadStatus status = webkit_download_get_status(download);
4136 struct tab *tt = NULL, *t = NULL;
4139 * find the webview instead of passing in the tab as it could have been
4140 * deleted from underneath us.
4142 TAILQ_FOREACH(tt, &tabs, entry) {
4143 if (tt->wv == wv) {
4144 t = tt;
4145 break;
4148 if (t == NULL)
4149 return;
4151 DNPRINTF(XT_D_DOWNLOAD, "%s: tab %d status %d\n",
4152 __func__, t->tab_id, status);
4154 switch (status) {
4155 case WEBKIT_DOWNLOAD_STATUS_ERROR:
4156 /* -1 */
4157 t->icon_download = NULL;
4158 free_favicon(t);
4159 break;
4160 case WEBKIT_DOWNLOAD_STATUS_CREATED:
4161 /* 0 */
4162 break;
4163 case WEBKIT_DOWNLOAD_STATUS_STARTED:
4164 /* 1 */
4165 break;
4166 case WEBKIT_DOWNLOAD_STATUS_CANCELLED:
4167 /* 2 */
4168 DNPRINTF(XT_D_DOWNLOAD, "%s: freeing favicon %d\n",
4169 __func__, t->tab_id);
4170 t->icon_download = NULL;
4171 free_favicon(t);
4172 break;
4173 case WEBKIT_DOWNLOAD_STATUS_FINISHED:
4174 /* 3 */
4176 DNPRINTF(XT_D_DOWNLOAD, "%s: setting icon to %s\n",
4177 __func__, t->icon_dest_uri);
4178 set_favicon_from_file(t, t->icon_dest_uri);
4179 /* these will be freed post callback */
4180 t->icon_request = NULL;
4181 t->icon_download = NULL;
4182 break;
4183 default:
4184 break;
4188 void
4189 abort_favicon_download(struct tab *t)
4191 DNPRINTF(XT_D_DOWNLOAD, "%s: down %p\n", __func__, t->icon_download);
4193 #if !WEBKIT_CHECK_VERSION(1, 4, 0)
4194 if (t->icon_download) {
4195 g_signal_handlers_disconnect_by_func(G_OBJECT(t->icon_download),
4196 G_CALLBACK(favicon_download_status_changed_cb), t->wv);
4197 webkit_download_cancel(t->icon_download);
4198 t->icon_download = NULL;
4199 } else
4200 free_favicon(t);
4201 #endif
4203 xt_icon_from_name(t, "text-html");
4206 void
4207 notify_icon_loaded_cb(WebKitWebView *wv, gchar *uri, struct tab *t)
4209 DNPRINTF(XT_D_DOWNLOAD, "%s %s\n", __func__, uri);
4211 if (uri == NULL || t == NULL)
4212 return;
4214 #if WEBKIT_CHECK_VERSION(1, 4, 0)
4215 /* take icon from WebKitIconDatabase */
4216 GdkPixbuf *pb = NULL;
4218 /* webkit_web_view_get_icon_pixbuf is depreciated in 1.8 */
4219 #if WEBKIT_CHECK_VERSION(1, 8, 0)
4221 * If the page was not loaded (for example, via ssl_strict_certs), do
4222 * not attempt to get the webview's pixbuf. This prevents a CRITICAL
4223 * glib warning.
4225 if (wv && webkit_web_view_get_uri(wv))
4226 pb = webkit_web_view_try_get_favicon_pixbuf(wv, 0, 0);
4227 #else
4228 if (wv && webkit_web_view_get_uri(wv))
4229 pb = webkit_web_view_get_icon_pixbuf(wv);
4230 #endif
4231 if (pb) {
4232 xt_icon_from_pixbuf(t, pb);
4233 g_object_unref(pb);
4234 } else
4235 xt_icon_from_name(t, "text-html");
4236 #elif WEBKIT_CHECK_VERSION(1, 1, 18)
4237 /* download icon to cache dir */
4238 gchar *name_hash, file[PATH_MAX];
4239 struct stat sb;
4241 if (t->icon_request) {
4242 DNPRINTF(XT_D_DOWNLOAD, "%s: download in progress\n", __func__);
4243 return;
4246 /* check to see if we got the icon in cache */
4247 name_hash = g_compute_checksum_for_string(G_CHECKSUM_SHA256, uri, -1);
4248 snprintf(file, sizeof file, "%s" PS "%s.ico", cache_dir, name_hash);
4249 g_free(name_hash);
4251 if (!stat(file, &sb)) {
4252 if (sb.st_size > 0) {
4253 DNPRINTF(XT_D_DOWNLOAD, "%s: loading from cache %s\n",
4254 __func__, file);
4255 set_favicon_from_file(t, file);
4256 return;
4259 /* corrupt icon so trash it */
4260 DNPRINTF(XT_D_DOWNLOAD, "%s: corrupt icon %s\n",
4261 __func__, file);
4262 unlink(file);
4265 /* create download for icon */
4266 t->icon_request = webkit_network_request_new(uri);
4267 if (t->icon_request == NULL) {
4268 DNPRINTF(XT_D_DOWNLOAD, "%s: invalid uri %s\n",
4269 __func__, uri);
4270 return;
4273 t->icon_download = webkit_download_new(t->icon_request);
4274 if (t->icon_download == NULL)
4275 return;
4277 /* we have to free icon_dest_uri later */
4278 if ((t->icon_dest_uri = g_filename_to_uri(file, NULL, NULL)) == NULL)
4279 return;
4280 webkit_download_set_destination_uri(t->icon_download,
4281 t->icon_dest_uri);
4283 if (webkit_download_get_status(t->icon_download) ==
4284 WEBKIT_DOWNLOAD_STATUS_ERROR) {
4285 g_object_unref(t->icon_request);
4286 g_free(t->icon_dest_uri);
4287 t->icon_request = NULL;
4288 t->icon_dest_uri = NULL;
4289 return;
4292 g_signal_connect(G_OBJECT(t->icon_download), "notify::status",
4293 G_CALLBACK(favicon_download_status_changed_cb), t->wv);
4295 webkit_download_start(t->icon_download);
4296 #endif
4299 void
4300 notify_load_status_cb(WebKitWebView* wview, GParamSpec* pspec, struct tab *t)
4302 const gchar *uri = NULL;
4303 struct history *h, find;
4304 struct karg a;
4305 gchar *tmp_uri = NULL;
4306 #if !GTK_CHECK_VERSION(3, 0, 0)
4307 gchar *text, *base;
4308 #endif
4310 DNPRINTF(XT_D_URL, "notify_load_status_cb: %d %s\n",
4311 webkit_web_view_get_load_status(wview),
4312 get_uri(t) ? get_uri(t) : "NOTHING");
4314 if (t == NULL) {
4315 show_oops(NULL, "notify_load_status_cb invalid parameters");
4316 return;
4319 switch (webkit_web_view_get_load_status(wview)) {
4320 case WEBKIT_LOAD_PROVISIONAL:
4321 /* 0 */
4322 abort_favicon_download(t);
4323 #if GTK_CHECK_VERSION(2, 20, 0)
4324 gtk_widget_show(t->spinner);
4325 gtk_spinner_start(GTK_SPINNER(t->spinner));
4326 #endif
4327 t->download_requested = 0;
4329 gtk_widget_set_sensitive(GTK_WIDGET(t->stop), TRUE);
4331 /* assume we are a new address */
4332 #if GTK_CHECK_VERSION(3, 0, 0)
4333 gtk_widget_set_name(t->uri_entry, XT_CSS_NORMAL);
4334 statusbar_modify_attr(t, XT_CSS_NORMAL);
4335 #else
4336 text = gdk_color_to_string(
4337 &t->default_style->text[GTK_STATE_NORMAL]);
4338 base = gdk_color_to_string(
4339 &t->default_style->base[GTK_STATE_NORMAL]);
4340 gtk_widget_modify_base(t->uri_entry, GTK_STATE_NORMAL,
4341 &t->default_style->base[GTK_STATE_NORMAL]);
4342 statusbar_modify_attr(t, text, base);
4343 g_free(text);
4344 g_free(base);
4345 #endif
4347 /* DOM is changing, unreference the previous focused element */
4348 #if WEBKIT_CHECK_VERSION(1, 5, 0)
4349 if (t->active)
4350 g_object_unref(t->active);
4351 t->active = NULL;
4352 if (t->active_text) {
4353 g_free(t->active_text);
4354 t->active_text = NULL;
4356 #endif
4358 /* take focus if we are visible */
4359 focus_webview(t);
4360 t->focus_wv = 1;
4362 marks_clear(t);
4363 #ifdef USE_THREAD
4364 /* kill color thread */
4365 t->thread = NULL;
4366 #endif
4367 break;
4369 case WEBKIT_LOAD_COMMITTED:
4370 /* 1 */
4371 uri = get_uri(t);
4372 if (uri == NULL)
4373 return;
4374 gtk_entry_set_text(GTK_ENTRY(t->uri_entry), uri);
4376 if (t->status) {
4377 g_free(t->status);
4378 t->status = NULL;
4380 set_status(t, "Loading: %s", (char *)uri);
4382 /* clear t->item, except if we're switching to an about: page */
4383 if (t->item && !g_str_has_prefix(uri, "xxxt://") &&
4384 !g_str_has_prefix(uri, "about:")) {
4385 g_object_unref(t->item);
4386 t->item = NULL;
4389 /* check if js white listing is enabled */
4390 if (enable_plugin_whitelist)
4391 check_and_set_pl(uri, t);
4392 if (enable_cookie_whitelist)
4393 check_and_set_cookie(uri, t);
4394 if (enable_js_whitelist)
4395 check_and_set_js(uri, t);
4397 if (t->styled)
4398 apply_style(t);
4401 /* we know enough to autosave the session */
4402 if (session_autosave) {
4403 a.s = NULL;
4404 save_tabs(t, &a);
4407 show_ca_status(t, uri);
4408 run_script(t, JS_HINTING);
4409 if (enable_autoscroll)
4410 run_script(t, JS_AUTOSCROLL);
4411 break;
4413 case WEBKIT_LOAD_FIRST_VISUALLY_NON_EMPTY_LAYOUT:
4414 /* 3 */
4415 if (color_visited_uris) {
4416 color_visited(t, color_visited_helper());
4419 * This colors the links you middle-click (open in new
4420 * tab) in the current tab.
4422 if (t->tab_id != gtk_notebook_get_current_page(notebook) &&
4423 (uri = get_uri(t)) != NULL)
4424 color_visited(get_current_tab(),
4425 g_strdup_printf("{'%s' : 'dummy'}", uri));
4427 break;
4429 case WEBKIT_LOAD_FINISHED:
4430 /* 2 */
4431 if ((uri = get_uri(t)) == NULL)
4432 return;
4434 * js_autorun calls get_uri which frees t->tmp_uri if on an
4435 * "about:" page. On "about:" pages, uri points to t->tmp_uri.
4436 * I.e. we will use freed memory. Prevent that.
4438 tmp_uri = g_strdup(uri);
4440 /* autorun some js if enabled */
4441 js_autorun(t);
4443 input_autofocus(t);
4445 if (!strncmp(tmp_uri, "http://", strlen("http://")) ||
4446 !strncmp(tmp_uri, "https://", strlen("https://")) ||
4447 !strncmp(tmp_uri, "file://", strlen("file://"))) {
4448 find.uri = (gchar *)tmp_uri;
4449 h = RB_FIND(history_list, &hl, &find);
4450 if (!h)
4451 insert_history_item(tmp_uri,
4452 get_title(t, FALSE), time(NULL));
4453 else
4454 h->time = time(NULL);
4457 if (statusbar_style == XT_STATUSBAR_URL)
4458 set_status(t, "%s", (char *)tmp_uri);
4459 else
4460 set_status(t, "%s", (char *)get_title(t, FALSE));
4461 gtk_widget_set_sensitive(GTK_WIDGET(t->stop), FALSE);
4462 #if GTK_CHECK_VERSION(2, 20, 0)
4463 gtk_spinner_stop(GTK_SPINNER(t->spinner));
4464 gtk_widget_hide(t->spinner);
4465 #endif
4466 g_free(tmp_uri);
4467 break;
4469 #if WEBKIT_CHECK_VERSION(1, 1, 18)
4470 case WEBKIT_LOAD_FAILED:
4471 /* 4 */
4472 if (!t->download_requested) {
4473 gtk_label_set_text(GTK_LABEL(t->label),
4474 get_title(t, FALSE));
4475 gtk_label_set_text(GTK_LABEL(t->tab_elems.label),
4476 get_title(t, FALSE));
4477 set_status(t, "%s", (char *)get_title(t, FALSE));
4478 gtk_window_set_title(GTK_WINDOW(main_window),
4479 get_title(t, TRUE));
4480 } else {
4483 #endif
4484 default:
4485 #if GTK_CHECK_VERSION(2, 20, 0)
4486 gtk_spinner_stop(GTK_SPINNER(t->spinner));
4487 gtk_widget_hide(t->spinner);
4488 #endif
4489 gtk_widget_set_sensitive(GTK_WIDGET(t->stop), FALSE);
4490 break;
4493 gtk_widget_set_sensitive(GTK_WIDGET(t->backward),
4494 can_go_back_for_real(t));
4496 gtk_widget_set_sensitive(GTK_WIDGET(t->forward),
4497 can_go_forward_for_real(t));
4500 void
4501 notify_title_cb(WebKitWebView* wview, GParamSpec* pspec, struct tab *t)
4503 const gchar *title = NULL, *win_title = NULL;
4505 title = get_title(t, FALSE);
4506 win_title = get_title(t, TRUE);
4507 if (title) {
4508 gtk_label_set_text(GTK_LABEL(t->label), title);
4509 gtk_label_set_text(GTK_LABEL(t->tab_elems.label), title);
4512 if (win_title && t->tab_id == gtk_notebook_get_current_page(notebook))
4513 gtk_window_set_title(GTK_WINDOW(main_window), win_title);
4516 char *
4517 get_domain(const gchar *host)
4519 size_t x;
4520 char *p;
4522 /* handle silly domains like .co.uk */
4524 if ((x = strlen(host)) <= 6)
4525 return (g_strdup(host));
4527 if (host[x - 3] == '.' && host[x - 6] == '.') {
4528 x = x - 7;
4529 while (x > 0)
4530 if (host[x] != '.')
4531 x--;
4532 else
4533 return (g_strdup(&host[x + 1]));
4536 /* find first . */
4537 p = g_strrstr(host, ".");
4538 if (p == NULL)
4539 return (g_strdup(""));
4540 p--;
4541 while (p > host)
4542 if (*p != '.')
4543 p--;
4544 else
4545 return (g_strdup(p + 1));
4547 return (g_strdup(host));
4550 void
4551 js_autorun(struct tab *t)
4553 SoupURI *su = NULL;
4554 const gchar *uri;
4555 size_t got_default = 0, got_host = 0;
4556 struct stat sb;
4557 char deff[PATH_MAX], hostf[PATH_MAX];
4558 char *js = NULL, *jsat, *domain = NULL;
4559 FILE *deffile = NULL, *hostfile = NULL;
4561 if (enable_js_autorun == 0)
4562 return;
4564 uri = get_uri(t);
4565 if (uri &&
4566 !(g_str_has_prefix(uri, "http://") ||
4567 g_str_has_prefix(uri, "https://")))
4568 goto done;
4570 su = soup_uri_new(uri);
4571 if (su == NULL)
4572 goto done;
4573 if (!SOUP_URI_VALID_FOR_HTTP(su))
4574 goto done;
4576 DNPRINTF(XT_D_JS, "%s: host: %s domain: %s\n", __func__,
4577 su->host, domain);
4578 domain = get_domain(su->host);
4580 snprintf(deff, sizeof deff, "%s" PS "default.js", js_dir);
4581 if ((deffile = fopen(deff, "r")) != NULL) {
4582 if (fstat(fileno(deffile), &sb) == -1) {
4583 show_oops(t, "can't stat default JS file");
4584 goto done;
4586 got_default = sb.st_size;
4589 /* try host first followed by domain */
4590 snprintf(hostf, sizeof hostf, "%s" PS "%s.js", js_dir, su->host);
4591 DNPRINTF(XT_D_JS, "trying file: %s\n", hostf);
4592 if ((hostfile = fopen(hostf, "r")) == NULL) {
4593 snprintf(hostf, sizeof hostf, "%s" PS "%s.js", js_dir, domain);
4594 DNPRINTF(XT_D_JS, "trying file: %s\n", hostf);
4595 if ((hostfile = fopen(hostf, "r")) == NULL)
4596 goto nofile;
4598 DNPRINTF(XT_D_JS, "file: %s\n", hostf);
4599 if (fstat(fileno(hostfile), &sb) == -1) {
4600 show_oops(t, "can't stat %s JS file", hostf);
4601 goto done;
4603 got_host = sb.st_size;
4605 nofile:
4606 if (got_default + got_host == 0)
4607 goto done;
4609 js = g_malloc0(got_default + got_host + 1);
4610 jsat = js;
4612 if (got_default) {
4613 if (fread(js, got_default, 1, deffile) != 1) {
4614 show_oops(t, "default file read error");
4615 goto done;
4617 jsat = js + got_default;
4620 if (got_host) {
4621 if (fread(jsat, got_host, 1, hostfile) != 1) {
4622 show_oops(t, "host file read error");
4623 goto done;
4627 DNPRINTF(XT_D_JS, "%s: about to run script\n", __func__);
4628 run_script_locked(t, js);
4630 done:
4631 if (su)
4632 soup_uri_free(su);
4633 if (js)
4634 g_free(js);
4635 if (deffile)
4636 fclose(deffile);
4637 if (hostfile)
4638 fclose(hostfile);
4639 if (domain)
4640 g_free(domain);
4643 void
4644 webview_progress_changed_cb(WebKitWebView *wv, GParamSpec *pspec, struct tab *t)
4646 gdouble progress;
4648 progress = webkit_web_view_get_progress(wv);
4649 gtk_entry_set_progress_fraction(GTK_ENTRY(t->sbe.uri),
4650 progress == 1.0 ? 0 : progress);
4651 gtk_entry_set_progress_fraction(GTK_ENTRY(t->uri_entry),
4652 progress == 1.0 ? 0 : progress);
4654 update_statusbar_position(NULL, NULL);
4658 strict_transport_rb_cmp(struct strict_transport *a, struct strict_transport *b)
4660 char *p1, *p2;
4661 int l1, l2;
4663 /* compare strings from the end */
4664 l1 = strlen(a->host);
4665 l2 = strlen(b->host);
4667 p1 = a->host + l1;
4668 p2 = b->host + l2;
4669 for (; *p1 == *p2 && p1 > a->host && p2 > b->host;
4670 p1--, p2--)
4674 * Check if we need to do pattern expansion,
4675 * or if we're just keeping the tree in order
4677 if (a->flags & XT_STS_FLAGS_EXPAND &&
4678 b->flags & XT_STS_FLAGS_INCLUDE_SUBDOMAINS) {
4679 /* Check if we're matching the
4680 * 'host.xyz' part in '*.host.xyz'
4682 if (p2 == b->host && (p1 == a->host || *(p1-1) == '.')) {
4683 return (0);
4687 if (p1 == a->host && p2 == b->host)
4688 return (0);
4689 if (p1 == a->host)
4690 return (1);
4691 if (p2 == b->host)
4692 return (-1);
4694 if (*p1 < *p2)
4695 return (-1);
4696 if (*p1 > *p2)
4697 return (1);
4699 return (0);
4701 RB_GENERATE(strict_transport_tree, strict_transport, entry,
4702 strict_transport_rb_cmp);
4705 strict_transport_add(const char *domain, time_t timeout, int subdomains)
4707 struct strict_transport *d, find;
4708 time_t now;
4709 FILE *f;
4711 if (enable_strict_transport == FALSE)
4712 return (0);
4714 DPRINTF("strict_transport_add(%s,%" PRIi64 ",%d)\n", domain,
4715 (uint64_t)timeout, subdomains);
4717 now = time(NULL);
4718 if (timeout < now)
4719 return (0);
4721 find.host = (char *)domain;
4722 find.flags = 0;
4723 d = RB_FIND(strict_transport_tree, &st_tree, &find);
4725 /* update flags */
4726 if (d) {
4727 /* check if update is needed */
4728 if (d->timeout == timeout &&
4729 (d->flags & XT_STS_FLAGS_INCLUDE_SUBDOMAINS) == subdomains)
4730 return (0);
4732 d->timeout = timeout;
4733 if (subdomains)
4734 d->flags |= XT_STS_FLAGS_INCLUDE_SUBDOMAINS;
4736 /* We're still initializing */
4737 if (strict_transport_file == NULL)
4738 return (0);
4740 if ((f = fopen(strict_transport_file, "w")) == NULL) {
4741 show_oops(NULL,
4742 "can't open strict-transport rules file");
4743 return (1);
4746 fprintf(f, "# Generated file - do not update unless you know "
4747 "what you're doing\n");
4748 RB_FOREACH(d, strict_transport_tree, &st_tree) {
4749 if (d->timeout < now)
4750 continue;
4751 fprintf(f, "%s\t%" PRIi64 "\t%d\n", d->host,
4752 (uint64_t)d->timeout,
4753 d->flags & XT_STS_FLAGS_INCLUDE_SUBDOMAINS);
4755 fclose(f);
4756 } else {
4757 d = g_malloc(sizeof *d);
4758 d->host= g_strdup(domain);
4759 d->timeout = timeout;
4760 if (subdomains)
4761 d->flags = XT_STS_FLAGS_INCLUDE_SUBDOMAINS;
4762 else
4763 d->flags = 0;
4764 RB_INSERT(strict_transport_tree, &st_tree, d);
4766 /* We're still initializing */
4767 if (strict_transport_file == NULL)
4768 return (0);
4770 if ((f = fopen(strict_transport_file, "a+")) == NULL) {
4771 show_oops(NULL,
4772 "can't open strict-transport rules file");
4773 return (1);
4776 fseek(f, 0, SEEK_END);
4777 fprintf(f,"%s\t%" PRIi64 "\t%d\n", d->host, (uint64_t)timeout,
4778 subdomains);
4779 fclose(f);
4781 return (0);
4785 strict_transport_check(const char *host)
4787 static struct strict_transport *d = NULL;
4788 struct strict_transport find;
4790 if (enable_strict_transport == FALSE)
4791 return (0);
4793 find.host = (char *)host;
4795 /* match for domains that include subdomains */
4796 find.flags = XT_STS_FLAGS_EXPAND;
4798 /* First, check if we're already at the right node */
4799 if (d != NULL && strict_transport_rb_cmp(&find, d) == 0) {
4800 return (1);
4803 d = RB_FIND(strict_transport_tree, &st_tree, &find);
4804 if (d != NULL)
4805 return (1);
4807 return (0);
4811 strict_transport_init()
4813 char file[PATH_MAX];
4814 char delim[3];
4815 char *rule;
4816 char *ptr;
4817 FILE *f;
4818 size_t len;
4819 time_t timeout, now;
4820 int subdomains;
4822 snprintf(file, sizeof file, "%s" PS "%s", work_dir, XT_STS_FILE);
4823 if ((f = fopen(file, "r")) == NULL) {
4824 strict_transport_file = g_strdup(file);
4825 return (0);
4828 delim[0] = '\\';
4829 delim[1] = '\\';
4830 delim[2] = '#';
4831 rule = NULL;
4832 now = time(NULL);
4834 for (;;) {
4835 if ((rule = fparseln(f, &len, NULL, delim, 0)) == NULL) {
4836 if (!feof(f) || ferror(f))
4837 goto corrupt_file;
4838 else
4839 break;
4842 /* get second entry */
4843 if ((ptr = strpbrk(rule, " \t")) == NULL)
4844 goto corrupt_file;
4846 *ptr++ = '\0';
4847 timeout = atoi(ptr);
4849 /* get third entry */
4850 if ((ptr = strpbrk(ptr, " \t")) == NULL)
4851 goto corrupt_file;
4853 ptr ++;
4854 subdomains = atoi(ptr);
4856 if (timeout > now)
4857 strict_transport_add(rule, timeout, subdomains);
4858 free(rule);
4861 fclose(f);
4862 strict_transport_file = g_strdup(file);
4863 return (0);
4865 corrupt_file:
4866 startpage_add("strict-transport rules file ('%s') is corrupt", file);
4867 if (rule)
4868 free(rule);
4869 fclose(f);
4870 return (1);
4874 force_https_check(const char *uri)
4876 struct wl_entry *w = NULL;
4878 if (uri == NULL)
4879 return (0);
4881 if ((w = wl_find_uri(uri, &force_https)) == NULL)
4882 return (0);
4883 else
4884 return (1);
4887 void
4888 strict_transport_security_cb(SoupMessage *msg, gpointer data)
4890 SoupURI *uri;
4891 const char *sts;
4892 char *ptr;
4893 time_t timeout = 0;
4894 int subdomains = FALSE;
4896 if (msg == NULL)
4897 return;
4899 sts = soup_message_headers_get_one(msg->response_headers,
4900 "Strict-Transport-Security");
4901 uri = soup_message_get_uri(msg);
4903 if (sts == NULL || uri == NULL)
4904 return;
4906 if ((ptr = strcasestr(sts, "max-age="))) {
4907 ptr += strlen("max-age=");
4908 timeout = atoll(ptr);
4909 } else
4910 return; /* malformed header - max-age must be included */
4912 if ((ptr = strcasestr(sts, "includeSubDomains")))
4913 subdomains = TRUE;
4915 strict_transport_add(uri->host, timeout + time(NULL), subdomains);
4918 void
4919 session_rq_cb(SoupSession *s, SoupMessage *msg, SoupSocket *socket,
4920 gpointer data)
4922 SoupURI *dest;
4923 SoupURI *ref_uri;
4924 const char *ref;
4926 char *ref_suffix;
4927 char *dest_suffix;
4929 if (s == NULL || msg == NULL)
4930 return;
4932 if (enable_strict_transport) {
4933 soup_message_add_header_handler(msg, "finished",
4934 "Strict-Transport-Security",
4935 G_CALLBACK(strict_transport_security_cb), NULL);
4938 if (referer_mode == XT_REFERER_ALWAYS)
4939 return;
4941 /* Check if referer is set - and what the user requested for referers */
4942 ref = soup_message_headers_get_one(msg->request_headers, "Referer");
4943 if (ref) {
4944 DNPRINTF(XT_D_NAV, "session_rq_cb: Referer: %s\n", ref);
4945 switch (referer_mode) {
4946 case XT_REFERER_NEVER:
4947 DNPRINTF(XT_D_NAV, "session_rq_cb: removing referer\n");
4948 soup_message_headers_remove(msg->request_headers,
4949 "Referer");
4950 break;
4951 case XT_REFERER_SAME_DOMAIN:
4952 ref_uri = soup_uri_new(ref);
4953 dest = soup_message_get_uri(msg);
4955 ref_suffix = tld_get_suffix(ref_uri->host);
4956 dest_suffix = tld_get_suffix(dest->host);
4958 if (dest && ref_suffix && dest_suffix &&
4959 strcmp(ref_suffix, dest_suffix) != 0) {
4960 soup_message_headers_remove(msg->request_headers,
4961 "Referer");
4962 DNPRINTF(XT_D_NAV, "session_rq_cb: removing "
4963 "referer (not same domain) (suffixes: %s - %s)\n",
4964 ref_suffix, dest_suffix);
4966 soup_uri_free(ref_uri);
4967 break;
4968 case XT_REFERER_SAME_FQDN:
4969 ref_uri = soup_uri_new(ref);
4970 dest = soup_message_get_uri(msg);
4971 if (dest && strcmp(ref_uri->host, dest->host) != 0) {
4972 soup_message_headers_remove(msg->request_headers,
4973 "Referer");
4974 DNPRINTF(XT_D_NAV, "session_rq_cb: removing "
4975 "referer (not same fqdn) (should be %s)\n",
4976 dest->host);
4978 soup_uri_free(ref_uri);
4979 break;
4980 case XT_REFERER_CUSTOM:
4981 DNPRINTF(XT_D_NAV, "session_rq_cb: setting referer "
4982 "to %s\n", referer_custom);
4983 soup_message_headers_replace(msg->request_headers,
4984 "Referer", referer_custom);
4985 break;
4991 webview_npd_cb(WebKitWebView *wv, WebKitWebFrame *wf,
4992 WebKitNetworkRequest *request, WebKitWebNavigationAction *na,
4993 WebKitWebPolicyDecision *pd, struct tab *t)
4995 WebKitWebNavigationReason reason;
4996 char *uri;
4998 if (t == NULL) {
4999 show_oops(NULL, "webview_npd_cb invalid parameters");
5000 return (FALSE);
5003 DNPRINTF(XT_D_NAV, "webview_npd_cb: ctrl_click %d %s\n",
5004 t->ctrl_click,
5005 webkit_network_request_get_uri(request));
5007 uri = (char *)webkit_network_request_get_uri(request);
5009 if (!auto_load_images && t->load_images) {
5011 /* Disable autoloading of images, now that we're done loading
5012 * them. */
5013 g_object_set(G_OBJECT(t->settings),
5014 "auto-load-images", FALSE, (char *)NULL);
5015 webkit_web_view_set_settings(t->wv, t->settings);
5017 t->load_images = FALSE;
5020 /* If this is an xtp url, we don't load anything else. */
5021 if (parse_xtp_url(t, uri)) {
5022 webkit_web_policy_decision_ignore(pd);
5023 return (TRUE);
5026 if (parse_custom_uri(t, uri)) {
5027 webkit_web_policy_decision_ignore(pd);
5028 return (TRUE);
5031 if (valid_url_type(uri)) {
5032 show_oops(t, "Stopping attempt to load an invalid URI (possible"
5033 " bait and switch attack)");
5034 webkit_web_policy_decision_ignore(pd);
5035 return (TRUE);
5038 if ((t->mode == XT_MODE_HINT && t->new_tab) || t->ctrl_click) {
5039 t->ctrl_click = 0;
5040 create_new_tab(uri, NULL, ctrl_click_focus, -1);
5041 webkit_web_policy_decision_ignore(pd);
5042 return (TRUE); /* we made the decission */
5046 * This is a little hairy but it comes down to this:
5047 * when we run in whitelist mode we have to assist the browser in
5048 * opening the URL that it would have opened in a new tab.
5050 reason = webkit_web_navigation_action_get_reason(na);
5051 if (reason == WEBKIT_WEB_NAVIGATION_REASON_LINK_CLICKED) {
5052 set_normal_tab_meaning(t);
5053 if (enable_scripts == 0 && enable_cookie_whitelist == 1)
5054 load_uri(t, uri);
5055 webkit_web_policy_decision_use(pd);
5056 return (TRUE); /* we made the decision */
5059 return (FALSE);
5062 void
5063 webview_rrs_cb(WebKitWebView *wv, WebKitWebFrame *wf, WebKitWebResource *res,
5064 WebKitNetworkRequest *request, WebKitNetworkResponse *response,
5065 struct tab *t)
5067 SoupMessage *msg = NULL;
5068 SoupURI *uri = NULL;
5069 struct http_accept ha_find, *ha = NULL;
5070 struct user_agent ua_find, *ua = NULL;
5071 struct domain_id di_find, *di = NULL;
5072 char *uri_s = NULL;
5074 msg = webkit_network_request_get_message(request);
5075 if (!msg) return;
5077 uri = soup_message_get_uri(msg);
5078 if (!uri)
5079 return;
5080 uri_s = soup_uri_to_string(uri, FALSE);
5082 if (strcmp(uri->scheme, SOUP_URI_SCHEME_HTTP) == 0) {
5083 if (strict_transport_check(uri->host) ||
5084 force_https_check(uri_s)) {
5085 DNPRINTF(XT_D_NAV, "webview_rrs_cb: force https for %s\n",
5086 uri->host);
5087 soup_uri_set_scheme(uri, SOUP_URI_SCHEME_HTTPS);
5091 if (do_not_track)
5092 soup_message_headers_append(msg->request_headers, "DNT", "1");
5095 * Check if resources on this domain have been loaded before. If
5096 * not, add the current tab's http-accept and user-agent id's to a
5097 * new domain_id and insert into the RB tree. Use these http headers
5098 * for all resources loaded from this domain for the lifetime of the
5099 * browser.
5101 if ((di_find.domain = uri->host) == NULL)
5102 goto done;
5103 if ((di = RB_FIND(domain_id_list, &di_list, &di_find)) == NULL) {
5104 di = g_malloc(sizeof *di);
5105 di->domain = g_strdup(uri->host);
5106 di->ua_id = t->user_agent_id++;
5107 di->ha_id = t->http_accept_id++;
5108 RB_INSERT(domain_id_list, &di_list, di);
5110 ua_find.id = t->user_agent_id;
5111 ua = RB_FIND(user_agent_list, &ua_list, &ua_find);
5112 if (ua == NULL)
5113 t->user_agent_id = 0;
5115 ha_find.id = t->http_accept_id;
5116 ha = RB_FIND(http_accept_list, &ha_list, &ha_find);
5117 if (ha == NULL)
5118 t->http_accept_id = 0;
5121 ua_find.id = di->ua_id;
5122 ua = RB_FIND(user_agent_list, &ua_list, &ua_find);
5123 ha_find.id = di->ha_id;
5124 ha = RB_FIND(http_accept_list, &ha_list, &ha_find);
5126 if (ua != NULL)
5127 soup_message_headers_replace(msg->request_headers,
5128 "User-Agent", ua->value);
5129 if (ha != NULL)
5130 soup_message_headers_replace(msg->request_headers,
5131 "Accept", ha->value);
5133 done:
5134 if (uri_s)
5135 g_free(uri_s);
5138 WebKitWebView *
5139 webview_cwv_cb(WebKitWebView *wv, WebKitWebFrame *wf, struct tab *t)
5141 struct tab *tt;
5142 struct wl_entry *w = NULL;
5143 const gchar *uri;
5144 WebKitWebView *webview = NULL;
5145 int x = 1;
5147 DNPRINTF(XT_D_NAV, "webview_cwv_cb: %s\n",
5148 webkit_web_view_get_uri(wv));
5150 if (tabless) {
5151 /* open in current tab */
5152 webview = t->wv;
5153 } else if (enable_scripts == 0 && enable_js_whitelist == 1) {
5154 uri = webkit_web_view_get_uri(wv);
5155 if (uri && (w = wl_find_uri(uri, &js_wl)) == NULL)
5156 return (NULL);
5158 if (t->ctrl_click) {
5159 x = ctrl_click_focus;
5160 t->ctrl_click = 0;
5162 tt = create_new_tab(NULL, NULL, x, -1);
5163 webview = tt->wv;
5164 } else if (enable_scripts == 1) {
5165 if (t->ctrl_click) {
5166 x = ctrl_click_focus;
5167 t->ctrl_click = 0;
5169 tt = create_new_tab(NULL, NULL, x, -1);
5170 webview = tt->wv;
5173 return (webview);
5176 gboolean
5177 webview_closewv_cb(WebKitWebView *wv, struct tab *t)
5179 const gchar *uri;
5180 struct wl_entry *w = NULL;
5182 DNPRINTF(XT_D_NAV, "webview_close_cb: %d\n", t->tab_id);
5184 if (enable_scripts == 0 && enable_cookie_whitelist == 1) {
5185 uri = webkit_web_view_get_uri(wv);
5186 if (uri && (w = wl_find_uri(uri, &js_wl)) == NULL)
5187 return (FALSE);
5189 delete_tab(t);
5190 } else if (enable_scripts == 1)
5191 delete_tab(t);
5193 return (TRUE);
5197 webview_event_cb(GtkWidget *w, GdkEventButton *e, struct tab *t)
5199 /* we can not eat the event without throwing gtk off so defer it */
5201 /* catch middle click */
5202 if (e->type == GDK_BUTTON_RELEASE && e->button == 2) {
5203 t->ctrl_click = 1;
5204 goto done;
5207 /* catch ctrl click */
5208 if (e->type == GDK_BUTTON_RELEASE &&
5209 CLEAN(e->state) == GDK_CONTROL_MASK)
5210 t->ctrl_click = 1;
5211 else
5212 t->ctrl_click = 0;
5213 done:
5214 return (XT_CB_PASSTHROUGH);
5218 run_mimehandler(struct tab *t, char *mime_type, WebKitNetworkRequest *request)
5220 struct mime_type *m;
5221 char *sv[3];
5222 GError *gerr = NULL;
5224 m = find_mime_type(mime_type);
5225 if (m == NULL)
5226 return (1);
5227 if (m->mt_download)
5228 return (1);
5230 sv[0] = m->mt_action;
5231 sv[1] = (char *)webkit_network_request_get_uri(request);
5232 sv[2] = NULL;
5234 /* ignore donothing from example config */
5235 if (m->mt_action && !strcmp(m->mt_action, "donothing"))
5236 return (0);
5238 if (!g_spawn_async(NULL, sv, NULL, G_SPAWN_SEARCH_PATH, NULL, NULL,
5239 NULL, &gerr))
5240 show_oops(t, "%s: could not spawn process (%s)", __func__,
5241 gerr ? gerr->message : "N/A");
5242 return (0);
5245 char *
5246 get_mime_type(const char *uri)
5248 GFileInfo *fi;
5249 GFile *gf;
5250 const gchar *m;
5251 char *mime_type = NULL;
5252 char *file;
5254 if (uri == NULL) {
5255 show_oops(NULL, "%s: invalid parameters", __func__);
5256 return (NULL);
5259 if (g_str_has_prefix(uri, "file://"))
5260 file = g_filename_from_uri(uri, NULL, NULL);
5261 else
5262 file = g_strdup(uri);
5264 if (file == NULL)
5265 return (NULL);
5267 gf = g_file_new_for_path(file);
5268 fi = g_file_query_info(gf, G_FILE_ATTRIBUTE_STANDARD_CONTENT_TYPE, 0,
5269 NULL, NULL);
5270 if ((m = g_file_info_get_content_type(fi)) != NULL)
5271 mime_type = g_strdup(m);
5272 g_object_unref(fi);
5273 g_object_unref(gf);
5274 g_free(file);
5276 return (mime_type);
5280 run_download_mimehandler(char *mime_type, char *file)
5282 struct mime_type *m;
5283 char *sv[3];
5285 m = find_mime_type(mime_type);
5286 if (m == NULL)
5287 return (1);
5289 sv[0] = m->mt_action;
5290 sv[1] = file;
5291 sv[2] = NULL;
5292 if (!g_spawn_async(NULL, sv, NULL, G_SPAWN_SEARCH_PATH, NULL, NULL,
5293 NULL, NULL)) {
5294 show_oops(NULL, "%s: could not spawn process: %s %s", __func__,
5295 sv[0], sv[1]);
5296 return (1);
5298 return (0);
5301 void
5302 download_status_changed_cb(WebKitDownload *download, GParamSpec *spec,
5303 WebKitWebView *wv)
5305 WebKitDownloadStatus status;
5306 const char *uri;
5307 char *file = NULL;
5308 char *mime = NULL;
5310 if (download == NULL)
5311 return;
5312 status = webkit_download_get_status(download);
5313 if (status != WEBKIT_DOWNLOAD_STATUS_FINISHED)
5314 return;
5316 if (download_notifications)
5317 show_oops(NULL, "Download of '%s' finished",
5318 basename((char *)webkit_download_get_destination_uri(download)));
5319 uri = webkit_download_get_destination_uri(download);
5320 if (uri == NULL)
5321 return;
5322 mime = get_mime_type(uri);
5323 if (mime == NULL)
5324 return;
5326 if (g_str_has_prefix(uri, "file://"))
5327 file = g_filename_from_uri(uri, NULL, NULL);
5328 else
5329 file = g_strdup(uri);
5331 if (file == NULL)
5332 goto done;
5334 run_download_mimehandler((char *)mime, file);
5336 done:
5337 g_free(mime);
5341 webview_mimetype_cb(WebKitWebView *wv, WebKitWebFrame *frame,
5342 WebKitNetworkRequest *request, char *mime_type,
5343 WebKitWebPolicyDecision *decision, struct tab *t)
5345 if (t == NULL) {
5346 show_oops(NULL, "webview_mimetype_cb invalid parameters");
5347 return (FALSE);
5350 DNPRINTF(XT_D_DOWNLOAD, "webview_mimetype_cb: tab %d mime %s\n",
5351 t->tab_id, mime_type);
5353 if (run_mimehandler(t, mime_type, request) == 0) {
5354 webkit_web_policy_decision_ignore(decision);
5355 focus_webview(t);
5356 return (TRUE);
5359 if (webkit_web_view_can_show_mime_type(wv, mime_type) == FALSE) {
5360 webkit_web_policy_decision_download(decision);
5361 return (TRUE);
5364 return (FALSE);
5368 download_start(struct tab *t, struct download *d, int flag)
5370 WebKitNetworkRequest *req;
5371 struct stat sb;
5372 const gchar *suggested_name;
5373 gchar *filename = NULL;
5374 char *uri = NULL;
5375 char *path = NULL;
5376 int ret = TRUE;
5377 int i;
5379 if (d == NULL || t == NULL) {
5380 show_oops(NULL, "%s invalid parameters", __func__);
5381 return (FALSE);
5384 suggested_name = webkit_download_get_suggested_filename(d->download);
5385 if (suggested_name == NULL)
5386 return (FALSE); /* abort download */
5388 i = 0;
5389 do {
5390 if (filename) {
5391 g_free(filename);
5392 filename = NULL;
5394 if (i) {
5395 g_free(uri);
5396 uri = NULL;
5397 filename = g_strdup_printf("%d%s", i, suggested_name);
5399 #ifdef __MINGW32__
5400 /* XXX using urls doesn't work properly in windows? */
5401 uri = g_strdup_printf("%s\\%s", download_dir, i ?
5402 filename : suggested_name);
5403 #else
5404 path = g_strdup_printf("%s" PS "%s", download_dir, i ?
5405 filename : suggested_name);
5406 if ((uri = g_filename_to_uri(path, NULL, NULL)) == NULL)
5407 break; /* XXX */
5408 #endif
5409 i++;
5410 #ifdef __MINGW32__
5411 } while (!stat(uri, &sb));
5412 #else
5413 } while (!stat(path, &sb));
5414 #endif
5416 DNPRINTF(XT_D_DOWNLOAD, "%s: tab %d filename %s "
5417 "local %s\n", __func__, t->tab_id, filename, uri);
5419 /* if we're restarting the download, or starting
5420 * it after doing something else, we need to recreate
5421 * the download request.
5423 if (flag == XT_DL_RESTART) {
5424 req = webkit_network_request_new(webkit_download_get_uri(d->download));
5425 webkit_download_cancel(d->download);
5426 g_object_unref(d->download);
5427 d->download = webkit_download_new(req);
5430 webkit_download_set_destination_uri(d->download, uri);
5432 if (webkit_download_get_status(d->download) ==
5433 WEBKIT_DOWNLOAD_STATUS_ERROR) {
5434 show_oops(t, "%s: download failed to start", __func__);
5435 ret = FALSE;
5436 show_oops(t, "Download Failed");
5437 } else {
5438 /* connect "download first" mime handler */
5439 g_signal_connect(G_OBJECT(d->download), "notify::status",
5440 G_CALLBACK(download_status_changed_cb), NULL);
5442 /* get from history */
5443 g_object_ref(d->download);
5444 show_oops(t, "Download of '%s' started...",
5445 basename((char *)webkit_download_get_destination_uri(d->download)));
5448 if (flag != XT_DL_START)
5449 webkit_download_start(d->download);
5451 DNPRINTF(XT_D_DOWNLOAD, "download status : %d",
5452 webkit_download_get_status(d->download));
5454 /* sync other download manager tabs */
5455 update_download_tabs(NULL);
5457 if (uri)
5458 g_free(uri);
5459 if (path)
5460 g_free(path);
5461 if (filename)
5462 g_free(filename);
5464 return (ret);
5468 download_ask_cb(struct tab *t, GdkEventKey *e, gpointer data)
5470 struct download *d = data;
5472 /* unset mode */
5473 t->mode_cb = NULL;
5474 t->mode_cb_data = NULL;
5476 if (!e || !d) {
5477 e->keyval = GDK_Escape;
5478 return (XT_CB_PASSTHROUGH);
5481 DPRINTF("download_ask_cb: User pressed %c\n", e->keyval);
5482 if (e->keyval == 'y' || e->keyval == 'Y' || e->keyval == GDK_Return)
5483 /* We need to do a RESTART, because we're not calling from
5484 * webview_download_cb
5486 download_start(t, d, XT_DL_RESTART);
5488 /* for all other keyvals, we just let the download be */
5489 e->keyval = GDK_Escape;
5490 return (XT_CB_HANDLED);
5494 download_ask(struct tab *t, struct download *d)
5496 const gchar *suggested_name;
5498 suggested_name = webkit_download_get_suggested_filename(d->download);
5499 if (suggested_name == NULL)
5500 return (FALSE); /* abort download */
5502 show_oops(t, "download file %s [y/n] ?", suggested_name);
5503 t->mode_cb = download_ask_cb;
5504 t->mode_cb_data = d;
5506 return (TRUE);
5510 webview_download_cb(WebKitWebView *wv, WebKitDownload *wk_download,
5511 struct tab *t)
5513 const gchar *suggested_name;
5514 struct download *download_entry;
5515 int ret = TRUE;
5517 if (wk_download == NULL || t == NULL) {
5518 show_oops(NULL, "%s invalid parameters", __func__);
5519 return (FALSE);
5522 suggested_name = webkit_download_get_suggested_filename(wk_download);
5523 if (suggested_name == NULL)
5524 return (FALSE); /* abort download */
5526 download_entry = g_malloc(sizeof(struct download));
5527 download_entry->download = wk_download;
5528 download_entry->tab = t;
5529 download_entry->id = next_download_id++;
5530 RB_INSERT(download_list, &downloads, download_entry);
5531 t->download_requested = 1;
5533 if (download_mode == XT_DM_START)
5534 ret = download_start(t, download_entry, XT_DL_START);
5535 else if (download_mode == XT_DM_ASK)
5536 ret = download_ask(t, download_entry);
5537 else if (download_mode == XT_DM_ADD)
5538 show_oops(t, "added %s to download manager",
5539 suggested_name);
5541 /* sync other download manager tabs */
5542 update_download_tabs(NULL);
5545 * NOTE: never redirect/render the current tab before this
5546 * function returns. This will cause the download to never start.
5548 return (ret); /* start download */
5551 void
5552 webview_hover_cb(WebKitWebView *wv, gchar *title, gchar *uri, struct tab *t)
5554 DNPRINTF(XT_D_KEY, "webview_hover_cb: %s %s\n", title, uri);
5556 if (t == NULL) {
5557 show_oops(NULL, "webview_hover_cb");
5558 return;
5561 if (uri)
5562 set_status(t, "Link: %s", uri);
5563 else {
5564 if (statusbar_style == XT_STATUSBAR_URL) {
5565 const gchar *page_uri;
5567 if ((page_uri = get_uri(t)) != NULL)
5568 set_status(t, "%s", page_uri);
5569 } else
5570 set_status(t, "%s", (char *)get_title(t, FALSE));
5575 mark(struct tab *t, struct karg *arg)
5577 char mark;
5578 int index;
5579 double pos;
5581 mark = arg->s[1];
5582 if ((index = marktoindex(mark)) == -1)
5583 return (-1);
5585 if (arg->i == XT_MARK_SET)
5586 t->mark[index] = gtk_adjustment_get_value(t->adjust_v);
5587 else if (arg->i == XT_MARK_GOTO) {
5588 if (t->mark[index] == XT_INVALID_MARK) {
5589 show_oops(t, "mark '%c' does not exist", mark);
5590 return (-1);
5592 /* XXX t->mark[index] can be bigger than the maximum if ajax or
5593 something changes the document size */
5594 pos = gtk_adjustment_get_value(t->adjust_v);
5595 gtk_adjustment_set_value(t->adjust_v, t->mark[index]);
5596 t->mark[marktoindex('\'')] = pos;
5599 return (0);
5602 void
5603 marks_clear(struct tab *t)
5605 int i;
5607 for (i = 0; i < LENGTH(t->mark); i++)
5608 t->mark[i] = XT_INVALID_MARK;
5612 qmarks_load(void)
5614 char file[PATH_MAX];
5615 char *line = NULL, *p;
5616 int index, i;
5617 FILE *f;
5618 size_t linelen;
5620 snprintf(file, sizeof file, "%s" PS "%s", work_dir, XT_QMARKS_FILE);
5621 if ((f = fopen(file, "r+")) == NULL) {
5622 show_oops(NULL, "Can't open quickmarks file: %s", strerror(errno));
5623 return (1);
5626 for (i = 1; ; i++) {
5627 if ((line = fparseln(f, &linelen, NULL, NULL, 0)) == NULL)
5628 break;
5629 if (strlen(line) == 0 || line[0] == '#') {
5630 free(line);
5631 line = NULL;
5632 continue;
5635 p = strtok(line, " \t");
5637 if (p == NULL || strlen(p) != 1 ||
5638 (index = qmarktoindex(*p)) == -1) {
5639 warnx("corrupt quickmarks file, line %d", i);
5640 break;
5643 p = strtok(NULL, " \t");
5644 if (qmarks[index] != NULL)
5645 g_free(qmarks[index]);
5646 qmarks[index] = g_strdup(p);
5649 fclose(f);
5651 return (0);
5655 qmarks_save(void)
5657 char file[PATH_MAX];
5658 int i;
5659 FILE *f;
5661 snprintf(file, sizeof file, "%s" PS "%s", work_dir, XT_QMARKS_FILE);
5662 if ((f = fopen(file, "r+")) == NULL) {
5663 show_oops(NULL, "Can't open quickmarks file: %s", strerror(errno));
5664 return (1);
5667 for (i = 0; i < XT_NOQMARKS; i++)
5668 if (qmarks[i] != NULL)
5669 fprintf(f, "%c %s\n", indextoqmark(i), qmarks[i]);
5671 fclose(f);
5673 return (0);
5677 qmark(struct tab *t, struct karg *arg)
5679 char mark;
5680 int index;
5682 mark = arg->s[strlen(arg->s)-1];
5683 index = qmarktoindex(mark);
5684 if (index == -1)
5685 return (-1);
5687 switch (arg->i) {
5688 case XT_QMARK_SET:
5689 if (qmarks[index] != NULL) {
5690 g_free(qmarks[index]);
5691 qmarks[index] = NULL;
5694 qmarks_load(); /* sync if multiple instances */
5695 qmarks[index] = g_strdup(get_uri(t));
5696 qmarks_save();
5697 break;
5698 case XT_QMARK_OPEN:
5699 if (qmarks[index] != NULL)
5700 load_uri(t, qmarks[index]);
5701 else {
5702 show_oops(t, "quickmark \"%c\" does not exist",
5703 mark);
5704 return (-1);
5706 break;
5707 case XT_QMARK_TAB:
5708 if (qmarks[index] != NULL)
5709 create_new_tab(qmarks[index], NULL, 1, -1);
5710 else {
5711 show_oops(t, "quickmark \"%c\" does not exist",
5712 mark);
5713 return (-1);
5715 break;
5718 return (0);
5722 go_up(struct tab *t, struct karg *args)
5724 int levels;
5725 int lastidx;
5726 char *uri;
5727 char *tmp;
5728 char *p;
5730 if (args->i == XT_GO_UP_ROOT)
5731 levels = XT_GO_UP_ROOT;
5732 else if ((levels = atoi(args->s)) == 0)
5733 levels = 1;
5735 uri = g_strdup(get_uri(t));
5736 if (uri == NULL)
5737 return (1);
5739 if ((tmp = strstr(uri, XT_PROTO_DELIM)) == NULL)
5740 return (1);
5742 tmp += strlen(XT_PROTO_DELIM);
5744 /* it makes no sense to strip the last slash from ".../dir/", skip it */
5745 lastidx = strlen(tmp) - 1;
5746 if (lastidx > 0) {
5747 if (tmp[lastidx] == '/')
5748 tmp[lastidx] = '\0';
5751 while (levels--) {
5752 p = strrchr(tmp, '/');
5753 if (p == tmp) { /* Are we at the root of a file://-path? */
5754 p[1] = '\0';
5755 break;
5756 } else if (p != NULL)
5757 *p = '\0';
5758 else
5759 break;
5762 load_uri(t, uri);
5763 g_free(uri);
5765 return (0);
5769 gototab(struct tab *t, struct karg *args)
5771 int tab;
5772 struct karg arg = {0, NULL, -1};
5774 tab = atoi(args->s);
5776 if (args->i == 0)
5777 arg.i = XT_TAB_NEXT;
5778 else
5779 arg.i = args->i;
5781 arg.precount = tab;
5783 movetab(t, &arg);
5785 return (0);
5789 zoom_amount(struct tab *t, struct karg *arg)
5791 struct karg narg = {0, NULL, -1};
5793 narg.i = atoi(arg->s);
5794 resizetab(t, &narg);
5796 return (0);
5800 flip_colon(struct tab *t, struct karg *arg)
5802 struct karg narg = {0, NULL, -1};
5803 char *p;
5805 if (t == NULL || arg == NULL)
5806 return (1);
5808 p = strstr(arg->s, ":");
5809 if (p == NULL)
5810 return (1);
5811 *p = '\0';
5813 narg.i = ':';
5814 narg.s = arg->s;
5815 command(t, &narg);
5817 return (0);
5820 /* buffer commands receive the regex that triggered them in arg.s */
5821 char bcmd[XT_BUFCMD_SZ];
5822 struct buffercmd {
5823 char *regex;
5824 int precount;
5825 #define XT_PRE_NO (0)
5826 #define XT_PRE_YES (1)
5827 #define XT_PRE_MAYBE (2)
5828 char *cmd;
5829 int (*func)(struct tab *, struct karg *);
5830 int arg;
5831 regex_t cregex;
5832 } buffercmds[] = {
5833 { "^[0-9]*gu$", XT_PRE_MAYBE, "gu", go_up, 0 },
5834 { "^gU$", XT_PRE_NO, "gU", go_up, XT_GO_UP_ROOT },
5835 { "^gg$", XT_PRE_NO, "gg", move, XT_MOVE_TOP },
5836 { "^gG$", XT_PRE_NO, "gG", move, XT_MOVE_BOTTOM },
5837 { "^[0-9]+%$", XT_PRE_YES, "%", move, XT_MOVE_PERCENT },
5838 { "^zz$", XT_PRE_NO, "zz", move, XT_MOVE_CENTER },
5839 { "^gh$", XT_PRE_NO, "gh", go_home, 0 },
5840 { "^m[a-zA-Z0-9]$", XT_PRE_NO, "m", mark, XT_MARK_SET },
5841 { "^['][a-zA-Z0-9']$", XT_PRE_NO, "'", mark, XT_MARK_GOTO },
5842 { "^[0-9]+t$", XT_PRE_YES, "t", gototab, 0 },
5843 { "^g0$", XT_PRE_YES, "g0", movetab, XT_TAB_FIRST },
5844 { "^g[$]$", XT_PRE_YES, "g$", movetab, XT_TAB_LAST },
5845 { "^[0-9]*gt$", XT_PRE_YES, "t", movetab, XT_TAB_NEXT },
5846 { "^[0-9]*gT$", XT_PRE_YES, "T", movetab, XT_TAB_PREV },
5847 { "^M[a-zA-Z0-9]$", XT_PRE_NO, "M", qmark, XT_QMARK_SET },
5848 { "^go[a-zA-Z0-9]$", XT_PRE_NO, "go", qmark, XT_QMARK_OPEN },
5849 { "^gn[a-zA-Z0-9]$", XT_PRE_NO, "gn", qmark, XT_QMARK_TAB },
5850 { "^ZR$", XT_PRE_NO, "ZR", restart, 0 },
5851 { "^ZZ$", XT_PRE_NO, "ZZ", quit, 0 },
5852 { "^zi$", XT_PRE_NO, "zi", resizetab, XT_ZOOM_IN },
5853 { "^zo$", XT_PRE_NO, "zo", resizetab, XT_ZOOM_OUT },
5854 { "^z0$", XT_PRE_NO, "z0", resizetab, XT_ZOOM_NORMAL },
5855 { "^[0-9]+Z$", XT_PRE_YES, "Z", zoom_amount, 0 },
5856 { "^[0-9]+:$", XT_PRE_YES, ":", flip_colon, 0 },
5859 void
5860 buffercmd_init(void)
5862 int i;
5864 for (i = 0; i < LENGTH(buffercmds); i++)
5865 if (regcomp(&buffercmds[i].cregex, buffercmds[i].regex,
5866 REG_EXTENDED | REG_NOSUB))
5867 startpage_add("invalid buffercmd regex %s",
5868 buffercmds[i].regex);
5871 void
5872 buffercmd_abort(struct tab *t)
5874 int i;
5876 if (t == NULL)
5877 return;
5879 DNPRINTF(XT_D_BUFFERCMD, "%s: clearing buffer\n", __func__);
5881 for (i = 0; i < LENGTH(bcmd); i++)
5882 bcmd[i] = '\0';
5884 cmd_prefix = 0; /* clear prefix for non-buffer commands */
5885 gtk_label_set_text(GTK_LABEL(t->sbe.buffercmd), bcmd);
5888 void
5889 buffercmd_execute(struct tab *t, struct buffercmd *cmd)
5891 struct karg arg = {0, NULL, -1};
5893 arg.i = cmd->arg;
5894 arg.s = g_strdup(bcmd);
5896 DNPRINTF(XT_D_BUFFERCMD, "buffercmd_execute: buffer \"%s\" "
5897 "matches regex \"%s\", executing\n", bcmd, cmd->regex);
5898 cmd->func(t, &arg);
5900 if (arg.s)
5901 g_free(arg.s);
5903 buffercmd_abort(t);
5906 gboolean
5907 buffercmd_addkey(struct tab *t, guint keyval)
5909 int i, c, match ;
5910 char s[XT_BUFCMD_SZ];
5912 if (gtk_widget_get_visible(GTK_WIDGET(t->buffers))) {
5913 buffercmd_abort(t);
5914 return (XT_CB_PASSTHROUGH);
5917 if (keyval == GDK_Escape) {
5918 buffercmd_abort(t);
5919 return (XT_CB_HANDLED);
5922 /* key with modifier or non-ascii character */
5923 if (!isascii(keyval)) {
5925 * XXX this looks wrong but fixes some sites like
5926 * http://www.seslisozluk.com/
5927 * that eat a shift or ctrl and end putting default focus in js
5928 * instead of ignoring the keystroke
5929 * so instead of return (XT_CB_PASSTHROUGH); eat the key
5931 return (XT_CB_HANDLED);
5934 DNPRINTF(XT_D_BUFFERCMD, "buffercmd_addkey: adding key \"%c\" "
5935 "to buffer \"%s\"\n", keyval, bcmd);
5937 for (i = 0; i < LENGTH(bcmd); i++)
5938 if (bcmd[i] == '\0') {
5939 bcmd[i] = keyval;
5940 break;
5943 /* buffer full, ignore input */
5944 if (i >= LENGTH(bcmd) -1) {
5945 DNPRINTF(XT_D_BUFFERCMD, "buffercmd_addkey: buffer full\n");
5946 buffercmd_abort(t);
5947 return (XT_CB_HANDLED);
5950 gtk_label_set_text(GTK_LABEL(t->sbe.buffercmd), bcmd);
5952 /* find exact match */
5953 for (i = 0; i < LENGTH(buffercmds); i++)
5954 if (regexec(&buffercmds[i].cregex, bcmd,
5955 (size_t) 0, NULL, 0) == 0) {
5956 buffercmd_execute(t, &buffercmds[i]);
5957 goto done;
5960 /* find non exact matches to see if we need to abort ot not */
5961 for (i = 0, match = 0; i < LENGTH(buffercmds); i++) {
5962 DNPRINTF(XT_D_BUFFERCMD, "trying: %s\n", bcmd);
5963 c = -1;
5964 s[0] = '\0';
5965 if (buffercmds[i].precount == XT_PRE_MAYBE) {
5966 if (isdigit(bcmd[0])) {
5967 if (sscanf(bcmd, "%d%s", &c, s) == 0)
5968 continue;
5969 } else {
5970 c = 0;
5971 if (sscanf(bcmd, "%s", s) == 0)
5972 continue;
5974 } else if (buffercmds[i].precount == XT_PRE_YES) {
5975 if (sscanf(bcmd, "%d%s", &c, s) == 0)
5976 continue;
5977 } else {
5978 if (sscanf(bcmd, "%s", s) == 0)
5979 continue;
5981 if (c == -1 && buffercmds[i].precount)
5982 continue;
5983 if (!strncmp(s, buffercmds[i].cmd, strlen(s)))
5984 match++;
5986 DNPRINTF(XT_D_BUFFERCMD, "got[%d] %d <%s>: %d %s\n",
5987 i, match, buffercmds[i].cmd, c, s);
5989 if (match == 0) {
5990 DNPRINTF(XT_D_BUFFERCMD, "aborting: %s\n", bcmd);
5991 buffercmd_abort(t);
5994 done:
5995 return (XT_CB_HANDLED);
5999 * XXX we were seeing a bunch of focus issues with the toplevel
6000 * main_window losing its is-active and has-toplevel-focus properties.
6001 * This is the most correct and portable solution we could come up with
6002 * without relying on calling internal GTK functions (which we
6003 * couldn't link to in Linux).
6005 #if GTK_CHECK_VERSION(3, 0, 0)
6006 void
6007 fake_focus_in(GtkWidget *w)
6009 if (fevent == NULL) {
6010 fevent = gdk_event_new(GDK_FOCUS_CHANGE);
6011 fevent->focus_change.window =
6012 gtk_widget_get_window(main_window);
6013 fevent->focus_change.type = GDK_FOCUS_CHANGE;
6014 fevent->focus_change.in = TRUE;
6016 gtk_widget_send_focus_change(main_window, fevent);
6018 #endif
6020 gboolean
6021 handle_keypress(struct tab *t, GdkEventKey *e, int entry)
6023 struct karg args;
6024 struct key_binding *k;
6027 * This sometimes gets randomly unset for whatever reason in GTK3.
6028 * If we're handling a keypress, the main window's is-active propery
6029 * *must* be true, or else many things will break.
6031 #if GTK_CHECK_VERSION(3, 0, 0)
6032 fake_focus_in(main_window);
6033 #endif
6035 /* handle keybindings if buffercmd is empty.
6036 if not empty, allow commands like C-n */
6037 if (bcmd[0] == '\0' || ((e->state & (CTRL | MOD1)) != 0))
6038 TAILQ_FOREACH(k, &kbl, entry)
6039 if (e->keyval == k->key
6040 && (entry ? k->use_in_entry : 1)) {
6041 /* when we are edditing eat ctrl/mod keys */
6042 if (edit_mode == XT_EM_VI &&
6043 t->mode == XT_MODE_INSERT &&
6044 (e->state & CTRL || e->state & MOD1))
6045 return (XT_CB_PASSTHROUGH);
6047 if (k->mask == 0) {
6048 if ((e->state & (CTRL | MOD1)) == 0)
6049 goto runcmd;
6050 } else if ((e->state & k->mask) == k->mask) {
6051 goto runcmd;
6055 if (!entry && ((e->state & (CTRL | MOD1)) == 0))
6056 return (buffercmd_addkey(t, e->keyval));
6058 return (XT_CB_PASSTHROUGH);
6060 runcmd:
6061 if (k->cmd[0] == ':') {
6062 args.i = ':';
6063 args.s = &k->cmd[1];
6064 return (command(t, &args));
6065 } else
6066 return (cmd_execute(t, k->cmd));
6070 wv_keypress_cb(GtkEntry *w, GdkEventKey *e, struct tab *t)
6072 char s[2];
6074 /* don't use w directly; use t->whatever instead */
6076 if (t == NULL) {
6077 show_oops(NULL, "wv_keypress_cb");
6078 return (XT_CB_PASSTHROUGH);
6081 hide_oops(t);
6083 if (t->mode_cb)
6084 return (t->mode_cb(t, e, t->mode_cb_data));
6086 DNPRINTF(XT_D_KEY, "wv_keypress_cb: mode %d keyval 0x%x mask "
6087 "0x%x tab %d\n", t->mode, e->keyval, e->state, t->tab_id);
6089 /* Hide buffers, if they are visible, with escape. */
6090 if (gtk_widget_get_visible(GTK_WIDGET(t->buffers)) &&
6091 CLEAN(e->state) == 0 && e->keyval == GDK_Escape) {
6092 gtk_widget_grab_focus(GTK_WIDGET(t->wv));
6093 hide_buffers(t);
6094 return (XT_CB_HANDLED);
6097 if ((CLEAN(e->state) == 0 && e->keyval == GDK_Tab) ||
6098 (CLEAN(e->state) == SHFT && e->keyval == GDK_Tab))
6099 /* something focussy is about to happen */
6100 return (XT_CB_PASSTHROUGH);
6102 /* check if we are some sort of text input thing in the dom */
6103 input_check_mode(t);
6105 if (t->mode == XT_MODE_PASSTHROUGH) {
6106 if (CLEAN(e->state) == 0 && e->keyval == GDK_Escape)
6107 t->mode = XT_MODE_COMMAND;
6108 return (XT_CB_PASSTHROUGH);
6109 } else if (t->mode == XT_MODE_COMMAND || t->mode == XT_MODE_HINT) {
6110 /* prefix input */
6111 snprintf(s, sizeof s, "%c", e->keyval);
6112 if (CLEAN(e->state) == 0 && isdigit(s[0]))
6113 cmd_prefix = 10 * cmd_prefix + atoi(s);
6114 return (handle_keypress(t, e, 0));
6115 } else {
6116 /* insert mode */
6117 return (handle_keypress(t, e, 1));
6120 /* NOTREACHED */
6121 return (XT_CB_PASSTHROUGH);
6124 gboolean
6125 hint_continue(struct tab *t)
6127 const gchar *c = gtk_entry_get_text(GTK_ENTRY(t->cmd));
6128 char *s;
6129 const gchar *errstr = NULL;
6130 gboolean rv = TRUE;
6131 int i;
6133 if (!(c[0] == '.' || c[0] == ','))
6134 goto done;
6135 if (strlen(c) == 1) {
6136 /* XXX should not happen */
6137 rv = TRUE;
6138 goto done;
6141 if (isdigit(c[1])) {
6142 /* numeric input */
6143 i = strtonum(&c[1], 1, 4096, &errstr);
6144 if (errstr) {
6145 show_oops(t, "invalid numerical hint %s", &c[1]);
6146 goto done;
6148 s = g_strdup_printf("hints.updateHints(%d);", i);
6149 run_script(t, s);
6150 g_free(s);
6151 } else {
6152 /* alphanumeric input */
6153 s = g_strdup_printf("hints.createHints('%s', '%c');",
6154 &c[1], c[0] == '.' ? 'f' : 'F');
6155 run_script(t, s);
6156 g_free(s);
6159 rv = FALSE;
6160 done:
6161 return (rv);
6164 gboolean
6165 search_continue(struct tab *t)
6167 const gchar *c = gtk_entry_get_text(GTK_ENTRY(t->cmd));
6168 gboolean rv = FALSE;
6170 if (c[0] == ':' || c[0] == '.' || c[0] == ',')
6171 goto done;
6172 if (strlen(c) == 1) {
6173 webkit_web_view_unmark_text_matches(t->wv);
6174 goto done;
6177 if (c[0] == '/')
6178 t->search_forward = TRUE;
6179 else if (c[0] == '?')
6180 t->search_forward = FALSE;
6181 else
6182 goto done;
6184 rv = TRUE;
6185 done:
6186 return (rv);
6189 gboolean
6190 search_cb(struct tab *t)
6192 const gchar *c = gtk_entry_get_text(GTK_ENTRY(t->cmd));
6193 #if !GTK_CHECK_VERSION(3, 0, 0)
6194 GdkColor color;
6195 #endif
6197 if (search_continue(t) == FALSE)
6198 goto done;
6200 /* search */
6201 if (webkit_web_view_search_text(t->wv, &c[1], FALSE, t->search_forward,
6202 TRUE) == FALSE) {
6203 /* not found, mark red */
6204 #if GTK_CHECK_VERSION(3, 0, 0)
6205 gtk_widget_set_name(t->cmd, XT_CSS_RED);
6206 #else
6207 gdk_color_parse(XT_COLOR_RED, &color);
6208 gtk_widget_modify_base(t->cmd, GTK_STATE_NORMAL, &color);
6209 #endif
6210 /* unmark and remove selection */
6211 webkit_web_view_unmark_text_matches(t->wv);
6212 /* my kingdom for a way to unselect text in webview */
6213 } else {
6214 /* found, highlight all */
6215 webkit_web_view_unmark_text_matches(t->wv);
6216 webkit_web_view_mark_text_matches(t->wv, &c[1], FALSE, 0);
6217 webkit_web_view_set_highlight_text_matches(t->wv, TRUE);
6218 #if GTK_CHECK_VERSION(3, 0, 0)
6219 gtk_widget_set_name(t->cmd, XT_CSS_NORMAL);
6220 #else
6221 gtk_widget_modify_base(t->cmd, GTK_STATE_NORMAL,
6222 &t->default_style->base[GTK_STATE_NORMAL]);
6223 #endif
6225 done:
6226 t->search_id = 0;
6227 return (FALSE);
6231 cmd_keyrelease_cb(GtkEntry *w, GdkEventKey *e, struct tab *t)
6233 const gchar *c = gtk_entry_get_text(w);
6235 if (t == NULL) {
6236 show_oops(NULL, "cmd_keyrelease_cb invalid parameters");
6237 return (XT_CB_PASSTHROUGH);
6240 DNPRINTF(XT_D_CMD, "cmd_keyrelease_cb: keyval 0x%x mask 0x%x tab %d\n",
6241 e->keyval, e->state, t->tab_id);
6243 /* hinting */
6244 if (!(e->keyval == GDK_Tab || e->keyval == GDK_ISO_Left_Tab)) {
6245 if (hint_continue(t) == FALSE)
6246 goto done;
6249 /* search */
6250 if (search_continue(t) == FALSE)
6251 goto done;
6253 /* if search length is > 4 then no longer play timeout games */
6254 if (strlen(c) > 4) {
6255 if (t->search_id) {
6256 g_source_remove(t->search_id);
6257 t->search_id = 0;
6259 search_cb(t);
6260 goto done;
6263 /* reestablish a new timer if the user types fast */
6264 if (t->search_id)
6265 g_source_remove(t->search_id);
6266 t->search_id = g_timeout_add(250, (GSourceFunc)search_cb, (gpointer)t);
6268 done:
6269 return (XT_CB_PASSTHROUGH);
6272 gboolean
6273 match_uri(const gchar *uri, const gchar *key) {
6274 gchar *voffset;
6275 size_t len;
6276 gboolean match = FALSE;
6278 len = strlen(key);
6280 if (!strncmp(key, uri, len))
6281 match = TRUE;
6282 else {
6283 voffset = strstr(uri, "/") + 2;
6284 if (!strncmp(key, voffset, len))
6285 match = TRUE;
6286 else if (g_str_has_prefix(voffset, "www.")) {
6287 voffset = voffset + strlen("www.");
6288 if (!strncmp(key, voffset, len))
6289 match = TRUE;
6293 return (match);
6296 gboolean
6297 match_session(const gchar *name, const gchar *key) {
6298 char *sub;
6300 sub = strcasestr(name, key);
6302 return sub == name;
6305 void
6306 cmd_getlist(int id, char *key)
6308 int i, dep, c = 0;
6309 struct history *h;
6310 struct session *s;
6312 if (id >= 0) {
6313 if (cmds[id].type & XT_URLARG) {
6314 RB_FOREACH_REVERSE(h, history_list, &hl)
6315 if (match_uri(h->uri, key)) {
6316 cmd_status.list[c] = (char *)h->uri;
6317 if (++c > 255)
6318 break;
6320 cmd_status.len = c;
6321 return;
6322 } else if (cmds[id].type & XT_SESSARG) {
6323 TAILQ_FOREACH(s, &sessions, entry)
6324 if (match_session(s->name, key)) {
6325 cmd_status.list[c] = (char *)s->name;
6326 if (++c > 255)
6327 break;
6329 cmd_status.len = c;
6330 return;
6331 } else if (cmds[id].type & XT_SETARG) {
6332 for (i = 0; i < get_settings_size(); i++)
6333 if (!strncmp(key, get_setting_name(i),
6334 strlen(key)))
6335 cmd_status.list[c++] =
6336 get_setting_name(i);
6337 cmd_status.len = c;
6338 return;
6342 dep = (id == -1) ? 0 : cmds[id].level + 1;
6344 for (i = id + 1; i < LENGTH(cmds); i++) {
6345 if (cmds[i].level < dep)
6346 break;
6347 if (cmds[i].level == dep && !strncmp(key, cmds[i].cmd,
6348 strlen(key)) && !isdigit(cmds[i].cmd[0]))
6349 cmd_status.list[c++] = cmds[i].cmd;
6353 cmd_status.len = c;
6356 char *
6357 cmd_getnext(int dir)
6359 cmd_status.index += dir;
6361 if (cmd_status.index < 0)
6362 cmd_status.index = cmd_status.len - 1;
6363 else if (cmd_status.index >= cmd_status.len)
6364 cmd_status.index = 0;
6366 return cmd_status.list[cmd_status.index];
6370 cmd_tokenize(char *s, char *tokens[])
6372 int i = 0;
6373 char *tok, *last = NULL;
6374 size_t len = strlen(s);
6375 bool blank;
6377 blank = len == 0 || (len > 0 && s[len - 1] == ' ');
6378 for (tok = strtok_r(s, " ", &last); tok && i < 3;
6379 tok = strtok_r(NULL, " ", &last), i++)
6380 tokens[i] = tok;
6382 if (blank && i < 3)
6383 tokens[i++] = "";
6385 return (i);
6388 void
6389 cmd_complete(struct tab *t, char *str, int dir)
6391 GtkEntry *w = GTK_ENTRY(t->cmd);
6392 int i, j, levels, c = 0, dep = 0, parent = -1;
6393 int matchcount = 0;
6394 char *tok, *match, *s = g_strdup(str);
6395 char *tokens[3];
6396 char res[XT_MAX_URL_LENGTH + 32] = ":";
6397 char *sc = s;
6399 DNPRINTF(XT_D_CMD, "%s: complete %s\n", __func__, str);
6401 /* copy prefix*/
6402 for (i = 0; isdigit(s[i]); i++)
6403 res[i + 1] = s[i];
6405 for (; isspace(s[i]); i++)
6406 res[i + 1] = s[i];
6408 s += i;
6410 levels = cmd_tokenize(s, tokens);
6412 for (i = 0; i < levels - 1; i++) {
6413 tok = tokens[i];
6414 matchcount = 0;
6415 for (j = c; j < LENGTH(cmds); j++) {
6416 if (cmds[j].level < dep)
6417 break;
6418 if (cmds[j].level == dep && !strncmp(tok, cmds[j].cmd,
6419 strlen(tok))) {
6420 matchcount++;
6421 c = j + 1;
6422 if (strlen(tok) == strlen(cmds[j].cmd)) {
6423 matchcount = 1;
6424 break;
6429 if (matchcount == 1) {
6430 strlcat(res, tok, sizeof res);
6431 strlcat(res, " ", sizeof res);
6432 dep++;
6433 } else {
6434 g_free(sc);
6435 return;
6438 parent = c - 1;
6441 if (cmd_status.index == -1)
6442 cmd_getlist(parent, tokens[i]);
6444 if (cmd_status.len > 0) {
6445 match = cmd_getnext(dir);
6446 strlcat(res, match, sizeof res);
6447 gtk_entry_set_text(w, res);
6448 gtk_editable_set_position(GTK_EDITABLE(w), -1);
6451 g_free(sc);
6454 char *
6455 parse_prefix_and_alias(const char *str, int *prefix)
6457 struct cmd_alias *c;
6458 char *s = g_strdup(str), *sc;
6460 g_strstrip(s);
6461 sc = s;
6463 if (isdigit(s[0])) {
6464 sscanf(s, "%d", prefix);
6465 while (isdigit(s[0]) || isspace(s[0]))
6466 ++s;
6469 TAILQ_FOREACH(c, &cal, entry) {
6470 if (strncmp(s, c->alias, strlen(c->alias)))
6471 continue;
6473 if (strlen(s) == strlen(c->alias)) {
6474 g_free(sc);
6475 return (g_strdup(c->cmd));
6478 if (!isspace(s[strlen(c->alias)]))
6479 continue;
6481 s = g_strdup_printf("%s %s", c->cmd, &s[strlen(c->alias) + 1]);
6482 g_free(sc);
6483 return (s);
6485 s = g_strdup(s);
6486 g_free(sc);
6487 return (s);
6490 gboolean
6491 cmd_execute(struct tab *t, char *str)
6493 struct cmd *cmd = NULL;
6494 char *tok, *last = NULL, *s = str;
6495 int j = 0, len, c = 0, dep = 0, matchcount = 0;
6496 int prefix = -1, rv = XT_CB_PASSTHROUGH;
6497 struct karg arg = {0, NULL, -1};
6499 s = parse_prefix_and_alias(s, &prefix);
6501 for (tok = strtok_r(s, " ", &last); tok;
6502 tok = strtok_r(NULL, " ", &last)) {
6503 matchcount = 0;
6504 for (j = c; j < LENGTH(cmds); j++) {
6505 if (cmds[j].level < dep)
6506 break;
6507 len = (tok[strlen(tok) - 1] == '!') ? strlen(tok) - 1 :
6508 strlen(tok);
6509 if (cmds[j].level == dep &&
6510 !strncmp(tok, cmds[j].cmd, len)) {
6511 matchcount++;
6512 c = j + 1;
6513 cmd = &cmds[j];
6514 if (len == strlen(cmds[j].cmd)) {
6515 matchcount = 1;
6516 break;
6520 if (matchcount == 1) {
6521 if (cmd->type > 0)
6522 goto execute_cmd;
6523 dep++;
6524 } else {
6525 show_oops(t, "Invalid command: %s", str);
6526 goto done;
6529 execute_cmd:
6530 if (cmd == NULL) {
6531 show_oops(t, "Empty command");
6532 goto done;
6534 arg.i = cmd->arg;
6536 if (prefix != -1)
6537 arg.precount = prefix;
6538 else if (cmd_prefix > 0)
6539 arg.precount = cmd_prefix;
6541 if (j > 0 && !(cmd->type & XT_PREFIX) && arg.precount > -1) {
6542 show_oops(t, "No prefix allowed: %s", str);
6543 goto done;
6545 if (cmd->type > 1)
6546 arg.s = last ? g_strdup(last) : g_strdup("");
6547 if (cmd->type & XT_INTARG && last && strlen(last) > 0) {
6548 if (arg.s == NULL) {
6549 show_oops(t, "Invalid command");
6550 goto done;
6552 arg.precount = atoi(arg.s);
6553 if (arg.precount <= 0) {
6554 if (arg.s[0] == '0')
6555 show_oops(t, "Zero count");
6556 else
6557 show_oops(t, "Trailing characters");
6558 goto done;
6562 DNPRINTF(XT_D_CMD, "%s: prefix %d arg %s\n",
6563 __func__, arg.precount, arg.s);
6565 cmd->func(t, &arg);
6567 rv = XT_CB_HANDLED;
6568 done:
6569 if (j > 0)
6570 cmd_prefix = 0;
6571 g_free(s);
6572 if (arg.s)
6573 g_free(arg.s);
6575 return (rv);
6579 save_runtime_setting(const char *name, const char *val)
6581 struct stat sb;
6582 FILE *f;
6583 size_t linelen;
6584 int found = 0;
6585 char file[PATH_MAX];
6586 char delim[3] = { '\0', '\0', '\0' };
6587 char *line, *lt, *start;
6588 char *contents, *tmp;
6590 if (runtime_settings == NULL || strlen(runtime_settings) == 0)
6591 return (-1);
6593 snprintf(file, sizeof file, "%s" PS "%s", work_dir, runtime_settings);
6594 if (stat(file, &sb) || (f = fopen(file, "r+")) == NULL)
6595 return (-1);
6596 lt = g_strdup_printf("%s=%s", name, val);
6597 contents = g_strdup("");
6598 while (!feof(f)) {
6599 line = fparseln(f, &linelen, NULL, delim, 0);
6600 if (line == NULL || linelen == 0)
6601 continue;
6602 tmp = contents;
6603 start = g_strdup_printf("%s=", name);
6604 if (strstr(line, start) == NULL)
6605 contents = g_strdup_printf("%s%s\n", contents, line);
6606 else {
6607 found = 1;
6608 contents = g_strdup_printf("%s%s\n", contents, lt);
6610 g_free(tmp);
6611 g_free(start);
6612 free(line);
6613 line = NULL;
6615 if (found == 0) {
6616 tmp = contents;
6617 contents = g_strdup_printf("%s%s\n", contents, lt);
6618 g_free(tmp);
6620 if ((f = freopen(file, "w", f)) == NULL)
6621 return (-1);
6622 else {
6623 fputs(contents, f);
6624 fclose(f);
6626 g_free(lt);
6627 g_free(contents);
6629 return (0);
6633 entry_focus_cb(GtkWidget *w, GdkEvent e, struct tab *t)
6636 * This sometimes gets randomly unset for whatever reason in GTK3,
6637 * causing a GtkEntry's text cursor becomes invisible. When we focus
6638 * a GtkEntry, be sure to manually reset the main window's is-active
6639 * property so the cursor is shown correctly.
6641 #if GTK_CHECK_VERSION(3, 0, 0)
6642 fake_focus_in(main_window);
6643 #endif
6644 return (XT_CB_PASSTHROUGH);
6648 entry_key_cb(GtkEntry *w, GdkEventKey *e, struct tab *t)
6650 if (t == NULL) {
6651 show_oops(NULL, "entry_key_cb invalid parameters");
6652 return (XT_CB_PASSTHROUGH);
6655 DNPRINTF(XT_D_CMD, "entry_key_cb: keyval 0x%x mask 0x%x tab %d\n",
6656 e->keyval, e->state, t->tab_id);
6658 hide_oops(t);
6660 if (e->keyval == GDK_Escape) {
6661 /* don't use focus_webview(t) because we want to type :cmds */
6662 gtk_widget_grab_focus(GTK_WIDGET(t->wv));
6665 return (handle_keypress(t, e, 1));
6668 struct command_entry *
6669 history_prev(struct command_list *l, struct command_entry *at)
6671 if (at == NULL)
6672 at = TAILQ_LAST(l, command_list);
6673 else {
6674 at = TAILQ_PREV(at, command_list, entry);
6675 if (at == NULL)
6676 at = TAILQ_LAST(l, command_list);
6679 return (at);
6682 struct command_entry *
6683 history_next(struct command_list *l, struct command_entry *at)
6685 if (at == NULL)
6686 at = TAILQ_FIRST(l);
6687 else {
6688 at = TAILQ_NEXT(at, entry);
6689 if (at == NULL)
6690 at = TAILQ_FIRST(l);
6693 return (at);
6697 cmd_keypress_cb(GtkEntry *w, GdkEventKey *e, struct tab *t)
6699 int rv = XT_CB_HANDLED;
6700 const gchar *c = gtk_entry_get_text(w);
6701 char *s;
6703 if (t == NULL) {
6704 show_oops(NULL, "cmd_keypress_cb parameters");
6705 return (XT_CB_PASSTHROUGH);
6708 DNPRINTF(XT_D_CMD, "cmd_keypress_cb: keyval 0x%x mask 0x%x tab %d\n",
6709 e->keyval, e->state, t->tab_id);
6711 /* sanity */
6712 if (c == NULL)
6713 e->keyval = GDK_Escape;
6714 else if (!(c[0] == ':' || c[0] == '/' || c[0] == '?' ||
6715 c[0] == '.' || c[0] == ','))
6716 e->keyval = GDK_Escape;
6718 if (e->keyval != GDK_Tab && e->keyval != GDK_Shift_L &&
6719 e->keyval != GDK_ISO_Left_Tab)
6720 cmd_status.index = -1;
6722 switch (e->keyval) {
6723 case GDK_Tab:
6724 if (c[0] == ':')
6725 cmd_complete(t, (char *)&c[1], 1);
6726 else if (c[0] == '.' || c[0] == ',')
6727 run_script(t, "hints.focusNextHint();");
6728 goto done;
6729 case GDK_ISO_Left_Tab:
6730 if (c[0] == ':')
6731 cmd_complete(t, (char *)&c[1], -1);
6732 else if (c[0] == '.' || c[0] == ',')
6733 run_script(t, "hints.focusPreviousHint();");
6734 goto done;
6735 case GDK_Down:
6736 if (c[0] == '?') {
6737 if ((search_at = history_next(&shl, search_at))) {
6738 search_at->line[0] = c[0];
6739 gtk_entry_set_text(w, search_at->line);
6740 gtk_editable_set_position(GTK_EDITABLE(w), -1);
6742 } else if (c[0] == '/') {
6743 if ((search_at = history_prev(&shl, search_at))) {
6744 search_at->line[0] = c[0];
6745 gtk_entry_set_text(w, search_at->line);
6746 gtk_editable_set_position(GTK_EDITABLE(w), -1);
6748 } else if (c[0] == ':') {
6749 if ((history_at = history_prev(&chl, history_at))) {
6750 history_at->line[0] = c[0];
6751 gtk_entry_set_text(w, history_at->line);
6752 gtk_editable_set_position(GTK_EDITABLE(w), -1);
6755 goto done;
6756 case GDK_Up:
6757 if (c[0] == '/') {
6758 if ((search_at = history_next(&shl, search_at))) {
6759 search_at->line[0] = c[0];
6760 gtk_entry_set_text(w, search_at->line);
6761 gtk_editable_set_position(GTK_EDITABLE(w), -1);
6763 } else if (c[0] == '?') {
6764 if ((search_at = history_prev(&shl, search_at))) {
6765 search_at->line[0] = c[0];
6766 gtk_entry_set_text(w, search_at->line);
6767 gtk_editable_set_position(GTK_EDITABLE(w), -1);
6769 } if (c[0] == ':') {
6770 if ((history_at = history_next(&chl, history_at))) {
6771 history_at->line[0] = c[0];
6772 gtk_entry_set_text(w, history_at->line);
6773 gtk_editable_set_position(GTK_EDITABLE(w), -1);
6776 goto done;
6777 case GDK_BackSpace:
6778 if (!(!strcmp(c, ":") || !strcmp(c, "/") || !strcmp(c, "?") ||
6779 !strcmp(c, ".") || !strcmp(c, ","))) {
6780 /* see if we are doing hinting and reset it */
6781 if (c[0] == '.' || c[0] == ',') {
6782 /* recreate hints */
6783 s = g_strdup_printf("hints.createHints('', "
6784 "'%c');", c[0] == '.' ? 'f' : 'F');
6785 run_script(t, s);
6786 g_free(s);
6788 break;
6791 /* FALLTHROUGH */
6792 case GDK_Escape:
6793 hide_cmd(t);
6795 /* cancel search */
6796 if (c != NULL && (c[0] == '/' || c[0] == '?'))
6797 webkit_web_view_unmark_text_matches(t->wv);
6799 /* no need to cancel hints */
6800 goto done;
6803 rv = XT_CB_PASSTHROUGH;
6804 done:
6805 return (rv);
6808 void
6809 wv_popup_activ_cb(GtkMenuItem *menu, struct tab *t)
6811 GtkAction *a = NULL;
6812 GtkClipboard *clipboard, *primary;
6813 const gchar *name, *uri;
6815 a = gtk_activatable_get_related_action(GTK_ACTIVATABLE(menu));
6816 if (a == NULL)
6817 return;
6818 name = gtk_action_get_name(a);
6820 DNPRINTF(XT_D_CMD, "wv_popup_activ_cb: tab %d action %s\n",
6821 t->tab_id, name);
6824 * context-menu-action-3 copy link location
6825 * context-menu-action-7 copy image address
6826 * context-menu-action-2030 copy video link location
6829 /* copy actions */
6830 if ((g_strcmp0(name, "context-menu-action-3") == 0) ||
6831 (g_strcmp0(name, "context-menu-action-7") == 0) ||
6832 (g_strcmp0(name, "context-menu-action-2030") == 0)) {
6833 clipboard = gtk_clipboard_get(GDK_SELECTION_CLIPBOARD);
6834 primary = gtk_clipboard_get(GDK_SELECTION_PRIMARY);
6835 uri = gtk_clipboard_wait_for_text(clipboard);
6836 if (uri == NULL)
6837 return;
6838 gtk_clipboard_set_text(primary, uri, -1);
6842 void
6843 wv_popup_cb(WebKitWebView *wview, GtkMenu *menu, struct tab *t)
6845 GList *items, *l;
6847 DNPRINTF(XT_D_CMD, "wv_popup_cb: tab %d\n", t->tab_id);
6849 items = gtk_container_get_children(GTK_CONTAINER(menu));
6850 for (l = items; l; l = l->next)
6851 g_signal_connect(l->data, "activate",
6852 G_CALLBACK(wv_popup_activ_cb), t);
6853 g_list_free(items);
6856 void
6857 cmd_popup_cb(GtkEntry *entry, GtkMenu *menu, struct tab *t)
6859 /* popup menu enabled */
6860 t->popup = 1;
6864 cmd_focusout_cb(GtkWidget *w, GdkEventFocus *e, struct tab *t)
6866 if (t == NULL) {
6867 show_oops(NULL, "cmd_focusout_cb invalid parameters");
6868 return (XT_CB_PASSTHROUGH);
6871 DNPRINTF(XT_D_CMD, "cmd_focusout_cb: tab %d popup %d\n",
6872 t->tab_id, t->popup);
6874 /* if popup is enabled don't lose focus */
6875 if (t->popup) {
6876 t->popup = 0;
6877 return (XT_CB_PASSTHROUGH);
6880 hide_cmd(t);
6881 hide_oops(t);
6882 disable_hints(t);
6884 return (XT_CB_PASSTHROUGH);
6887 void
6888 cmd_hide_cb(GtkWidget *w, struct tab *t)
6890 if (t == NULL) {
6891 show_oops(NULL, "%s: invalid parameters", __func__);
6892 return;
6895 if (show_url == 0 || t->focus_wv)
6896 focus_webview(t);
6897 else
6898 gtk_widget_grab_focus(GTK_WIDGET(t->uri_entry));
6901 void
6902 cmd_activate_cb(GtkEntry *entry, struct tab *t)
6904 char *s;
6905 const gchar *c = gtk_entry_get_text(entry);
6907 if (t == NULL) {
6908 show_oops(NULL, "cmd_activate_cb invalid parameters");
6909 return;
6912 DNPRINTF(XT_D_CMD, "cmd_activate_cb: tab %d %s\n", t->tab_id, c);
6914 /* sanity */
6915 if (c == NULL)
6916 goto done;
6917 else if (!(c[0] == ':' || c[0] == '/' || c[0] == '?' ||
6918 c[0] == '.' || c[0] == ','))
6919 goto done;
6920 if (strlen(c) < 1)
6921 goto done;
6922 s = (char *)&c[1];
6924 if (c[0] == '/' || c[0] == '?') {
6925 /* see if there is a timer pending */
6926 if (t->search_id) {
6927 g_source_remove(t->search_id);
6928 t->search_id = 0;
6929 search_cb(t);
6932 if (t->search_text) {
6933 g_free(t->search_text);
6934 t->search_text = NULL;
6937 t->search_text = g_strdup(s);
6938 if (global_search)
6939 g_free(global_search);
6940 global_search = g_strdup(s);
6941 t->search_forward = c[0] == '/';
6943 history_add(&shl, search_file, s, &search_history_count);
6944 } else if (c[0] == '.' || c[0] == ',') {
6945 run_script(t, "hints.fire();");
6946 /* XXX history for link following? */
6947 } else if (c[0] == ':') {
6948 history_add(&chl, command_file, s, &cmd_history_count);
6949 /* can't call hide_cmd after cmd_execute */
6950 hide_cmd(t);
6951 cmd_execute(t, s);
6952 return;
6955 done:
6956 hide_cmd(t);
6959 void
6960 backward_cb(GtkWidget *w, struct tab *t)
6962 struct karg a;
6964 if (t == NULL) {
6965 show_oops(NULL, "backward_cb invalid parameters");
6966 return;
6969 DNPRINTF(XT_D_NAV, "backward_cb: tab %d\n", t->tab_id);
6971 a.i = XT_NAV_BACK;
6972 navaction(t, &a);
6975 void
6976 forward_cb(GtkWidget *w, struct tab *t)
6978 struct karg a;
6980 if (t == NULL) {
6981 show_oops(NULL, "forward_cb invalid parameters");
6982 return;
6985 DNPRINTF(XT_D_NAV, "forward_cb: tab %d\n", t->tab_id);
6987 a.i = XT_NAV_FORWARD;
6988 navaction(t, &a);
6991 void
6992 home_cb(GtkWidget *w, struct tab *t)
6994 if (t == NULL) {
6995 show_oops(NULL, "home_cb invalid parameters");
6996 return;
6999 DNPRINTF(XT_D_NAV, "home_cb: tab %d\n", t->tab_id);
7001 load_uri(t, home);
7004 void
7005 stop_cb(GtkWidget *w, struct tab *t)
7007 WebKitWebFrame *frame;
7009 if (t == NULL) {
7010 show_oops(NULL, "stop_cb invalid parameters");
7011 return;
7014 DNPRINTF(XT_D_NAV, "stop_cb: tab %d\n", t->tab_id);
7016 frame = webkit_web_view_get_main_frame(t->wv);
7017 if (frame == NULL) {
7018 show_oops(t, "stop_cb: no frame");
7019 return;
7022 webkit_web_frame_stop_loading(frame);
7023 abort_favicon_download(t);
7026 void
7027 setup_webkit(struct tab *t)
7029 if (is_g_object_setting(G_OBJECT(t->settings), "enable-dns-prefetching"))
7030 g_object_set(G_OBJECT(t->settings), "enable-dns-prefetching",
7031 FALSE, (char *)NULL);
7032 else
7033 warnx("webkit does not have \"enable-dns-prefetching\" property");
7034 g_object_set(G_OBJECT(t->settings),
7035 "enable-scripts", enable_scripts, (char *)NULL);
7036 g_object_set(G_OBJECT(t->settings),
7037 "enable-plugins", enable_plugins, (char *)NULL);
7038 g_object_set(G_OBJECT(t->settings),
7039 "javascript-can-open-windows-automatically", enable_scripts,
7040 (char *)NULL);
7041 g_object_set(G_OBJECT(t->settings),
7042 "enable-html5-database", FALSE, (char *)NULL);
7043 g_object_set(G_OBJECT(t->settings),
7044 "enable-html5-local-storage", enable_localstorage, (char *)NULL);
7045 g_object_set(G_OBJECT(t->settings),
7046 "enable_spell_checking", enable_spell_checking, (char *)NULL);
7047 g_object_set(G_OBJECT(t->settings),
7048 "spell_checking_languages", spell_check_languages, (char *)NULL);
7049 g_object_set(G_OBJECT(t->settings),
7050 "enable-developer-extras", TRUE, (char *)NULL);
7051 g_object_set(G_OBJECT(t->wv),
7052 "full-content-zoom", TRUE, (char *)NULL);
7053 g_object_set(G_OBJECT(t->settings),
7054 "auto-load-images", auto_load_images, (char *)NULL);
7055 if (is_g_object_setting(G_OBJECT(t->settings),
7056 "enable-display-of-insecure-content"))
7057 g_object_set(G_OBJECT(t->settings),
7058 "enable-display-of-insecure-content",
7059 allow_insecure_content, (char *)NULL);
7060 if (is_g_object_setting(G_OBJECT(t->settings),
7061 "enable-running-of-insecure-content"))
7062 g_object_set(G_OBJECT(t->settings),
7063 "enable-running-of-insecure-content",
7064 allow_insecure_scripts, (char *)NULL);
7066 webkit_web_view_set_settings(t->wv, t->settings);
7069 gboolean
7070 update_statusbar_position(GtkAdjustment* adjustment, gpointer data)
7072 struct tab *ti, *t = NULL;
7073 gdouble view_size, value, max;
7074 gchar *position;
7076 TAILQ_FOREACH(ti, &tabs, entry)
7077 if (ti->tab_id == gtk_notebook_get_current_page(notebook)) {
7078 t = ti;
7079 break;
7082 if (t == NULL)
7083 return FALSE;
7085 if (adjustment == NULL)
7086 adjustment = gtk_scrolled_window_get_vadjustment(
7087 GTK_SCROLLED_WINDOW(t->browser_win));
7089 view_size = gtk_adjustment_get_page_size(adjustment);
7090 value = gtk_adjustment_get_value(adjustment);
7091 max = gtk_adjustment_get_upper(adjustment) - view_size;
7093 if (max == 0)
7094 position = g_strdup("All");
7095 else if (value == max)
7096 position = g_strdup("Bot");
7097 else if (value == 0)
7098 position = g_strdup("Top");
7099 else
7100 position = g_strdup_printf("%d%%", (int) ((value / max) * 100));
7102 gtk_label_set_text(GTK_LABEL(t->sbe.position), position);
7103 g_free(position);
7105 return (TRUE);
7108 GtkWidget *
7109 create_window(const gchar *name)
7111 GtkWidget *w;
7113 w = gtk_window_new(GTK_WINDOW_TOPLEVEL);
7114 if (window_maximize)
7115 gtk_window_maximize(GTK_WINDOW(w));
7116 else
7117 gtk_window_set_default_size(GTK_WINDOW(w), window_width, window_height);
7118 gtk_widget_set_name(w, name);
7119 gtk_window_set_wmclass(GTK_WINDOW(w), name, "Xombrero");
7121 return (w);
7124 GtkWidget *
7125 create_browser(struct tab *t)
7127 GtkWidget *w;
7128 GtkAdjustment *adjustment;
7130 if (t == NULL) {
7131 show_oops(NULL, "create_browser invalid parameters");
7132 return (NULL);
7135 w = gtk_scrolled_window_new(NULL, NULL);
7136 gtk_widget_set_can_focus(w, FALSE);
7137 t->adjust_h = gtk_scrolled_window_get_hadjustment(
7138 GTK_SCROLLED_WINDOW(w));
7139 t->adjust_v = gtk_scrolled_window_get_vadjustment(
7140 GTK_SCROLLED_WINDOW(w));
7141 #if !GTK_CHECK_VERSION(3, 0, 0)
7142 gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(w),
7143 GTK_POLICY_AUTOMATIC, GTK_POLICY_AUTOMATIC);
7144 #endif
7147 t->wv = WEBKIT_WEB_VIEW(webkit_web_view_new());
7148 gtk_container_add(GTK_CONTAINER(w), GTK_WIDGET(t->wv));
7150 /* set defaults */
7151 t->settings = webkit_web_settings_new();
7153 g_object_set(t->settings, "default-encoding", encoding, (char *)NULL);
7155 t->stylesheet = g_strdup(stylesheet);
7156 t->load_images = auto_load_images;
7158 adjustment =
7159 gtk_scrolled_window_get_vadjustment(GTK_SCROLLED_WINDOW(w));
7160 g_signal_connect(G_OBJECT(adjustment), "value-changed",
7161 G_CALLBACK(update_statusbar_position), NULL);
7163 setup_webkit(t);
7164 setup_inspector(t);
7166 return (w);
7169 GtkWidget *
7170 create_kiosk_toolbar(struct tab *t)
7172 GtkWidget *toolbar = NULL, *b;
7174 #if GTK_CHECK_VERSION(3, 0, 0)
7175 b = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 0);
7176 gtk_widget_set_name(GTK_WIDGET(b), "toolbar");
7177 #else
7178 b = gtk_hbox_new(FALSE, 0);
7179 #endif
7180 toolbar = b;
7181 gtk_container_set_border_width(GTK_CONTAINER(toolbar), 0);
7183 /* backward button */
7184 t->backward = create_button("Back", GTK_STOCK_GO_BACK, 0);
7185 gtk_widget_set_sensitive(t->backward, FALSE);
7186 g_signal_connect(G_OBJECT(t->backward), "clicked",
7187 G_CALLBACK(backward_cb), t);
7188 gtk_box_pack_start(GTK_BOX(b), t->backward, TRUE, TRUE, 0);
7190 /* forward button */
7191 t->forward = create_button("Forward", GTK_STOCK_GO_FORWARD, 0);
7192 gtk_widget_set_sensitive(t->forward, FALSE);
7193 g_signal_connect(G_OBJECT(t->forward), "clicked",
7194 G_CALLBACK(forward_cb), t);
7195 gtk_box_pack_start(GTK_BOX(b), t->forward, TRUE, TRUE, 0);
7197 /* home button */
7198 t->gohome = create_button("Home", GTK_STOCK_HOME, 0);
7199 gtk_widget_set_sensitive(t->gohome, true);
7200 g_signal_connect(G_OBJECT(t->gohome), "clicked",
7201 G_CALLBACK(home_cb), t);
7202 gtk_box_pack_start(GTK_BOX(b), t->gohome, TRUE, TRUE, 0);
7204 /* create widgets but don't use them */
7205 t->uri_entry = gtk_entry_new();
7206 g_signal_connect(G_OBJECT(t->uri_entry), "focus-in-event",
7207 G_CALLBACK(entry_focus_cb), t);
7208 #if !GTK_CHECK_VERSION(3, 0, 0)
7209 t->default_style = gtk_rc_get_style(t->uri_entry);
7210 #endif
7211 t->stop = create_button("Stop", GTK_STOCK_STOP, 0);
7212 t->js_toggle = create_button("JS-Toggle", enable_scripts ?
7213 GTK_STOCK_MEDIA_PLAY : GTK_STOCK_MEDIA_PAUSE, 0);
7215 return (toolbar);
7218 GtkWidget *
7219 create_toolbar(struct tab *t)
7221 GtkWidget *toolbar = NULL, *b;
7223 #if GTK_CHECK_VERSION(3, 0, 0)
7224 b = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 0);
7225 gtk_widget_set_name(GTK_WIDGET(b), "toolbar");
7226 #else
7227 b = gtk_hbox_new(FALSE, 0);
7228 #endif
7229 toolbar = b;
7230 gtk_container_set_border_width(GTK_CONTAINER(toolbar), 0);
7232 /* backward button */
7233 t->backward = create_button("Back", GTK_STOCK_GO_BACK, 0);
7234 gtk_widget_set_sensitive(t->backward, FALSE);
7235 g_signal_connect(G_OBJECT(t->backward), "clicked",
7236 G_CALLBACK(backward_cb), t);
7237 gtk_box_pack_start(GTK_BOX(b), t->backward, FALSE, FALSE, 0);
7239 /* forward button */
7240 t->forward = create_button("Forward",GTK_STOCK_GO_FORWARD, 0);
7241 gtk_widget_set_sensitive(t->forward, FALSE);
7242 g_signal_connect(G_OBJECT(t->forward), "clicked",
7243 G_CALLBACK(forward_cb), t);
7244 gtk_box_pack_start(GTK_BOX(b), t->forward, FALSE, FALSE, 0);
7246 /* stop button */
7247 t->stop = create_button("Stop", GTK_STOCK_STOP, 0);
7248 gtk_widget_set_sensitive(t->stop, FALSE);
7249 g_signal_connect(G_OBJECT(t->stop), "clicked", G_CALLBACK(stop_cb), t);
7250 gtk_box_pack_start(GTK_BOX(b), t->stop, FALSE, FALSE, 0);
7252 /* JS button */
7253 t->js_toggle = create_button("JS-Toggle", enable_scripts ?
7254 GTK_STOCK_MEDIA_PLAY : GTK_STOCK_MEDIA_PAUSE, 0);
7255 gtk_widget_set_sensitive(t->js_toggle, TRUE);
7256 g_signal_connect(G_OBJECT(t->js_toggle), "clicked",
7257 G_CALLBACK(js_toggle_cb), t);
7258 gtk_box_pack_start(GTK_BOX(b), t->js_toggle, FALSE, FALSE, 0);
7260 /* toggle proxy button */
7261 t->proxy_toggle = create_button("Proxy-Toggle", proxy_uri ?
7262 GTK_STOCK_CONNECT : GTK_STOCK_DISCONNECT, 0);
7263 /* override icons */
7264 if (proxy_uri)
7265 button_set_file(t->proxy_toggle, "torenabled.ico");
7266 else
7267 button_set_file(t->proxy_toggle, "tordisabled.ico");
7268 gtk_widget_set_sensitive(t->proxy_toggle, TRUE);
7269 g_signal_connect(G_OBJECT(t->proxy_toggle), "clicked",
7270 G_CALLBACK(proxy_toggle_cb), t);
7271 gtk_box_pack_start(GTK_BOX(b), t->proxy_toggle, FALSE, FALSE, 0);
7273 t->uri_entry = gtk_entry_new();
7274 g_signal_connect(G_OBJECT(t->uri_entry), "activate",
7275 G_CALLBACK(activate_uri_entry_cb), t);
7276 g_signal_connect(G_OBJECT(t->uri_entry), "key-press-event",
7277 G_CALLBACK(entry_key_cb), t);
7278 g_signal_connect(G_OBJECT(t->uri_entry), "focus-in-event",
7279 G_CALLBACK(entry_focus_cb), t);
7280 completion_add(t);
7281 gtk_box_pack_start(GTK_BOX(b), t->uri_entry, TRUE, TRUE, 0);
7283 /* search entry */
7284 t->search_entry = gtk_entry_new();
7285 gtk_entry_set_width_chars(GTK_ENTRY(t->search_entry), 30);
7286 g_signal_connect(G_OBJECT(t->search_entry), "activate",
7287 G_CALLBACK(activate_search_entry_cb), t);
7288 g_signal_connect(G_OBJECT(t->search_entry), "key-press-event",
7289 G_CALLBACK(entry_key_cb), t);
7290 g_signal_connect(G_OBJECT(t->search_entry), "focus-in-event",
7291 G_CALLBACK(entry_focus_cb), t);
7292 gtk_box_pack_start(GTK_BOX(b), t->search_entry, FALSE, FALSE, 0);
7294 #if !GTK_CHECK_VERSION(3, 0, 0)
7295 t->default_style = gtk_rc_get_style(t->uri_entry);
7296 #endif
7298 return (toolbar);
7301 GtkWidget *
7302 create_buffers(struct tab *t)
7304 GtkCellRenderer *renderer;
7305 GtkWidget *view;
7307 view = gtk_tree_view_new();
7309 gtk_tree_view_set_headers_visible(GTK_TREE_VIEW(view), FALSE);
7311 renderer = gtk_cell_renderer_text_new();
7312 gtk_tree_view_insert_column_with_attributes
7313 (GTK_TREE_VIEW(view), -1, "Id", renderer, "text", COL_ID, (char *)NULL);
7315 renderer = gtk_cell_renderer_pixbuf_new();
7316 gtk_tree_view_insert_column_with_attributes
7317 (GTK_TREE_VIEW(view), -1, "Favicon", renderer, "pixbuf", COL_FAVICON,
7318 (char *)NULL);
7320 renderer = gtk_cell_renderer_text_new();
7321 gtk_tree_view_insert_column_with_attributes
7322 (GTK_TREE_VIEW(view), -1, "Title", renderer, "text", COL_TITLE,
7323 (char *)NULL);
7325 gtk_tree_view_set_model
7326 (GTK_TREE_VIEW(view), GTK_TREE_MODEL(buffers_store));
7328 return (view);
7331 void
7332 row_activated_cb(GtkTreeView *view, GtkTreePath *path,
7333 GtkTreeViewColumn *col, struct tab *t)
7335 GtkTreeIter iter;
7336 guint id;
7338 gtk_widget_grab_focus(GTK_WIDGET(t->wv));
7340 if (gtk_tree_model_get_iter(GTK_TREE_MODEL(buffers_store), &iter,
7341 path)) {
7342 gtk_tree_model_get
7343 (GTK_TREE_MODEL(buffers_store), &iter, COL_ID, &id, -1);
7344 set_current_tab(id - 1);
7347 hide_buffers(t);
7350 /* after tab reordering/creation/removal */
7351 void
7352 recalc_tabs(void)
7354 struct tab *t;
7356 TAILQ_FOREACH(t, &tabs, entry)
7357 t->tab_id = gtk_notebook_page_num(notebook, t->vbox);
7360 void
7361 update_statusbar_tabs(struct tab *t)
7363 int tab_id, max_tab_id;
7364 char s[16];
7366 if (t != NULL)
7367 tab_id = t->tab_id;
7368 else
7369 tab_id = gtk_notebook_get_current_page(notebook);
7371 max_tab_id = gtk_notebook_get_n_pages(notebook);
7372 snprintf(s, sizeof s, "%d/%d", tab_id + 1, max_tab_id);
7374 if (t == NULL)
7375 t = get_current_tab();
7377 if (t != NULL)
7378 gtk_label_set_text(GTK_LABEL(t->sbe.tabs), s);
7381 /* after active tab change */
7382 void
7383 recolor_compact_tabs(void)
7385 struct tab *t;
7386 int curid = 0;
7387 #if !GTK_CHECK_VERSION(3, 0, 0)
7388 GdkColor color_active, color_inactive;
7390 gdk_color_parse(XT_COLOR_CT_ACTIVE, &color_active);
7391 gdk_color_parse(XT_COLOR_CT_INACTIVE, &color_inactive);
7392 #endif
7393 curid = gtk_notebook_get_current_page(notebook);
7395 TAILQ_FOREACH(t, &tabs, entry) {
7396 #if GTK_CHECK_VERSION(3, 0, 0)
7397 if (t->tab_id == curid)
7398 gtk_widget_set_name(t->tab_elems.label, XT_CSS_ACTIVE);
7399 else
7400 gtk_widget_set_name(t->tab_elems.label, "");
7401 #else
7402 if (t->tab_id == curid)
7403 gtk_widget_modify_fg(t->tab_elems.label,
7404 GTK_STATE_NORMAL, &color_active);
7405 else
7406 gtk_widget_modify_fg(t->tab_elems.label,
7407 GTK_STATE_NORMAL, &color_inactive);
7408 #endif
7412 void
7413 set_current_tab(int page_num)
7415 buffercmd_abort(get_current_tab());
7416 gtk_notebook_set_current_page(notebook, page_num);
7417 recolor_compact_tabs();
7418 update_statusbar_tabs(NULL);
7422 undo_close_tab_save(struct tab *t)
7424 int m, n;
7425 const gchar *uri;
7426 struct undo *u1, *u2;
7427 GList *items;
7428 WebKitWebHistoryItem *item;
7430 if ((uri = get_uri(t)) == NULL)
7431 return (1);
7433 u1 = g_malloc0(sizeof(struct undo));
7434 u1->uri = g_strdup(uri);
7436 t->bfl = webkit_web_view_get_back_forward_list(t->wv);
7438 m = webkit_web_back_forward_list_get_forward_length(t->bfl);
7439 n = webkit_web_back_forward_list_get_back_length(t->bfl);
7440 u1->back = n;
7442 /* forward history */
7443 items = webkit_web_back_forward_list_get_forward_list_with_limit(t->bfl, m);
7445 while (items) {
7446 item = items->data;
7447 u1->history = g_list_prepend(u1->history,
7448 webkit_web_history_item_copy(item));
7449 items = g_list_next(items);
7452 /* current item */
7453 if (m) {
7454 item = webkit_web_back_forward_list_get_current_item(t->bfl);
7455 u1->history = g_list_prepend(u1->history,
7456 webkit_web_history_item_copy(item));
7459 /* back history */
7460 items = webkit_web_back_forward_list_get_back_list_with_limit(t->bfl, n);
7462 while (items) {
7463 item = items->data;
7464 u1->history = g_list_prepend(u1->history,
7465 webkit_web_history_item_copy(item));
7466 items = g_list_next(items);
7469 TAILQ_INSERT_HEAD(&undos, u1, entry);
7471 if (undo_count > XT_MAX_UNDO_CLOSE_TAB) {
7472 u2 = TAILQ_LAST(&undos, undo_tailq);
7473 TAILQ_REMOVE(&undos, u2, entry);
7474 g_free(u2->uri);
7475 g_list_free(u2->history);
7476 g_free(u2);
7477 } else
7478 undo_count++;
7480 return (0);
7483 void
7484 delete_tab(struct tab *t)
7486 struct karg a;
7488 DNPRINTF(XT_D_TAB, "delete_tab: %p\n", t);
7490 if (t == NULL)
7491 return;
7494 * no need to join thread here because it won't access t on completion
7497 TAILQ_REMOVE(&tabs, t, entry);
7498 buffercmd_abort(t);
7500 /* Halt all webkit activity. */
7501 abort_favicon_download(t);
7502 webkit_web_view_stop_loading(t->wv);
7504 /* Save the tab, so we can undo the close. */
7505 undo_close_tab_save(t);
7507 /* just in case */
7508 if (t->search_id)
7509 g_source_remove(t->search_id);
7511 /* session key */
7512 if (t->session_key)
7513 g_free(t->session_key);
7515 /* inspector */
7516 bzero(&a, sizeof a);
7517 a.i = XT_INS_CLOSE;
7518 inspector_cmd(t, &a);
7520 if (browser_mode == XT_BM_KIOSK) {
7521 gtk_widget_destroy(t->uri_entry);
7522 gtk_widget_destroy(t->stop);
7523 gtk_widget_destroy(t->js_toggle);
7526 g_object_unref(t->completion);
7527 if (t->item)
7528 g_object_unref(t->item);
7530 gtk_widget_destroy(t->tab_elems.eventbox);
7531 gtk_widget_destroy(t->vbox);
7533 g_free(t->stylesheet);
7534 g_free(t->tmp_uri);
7535 g_free(t->status);
7536 g_free(t);
7537 t = NULL;
7539 if (TAILQ_EMPTY(&tabs)) {
7540 if (browser_mode == XT_BM_KIOSK)
7541 create_new_tab(home, NULL, 1, -1);
7542 else
7543 create_new_tab(NULL, NULL, 1, -1);
7546 /* recreate session */
7547 if (session_autosave) {
7548 bzero(&a, sizeof a);
7549 a.s = NULL;
7550 save_tabs(NULL, &a);
7553 recalc_tabs();
7554 recolor_compact_tabs();
7557 void
7558 update_statusbar_zoom(struct tab *t)
7560 gfloat zoom;
7561 char s[16] = { '\0' };
7563 g_object_get(G_OBJECT(t->wv), "zoom-level", &zoom, (char *)NULL);
7564 if ((zoom <= 0.99 || zoom >= 1.01))
7565 snprintf(s, sizeof s, "%d%%", (int)(zoom * 100));
7566 gtk_label_set_text(GTK_LABEL(t->sbe.zoom), s);
7569 void
7570 setzoom_webkit(struct tab *t, int adjust)
7572 #define XT_ZOOMPERCENT 0.04
7574 gfloat zoom;
7576 if (t == NULL) {
7577 show_oops(NULL, "setzoom_webkit invalid parameters");
7578 return;
7581 g_object_get(G_OBJECT(t->wv), "zoom-level", &zoom, (char *)NULL);
7582 if (adjust == XT_ZOOM_IN)
7583 zoom += XT_ZOOMPERCENT;
7584 else if (adjust == XT_ZOOM_OUT)
7585 zoom -= XT_ZOOMPERCENT;
7586 else if (adjust > 0)
7587 zoom = default_zoom_level + adjust / 100.0 - 1.0;
7588 else {
7589 show_oops(t, "setzoom_webkit invalid zoom value");
7590 return;
7593 if (zoom < XT_ZOOMPERCENT)
7594 zoom = XT_ZOOMPERCENT;
7595 g_object_set(G_OBJECT(t->wv), "zoom-level", zoom, (char *)NULL);
7596 update_statusbar_zoom(t);
7599 gboolean
7600 tab_clicked_cb(GtkWidget *widget, GdkEventButton *event, gpointer data)
7602 struct tab *t = (struct tab *) data;
7604 DNPRINTF(XT_D_TAB, "tab_clicked_cb: tab: %d\n", t->tab_id);
7606 switch (event->button) {
7607 case 1:
7608 set_current_tab(t->tab_id);
7609 break;
7610 case 2:
7611 delete_tab(t);
7612 break;
7615 return TRUE;
7618 void
7619 append_tab(struct tab *t)
7621 if (t == NULL)
7622 return;
7624 TAILQ_INSERT_TAIL(&tabs, t, entry);
7625 t->tab_id = gtk_notebook_append_page(notebook, t->vbox, t->tab_content);
7628 GtkWidget *
7629 create_sbe(void)
7631 GtkWidget *sbe;
7633 sbe = gtk_label_new(NULL);
7634 gtk_widget_set_can_focus(GTK_WIDGET(sbe), FALSE);
7635 gtk_widget_modify_font(GTK_WIDGET(sbe), statusbar_font);
7636 return (sbe);
7640 add_sbe(GtkWidget *box, char flag, int *used, GtkWidget *sbe)
7642 if (box == NULL || used == NULL || sbe == NULL) {
7643 DPRINTF("%s: invalid parameters", __func__);
7644 return (1);
7647 if (*used) {
7648 warnx("flag \"%c\" specified more than "
7649 "once in statusbar_elems\n", flag);
7650 return (1);
7653 gtk_box_pack_start(GTK_BOX(box), sbe, FALSE, FALSE, 0);
7654 *used = 1;
7656 return (0);
7660 statusbar_create(struct tab *t)
7662 GtkWidget *box; /* container for statusbar elems */
7663 GtkWidget *sep;
7664 char *p;
7665 int sbe_P = 0, sbe_B = 0, sbe_Z = 0, sbe_T = 0,
7666 sbe_p = 0;
7667 #if !GTK_CHECK_VERSION(3, 0, 0)
7668 GdkColor color;
7669 #endif
7671 if (t == NULL) {
7672 DPRINTF("%s: invalid parameters", __func__);
7673 return (1);
7676 #if GTK_CHECK_VERSION(3, 0, 0)
7677 t->statusbar = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 0);
7678 box = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 0);
7679 gtk_widget_set_name(GTK_WIDGET(t->statusbar), "statusbar");
7680 #else
7681 t->statusbar = gtk_hbox_new(FALSE, 0);
7682 box = gtk_hbox_new(FALSE, 0);
7683 #endif
7684 t->sbe.ebox = gtk_event_box_new();
7686 gtk_widget_set_can_focus(GTK_WIDGET(t->statusbar), FALSE);
7687 gtk_widget_set_can_focus(GTK_WIDGET(t->sbe.ebox), FALSE);
7688 gtk_widget_set_can_focus(GTK_WIDGET(box), FALSE);
7690 gtk_box_set_spacing(GTK_BOX(box), 10);
7691 gtk_box_pack_start(GTK_BOX(t->statusbar), t->sbe.ebox, TRUE, TRUE, 0);
7692 gtk_container_add(GTK_CONTAINER(t->sbe.ebox), box);
7694 /* create these widgets only if specified in statusbar_elems */
7695 t->sbe.uri = gtk_entry_new();
7696 gtk_widget_set_can_focus(GTK_WIDGET(t->sbe.uri), FALSE);
7697 gtk_widget_modify_font(GTK_WIDGET(t->sbe.uri), statusbar_font);
7698 #if !GTK_CHECK_VERSION(3, 0, 0)
7699 gtk_entry_set_inner_border(GTK_ENTRY(t->sbe.uri), NULL);
7700 gtk_entry_set_has_frame(GTK_ENTRY(t->sbe.uri), FALSE);
7701 #endif
7702 t->sbe.position = create_sbe();
7703 t->sbe.zoom = create_sbe();
7704 t->sbe.buffercmd = create_sbe();
7705 t->sbe.tabs = create_sbe();
7706 t->sbe.proxy = create_sbe();
7708 #if GTK_CHECK_VERSION(3, 0, 0)
7709 statusbar_modify_attr(t, XT_CSS_NORMAL);
7710 #else
7711 statusbar_modify_attr(t, XT_COLOR_WHITE, XT_COLOR_BLACK);
7712 #endif
7714 gtk_box_pack_start(GTK_BOX(box), t->sbe.uri, TRUE, TRUE, 0);
7717 * gtk widgets cannot be added to a box twice. The sbe_* variables
7718 * make sure of this
7720 for (p = statusbar_elems; *p != '\0'; p++) {
7721 switch (*p) {
7722 case '|':
7723 #if GTK_CHECK_VERSION(3, 0, 0)
7724 sep = gtk_separator_new(GTK_ORIENTATION_VERTICAL);
7725 #else
7726 sep = gtk_vseparator_new();
7727 gdk_color_parse(XT_COLOR_SB_SEPARATOR, &color);
7728 gtk_widget_modify_bg(sep, GTK_STATE_NORMAL, &color);
7729 #endif
7730 gtk_box_pack_start(GTK_BOX(box), sep, FALSE, FALSE, 0);
7731 break;
7732 case 'P':
7733 add_sbe(box, *p, &sbe_P, t->sbe.position);
7734 break;
7735 case 'B':
7736 add_sbe(box, *p, &sbe_B, t->sbe.buffercmd);
7737 break;
7738 case 'Z':
7739 add_sbe(box, *p, &sbe_Z, t->sbe.zoom);
7740 break;
7741 case 'T':
7742 add_sbe(box, *p, &sbe_T, t->sbe.tabs);
7743 break;
7744 case 'p':
7745 if (add_sbe(box, *p, &sbe_p, t->sbe.proxy) == 0)
7746 if (proxy_uri)
7747 gtk_entry_set_text(
7748 GTK_ENTRY(t->sbe.proxy), "proxy");
7749 break;
7750 default:
7751 warnx("illegal flag \"%c\" in statusbar_elems\n", *p);
7752 break;
7756 gtk_box_pack_end(GTK_BOX(t->vbox), t->statusbar, FALSE, FALSE, 0);
7758 return (0);
7761 struct tab *
7762 create_new_tab(char *title, struct undo *u, int focus, int position)
7764 struct tab *t;
7765 int load = 1, id;
7766 GtkWidget *b, *bb;
7767 WebKitWebHistoryItem *item;
7768 GList *items;
7769 char *sv[3];
7770 #if !GTK_CHECK_VERSION(3, 0, 0)
7771 GdkColor color;
7772 #endif
7774 DNPRINTF(XT_D_TAB, "create_new_tab: title %s focus %d\n", title, focus);
7776 if (tabless && !TAILQ_EMPTY(&tabs)) {
7777 if (single_instance) {
7778 DNPRINTF(XT_D_TAB,
7779 "create_new_tab: new tab rejected\n");
7780 return (NULL);
7782 sv[0] = start_argv[0];
7783 sv[1] = title;
7784 sv[2] = (char *)NULL;
7785 if (!g_spawn_async(NULL, sv, NULL, G_SPAWN_SEARCH_PATH,
7786 NULL, NULL, NULL, NULL))
7787 show_oops(NULL, "%s: could not spawn process",
7788 __func__);
7789 return (NULL);
7792 t = g_malloc0(sizeof *t);
7794 if (title == NULL) {
7795 title = "(untitled)";
7796 load = 0;
7799 #if GTK_CHECK_VERSION(3, 0, 0)
7800 t->vbox = gtk_box_new(GTK_ORIENTATION_VERTICAL, 0);
7801 b = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 0);
7802 gtk_widget_set_name(t->vbox, "vbox");
7803 #else
7804 t->vbox = gtk_vbox_new(FALSE, 0);
7805 b = gtk_hbox_new(FALSE, 0);
7806 #endif
7807 gtk_widget_set_can_focus(t->vbox, FALSE);
7809 /* label + button for tab */
7810 t->tab_content = b;
7811 gtk_widget_set_can_focus(t->tab_content, FALSE);
7813 t->user_agent_id = 0;
7814 t->http_accept_id = 0;
7816 #if WEBKIT_CHECK_VERSION(1, 5, 0)
7817 t->active = NULL;
7818 #endif
7820 #if GTK_CHECK_VERSION(2, 20, 0)
7821 t->spinner = gtk_spinner_new();
7822 #endif
7823 t->label = gtk_label_new(title);
7824 bb = create_button("Close", GTK_STOCK_CLOSE, 1);
7825 gtk_label_set_max_width_chars(GTK_LABEL(t->label), 20);
7826 gtk_label_set_ellipsize(GTK_LABEL(t->label), PANGO_ELLIPSIZE_END);
7827 gtk_label_set_line_wrap(GTK_LABEL(t->label), FALSE);
7828 gtk_widget_set_size_request(b, 130, 0);
7831 * this is a total hack and most likely breaks with other styles but
7832 * is necessary so the text doesn't bounce around when the spinner is
7833 * shown/hidden
7835 #if GTK_CHECK_VERSION(3, 0, 0)
7836 gtk_widget_set_size_request(t->label, 95, 0);
7837 #else
7838 gtk_widget_set_size_request(t->label, 100, 0);
7839 #endif
7841 gtk_box_pack_start(GTK_BOX(b), bb, FALSE, FALSE, 0);
7842 gtk_box_pack_start(GTK_BOX(b), t->label, FALSE, FALSE, 0);
7843 #if GTK_CHECK_VERSION(2, 20, 0)
7844 gtk_box_pack_end(GTK_BOX(b), t->spinner, FALSE, FALSE, 0);
7845 #endif
7847 /* toolbar */
7848 if (browser_mode == XT_BM_KIOSK) {
7849 t->toolbar = create_kiosk_toolbar(t);
7850 gtk_box_pack_start(GTK_BOX(t->vbox), t->toolbar, FALSE, FALSE,
7852 } else {
7853 t->toolbar = create_toolbar(t);
7854 gtk_box_pack_start(GTK_BOX(t->vbox), t->toolbar, FALSE, FALSE,
7858 /* marks */
7859 marks_clear(t);
7861 /* browser */
7862 t->browser_win = create_browser(t);
7863 set_scrollbar_visibility(t, show_scrollbars);
7864 gtk_box_pack_start(GTK_BOX(t->vbox), t->browser_win, TRUE, TRUE, 0);
7866 /* oops message for user feedback */
7867 t->oops = gtk_entry_new();
7868 gtk_entry_set_inner_border(GTK_ENTRY(t->oops), NULL);
7869 gtk_entry_set_has_frame(GTK_ENTRY(t->oops), FALSE);
7870 gtk_widget_set_can_focus(GTK_WIDGET(t->oops), FALSE);
7871 #if GTK_CHECK_VERSION(3, 0, 0)
7872 gtk_widget_set_name(t->oops, XT_CSS_RED);
7873 #else
7874 gdk_color_parse(XT_COLOR_RED, &color);
7875 gtk_widget_modify_base(t->oops, GTK_STATE_NORMAL, &color);
7876 #endif
7877 gtk_box_pack_end(GTK_BOX(t->vbox), t->oops, FALSE, FALSE, 0);
7878 gtk_widget_modify_font(GTK_WIDGET(t->oops), oops_font);
7880 /* command entry */
7881 t->cmd = gtk_entry_new();
7882 g_signal_connect(G_OBJECT(t->cmd), "focus-in-event",
7883 G_CALLBACK(entry_focus_cb), t);
7884 gtk_entry_set_inner_border(GTK_ENTRY(t->cmd), NULL);
7885 gtk_entry_set_has_frame(GTK_ENTRY(t->cmd), FALSE);
7886 gtk_box_pack_end(GTK_BOX(t->vbox), t->cmd, FALSE, FALSE, 0);
7887 gtk_widget_modify_font(GTK_WIDGET(t->cmd), cmd_font);
7889 /* status bar */
7890 statusbar_create(t);
7892 /* buffer list */
7893 t->buffers = create_buffers(t);
7894 gtk_box_pack_end(GTK_BOX(t->vbox), t->buffers, FALSE, FALSE, 0);
7896 /* xtp meaning is normal by default */
7897 set_normal_tab_meaning(t);
7899 /* set empty favicon */
7900 xt_icon_from_name(t, "text-html");
7902 /* and show it all */
7903 gtk_widget_show_all(b);
7904 gtk_widget_show_all(t->vbox);
7906 if (!fancy_bar) {
7907 gtk_widget_hide(t->backward);
7908 gtk_widget_hide(t->forward);
7909 gtk_widget_hide(t->stop);
7910 gtk_widget_hide(t->js_toggle);
7912 if (!fancy_bar || (search_string == NULL || strlen(search_string) == 0))
7913 gtk_widget_hide(t->search_entry);
7914 if (http_proxy == NULL && http_proxy_save == NULL)
7915 gtk_widget_hide(t->proxy_toggle);
7917 /* compact tab bar */
7918 t->tab_elems.label = gtk_label_new(title);
7919 t->tab_elems.favicon = gtk_image_new();
7921 t->tab_elems.eventbox = gtk_event_box_new();
7922 gtk_widget_set_name(t->tab_elems.eventbox, "compact_tab");
7923 #if GTK_CHECK_VERSION(3, 0, 0)
7924 t->tab_elems.box = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 0);
7926 gtk_label_set_ellipsize(GTK_LABEL(t->tab_elems.label),
7927 PANGO_ELLIPSIZE_END);
7928 gtk_widget_override_font(t->tab_elems.label, tabbar_font);
7929 gtk_widget_set_halign(t->tab_elems.label, GTK_ALIGN_START);
7930 gtk_widget_set_valign(t->tab_elems.label, GTK_ALIGN_START);
7931 #else
7932 t->tab_elems.box = gtk_hbox_new(FALSE, 0);
7934 gtk_label_set_width_chars(GTK_LABEL(t->tab_elems.label), 1);
7935 gtk_misc_set_alignment(GTK_MISC(t->tab_elems.label), 0.0, 0.0);
7936 gtk_misc_set_padding(GTK_MISC(t->tab_elems.label), 4.0, 4.0);
7937 gtk_widget_modify_font(GTK_WIDGET(t->tab_elems.label), tabbar_font);
7939 gdk_color_parse(XT_COLOR_CT_BACKGROUND, &color);
7940 gtk_widget_modify_bg(t->tab_elems.eventbox, GTK_STATE_NORMAL, &color);
7941 gdk_color_parse(XT_COLOR_CT_INACTIVE, &color);
7942 gtk_widget_modify_fg(t->tab_elems.label, GTK_STATE_NORMAL, &color);
7943 #endif
7945 gtk_box_pack_start(GTK_BOX(t->tab_elems.box), t->tab_elems.favicon, FALSE,
7946 FALSE, 0);
7947 gtk_box_pack_start(GTK_BOX(t->tab_elems.box), t->tab_elems.label, TRUE,
7948 TRUE, 0);
7949 gtk_container_add(GTK_CONTAINER(t->tab_elems.eventbox),
7950 t->tab_elems.box);
7952 gtk_box_pack_start(GTK_BOX(tab_bar_box), t->tab_elems.eventbox, TRUE,
7953 TRUE, 0);
7954 gtk_widget_show_all(t->tab_elems.eventbox);
7956 if (append_next == 0 || gtk_notebook_get_n_pages(notebook) == 0)
7957 append_tab(t);
7958 else {
7959 id = position >= 0 ? position :
7960 gtk_notebook_get_current_page(notebook) + 1;
7961 if (id > gtk_notebook_get_n_pages(notebook))
7962 append_tab(t);
7963 else {
7964 TAILQ_INSERT_TAIL(&tabs, t, entry);
7965 gtk_notebook_insert_page(notebook, t->vbox, b, id);
7966 gtk_box_reorder_child(GTK_BOX(tab_bar_box),
7967 t->tab_elems.eventbox, id);
7968 recalc_tabs();
7972 #if GTK_CHECK_VERSION(2, 20, 0)
7973 /* turn spinner off if we are a new tab without uri */
7974 if (!load) {
7975 gtk_spinner_stop(GTK_SPINNER(t->spinner));
7976 gtk_widget_hide(t->spinner);
7978 #endif
7979 /* make notebook tabs reorderable */
7980 gtk_notebook_set_tab_reorderable(notebook, t->vbox, TRUE);
7982 /* compact tabs clickable */
7983 g_signal_connect(G_OBJECT(t->tab_elems.eventbox),
7984 "button_press_event", G_CALLBACK(tab_clicked_cb), t);
7986 g_object_connect(G_OBJECT(t->cmd),
7987 "signal::button-release-event", G_CALLBACK(cmd_keyrelease_cb), t,
7988 "signal::key-press-event", G_CALLBACK(cmd_keypress_cb), t,
7989 "signal::key-release-event", G_CALLBACK(cmd_keyrelease_cb), t,
7990 "signal::focus-out-event", G_CALLBACK(cmd_focusout_cb), t,
7991 "signal::activate", G_CALLBACK(cmd_activate_cb), t,
7992 "signal::populate-popup", G_CALLBACK(cmd_popup_cb), t,
7993 "signal::hide", G_CALLBACK(cmd_hide_cb), t,
7994 (char *)NULL);
7996 /* reuse wv_button_cb to hide oops */
7997 g_object_connect(G_OBJECT(t->oops),
7998 "signal::button_press_event", G_CALLBACK(wv_button_cb), t,
7999 (char *)NULL);
8001 g_signal_connect(t->buffers,
8002 "row-activated", G_CALLBACK(row_activated_cb), t);
8003 g_object_connect(G_OBJECT(t->buffers),
8004 "signal::key-press-event", G_CALLBACK(wv_keypress_cb), t, (char *)NULL);
8006 g_object_connect(G_OBJECT(t->wv),
8007 "signal::key-press-event", G_CALLBACK(wv_keypress_cb), t,
8008 "signal::hovering-over-link", G_CALLBACK(webview_hover_cb), t,
8009 "signal::download-requested", G_CALLBACK(webview_download_cb), t,
8010 "signal::mime-type-policy-decision-requested", G_CALLBACK(webview_mimetype_cb), t,
8011 "signal::navigation-policy-decision-requested", G_CALLBACK(webview_npd_cb), t,
8012 "signal::new-window-policy-decision-requested", G_CALLBACK(webview_npd_cb), t,
8013 "signal::resource-request-starting", G_CALLBACK(webview_rrs_cb), t,
8014 "signal::create-web-view", G_CALLBACK(webview_cwv_cb), t,
8015 "signal::close-web-view", G_CALLBACK(webview_closewv_cb), t,
8016 "signal::event", G_CALLBACK(webview_event_cb), t,
8017 "signal::icon-loaded", G_CALLBACK(notify_icon_loaded_cb), t,
8018 "signal::button_press_event", G_CALLBACK(wv_button_cb), t,
8019 "signal::button_release_event", G_CALLBACK(wv_release_button_cb), t,
8020 "signal::populate-popup", G_CALLBACK(wv_popup_cb), t,
8021 (char *)NULL);
8022 g_signal_connect(t->wv,
8023 "notify::load-status", G_CALLBACK(notify_load_status_cb), t);
8024 g_signal_connect(t->wv,
8025 "notify::title", G_CALLBACK(notify_title_cb), t);
8026 t->progress_handle = g_signal_connect(t->wv,
8027 "notify::progress", G_CALLBACK(webview_progress_changed_cb), t);
8029 /* hijack the unused keys as if we were the browser */
8030 //g_object_connect(G_OBJECT(t->toolbar),
8031 // "signal-after::key-press-event", G_CALLBACK(wv_keypress_after_cb), t,
8032 // (char *)NULL);
8034 g_signal_connect(G_OBJECT(bb), "button_press_event",
8035 G_CALLBACK(tab_close_cb), t);
8037 /* setup history */
8038 t->bfl = webkit_web_view_get_back_forward_list(t->wv);
8039 /* restore the tab's history */
8040 if (u && u->history) {
8041 items = u->history;
8042 while (items) {
8043 item = items->data;
8044 webkit_web_back_forward_list_add_item(t->bfl, item);
8045 items = g_list_next(items);
8048 item = g_list_nth_data(u->history, u->back);
8049 if (item)
8050 webkit_web_view_go_to_back_forward_item(t->wv, item);
8052 g_list_free(items);
8053 g_list_free(u->history);
8054 } else
8055 webkit_web_back_forward_list_clear(t->bfl);
8057 /* check and show url and statusbar */
8058 url_set_visibility();
8059 statusbar_set_visibility();
8061 if (focus) {
8062 set_current_tab(t->tab_id);
8063 DNPRINTF(XT_D_TAB, "create_new_tab: going to tab: %d\n",
8064 t->tab_id);
8066 if (load) {
8067 gtk_entry_set_text(GTK_ENTRY(t->uri_entry), title);
8068 load_uri(t, title);
8069 } else {
8070 if (show_url == 1)
8071 gtk_widget_grab_focus(GTK_WIDGET(t->uri_entry));
8072 else
8073 focus_webview(t);
8075 } else if (load)
8076 load_uri(t, title);
8078 if (userstyle_global)
8079 apply_style(t);
8081 recolor_compact_tabs();
8082 setzoom_webkit(t, XT_ZOOM_NORMAL);
8083 return (t);
8086 void
8087 notebook_switchpage_cb(GtkNotebook *nb, GtkWidget *nbp, guint pn,
8088 gpointer *udata)
8090 struct tab *t;
8091 const gchar *uri;
8093 DNPRINTF(XT_D_TAB, "notebook_switchpage_cb: tab: %d\n", pn);
8095 if (gtk_notebook_get_current_page(notebook) == -1)
8096 recalc_tabs();
8098 TAILQ_FOREACH(t, &tabs, entry) {
8099 if (t->tab_id == pn) {
8100 DNPRINTF(XT_D_TAB, "notebook_switchpage_cb: going to "
8101 "%d\n", pn);
8103 uri = get_title(t, TRUE);
8104 gtk_window_set_title(GTK_WINDOW(main_window), uri);
8106 hide_cmd(t);
8107 hide_oops(t);
8108 hide_buffers(t);
8110 if (t->focus_wv) {
8111 /* can't use focus_webview here */
8112 gtk_widget_grab_focus(GTK_WIDGET(t->wv));
8114 update_statusbar_tabs(t);
8115 break;
8120 void
8121 notebook_pagereordered_cb(GtkNotebook *nb, GtkWidget *nbp, guint pn,
8122 gpointer *udata)
8124 struct tab *t = NULL, *tt;
8126 recalc_tabs();
8128 TAILQ_FOREACH(tt, &tabs, entry)
8129 if (tt->tab_id == pn) {
8130 t = tt;
8131 break;
8133 if (t == NULL)
8134 return;
8135 DNPRINTF(XT_D_TAB, "page_reordered_cb: tab: %d\n", t->tab_id);
8137 gtk_box_reorder_child(GTK_BOX(tab_bar_box), t->tab_elems.eventbox,
8138 t->tab_id);
8140 update_statusbar_tabs(t);
8143 void
8144 menuitem_response(struct tab *t)
8146 gtk_notebook_set_current_page(notebook, t->tab_id);
8150 destroy_menu(GtkMenuShell *m, void *notused)
8152 gtk_widget_destroy(GTK_WIDGET(m));
8153 return (XT_CB_PASSTHROUGH);
8156 gboolean
8157 arrow_cb(GtkWidget *w, GdkEventButton *event, gpointer user_data)
8159 GtkWidget *menu = NULL, *menu_items;
8160 GdkEventButton *bevent;
8161 struct tab **stabs = NULL;
8162 int i, num_tabs;
8163 const gchar *uri;
8165 if (event->type == GDK_BUTTON_PRESS) {
8166 bevent = (GdkEventButton *) event;
8167 menu = gtk_menu_new();
8169 num_tabs = sort_tabs_by_page_num(&stabs);
8170 for (i = 0; i < num_tabs; ++i) {
8171 if (stabs[i] == NULL)
8172 continue;
8173 if ((uri = get_uri(stabs[i])) == NULL)
8174 /* XXX make sure there is something to print */
8175 /* XXX add gui pages in here to look purdy */
8176 uri = "(untitled)";
8177 menu_items = gtk_menu_item_new_with_label(uri);
8178 gtk_menu_shell_append(GTK_MENU_SHELL(menu), menu_items);
8179 gtk_widget_show(menu_items);
8181 g_signal_connect_swapped(menu_items,
8182 "activate", G_CALLBACK(menuitem_response),
8183 (gpointer)stabs[i]);
8185 g_free(stabs);
8187 gtk_menu_popup(GTK_MENU(menu), NULL, NULL, NULL, NULL,
8188 bevent->button, bevent->time);
8190 g_object_connect(G_OBJECT(menu),
8191 "signal::selection-done", G_CALLBACK(destroy_menu), NULL,
8192 (char *)NULL);
8194 return (TRUE /* eat event */);
8197 return (FALSE /* propagate */);
8201 icon_size_map(int iconsz)
8203 if (iconsz <= GTK_ICON_SIZE_INVALID ||
8204 iconsz > GTK_ICON_SIZE_DIALOG)
8205 return (GTK_ICON_SIZE_SMALL_TOOLBAR);
8207 return (iconsz);
8210 GtkWidget *
8211 create_button(char *name, char *stockid, int size)
8213 GtkWidget *button, *image;
8214 int gtk_icon_size;
8215 #if !GTK_CHECK_VERSION(3, 0, 0)
8216 gchar *newstyle;
8217 #endif
8219 #if !GTK_CHECK_VERSION(3, 0, 0)
8220 newstyle = g_strdup_printf(
8221 "style \"%s-style\"\n"
8222 "{\n"
8223 " GtkWidget::focus-padding = 0\n"
8224 " GtkWidget::focus-line-width = 0\n"
8225 " xthickness = 0\n"
8226 " ythickness = 0\n"
8227 "}\n"
8228 "widget \"*.%s\" style \"%s-style\"", name, name, name);
8229 gtk_rc_parse_string(newstyle);
8230 g_free(newstyle);
8231 #endif
8232 button = gtk_button_new();
8233 gtk_widget_set_can_focus(button, FALSE);
8234 gtk_button_set_focus_on_click(GTK_BUTTON(button), FALSE);
8235 gtk_icon_size = icon_size_map(size ? size : icon_size);
8237 image = gtk_image_new_from_stock(stockid, gtk_icon_size);
8238 gtk_container_set_border_width(GTK_CONTAINER(button), 1);
8239 gtk_container_add(GTK_CONTAINER(button), GTK_WIDGET(image));
8240 gtk_widget_set_name(button, name);
8241 gtk_button_set_relief(GTK_BUTTON(button), GTK_RELIEF_NONE);
8243 return (button);
8246 void
8247 button_set_file(GtkWidget *button, char *filename)
8249 GtkWidget *image;
8250 char file[PATH_MAX];
8252 snprintf(file, sizeof file, "%s" PS "%s", resource_dir, filename);
8253 image = gtk_image_new_from_file(file);
8254 gtk_button_set_image(GTK_BUTTON(button), image);
8257 void
8258 button_set_stockid(GtkWidget *button, char *stockid)
8260 GtkWidget *image;
8262 image = gtk_image_new_from_stock(stockid, icon_size_map(icon_size));
8263 gtk_button_set_image(GTK_BUTTON(button), image);
8266 void
8267 create_canvas(void)
8269 GtkWidget *vbox;
8270 GList *l = NULL;
8271 GdkPixbuf *pb;
8272 char file[PATH_MAX];
8273 int i;
8274 #if !GTK_CHECK_VERSION(3, 0, 0)
8275 GdkColor color;
8276 #endif
8278 #if GTK_CHECK_VERSION(3, 0, 0)
8279 vbox = gtk_box_new(GTK_ORIENTATION_VERTICAL, 0);
8280 #else
8281 vbox = gtk_vbox_new(FALSE, 0);
8282 #endif
8283 gtk_box_set_spacing(GTK_BOX(vbox), 0);
8284 gtk_widget_set_can_focus(vbox, FALSE);
8285 notebook = GTK_NOTEBOOK(gtk_notebook_new());
8286 #if !GTK_CHECK_VERSION(3, 0, 0)
8287 /* XXX seems to be needed with gtk+2 */
8288 g_object_set(G_OBJECT(notebook), "tab-border", 0, NULL);
8289 #endif
8290 gtk_notebook_set_scrollable(notebook, TRUE);
8291 gtk_notebook_set_show_border(notebook, FALSE);
8292 gtk_widget_set_can_focus(GTK_WIDGET(notebook), FALSE);
8294 abtn = gtk_button_new();
8295 gtk_widget_set_can_focus(abtn, FALSE);
8296 arrow = gtk_arrow_new(GTK_ARROW_DOWN, GTK_SHADOW_NONE);
8297 gtk_widget_set_name(abtn, "Arrow");
8298 gtk_container_add(GTK_CONTAINER(abtn), arrow);
8299 gtk_widget_set_size_request(abtn, -1, 20);
8301 #if GTK_CHECK_VERSION(2, 20, 0)
8302 gtk_notebook_set_action_widget(notebook, abtn, GTK_PACK_END);
8303 #endif
8304 /* compact tab bar */
8305 tab_bar = gtk_event_box_new();
8306 #if GTK_CHECK_VERSION(3, 0, 0)
8307 gtk_widget_set_name(tab_bar, "tab_bar");
8308 tab_bar_box = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 0);
8309 #else
8310 gdk_color_parse(XT_COLOR_CT_SEPARATOR, &color);
8311 gtk_widget_modify_bg(tab_bar, GTK_STATE_NORMAL, &color);
8312 tab_bar_box = gtk_hbox_new(TRUE, 0);
8313 #endif
8314 gtk_container_add(GTK_CONTAINER(tab_bar), tab_bar_box);
8315 gtk_box_set_homogeneous(GTK_BOX(tab_bar_box), TRUE);
8316 gtk_box_set_spacing(GTK_BOX(tab_bar_box), 2);
8318 gtk_box_pack_start(GTK_BOX(vbox), tab_bar, FALSE, FALSE, 0);
8319 gtk_box_pack_start(GTK_BOX(vbox), GTK_WIDGET(notebook), TRUE, TRUE, 0);
8321 g_object_connect(G_OBJECT(notebook),
8322 "signal::switch-page", G_CALLBACK(notebook_switchpage_cb), NULL,
8323 (char *)NULL);
8324 g_object_connect(G_OBJECT(notebook),
8325 "signal::page-reordered", G_CALLBACK(notebook_pagereordered_cb),
8326 NULL, (char *)NULL);
8327 g_signal_connect(G_OBJECT(abtn), "button_press_event",
8328 G_CALLBACK(arrow_cb), NULL);
8330 main_window = create_window("xombrero");
8331 gtk_container_add(GTK_CONTAINER(main_window), vbox);
8332 g_signal_connect(G_OBJECT(main_window), "delete_event",
8333 G_CALLBACK(gtk_main_quit), NULL);
8334 #if GTK_CHECK_VERSION(3, 0, 0)
8335 gtk_window_set_has_resize_grip(GTK_WINDOW(main_window), FALSE);
8336 #endif
8338 /* icons */
8339 for (i = 0; i < LENGTH(icons); i++) {
8340 snprintf(file, sizeof file, "%s" PS "%s", resource_dir, icons[i]);
8341 pb = gdk_pixbuf_new_from_file(file, NULL);
8342 l = g_list_append(l, pb);
8344 gtk_window_set_default_icon_list(l);
8346 gtk_widget_show_all(abtn);
8347 gtk_widget_show_all(main_window);
8348 notebook_tab_set_visibility();
8351 #ifndef XT_SOCKET_DISABLE
8353 send_cmd_to_socket(char *cmd)
8355 int s, len, rv = 1;
8356 struct sockaddr_un sa;
8358 if ((s = socket(AF_UNIX, SOCK_STREAM, 0)) == -1) {
8359 warnx("%s: socket", __func__);
8360 return (rv);
8363 sa.sun_family = AF_UNIX;
8364 snprintf(sa.sun_path, sizeof(sa.sun_path), "%s" PS "%s",
8365 work_dir, XT_SOCKET_FILE);
8366 len = SUN_LEN(&sa);
8368 if (connect(s, (struct sockaddr *)&sa, len) == -1) {
8369 warnx("%s: connect", __func__);
8370 goto done;
8373 if (send(s, cmd, strlen(cmd) + 1, 0) == -1) {
8374 warnx("%s: send", __func__);
8375 goto done;
8378 rv = 0;
8379 done:
8380 close(s);
8381 return (rv);
8384 gboolean
8385 socket_watcher(GIOChannel *source, GIOCondition condition, gpointer data)
8387 int s, n;
8388 char str[XT_MAX_URL_LENGTH];
8389 socklen_t t = sizeof(struct sockaddr_un);
8390 struct sockaddr_un sa;
8391 struct passwd *p;
8392 uid_t uid;
8393 gid_t gid;
8394 struct tab *tt;
8395 gint fd = g_io_channel_unix_get_fd(source);
8397 if ((s = accept(fd, (struct sockaddr *)&sa, &t)) == -1) {
8398 warn("accept");
8399 return (FALSE);
8402 if (getpeereid(s, &uid, &gid) == -1) {
8403 warn("getpeereid");
8404 return (FALSE);
8406 if (uid != getuid() || gid != getgid()) {
8407 warnx("unauthorized user");
8408 return (FALSE);
8411 p = getpwuid(uid);
8412 if (p == NULL) {
8413 warnx("not a valid user");
8414 return (FALSE);
8417 n = recv(s, str, sizeof(str), 0);
8418 if (n <= 0)
8419 return (TRUE);
8421 tt = get_current_tab();
8422 cmd_execute(tt, str);
8423 return (TRUE);
8427 is_running(void)
8429 int s, len, rv = 1;
8430 struct sockaddr_un sa;
8432 if ((s = socket(AF_UNIX, SOCK_STREAM, 0)) == -1) {
8433 warn("is_running: socket");
8434 return (-1);
8437 sa.sun_family = AF_UNIX;
8438 snprintf(sa.sun_path, sizeof(sa.sun_path), "%s" PS "%s",
8439 work_dir, XT_SOCKET_FILE);
8440 len = SUN_LEN(&sa);
8442 /* connect to see if there is a listener */
8443 if (connect(s, (struct sockaddr *)&sa, len) == -1)
8444 rv = 0; /* not running */
8445 else
8446 rv = 1; /* already running */
8448 close(s);
8450 return (rv);
8454 build_socket(void)
8456 int s, len;
8457 struct sockaddr_un sa;
8459 if ((s = socket(AF_UNIX, SOCK_STREAM, 0)) == -1) {
8460 warn("build_socket: socket");
8461 return (-1);
8464 sa.sun_family = AF_UNIX;
8465 snprintf(sa.sun_path, sizeof(sa.sun_path), "%s" PS "%s",
8466 work_dir, XT_SOCKET_FILE);
8467 len = SUN_LEN(&sa);
8469 /* connect to see if there is a listener */
8470 if (connect(s, (struct sockaddr *)&sa, len) == -1) {
8471 /* no listener so we will */
8472 unlink(sa.sun_path);
8474 if (bind(s, (struct sockaddr *)&sa, len) == -1) {
8475 warn("build_socket: bind");
8476 goto done;
8479 if (listen(s, 1) == -1) {
8480 warn("build_socket: listen");
8481 goto done;
8484 return (s);
8487 done:
8488 close(s);
8489 return (-1);
8491 #endif
8493 void
8494 xxx_dir(char *dir)
8496 struct stat sb;
8498 if (stat(dir, &sb)) {
8499 #if defined __MINGW32__
8500 if (mkdir(dir) == -1)
8501 #else
8502 if (mkdir(dir, S_IRWXU) == -1)
8503 #endif
8504 err(1, "mkdir %s", dir);
8505 if (stat(dir, &sb))
8506 err(1, "stat %s", dir);
8508 if (S_ISDIR(sb.st_mode) == 0)
8509 errx(1, "%s not a dir", dir);
8510 #if !defined __MINGW32__
8511 if (((sb.st_mode & (S_IRWXU | S_IRWXG | S_IRWXO))) != S_IRWXU) {
8512 warnx("fixing invalid permissions on %s", dir);
8513 if (chmod(dir, S_IRWXU) == -1)
8514 err(1, "chmod %s", dir);
8516 #endif
8519 void
8520 usage(void)
8522 fprintf(stderr,
8523 "%s [-nSTVt][-f file][-s session] url ...\n", __progname);
8524 exit(0);
8527 GStaticRecMutex my_gdk_mtx = G_STATIC_REC_MUTEX_INIT;
8528 volatile int mtx_depth;
8529 int mtx_complain;
8532 * The linux flash plugin violates the gdk locking mechanism.
8533 * Work around the issue by using a recursive mutex with some match applied
8534 * to see if we hit a buggy condition.
8536 * The following code is painful so just don't read it. It really doesn't
8537 * make much sense but seems to work.
8539 void
8540 mtx_lock(void)
8542 #ifdef XT_DEBUG
8543 char *s = NULL;
8544 #endif
8546 g_static_rec_mutex_lock(&my_gdk_mtx);
8547 if (my_gdk_mtx.depth <= 0) {
8548 #ifdef XT_DEBUG
8549 s = "lock <= 0";
8550 #endif
8551 g_static_rec_mutex_lock(&my_gdk_mtx);
8552 goto complain;
8553 } else if (my_gdk_mtx.depth != 1) {
8554 #ifdef XT_DEBUG
8555 s = "lock != 1";
8556 #endif
8557 do {
8558 g_static_rec_mutex_unlock(&my_gdk_mtx);
8559 } while (my_gdk_mtx.depth > 1);
8560 goto complain;
8562 return;
8564 complain:
8565 if (mtx_complain == 0) {
8566 DNPRINTF(XT_D_MTX, "buggy mutex implementation detected(%s), "
8567 "work around implemented", s);
8568 mtx_complain = 1;
8572 void
8573 mtx_unlock(void)
8575 #ifdef XT_DEBUG
8576 char *s = NULL;
8577 #endif
8579 if (my_gdk_mtx.depth <= 0) {
8580 #ifdef XT_DEBUG
8581 s = "unlock <= 0";
8582 #endif
8583 goto complain;
8584 } else if (my_gdk_mtx.depth != 1) {
8585 #ifdef XT_DEBUG
8586 s = "unlock != 1";
8587 #endif
8588 g_static_rec_mutex_unlock_full(&my_gdk_mtx);
8589 goto complain;
8591 g_static_rec_mutex_unlock(&my_gdk_mtx);
8592 return;
8594 complain:
8595 if (mtx_complain == 0) {
8596 DNPRINTF(XT_D_MTX, "buggy mutex implementation detected(%s), "
8597 "work around implemented", s);
8598 mtx_complain = 1;
8602 #if GTK_CHECK_VERSION(3, 0, 0)
8603 void
8604 setup_css(void)
8606 GtkCssProvider *provider;
8607 GdkDisplay *display;
8608 GdkScreen *screen;
8609 GFile *file;
8610 char path[PATH_MAX];
8611 #if defined __MINGW32__
8612 GtkCssProvider *windows_hacks;
8613 #endif
8615 provider = gtk_css_provider_new();
8616 display = gdk_display_get_default();
8617 screen = gdk_display_get_default_screen(display);
8618 snprintf(path, sizeof path, "%s" PS "%s", resource_dir, XT_CSS_FILE);
8619 file = g_file_new_for_path(path);
8620 gtk_css_provider_load_from_file(provider, file, NULL);
8621 gtk_style_context_add_provider_for_screen(screen,
8622 GTK_STYLE_PROVIDER(provider),
8623 GTK_STYLE_PROVIDER_PRIORITY_APPLICATION);
8624 #if defined __MINGW32__
8625 windows_hacks = gtk_css_provider_new();
8626 gtk_css_provider_load_from_data(windows_hacks,
8627 ".notebook tab {\n"
8628 " border-width: 0px;\n"
8629 "}", -1, NULL);
8630 gtk_style_context_add_provider_for_screen(screen,
8631 GTK_STYLE_PROVIDER(windows_hacks),
8632 GTK_STYLE_PROVIDER_PRIORITY_APPLICATION);
8633 #endif
8634 g_object_unref(file);
8636 #endif
8638 void
8639 welcome(void)
8641 startpage_add("<b>Welcome to xombrero %s!</b><p>", version);
8642 startpage_add("Details at "
8643 "<a href=https://opensource.conformal.com/wiki/xombrero>xombrero "
8644 "wiki page</a><p>");
8648 main(int argc, char **argv)
8650 struct stat sb;
8651 int c, optn = 0, opte = 0, focus = 1;
8652 char conf[PATH_MAX] = { '\0' };
8653 char file[PATH_MAX];
8654 char sodversion[32];
8655 char *env_proxy = NULL;
8656 char *path;
8657 FILE *f = NULL;
8658 struct karg a;
8660 start_argv = (char * const *)argv;
8662 if (os_init)
8663 os_init();
8665 /* prepare gtk */
8666 #ifdef USE_THREADS
8667 #if !defined __MINGW32__
8668 /* http://web.archiveorange.com/archive/v/UsPjxkX5PsaXBIoOjqxf */
8669 XInitThreads();
8670 #endif
8671 /* http://developer.gnome.org/gdk/stable/gdk-Threads.html */
8672 g_thread_init(NULL);
8673 gdk_threads_set_lock_functions(mtx_lock, mtx_unlock);
8674 gdk_threads_init();
8675 gdk_threads_enter();
8677 /* http://www.gnupg.org/documentation/manuals/gcrypt/Multi_002dThreading.html */
8678 gcry_control (GCRYCTL_SET_THREAD_CBS, &gcry_threads_pthread);
8679 #endif
8680 gtk_init(&argc, &argv);
8682 gnutls_global_init();
8684 strlcpy(named_session, XT_SAVED_TABS_FILE, sizeof named_session);
8686 RB_INIT(&hl);
8687 RB_INIT(&downloads);
8688 RB_INIT(&st_tree);
8689 RB_INIT(&svl);
8690 RB_INIT(&ua_list);
8691 RB_INIT(&ha_list);
8692 RB_INIT(&di_list);
8694 TAILQ_INIT(&sessions);
8695 TAILQ_INIT(&tabs);
8696 TAILQ_INIT(&mtl);
8697 TAILQ_INIT(&aliases);
8698 TAILQ_INIT(&undos);
8699 TAILQ_INIT(&kbl);
8700 TAILQ_INIT(&spl);
8701 TAILQ_INIT(&chl);
8702 TAILQ_INIT(&shl);
8703 TAILQ_INIT(&cul);
8704 TAILQ_INIT(&srl);
8705 TAILQ_INIT(&c_wl);
8706 TAILQ_INIT(&js_wl);
8707 TAILQ_INIT(&pl_wl);
8708 TAILQ_INIT(&force_https);
8709 TAILQ_INIT(&svil);
8711 #ifndef XT_RESOURCE_LIMITS_DISABLE
8712 struct rlimit rlp;
8713 char *cmd = NULL;
8714 int s;
8715 GIOChannel *channel;
8717 /* fiddle with ulimits */
8718 if (getrlimit(RLIMIT_NOFILE, &rlp) == -1)
8719 warn("getrlimit");
8720 else {
8721 /* just use them all */
8722 rlp.rlim_cur = rlp.rlim_max;
8723 if (setrlimit(RLIMIT_NOFILE, &rlp) == -1)
8724 warn("setrlimit");
8725 if (getrlimit(RLIMIT_NOFILE, &rlp) == -1)
8726 warn("getrlimit");
8727 else if (rlp.rlim_cur < 1024)
8728 startpage_add("%s requires at least 1024 "
8729 "(2048 recommended) file " "descriptors, "
8730 "currently it has up to %d available",
8731 __progname, rlp.rlim_cur);
8733 #endif
8735 while ((c = getopt(argc, argv, "STVf:s:tne")) != -1) {
8736 switch (c) {
8737 case 'S':
8738 show_url = 0;
8739 break;
8740 case 'T':
8741 show_tabs = 0;
8742 break;
8743 case 'V':
8744 #ifdef XOMBRERO_BUILDSTR
8745 errx(0 , "Version: %s Build: %s",
8746 version, XOMBRERO_BUILDSTR);
8747 #else
8748 errx(0 , "Version: %s", version);
8749 #endif
8750 break;
8751 case 'f':
8752 strlcpy(conf, optarg, sizeof(conf));
8753 break;
8754 case 's':
8755 strlcpy(named_session, optarg, sizeof(named_session));
8756 break;
8757 case 't':
8758 tabless = 1;
8759 break;
8760 case 'n':
8761 optn = 1;
8762 break;
8763 case 'e':
8764 opte = 1;
8765 break;
8766 default:
8767 usage();
8768 /* NOTREACHED */
8771 argc -= optind;
8772 argv += optind;
8774 init_keybindings();
8776 pwd = getpwuid(getuid());
8777 if (pwd == NULL)
8778 errx(1, "invalid user %d", getuid());
8780 /* set download dir */
8781 if (strlen(download_dir) == 0)
8782 strlcpy(download_dir, pwd->pw_dir, sizeof download_dir);
8784 /* compile buffer command regexes */
8785 buffercmd_init();
8787 /* set default dynamic string settings */
8788 home = g_strdup(XT_DS_HOME);
8789 search_string = g_strdup(XT_DS_SEARCH_STRING);
8790 strlcpy(runtime_settings, "runtime", sizeof runtime_settings);
8791 cmd_font_name = g_strdup(XT_DS_CMD_FONT_NAME);
8792 oops_font_name = g_strdup(XT_DS_OOPS_FONT_NAME);
8793 statusbar_font_name = g_strdup(XT_DS_STATUSBAR_FONT_NAME);
8794 tabbar_font_name = g_strdup(XT_DS_TABBAR_FONT_NAME);
8795 statusbar_elems = g_strdup("BP");
8796 spell_check_languages = g_strdup(XT_DS_SPELL_CHECK_LANGUAGES);
8797 encoding = g_strdup(XT_DS_ENCODING);
8798 spell_check_languages = g_strdup(XT_DS_SPELL_CHECK_LANGUAGES);
8799 path = g_strdup_printf("%s" PS "style.css", resource_dir);
8800 userstyle = g_filename_to_uri(path, NULL, NULL);
8801 g_free(path);
8802 stylesheet = g_strdup(userstyle);
8804 /* set statically allocated (struct special) settings */
8805 if (strlen(default_script) == 0)
8806 expand_tilde(default_script, sizeof default_script,
8807 XT_DS_DEFAULT_SCRIPT);
8808 if (strlen(ssl_ca_file) == 0)
8809 expand_tilde(ssl_ca_file, sizeof ssl_ca_file,
8810 XT_DS_SSL_CA_FILE);
8812 /* soup session */
8813 session = webkit_get_default_session();
8815 /* read config file */
8816 if (strlen(conf) == 0)
8817 snprintf(conf, sizeof conf, "%s" PS ".%s",
8818 pwd->pw_dir, XT_CONF_FILE);
8819 config_parse(conf, 0);
8821 /* read preloaded HSTS list */
8822 if (preload_strict_transport) {
8823 snprintf(conf, sizeof conf, "%s" PS "%s",
8824 resource_dir, XT_HSTS_PRELOAD_FILE);
8825 config_parse(conf, 0);
8828 /* check whether to read in a crapton of additional http headers */
8829 if (anonymize_headers) {
8830 snprintf(conf, sizeof conf, "%s" PS "%s",
8831 resource_dir, XT_USER_AGENT_FILE);
8832 config_parse(conf, 0);
8833 snprintf(conf, sizeof conf, "%s" PS "%s",
8834 resource_dir, XT_HTTP_ACCEPT_FILE);
8835 config_parse(conf, 0);
8838 /* init fonts */
8839 cmd_font = pango_font_description_from_string(cmd_font_name);
8840 oops_font = pango_font_description_from_string(oops_font_name);
8841 statusbar_font = pango_font_description_from_string(statusbar_font_name);
8842 tabbar_font = pango_font_description_from_string(tabbar_font_name);
8844 /* working directory */
8845 if (strlen(work_dir) == 0)
8846 snprintf(work_dir, sizeof work_dir, "%s" PS "%s",
8847 pwd->pw_dir, XT_DIR);
8848 xxx_dir(work_dir);
8850 /* icon cache dir */
8851 snprintf(cache_dir, sizeof cache_dir, "%s" PS "%s", work_dir, XT_CACHE_DIR);
8852 xxx_dir(cache_dir);
8854 /* certs dir */
8855 snprintf(certs_dir, sizeof certs_dir, "%s" PS "%s", work_dir, XT_CERT_DIR);
8856 xxx_dir(certs_dir);
8858 /* cert changes dir */
8859 snprintf(certs_cache_dir, sizeof certs_cache_dir, "%s" PS "%s",
8860 work_dir, XT_CERT_CACHE_DIR);
8861 xxx_dir(certs_cache_dir);
8863 /* sessions dir */
8864 snprintf(sessions_dir, sizeof sessions_dir, "%s" PS "%s",
8865 work_dir, XT_SESSIONS_DIR);
8866 xxx_dir(sessions_dir);
8868 /* js dir */
8869 snprintf(js_dir, sizeof js_dir, "%s" PS "%s", work_dir, XT_JS_DIR);
8870 xxx_dir(js_dir);
8872 /* temp dir */
8873 snprintf(temp_dir, sizeof temp_dir, "%s" PS "%s", work_dir, XT_TEMP_DIR);
8874 xxx_dir(temp_dir);
8876 /* runtime settings that can override config file */
8877 if (runtime_settings[0] != '\0')
8878 config_parse(runtime_settings, 1);
8880 /* download dir */
8881 if (!strcmp(download_dir, pwd->pw_dir))
8882 strlcat(download_dir, PS "downloads", sizeof download_dir);
8883 xxx_dir(download_dir);
8885 /* first start file */
8886 snprintf(file, sizeof file, "%s" PS "%s", work_dir, XT_SOD_FILE);
8887 if (stat(file, &sb)) {
8888 warnx("start of day file doesn't exist, creating it");
8889 if ((f = fopen(file, "w")) == NULL)
8890 err(1, "startofday");
8891 if (fputs(version, f) == EOF)
8892 err(1, "fputs");
8893 fclose(f);
8895 /* welcome user */
8896 welcome();
8897 } else {
8898 if ((f = fopen(file, "r+")) == NULL)
8899 err(1, "startofday");
8900 if (fgets(sodversion, sizeof sodversion, f) == NULL)
8901 err(1, "fgets");
8902 sodversion[strcspn(sodversion, "\n")] = '\0';
8903 if (strcmp(version, sodversion)) {
8904 if ((f = freopen(file, "w", f)) == NULL)
8905 err(1, "startofday");
8906 if (fputs(version, f) == EOF)
8907 err(1, "fputs");
8909 /* upgrade, say something smart */
8910 welcome();
8912 fclose(f);
8915 /* favorites file */
8916 snprintf(file, sizeof file, "%s" PS "%s", work_dir, XT_FAVS_FILE);
8917 if (stat(file, &sb)) {
8918 warnx("favorites file doesn't exist, creating it");
8919 if ((f = fopen(file, "w")) == NULL)
8920 err(1, "favorites");
8921 fclose(f);
8924 /* quickmarks file */
8925 snprintf(file, sizeof file, "%s" PS "%s", work_dir, XT_QMARKS_FILE);
8926 if (stat(file, &sb)) {
8927 warnx("quickmarks file doesn't exist, creating it");
8928 if ((f = fopen(file, "w")) == NULL)
8929 err(1, "quickmarks");
8930 fclose(f);
8933 /* search history */
8934 if (history_autosave) {
8935 snprintf(search_file, sizeof search_file, "%s" PS "%s",
8936 work_dir, XT_SEARCH_FILE);
8937 if (stat(search_file, &sb)) {
8938 warnx("search history file doesn't exist, creating it");
8939 if ((f = fopen(search_file, "w")) == NULL)
8940 err(1, "search_history");
8941 fclose(f);
8943 history_read(&shl, search_file, &search_history_count);
8946 /* command history */
8947 if (history_autosave) {
8948 snprintf(command_file, sizeof command_file, "%s" PS "%s",
8949 work_dir, XT_COMMAND_FILE);
8950 if (stat(command_file, &sb)) {
8951 warnx("command history file doesn't exist, creating it");
8952 if ((f = fopen(command_file, "w")) == NULL)
8953 err(1, "command_history");
8954 fclose(f);
8956 history_read(&chl, command_file, &cmd_history_count);
8959 /* cookies */
8960 setup_cookies();
8962 /* guess_search regex */
8963 if (url_regex == NULL)
8964 url_regex = g_strdup(XT_URL_REGEX);
8965 if (url_regex)
8966 if (regcomp(&url_re, url_regex, REG_EXTENDED | REG_NOSUB))
8967 startpage_add("invalid url regex %s", url_regex);
8969 /* proxy */
8970 env_proxy = getenv("http_proxy");
8971 if (env_proxy)
8972 setup_proxy(env_proxy);
8973 else {
8974 env_proxy = getenv("HTTP_PROXY");
8975 if (env_proxy)
8976 setup_proxy(env_proxy);
8977 else
8978 setup_proxy(http_proxy);
8981 /* the user can optionally have the proxy disabled at startup */
8982 if ((http_proxy_starts_enabled == 0) && (http_proxy != NULL)) {
8983 http_proxy_save = g_strdup(http_proxy);
8984 setup_proxy(NULL);
8987 #ifndef XT_SOCKET_DISABLE
8988 if (opte) {
8989 send_cmd_to_socket(argv[0]);
8990 exit(0);
8992 #else
8993 opte = opte; /* shut mingw up */
8994 #endif
8995 /* set some connection parameters */
8996 g_object_set(session, "max-conns", max_connections, (char *)NULL);
8997 g_object_set(session, "max-conns-per-host", max_host_connections,
8998 (char *)NULL);
8999 g_object_set(session, SOUP_SESSION_SSL_STRICT, ssl_strict_certs,
9000 (char *)NULL);
9002 g_signal_connect(session, "request-queued", G_CALLBACK(session_rq_cb),
9003 NULL);
9005 #ifndef XT_SOCKET_DISABLE
9006 /* see if there is already a xombrero running */
9007 if (single_instance && is_running()) {
9008 optn = 1;
9009 warnx("already running");
9012 if (optn) {
9013 while (argc) {
9014 cmd = g_strdup_printf("%s %s", "tabnew", argv[0]);
9015 send_cmd_to_socket(cmd);
9016 if (cmd)
9017 g_free(cmd);
9019 argc--;
9020 argv++;
9022 exit(0);
9024 #else
9025 optn = optn; /* shut mingw up */
9026 #endif
9027 /* tld list */
9028 tld_tree_init();
9030 if (enable_strict_transport)
9031 strict_transport_init();
9033 /* uri completion */
9034 completion_model = gtk_list_store_new(1, G_TYPE_STRING);
9036 /* buffers */
9037 buffers_store = gtk_list_store_new
9038 (NUM_COLS, G_TYPE_UINT, GDK_TYPE_PIXBUF, G_TYPE_STRING);
9040 qmarks_load();
9042 /* go graphical */
9043 create_canvas();
9044 notebook_tab_set_visibility();
9046 if (save_global_history)
9047 restore_global_history();
9049 /* restore session list */
9050 restore_sessions_list();
9052 if (!strcmp(named_session, XT_SAVED_TABS_FILE))
9053 restore_saved_tabs();
9054 else {
9055 a.s = named_session;
9056 a.i = XT_SES_DONOTHING;
9057 open_tabs(NULL, &a);
9060 /* see if we have an exception */
9061 if (!TAILQ_EMPTY(&spl)) {
9062 create_new_tab("about:startpage", NULL, focus, -1);
9063 focus = 0;
9066 while (argc) {
9067 create_new_tab(argv[0], NULL, focus, -1);
9068 focus = 0;
9070 argc--;
9071 argv++;
9074 if (TAILQ_EMPTY(&tabs))
9075 create_new_tab(home, NULL, 1, -1);
9076 #ifndef XT_SOCKET_DISABLE
9077 if (enable_socket)
9078 if ((s = build_socket()) != -1) {
9079 channel = g_io_channel_unix_new(s);
9080 g_io_add_watch(channel, G_IO_IN, socket_watcher, NULL);
9082 #endif
9084 #if GTK_CHECK_VERSION(3, 0, 0)
9085 setup_css();
9086 #endif
9088 gtk_main();
9090 #ifdef USE_THREADS
9091 GDK_FLUSH();
9092 gdk_threads_leave();
9093 g_static_rec_mutex_unlock_full(&my_gdk_mtx); /* just in case */
9094 #endif
9096 gnutls_global_deinit();
9098 if (url_regex)
9099 regfree(&url_re);
9101 return (0);