xtp-meaning freed memory usage fix
[xombrero.git] / xombrero.c
blob35d3911b84bc181b85a4fd78c7a4deb792e6e923
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, 2013 Josh Rickmar <jrick@devio.us>
9 * Copyright (c) 2013 David Hill <dhill@mindcry.org>
11 * Permission to use, copy, modify, and distribute this software for any
12 * purpose with or without fee is hereby granted, provided that the above
13 * copyright notice and this permission notice appear in all copies.
15 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
16 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
17 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
18 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
19 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
20 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
21 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
24 #include <xombrero.h>
25 #include "version.h"
27 char *version = XOMBRERO_VERSION;
29 #ifdef XT_DEBUG
30 uint32_t swm_debug = 0
31 | XT_D_MOVE
32 | XT_D_KEY
33 | XT_D_TAB
34 | XT_D_URL
35 | XT_D_CMD
36 | XT_D_NAV
37 | XT_D_DOWNLOAD
38 | XT_D_CONFIG
39 | XT_D_JS
40 | XT_D_FAVORITE
41 | XT_D_PRINTING
42 | XT_D_COOKIE
43 | XT_D_KEYBINDING
44 | XT_D_CLIP
45 | XT_D_BUFFERCMD
46 | XT_D_INSPECTOR
47 | XT_D_VISITED
48 | XT_D_HISTORY
50 #endif
52 char *icons[] = {
53 "xombreroicon16.png",
54 "xombreroicon32.png",
55 "xombreroicon48.png",
56 "xombreroicon64.png",
57 "xombreroicon128.png"
60 struct session {
61 TAILQ_ENTRY(session) entry;
62 const gchar *name;
64 TAILQ_HEAD(session_list, session);
66 struct undo {
67 TAILQ_ENTRY(undo) entry;
68 gchar *uri;
69 GList *history;
70 int back; /* Keeps track of how many back
71 * history items there are. */
73 TAILQ_HEAD(undo_tailq, undo);
75 struct command_entry {
76 char *line;
77 TAILQ_ENTRY(command_entry) entry;
79 TAILQ_HEAD(command_list, command_entry);
81 /* defines */
82 #define XT_CACHE_DIR ("cache")
83 #define XT_CERT_DIR ("certs")
84 #define XT_CERT_CACHE_DIR ("certs_cache")
85 #define XT_JS_DIR ("js")
86 #define XT_SESSIONS_DIR ("sessions")
87 #define XT_TEMP_DIR ("tmp")
88 #define XT_QMARKS_FILE ("quickmarks")
89 #define XT_SAVED_TABS_FILE ("main_session")
90 #define XT_RESTART_TABS_FILE ("restart_tabs")
91 #define XT_SOCKET_FILE ("socket")
92 #define XT_SAVE_SESSION_ID ("SESSION_NAME=")
93 #define XT_SEARCH_FILE ("search_history")
94 #define XT_COMMAND_FILE ("command_history")
95 #define XT_DLMAN_REFRESH "10"
96 #define XT_MAX_URL_LENGTH (4096) /* 1 page is atomic, don't make bigger */
97 #define XT_MAX_UNDO_CLOSE_TAB (32)
98 #define XT_PRINT_EXTRA_MARGIN 10
99 #define XT_URL_REGEX ("^[[:blank:]]*[^[:blank:]]*([[:alnum:]-]+\\.)+[[:alnum:]-][^[:blank:]]*[[:blank:]]*$")
100 #define XT_INVALID_MARK (-1) /* XXX this is a double, maybe use something else, like a nan */
101 #define XT_MAX_CERTS (32)
103 /* colors */
104 #define XT_COLOR_RED "#cc0000"
105 #define XT_COLOR_YELLOW "#ffff66"
106 #define XT_COLOR_BLUE "lightblue"
107 #define XT_COLOR_GREEN "#99ff66"
108 #define XT_COLOR_WHITE "white"
109 #define XT_COLOR_BLACK "black"
111 #define XT_COLOR_CT_BACKGROUND "#000000"
112 #define XT_COLOR_CT_INACTIVE "#dddddd"
113 #define XT_COLOR_CT_ACTIVE "#bbbb00"
114 #define XT_COLOR_CT_SEPARATOR "#555555"
116 #define XT_COLOR_SB_SEPARATOR "#555555"
118 /* CSS element names */
119 #define XT_CSS_NORMAL ""
120 #define XT_CSS_RED "red"
121 #define XT_CSS_YELLOW "yellow"
122 #define XT_CSS_GREEN "green"
123 #define XT_CSS_BLUE "blue"
124 #define XT_CSS_HIDDEN "hidden"
125 #define XT_CSS_ACTIVE "active"
127 #define XT_PROTO_DELIM "://"
129 /* actions */
130 #define XT_MOVE_INVALID (0)
131 #define XT_MOVE_DOWN (1)
132 #define XT_MOVE_UP (2)
133 #define XT_MOVE_BOTTOM (3)
134 #define XT_MOVE_TOP (4)
135 #define XT_MOVE_PAGEDOWN (5)
136 #define XT_MOVE_PAGEUP (6)
137 #define XT_MOVE_HALFDOWN (7)
138 #define XT_MOVE_HALFUP (8)
139 #define XT_MOVE_LEFT (9)
140 #define XT_MOVE_FARLEFT (10)
141 #define XT_MOVE_RIGHT (11)
142 #define XT_MOVE_FARRIGHT (12)
143 #define XT_MOVE_PERCENT (13)
144 #define XT_MOVE_CENTER (14)
146 #define XT_QMARK_SET (0)
147 #define XT_QMARK_OPEN (1)
148 #define XT_QMARK_TAB (2)
150 #define XT_MARK_SET (0)
151 #define XT_MARK_GOTO (1)
153 #define XT_GO_UP_ROOT (999)
155 #define XT_NAV_INVALID (0)
156 #define XT_NAV_BACK (1)
157 #define XT_NAV_FORWARD (2)
158 #define XT_NAV_RELOAD (3)
159 #define XT_NAV_STOP (4)
161 #define XT_FOCUS_INVALID (0)
162 #define XT_FOCUS_URI (1)
163 #define XT_FOCUS_SEARCH (2)
165 #define XT_SEARCH_INVALID (0)
166 #define XT_SEARCH_NEXT (1)
167 #define XT_SEARCH_PREV (2)
169 #define XT_PASTE_CURRENT_TAB (0)
170 #define XT_PASTE_NEW_TAB (1)
172 #define XT_ZOOM_IN (-1)
173 #define XT_ZOOM_OUT (-2)
174 #define XT_ZOOM_NORMAL (100)
176 #define XT_SES_DONOTHING (0)
177 #define XT_SES_CLOSETABS (1)
179 #define XT_PREFIX (1<<0)
180 #define XT_USERARG (1<<1)
181 #define XT_URLARG (1<<2)
182 #define XT_INTARG (1<<3)
183 #define XT_SESSARG (1<<4)
184 #define XT_SETARG (1<<5)
186 #define XT_HINT_NEWTAB (1<<0)
188 #define XT_BUFCMD_SZ (8)
190 #define XT_EJS_SHOW (1<<0)
192 GtkWidget * create_button(const char *, const char *, int);
194 void recalc_tabs(void);
195 void recolor_compact_tabs(void);
196 void set_current_tab(int page_num);
197 gboolean update_statusbar_position(GtkAdjustment*, gpointer);
198 void marks_clear(struct tab *t);
200 /* globals */
201 extern char *__progname;
202 char * const *start_argv;
203 struct passwd *pwd;
204 GtkWidget *main_window;
205 GtkNotebook *notebook;
206 GtkWidget *tab_bar;
207 GtkWidget *tab_bar_box;
208 GtkWidget *arrow, *abtn;
209 GdkEvent *fevent = NULL;
210 struct tab_list tabs;
211 struct history_list hl;
212 int hl_purge_count = 0;
213 struct session_list sessions;
214 struct wl_list c_wl;
215 struct wl_list js_wl;
216 struct wl_list pl_wl;
217 struct wl_list force_https;
218 struct wl_list svil;
219 struct strict_transport_tree st_tree;
220 struct undo_tailq undos;
221 struct keybinding_list kbl;
222 struct sp_list spl;
223 struct user_agent_list ua_list;
224 struct http_accept_list ha_list;
225 struct domain_id_list di_list;
226 struct cmd_alias_list cal;
227 struct custom_uri_list cul;
228 struct command_list chl;
229 struct command_list shl;
230 struct command_entry *history_at;
231 struct command_entry *search_at;
232 struct secviolation_list svl;
233 struct set_reject_list srl;
234 int undo_count;
235 int cmd_history_count = 0;
236 int search_history_count = 0;
237 char *global_search;
238 uint64_t blocked_cookies = 0;
239 char named_session[PATH_MAX];
240 GtkListStore *completion_model;
241 GtkListStore *buffers_store;
242 char *stylesheet;
244 char *qmarks[XT_NOQMARKS];
245 int btn_down; /* M1 down in any wv */
246 regex_t url_re; /* guess_search regex */
248 /* starts from 1 to catch atoi() failures when calling xtp_handle_dl() */
249 int next_download_id = 1;
251 void xxx_dir(char *);
252 int icon_size_map(int);
253 void activate_uri_entry_cb(GtkWidget*, struct tab *);
254 void activate_search_entry_cb(GtkWidget*, struct tab *);
256 void
257 history_delete(struct command_list *l, int *counter)
259 struct command_entry *c;
261 if (l == NULL || counter == NULL)
262 return;
264 c = TAILQ_LAST(l, command_list);
265 if (c == NULL)
266 return;
268 TAILQ_REMOVE(l, c, entry);
269 *counter -= 1;
270 g_free(c->line);
271 g_free(c);
274 void
275 history_add(struct command_list *list, char *file, char *l, int *counter)
277 struct command_entry *c;
278 FILE *f;
280 if (list == NULL || l == NULL || counter == NULL)
281 return;
283 /* don't add the same line */
284 c = TAILQ_FIRST(list);
285 if (c)
286 if (!strcmp(c->line + 1 /* skip space */, l))
287 return;
289 c = g_malloc0(sizeof *c);
290 c->line = g_strdup_printf(" %s", l);
292 *counter += 1;
293 TAILQ_INSERT_HEAD(list, c, entry);
295 if (*counter > 1000)
296 history_delete(list, counter);
298 if (history_autosave && file) {
299 f = fopen(file, "w");
300 if (f == NULL) {
301 show_oops(NULL, "couldn't write history %s", file);
302 return;
305 TAILQ_FOREACH_REVERSE(c, list, command_list, entry) {
306 c->line[0] = ' ';
307 fprintf(f, "%s\n", c->line);
310 fclose(f);
315 history_read(struct command_list *list, char *file, int *counter)
317 FILE *f;
318 char *s, line[65536];
320 if (list == NULL || file == NULL)
321 return (1);
323 f = fopen(file, "r");
324 if (f == NULL) {
325 startpage_add("couldn't open history file %s", file);
326 return (1);
329 for (;;) {
330 s = fgets(line, sizeof line, f);
331 if (s == NULL || feof(f) || ferror(f))
332 break;
333 if ((s = strchr(line, '\n')) == NULL) {
334 startpage_add("invalid history file %s", file);
335 fclose(f);
336 return (1);
338 *s = '\0';
340 history_add(list, NULL, line + 1, counter);
343 fclose(f);
345 return (0);
348 /* marks array storage. */
349 char
350 indextomark(int i)
352 if (i < 0 || i >= XT_NOMARKS)
353 return (0);
355 return XT_MARKS[i];
359 marktoindex(char m)
361 char *ret;
363 if ((ret = strchr(XT_MARKS, m)) != NULL)
364 return ret - XT_MARKS;
366 return (-1);
369 /* quickmarks array storage. */
370 char
371 indextoqmark(int i)
373 if (i < 0 || i >= XT_NOQMARKS)
374 return (0);
376 return XT_QMARKS[i];
380 qmarktoindex(char m)
382 char *ret;
384 if ((ret = strchr(XT_QMARKS, m)) != NULL)
385 return ret - XT_QMARKS;
387 return (-1);
391 is_g_object_setting(GObject *o, char *str)
393 guint n_props = 0, i;
394 GParamSpec **proplist;
395 int rv = 0;
397 if (!G_IS_OBJECT(o))
398 return (0);
400 proplist = g_object_class_list_properties(G_OBJECT_GET_CLASS(o),
401 &n_props);
403 for (i = 0; i < n_props; i++) {
404 if (! strcmp(proplist[i]->name, str)) {
405 rv = 1;
406 break;
410 g_free(proplist);
411 return (rv);
414 struct tab *
415 get_current_tab(void)
417 struct tab *t;
419 TAILQ_FOREACH(t, &tabs, entry) {
420 if (t->tab_id == gtk_notebook_get_current_page(notebook))
421 return (t);
424 warnx("%s: no current tab", __func__);
426 return (NULL);
430 set_ssl_ca_file(struct settings *s, char *file)
432 struct stat sb;
434 if (file == NULL || strlen(file) == 0)
435 return (-1);
436 if (stat(file, &sb)) {
437 warnx("no CA file: %s", file);
438 return (-1);
440 expand_tilde(ssl_ca_file, sizeof ssl_ca_file, file);
441 g_object_set(session,
442 SOUP_SESSION_SSL_CA_FILE, ssl_ca_file,
443 SOUP_SESSION_SSL_STRICT, ssl_strict_certs,
444 (void *)NULL);
445 return (0);
448 void
449 set_status(struct tab *t, gchar *fmt, ...)
451 va_list ap;
452 gchar *status;
454 va_start(ap, fmt);
456 status = g_strdup_vprintf(fmt, ap);
458 gtk_entry_set_text(GTK_ENTRY(t->sbe.uri), status);
460 if (!t->status)
461 t->status = status;
462 else if (strcmp(t->status, status)) {
463 /* set new status */
464 g_free(t->status);
465 t->status = status;
466 } else
467 g_free(status);
469 va_end(ap);
472 void
473 hide_cmd(struct tab *t)
475 DNPRINTF(XT_D_CMD, "%s: tab %d\n", __func__, t->tab_id);
477 history_at = NULL; /* just in case */
478 search_at = NULL; /* just in case */
479 gtk_widget_set_can_focus(t->cmd, FALSE);
480 gtk_widget_hide(t->cmd);
483 void
484 show_cmd(struct tab *t, const char *s)
486 DNPRINTF(XT_D_CMD, "%s: tab %d\n", __func__, t->tab_id);
488 /* without this you can't middle click in t->cmd to paste */
489 gtk_entry_set_text(GTK_ENTRY(t->cmd), "");
491 history_at = NULL;
492 search_at = NULL;
493 gtk_widget_hide(t->oops);
494 gtk_widget_set_can_focus(t->cmd, TRUE);
495 gtk_widget_show(t->cmd);
497 gtk_widget_grab_focus(GTK_WIDGET(t->cmd));
498 #if GTK_CHECK_VERSION(3, 0, 0)
499 gtk_widget_set_name(t->cmd, XT_CSS_NORMAL);
500 #else
501 gtk_widget_modify_base(t->cmd, GTK_STATE_NORMAL,
502 &t->default_style->base[GTK_STATE_NORMAL]);
503 #endif
504 gtk_entry_set_text(GTK_ENTRY(t->cmd), s);
505 gtk_editable_set_position(GTK_EDITABLE(t->cmd), -1);
508 void
509 hide_buffers(struct tab *t)
511 gtk_widget_hide(t->buffers);
512 gtk_widget_set_can_focus(t->buffers, FALSE);
513 gtk_list_store_clear(buffers_store);
516 enum {
517 COL_ID = 0,
518 COL_FAVICON,
519 COL_TITLE,
520 NUM_COLS
524 sort_tabs_by_page_num(struct tab ***stabs)
526 int num_tabs = 0;
527 struct tab *t;
529 num_tabs = gtk_notebook_get_n_pages(notebook);
531 *stabs = g_malloc0(num_tabs * sizeof(struct tab *));
533 TAILQ_FOREACH(t, &tabs, entry)
534 (*stabs)[gtk_notebook_page_num(notebook, t->vbox)] = t;
536 return (num_tabs);
539 void
540 buffers_make_list(void)
542 GtkTreeIter iter;
543 const gchar *title = NULL;
544 struct tab **stabs = NULL;
545 int i, num_tabs;
547 num_tabs = sort_tabs_by_page_num(&stabs);
549 for (i = 0; i < num_tabs; i++)
550 if (stabs[i]) {
551 gtk_list_store_append(buffers_store, &iter);
552 title = get_title(stabs[i], FALSE);
553 gtk_list_store_set(buffers_store, &iter,
554 COL_ID, i + 1, /* Enumerate the tabs starting from 1
555 * rather than 0. */
556 COL_FAVICON, gtk_image_get_pixbuf
557 (GTK_IMAGE(stabs[i]->tab_elems.favicon)),
558 COL_TITLE, title,
559 -1);
562 g_free(stabs);
565 void
566 show_buffers(struct tab *t)
568 GtkTreeIter iter;
569 GtkTreeSelection *sel;
570 GtkTreePath *path;
571 int index;
573 if (gtk_widget_get_visible(GTK_WIDGET(t->buffers)))
574 return;
576 buffers_make_list();
578 sel = gtk_tree_view_get_selection(GTK_TREE_VIEW(t->buffers));
579 index = gtk_notebook_get_current_page(notebook);
580 path = gtk_tree_path_new_from_indices(index, -1);
581 if (gtk_tree_model_get_iter(GTK_TREE_MODEL(buffers_store), &iter, path))
582 gtk_tree_selection_select_iter(sel, &iter);
583 gtk_tree_path_free(path);
585 gtk_widget_show(t->buffers);
586 gtk_widget_set_can_focus(t->buffers, TRUE);
587 gtk_widget_grab_focus(GTK_WIDGET(t->buffers));
590 void
591 toggle_buffers(struct tab *t)
593 if (gtk_widget_get_visible(t->buffers))
594 hide_buffers(t);
595 else
596 show_buffers(t);
600 buffers(struct tab *t, struct karg *args)
602 show_buffers(t);
604 return (0);
608 set_scrollbar_visibility(struct tab *t, int visible)
610 #if GTK_CHECK_VERSION(3, 0, 0)
611 GtkWidget *h_scrollbar, *v_scrollbar;
613 h_scrollbar = gtk_scrolled_window_get_hscrollbar(
614 GTK_SCROLLED_WINDOW(t->browser_win));
615 v_scrollbar = gtk_scrolled_window_get_vscrollbar(
616 GTK_SCROLLED_WINDOW(t->browser_win));
618 if (visible == 0) {
619 gtk_widget_set_name(h_scrollbar, XT_CSS_HIDDEN);
620 gtk_widget_set_name(v_scrollbar, XT_CSS_HIDDEN);
621 } else {
622 gtk_widget_set_name(h_scrollbar, "");
623 gtk_widget_set_name(v_scrollbar, "");
626 return (0);
627 #else
628 return (visible == 0);
629 #endif
632 void
633 hide_oops(struct tab *t)
635 gtk_widget_hide(t->oops);
638 void
639 show_oops(struct tab *at, const char *fmt, ...)
641 va_list ap;
642 char *msg = NULL;
643 struct tab *t = NULL;
645 if (fmt == NULL)
646 return;
648 if (at == NULL) {
649 if ((t = get_current_tab()) == NULL)
650 return;
651 } else
652 t = at;
654 va_start(ap, fmt);
655 if ((msg = g_strdup_vprintf(fmt, ap)) == NULL)
656 errx(1, "show_oops failed");
657 va_end(ap);
659 gtk_entry_set_text(GTK_ENTRY(t->oops), msg);
660 gtk_widget_hide(t->cmd);
661 gtk_widget_show(t->oops);
663 if (msg)
664 g_free(msg);
667 char work_dir[PATH_MAX];
668 char certs_dir[PATH_MAX];
669 char certs_cache_dir[PATH_MAX];
670 char js_dir[PATH_MAX];
671 char cache_dir[PATH_MAX];
672 char sessions_dir[PATH_MAX];
673 char temp_dir[PATH_MAX];
674 char cookie_file[PATH_MAX];
675 char *strict_transport_file = NULL;
676 SoupSession *session;
677 SoupCookieJar *s_cookiejar;
678 SoupCookieJar *p_cookiejar;
679 char rc_fname[PATH_MAX];
681 struct mime_type_list mtl;
682 struct alias_list aliases;
684 /* protos */
685 struct tab *create_new_tab(const char *, struct undo *, int, int);
686 void delete_tab(struct tab *);
687 void setzoom_webkit(struct tab *, int);
688 int download_rb_cmp(struct download *, struct download *);
689 gboolean cmd_execute(struct tab *t, char *str);
692 history_rb_cmp(struct history *h1, struct history *h2)
694 return (strcmp(h1->uri, h2->uri));
696 RB_GENERATE(history_list, history, entry, history_rb_cmp);
699 download_rb_cmp(struct download *e1, struct download *e2)
701 return (e1->id < e2->id ? -1 : e1->id > e2->id);
703 RB_GENERATE(download_list, download, entry, download_rb_cmp);
706 secviolation_rb_cmp(struct secviolation *s1, struct secviolation *s2)
708 return (s1->xtp_arg < s2->xtp_arg ? -1 : s1->xtp_arg > s2->xtp_arg);
710 RB_GENERATE(secviolation_list, secviolation, entry, secviolation_rb_cmp);
713 user_agent_rb_cmp(struct user_agent *ua1, struct user_agent *ua2)
715 return (ua1->id < ua2->id ? -1 : ua1->id > ua2->id);
717 RB_GENERATE(user_agent_list, user_agent, entry, user_agent_rb_cmp);
720 http_accept_rb_cmp(struct http_accept *ha1, struct http_accept *ha2)
722 return (ha1->id < ha2->id ? -1 : ha1->id > ha2->id);
724 RB_GENERATE(http_accept_list, http_accept, entry, http_accept_rb_cmp);
727 domain_id_rb_cmp(struct domain_id *d1, struct domain_id *d2)
729 return (strcmp(d1->domain, d2->domain));
731 RB_GENERATE(domain_id_list, domain_id, entry, domain_id_rb_cmp);
733 struct valid_url_types {
734 char *type;
735 } vut[] = {
736 { "http://" },
737 { "https://" },
738 { "ftp://" },
739 { "file://" },
740 { XT_URI_ABOUT },
741 { XT_XTP_STR },
745 valid_url_type(const char *url)
747 int i;
749 for (i = 0; i < LENGTH(vut); i++)
750 if (!strncasecmp(vut[i].type, url, strlen(vut[i].type)))
751 return (0);
753 return (1);
756 char *
757 match_alias(const char *url_in)
759 struct alias *a;
760 char *arg;
761 char *url_out = NULL, *search, *enc_arg;
762 char **sv;
764 search = g_strdup(url_in);
765 arg = search;
766 if (strsep(&arg, " \t") == NULL) {
767 show_oops(NULL, "match_alias: NULL URL");
768 goto done;
771 TAILQ_FOREACH(a, &aliases, entry) {
772 if (!strcmp(search, a->a_name))
773 break;
776 if (a != NULL) {
777 DNPRINTF(XT_D_URL, "match_alias: matched alias %s\n",
778 a->a_name);
779 if (arg == NULL)
780 arg = "";
781 enc_arg = soup_uri_encode(arg, XT_RESERVED_CHARS);
782 sv = g_strsplit(a->a_uri, "%s", 2);
783 if (arg != NULL)
784 url_out = g_strjoinv(enc_arg, sv);
785 else
786 url_out = g_strjoinv("", sv);
787 g_free(enc_arg);
788 g_strfreev(sv);
790 done:
791 g_free(search);
792 return (url_out);
795 char *
796 guess_url_type(const char *url_in)
798 struct stat sb;
799 char cwd[PATH_MAX] = {0};
800 char *url_out = NULL, *enc_search = NULL;
801 char *path = NULL;
802 char **sv = NULL;
803 int i;
806 /* substitute aliases */
807 url_out = match_alias(url_in);
808 if (url_out != NULL)
809 return (url_out);
811 /* see if we are an about page */
812 if (!strncmp(url_in, XT_URI_ABOUT, XT_URI_ABOUT_LEN))
813 for (i = 0; i < about_list_size(); i++)
814 if (!strcmp(&url_in[XT_URI_ABOUT_LEN],
815 about_list[i].name)) {
816 url_out = g_strdup(url_in);
817 goto done;
820 if (guess_search && url_regex &&
821 !(g_str_has_prefix(url_in, "http://") ||
822 g_str_has_prefix(url_in, "https://"))) {
823 if (regexec(&url_re, url_in, 0, NULL, 0)) {
824 /* invalid URI so search instead */
825 enc_search = soup_uri_encode(url_in, XT_RESERVED_CHARS);
826 sv = g_strsplit(search_string, "%s", 2);
827 url_out = g_strjoinv(enc_search, sv);
828 g_free(enc_search);
829 g_strfreev(sv);
830 goto done;
834 /* XXX not sure about this heuristic */
835 if (stat(url_in, &sb) == 0) {
836 if (url_in[0] == '/')
837 url_out = g_filename_to_uri(url_in, NULL, NULL);
838 else {
839 if (getcwd(cwd, PATH_MAX) != NULL) {
840 path = g_strdup_printf("%s" PS "%s", cwd,
841 url_in);
842 url_out = g_filename_to_uri(path, NULL, NULL);
843 g_free(path);
846 } else
847 url_out = g_strdup_printf("http://%s", url_in); /* guess http */
848 done:
849 DNPRINTF(XT_D_URL, "guess_url_type: guessed %s\n", url_out);
851 return (url_out);
854 void
855 set_normal_tab_meaning(struct tab *t)
857 if (t == NULL)
858 return;
860 set_xtp_meaning(t, XT_XTP_TAB_MEANING_NORMAL);
863 void
864 load_uri(struct tab *t, const gchar *uri)
866 struct karg args;
867 gchar *newuri = NULL;
868 int i;
870 if (uri == NULL)
871 return;
873 /* Strip leading spaces. */
874 while (*uri && isspace((unsigned char)*uri))
875 uri++;
877 if (strlen(uri) == 0) {
878 blank(t, NULL);
879 return;
882 set_normal_tab_meaning(t);
884 if (valid_url_type(uri)) {
885 if ((newuri = guess_url_type(uri)) != NULL)
886 uri = newuri;
887 else
888 uri = "";
891 /* clear :cert show host */
892 if (t->about_cert_host) {
893 g_free(t->about_cert_host);
894 t->about_cert_host = NULL;
897 if (!strncmp(uri, XT_URI_ABOUT, XT_URI_ABOUT_LEN)) {
898 for (i = 0; i < about_list_size(); i++)
899 if (!strcmp(&uri[XT_URI_ABOUT_LEN], about_list[i].name) &&
900 about_list[i].func != NULL) {
901 bzero(&args, sizeof args);
902 about_list[i].func(t, &args);
903 gtk_widget_set_sensitive(GTK_WIDGET(t->stop),
904 FALSE);
905 goto done;
907 show_oops(t, "invalid about page");
908 goto done;
911 /* remove old HTTPS cert chain (if any) */
912 if (t->pem) {
913 g_free(t->pem);
914 t->pem = NULL;
917 set_status(t, "Loading: %s", (char *)uri);
918 marks_clear(t);
919 webkit_web_view_load_uri(t->wv, uri);
920 done:
921 if (newuri)
922 g_free(newuri);
925 const gchar *
926 get_uri(struct tab *t)
928 const gchar *uri;
930 if (webkit_web_view_get_load_status(t->wv) == WEBKIT_LOAD_FAILED &&
931 !t->download_requested)
932 return (NULL);
933 if (t->xtp_meaning == XT_XTP_TAB_MEANING_NORMAL)
934 uri = webkit_web_view_get_uri(t->wv);
935 else
936 uri = t->tmp_uri;
937 return (uri);
940 void
941 set_xtp_meaning(struct tab *t, int tab_meaning)
943 t->xtp_meaning = tab_meaning;
944 if (tab_meaning == XT_XTP_TAB_MEANING_NORMAL) {
945 if (t->session_key != NULL) {
946 g_free(t->session_key);
947 t->session_key = NULL;
949 } else {
950 /* use tmp_uri to make sure it is g_freed */
951 if (t->tmp_uri)
952 g_free(t->tmp_uri);
953 t->tmp_uri = g_strdup_printf("%s%s", XT_URI_ABOUT,
954 about_list[t->xtp_meaning].name);
958 const gchar *
959 get_title(struct tab *t, bool window)
961 const gchar *set = NULL, *title = NULL;
962 WebKitLoadStatus status;
964 status = webkit_web_view_get_load_status(t->wv);
965 if (status == WEBKIT_LOAD_PROVISIONAL ||
966 (status == WEBKIT_LOAD_FAILED && !t->download_requested) ||
967 t->xtp_meaning == XT_XTP_TAB_MEANING_BL)
968 goto notitle;
970 title = webkit_web_view_get_title(t->wv);
971 if ((set = title ? title : get_uri(t)))
972 return set;
974 notitle:
975 set = window ? XT_NAME : "(untitled)";
977 return set;
980 struct mime_type *
981 find_mime_type(char *mime_type)
983 struct mime_type *m, *def = NULL, *rv = NULL;
985 TAILQ_FOREACH(m, &mtl, entry) {
986 if (m->mt_default &&
987 !strncmp(mime_type, m->mt_type, strlen(m->mt_type)))
988 def = m;
990 if (m->mt_default == 0 && !strcmp(mime_type, m->mt_type)) {
991 rv = m;
992 break;
996 if (rv == NULL)
997 rv = def;
999 return (rv);
1003 * This only escapes the & and < characters, as per the discussion found here:
1004 * http://lists.apple.com/archives/Webkitsdk-dev/2007/May/msg00056.html
1006 gchar *
1007 html_escape(const char *val)
1009 char *s, *sp;
1010 char **sv;
1012 if (val == NULL)
1013 return NULL;
1015 sv = g_strsplit(val, "&", -1);
1016 s = g_strjoinv("&amp;", sv);
1017 g_strfreev(sv);
1018 sp = s;
1019 sv = g_strsplit(val, "<", -1);
1020 s = g_strjoinv("&lt;", sv);
1021 g_strfreev(sv);
1022 g_free(sp);
1023 return (s);
1026 struct wl_entry *
1027 wl_find_uri(const gchar *s, struct wl_list *wl)
1029 int i;
1030 char *ss;
1031 struct wl_entry *w;
1033 if (s == NULL || wl == NULL)
1034 return (NULL);
1036 if (!strncmp(s, "http://", strlen("http://")))
1037 s = &s[strlen("http://")];
1038 else if (!strncmp(s, "https://", strlen("https://")))
1039 s = &s[strlen("https://")];
1041 if (strlen(s) < 2)
1042 return (NULL);
1044 for (i = 0; i < strlen(s) + 1 /* yes er need this */; i++)
1045 /* chop string at first slash */
1046 if (s[i] == '/' || s[i] == ':' || s[i] == '\0') {
1047 ss = g_strdup(s);
1048 ss[i] = '\0';
1049 w = wl_find(ss, wl);
1050 g_free(ss);
1051 return (w);
1054 return (NULL);
1057 char *
1058 js_ref_to_string(JSContextRef context, JSValueRef ref)
1060 char *s = NULL;
1061 size_t l;
1062 JSStringRef jsref;
1064 jsref = JSValueToStringCopy(context, ref, NULL);
1065 if (jsref == NULL)
1066 return (NULL);
1068 l = JSStringGetMaximumUTF8CStringSize(jsref);
1069 s = g_malloc(l);
1070 if (s)
1071 JSStringGetUTF8CString(jsref, s, l);
1072 JSStringRelease(jsref);
1074 return (s);
1077 #define XT_JS_DONE ("done;")
1078 #define XT_JS_DONE_LEN (strlen(XT_JS_DONE))
1079 #define XT_JS_INSERT ("insert;")
1080 #define XT_JS_INSERT_LEN (strlen(XT_JS_INSERT))
1083 run_script(struct tab *t, char *s)
1085 JSGlobalContextRef ctx;
1086 WebKitWebFrame *frame;
1087 JSStringRef str;
1088 JSValueRef val, exception;
1089 char *es;
1091 DNPRINTF(XT_D_JS, "%s: tab %d %s\n", __func__,
1092 t->tab_id, s == (char *)JS_HINTING ? "JS_HINTING" : s);
1094 frame = webkit_web_view_get_main_frame(t->wv);
1095 ctx = webkit_web_frame_get_global_context(frame);
1097 str = JSStringCreateWithUTF8CString(s);
1098 val = JSEvaluateScript(ctx, str, JSContextGetGlobalObject(ctx),
1099 NULL, 0, &exception);
1100 JSStringRelease(str);
1102 DNPRINTF(XT_D_JS, "%s: val %p\n", __func__, val);
1103 if (val == NULL) {
1104 es = js_ref_to_string(ctx, exception);
1105 if (es) {
1106 DNPRINTF(XT_D_JS, "%s: exception %s\n", __func__, es);
1107 g_free(es);
1109 return (1);
1110 } else {
1111 es = js_ref_to_string(ctx, val);
1112 #if 0
1113 /* return values */
1114 if (!strncmp(es, XT_JS_DONE, XT_JS_DONE_LEN))
1115 ; /* do nothing */
1116 if (!strncmp(es, XT_JS_INSERT, XT_JS_INSERT_LEN))
1117 ; /* do nothing */
1118 #endif
1119 if (es) {
1120 DNPRINTF(XT_D_JS, "%s: val %s\n", __func__, es);
1121 g_free(es);
1125 return (0);
1128 void
1129 enable_hints(struct tab *t)
1131 DNPRINTF(XT_D_JS, "%s: tab %d\n", __func__, t->tab_id);
1133 if (t->new_tab)
1134 run_script(t, "hints.createHints('', 'F');");
1135 else
1136 run_script(t, "hints.createHints('', 'f');");
1137 t->mode = XT_MODE_HINT;
1140 void
1141 disable_hints(struct tab *t)
1143 DNPRINTF(XT_D_JS, "%s: tab %d\n", __func__, t->tab_id);
1145 run_script(t, "hints.clearHints();");
1146 t->mode = XT_MODE_COMMAND;
1147 t->new_tab = 0;
1151 passthrough(struct tab *t, struct karg *args)
1153 t->mode = XT_MODE_PASSTHROUGH;
1154 return (0);
1158 modurl(struct tab *t, struct karg *args)
1160 const gchar *uri = NULL;
1161 char *u = NULL;
1163 /* XXX kind of a bad hack, but oh well */
1164 if (gtk_widget_has_focus(t->uri_entry)) {
1165 if ((uri = gtk_entry_get_text(GTK_ENTRY(t->uri_entry))) &&
1166 (strlen(uri))) {
1167 u = g_strdup_printf("www.%s.com", uri);
1168 gtk_entry_set_text(GTK_ENTRY(t->uri_entry), u);
1169 g_free(u);
1170 activate_uri_entry_cb(t->uri_entry, t);
1173 return (0);
1177 modsearchentry(struct tab *t, struct karg *args)
1179 const gchar *s = NULL;
1180 struct tab *tt;
1182 /* XXX kind of a bad hack (in honor of the modurl hack) */
1183 if (gtk_widget_has_focus(t->search_entry)) {
1184 if ((s = gtk_entry_get_text(GTK_ENTRY(t->search_entry))) &&
1185 (strlen(s))) {
1186 tt = create_new_tab(NULL, NULL, 1, -1);
1187 gtk_entry_set_text(GTK_ENTRY(tt->search_entry), s);
1188 activate_search_entry_cb(t->search_entry,tt);
1189 gtk_entry_set_text(GTK_ENTRY(t->search_entry), "");
1192 return (0);
1196 hint(struct tab *t, struct karg *args)
1199 DNPRINTF(XT_D_JS, "hint: tab %d args %d\n", t->tab_id, args->i);
1201 if (t->mode == XT_MODE_HINT) {
1202 if (args->i == XT_HINT_NEWTAB)
1203 t->new_tab = 1;
1204 enable_hints(t);
1205 } else
1206 disable_hints(t);
1208 return (0);
1211 void
1212 apply_style(struct tab *t)
1214 t->styled = 1;
1215 g_object_set(G_OBJECT(t->settings),
1216 "user-stylesheet-uri", t->stylesheet, (char *)NULL);
1219 void
1220 remove_style(struct tab *t)
1222 t->styled = 0;
1223 g_object_set(G_OBJECT(t->settings),
1224 "user-stylesheet-uri", NULL, (char *)NULL);
1228 userstyle_cmd(struct tab *t, struct karg *args)
1230 char script[PATH_MAX] = {'\0'};
1231 char *script_uri;
1232 struct tab *tt;
1234 DNPRINTF(XT_D_JS, "userstyle_cmd: tab %d\n", t->tab_id);
1236 if (args->s != NULL && strlen(args->s)) {
1237 expand_tilde(script, sizeof script, args->s);
1238 script_uri = g_filename_to_uri(script, NULL, NULL);
1239 } else
1240 script_uri = g_strdup(userstyle);
1242 if (script_uri == NULL)
1243 return (1);
1245 switch (args->i) {
1246 case XT_STYLE_CURRENT_TAB:
1247 if (t->styled && !strcmp(script_uri, t->stylesheet))
1248 remove_style(t);
1249 else {
1250 if (t->stylesheet)
1251 g_free(t->stylesheet);
1252 t->stylesheet = g_strdup(script_uri);
1253 apply_style(t);
1255 break;
1256 case XT_STYLE_GLOBAL:
1257 if (userstyle_global && !strcmp(script_uri, t->stylesheet)) {
1258 userstyle_global = 0;
1259 TAILQ_FOREACH(tt, &tabs, entry)
1260 remove_style(tt);
1261 } else {
1262 userstyle_global = 1;
1264 /* need to save this stylesheet for new tabs */
1265 if (stylesheet)
1266 g_free(stylesheet);
1267 stylesheet = g_strdup(script_uri);
1269 TAILQ_FOREACH(tt, &tabs, entry) {
1270 if (tt->stylesheet)
1271 g_free(tt->stylesheet);
1272 tt->stylesheet = g_strdup(script_uri);
1273 apply_style(tt);
1276 break;
1279 g_free(script_uri);
1281 return (0);
1285 quit(struct tab *t, struct karg *args)
1287 if (save_global_history)
1288 save_global_history_to_disk(t);
1290 gtk_main_quit();
1292 return (1);
1295 void
1296 restore_sessions_list(void)
1298 DIR *sdir = NULL;
1299 struct dirent *dp = NULL;
1300 struct session *s;
1301 int reg;
1303 sdir = opendir(sessions_dir);
1304 if (sdir) {
1305 while ((dp = readdir(sdir)) != NULL) {
1306 #if defined __MINGW32__
1307 reg = 1; /* windows only has regular files */
1308 #else
1309 reg = dp->d_type == DT_REG;
1310 #endif
1311 if (dp && reg) {
1312 s = g_malloc(sizeof(struct session));
1313 s->name = g_strdup(dp->d_name);
1314 TAILQ_INSERT_TAIL(&sessions, s, entry);
1317 closedir(sdir);
1322 open_tabs(struct tab *t, struct karg *a)
1324 char file[PATH_MAX];
1325 FILE *f = NULL;
1326 char *uri = NULL;
1327 int rv = 1;
1328 struct tab *ti, *tt;
1330 if (a == NULL)
1331 goto done;
1333 ti = TAILQ_LAST(&tabs, tab_list);
1335 snprintf(file, sizeof file, "%s" PS "%s", sessions_dir, a->s);
1336 if ((f = fopen(file, "r")) == NULL)
1337 goto done;
1339 for (;;) {
1340 if ((uri = fparseln(f, NULL, NULL, "\0\0\0", 0)) == NULL) {
1341 if (feof(f) || ferror(f))
1342 break;
1343 } else {
1344 /* retrieve session name */
1345 if (g_str_has_prefix(uri, XT_SAVE_SESSION_ID)) {
1346 strlcpy(named_session,
1347 &uri[strlen(XT_SAVE_SESSION_ID)],
1348 sizeof named_session);
1349 continue;
1352 if (strlen(uri))
1353 create_new_tab(uri, NULL, 1, -1);
1355 free(uri);
1359 /* close open tabs */
1360 if (a->i == XT_SES_CLOSETABS && ti != NULL) {
1361 for (;;) {
1362 tt = TAILQ_FIRST(&tabs);
1363 if (tt == NULL)
1364 break;
1365 if (tt != ti) {
1366 delete_tab(tt);
1367 continue;
1369 delete_tab(tt);
1370 break;
1374 rv = 0;
1375 done:
1376 if (f)
1377 fclose(f);
1379 return (rv);
1383 restore_saved_tabs(void)
1385 char file[PATH_MAX];
1386 int unlink_file = 0;
1387 struct stat sb;
1388 struct karg a;
1389 int rv = 0;
1391 snprintf(file, sizeof file, "%s" PS "%s",
1392 sessions_dir, XT_RESTART_TABS_FILE);
1393 if (stat(file, &sb) == -1)
1394 a.s = XT_SAVED_TABS_FILE;
1395 else {
1396 unlink_file = 1;
1397 a.s = XT_RESTART_TABS_FILE;
1400 a.i = XT_SES_DONOTHING;
1401 rv = open_tabs(NULL, &a);
1403 if (unlink_file)
1404 unlink(file);
1406 return (rv);
1410 save_tabs(struct tab *t, struct karg *a)
1412 char file[PATH_MAX];
1413 FILE *f;
1414 int num_tabs = 0, i;
1415 struct tab **stabs = NULL;
1417 /* tab may be null here */
1419 if (a == NULL)
1420 return (1);
1421 if (a->s == NULL)
1422 snprintf(file, sizeof file, "%s" PS "%s",
1423 sessions_dir, named_session);
1424 else
1425 snprintf(file, sizeof file, "%s" PS "%s", sessions_dir, a->s);
1427 if ((f = fopen(file, "w")) == NULL) {
1428 show_oops(t, "Can't open save_tabs file: %s", strerror(errno));
1429 return (1);
1432 /* save session name */
1433 fprintf(f, "%s%s\n", XT_SAVE_SESSION_ID, named_session);
1435 /* Save tabs, in the order they are arranged in the notebook. */
1436 num_tabs = sort_tabs_by_page_num(&stabs);
1438 for (i = 0; i < num_tabs; i++)
1439 if (stabs[i]) {
1440 if (get_uri(stabs[i]) != NULL)
1441 fprintf(f, "%s\n", get_uri(stabs[i]));
1442 else if (gtk_entry_get_text(GTK_ENTRY(
1443 stabs[i]->uri_entry)))
1444 fprintf(f, "%s\n", gtk_entry_get_text(GTK_ENTRY(
1445 stabs[i]->uri_entry)));
1448 g_free(stabs);
1450 /* try and make sure this gets to disk NOW. XXX Backup first? */
1451 if (fflush(f) != 0 || fsync(fileno(f)) != 0) {
1452 show_oops(t, "May not have managed to save session: %s",
1453 strerror(errno));
1456 fclose(f);
1458 return (0);
1462 save_tabs_and_quit(struct tab *t, struct karg *args)
1464 struct karg a;
1466 a.s = NULL;
1467 save_tabs(t, &a);
1468 quit(t, NULL);
1470 return (1);
1473 void
1474 expand_tilde(char *path, size_t len, const char *s)
1476 struct passwd *pwd;
1477 int i;
1478 char user[LOGIN_NAME_MAX];
1479 const char *sc = s;
1481 if (path == NULL || s == NULL)
1482 errx(1, "expand_tilde");
1484 if (s[0] != '~') {
1485 strlcpy(path, sc, len);
1486 return;
1489 ++s;
1490 for (i = 0; s[i] != PSC && s[i] != '\0'; ++i)
1491 user[i] = s[i];
1492 user[i] = '\0';
1493 s = &s[i];
1495 pwd = strlen(user) == 0 ? getpwuid(getuid()) : getpwnam(user);
1496 if (pwd == NULL)
1497 strlcpy(path, sc, len);
1498 else
1499 snprintf(path, len, "%s%s", pwd->pw_dir, s);
1503 run_page_script(struct tab *t, struct karg *args)
1505 const gchar *uri;
1506 char *tmp, script[PATH_MAX];
1507 char *sv[3];
1509 tmp = args->s != NULL && strlen(args->s) > 0 ? args->s : default_script;
1510 if (tmp[0] == '\0') {
1511 show_oops(t, "no script specified");
1512 return (1);
1515 if ((uri = get_uri(t)) == NULL) {
1516 show_oops(t, "tab is empty, not running script");
1517 return (1);
1520 expand_tilde(script, sizeof script, tmp);
1522 sv[0] = script;
1523 sv[1] = (char *)uri;
1524 sv[2] = NULL;
1525 if (!g_spawn_async(NULL, sv, NULL, G_SPAWN_SEARCH_PATH, NULL, NULL,
1526 NULL, NULL)) {
1527 show_oops(t, "%s: could not spawn process: %s %s", __func__,
1528 sv[0], sv[1]);
1529 return (1);
1530 } else
1531 show_oops(t, "running: %s %s", sv[0], sv[1]);
1533 return (0);
1537 yank_uri(struct tab *t, struct karg *args)
1539 const gchar *uri;
1540 GtkClipboard *clipboard, *primary;
1542 if ((uri = get_uri(t)) == NULL)
1543 return (1);
1545 primary = gtk_clipboard_get(GDK_SELECTION_PRIMARY);
1546 clipboard = gtk_clipboard_get(GDK_SELECTION_CLIPBOARD);
1547 gtk_clipboard_set_text(primary, uri, -1);
1548 gtk_clipboard_set_text(clipboard, uri, -1);
1550 return (0);
1554 paste_uri(struct tab *t, struct karg *args)
1556 GtkClipboard *clipboard, *primary;
1557 gchar *c = NULL, *p = NULL, *uri;
1558 int i;
1560 clipboard = gtk_clipboard_get(GDK_SELECTION_CLIPBOARD);
1561 primary = gtk_clipboard_get(GDK_SELECTION_PRIMARY);
1562 c = gtk_clipboard_wait_for_text(clipboard);
1563 p = gtk_clipboard_wait_for_text(primary);
1565 if (c || p) {
1566 #ifdef __MINGW32__
1567 /* Windows try clipboard first */
1568 uri = c ? c : p;
1569 #else
1570 /* UNIX try primary first */
1571 uri = p ? p : c;
1572 #endif
1573 /* replace all newlines with spaces */
1574 for (i = 0; uri[i] != '\0'; ++i)
1575 if (uri[i] == '\n')
1576 uri[i] = ' ';
1578 while (*uri && isspace((unsigned char)*uri))
1579 uri++;
1580 if (strlen(uri) == 0) {
1581 show_oops(t, "empty paste buffer");
1582 goto done;
1584 if (guess_search == 0 && valid_url_type(uri)) {
1585 /* we can be clever and paste this in search box */
1586 show_oops(t, "not a valid URL");
1587 goto done;
1590 if (args->i == XT_PASTE_CURRENT_TAB)
1591 load_uri(t, uri);
1592 else if (args->i == XT_PASTE_NEW_TAB)
1593 create_new_tab(uri, NULL, 1, -1);
1596 done:
1597 if (c)
1598 g_free(c);
1599 if (p)
1600 g_free(p);
1602 return (0);
1605 void
1606 js_toggle_cb(GtkWidget *w, struct tab *t)
1608 struct karg a;
1609 int es, set;
1611 g_object_get(G_OBJECT(t->settings),
1612 "enable-scripts", &es, (char *)NULL);
1613 es = !es;
1614 if (es)
1615 set = XT_WL_ENABLE;
1616 else
1617 set = XT_WL_DISABLE;
1619 a.i = set | XT_WL_TOPLEVEL;
1620 toggle_pl(t, &a);
1622 a.i = set | XT_WL_TOPLEVEL;
1623 toggle_cwl(t, &a);
1625 a.i = XT_WL_TOGGLE | XT_WL_TOPLEVEL | XT_WL_RELOAD;
1626 toggle_js(t, &a);
1629 void
1630 proxy_toggle_cb(GtkWidget *w, struct tab *t)
1632 struct karg args = {0};
1634 args.i = XT_PRXY_TOGGLE;
1635 proxy_cmd(t, &args);
1639 toggle_src(struct tab *t, struct karg *args)
1641 gboolean mode;
1643 if (t == NULL)
1644 return (0);
1646 mode = webkit_web_view_get_view_source_mode(t->wv);
1647 webkit_web_view_set_view_source_mode(t->wv, !mode);
1648 webkit_web_view_reload(t->wv);
1650 return (0);
1653 void
1654 focus_webview(struct tab *t)
1656 if (t == NULL)
1657 return;
1659 /* only grab focus if we are visible */
1660 if (gtk_notebook_get_current_page(notebook) == t->tab_id)
1661 gtk_widget_grab_focus(GTK_WIDGET(t->wv));
1665 focus(struct tab *t, struct karg *args)
1667 if (t == NULL || args == NULL)
1668 return (1);
1670 if (show_url == 0)
1671 return (0);
1673 if (args->i == XT_FOCUS_URI)
1674 gtk_widget_grab_focus(GTK_WIDGET(t->uri_entry));
1675 else if (args->i == XT_FOCUS_SEARCH)
1676 gtk_widget_grab_focus(GTK_WIDGET(t->search_entry));
1678 return (0);
1681 void
1682 free_connection_certs(gnutls_x509_crt_t *certs, size_t cert_count)
1684 int i;
1686 for (i = 0; i < cert_count; i++)
1687 gnutls_x509_crt_deinit(certs[i]);
1688 gnutls_free(certs);
1691 #if GTK_CHECK_VERSION(3, 0, 0)
1692 void
1693 statusbar_modify_attr(struct tab *t, const char *css_name)
1695 gtk_widget_set_name(t->sbe.ebox, css_name);
1697 #else
1698 void
1699 statusbar_modify_attr(struct tab *t, const char *text, const char *base)
1701 GdkColor c_text, c_base;
1703 gdk_color_parse(text, &c_text);
1704 gdk_color_parse(base, &c_base);
1706 gtk_widget_modify_bg(t->sbe.ebox, GTK_STATE_NORMAL, &c_base);
1707 gtk_widget_modify_base(t->sbe.uri, GTK_STATE_NORMAL, &c_base);
1708 gtk_widget_modify_text(t->sbe.uri, GTK_STATE_NORMAL, &c_text);
1710 #endif
1712 void
1713 save_certs(struct tab *t, gnutls_x509_crt_t *certs,
1714 size_t cert_count, const char *domain, const char *dir)
1716 size_t cert_buf_sz;
1717 char file[PATH_MAX];
1718 char *cert_buf = NULL;
1719 int rv;
1720 int i;
1721 FILE *f;
1723 if (t == NULL || certs == NULL || cert_count <= 0 || domain == NULL)
1724 return;
1726 snprintf(file, sizeof file, "%s" PS "%s", dir, domain);
1727 if ((f = fopen(file, "w")) == NULL) {
1728 show_oops(t, "Can't create cert file %s %s",
1729 file, strerror(errno));
1730 return;
1733 for (i = 0; i < cert_count; i++) {
1735 * Because we support old crap and can't use
1736 * gnutls_x509_crt_export2(), we intentionally use an empty
1737 * buffer and then make a second call with the known size
1738 * needed.
1740 cert_buf_sz = 0;
1741 gnutls_x509_crt_export(certs[i], GNUTLS_X509_FMT_PEM,
1742 NULL, &cert_buf_sz);
1743 if (cert_buf_sz == 0) {
1744 show_oops(t, "no certs found");
1745 goto done;
1747 cert_buf = gnutls_malloc(cert_buf_sz * sizeof(char));
1748 if (cert_buf == NULL) {
1749 show_oops(t, "gnutls_x509_crt_export failed");
1750 goto done;
1752 rv = gnutls_x509_crt_export(certs[i],
1753 GNUTLS_X509_FMT_PEM, cert_buf, &cert_buf_sz);
1754 if (rv != 0) {
1755 show_oops(t, "gnutls_x509_crt_export failure: %s",
1756 gnutls_strerror(rv));
1757 goto done;
1759 cert_buf[cert_buf_sz] = '\0';
1760 if (fwrite(cert_buf, cert_buf_sz, 1, f) != 1) {
1761 show_oops(t, "Can't write certs: %s", strerror(errno));
1762 goto done;
1764 gnutls_free(cert_buf);
1765 cert_buf = NULL;
1768 done:
1769 if (cert_buf)
1770 gnutls_free(cert_buf);
1771 fclose(f);
1774 enum cert_trust {
1775 CERT_LOCAL,
1776 CERT_TRUSTED,
1777 CERT_UNTRUSTED,
1778 CERT_BAD
1781 gnutls_x509_crt_t *
1782 get_local_cert_chain(const char *uri, size_t *ncerts, const char **error_str,
1783 const char *dir)
1785 SoupURI *su;
1786 unsigned char cert_buf[64 * 1024] = {0};
1787 gnutls_datum_t data;
1788 unsigned int max_certs = XT_MAX_CERTS;
1789 int bytes_read;
1790 char file[PATH_MAX];
1791 FILE *f;
1792 gnutls_x509_crt_t *certs;
1794 if ((su = soup_uri_new(uri)) == NULL) {
1795 *error_str = "Invalid URI";
1796 return (NULL);
1799 snprintf(file, sizeof file, "%s" PS "%s", dir, su->host);
1800 soup_uri_free(su);
1801 if ((f = fopen(file, "r")) == NULL) {
1802 *error_str = "Could not read local cert";
1803 return (NULL);
1806 bytes_read = fread(cert_buf, sizeof *cert_buf, sizeof cert_buf, f);
1807 if (bytes_read == 0) {
1808 *error_str = "Could not read local cert";
1809 return (NULL);
1812 certs = gnutls_malloc(sizeof(*certs) * max_certs);
1813 if (certs == NULL) {
1814 *error_str = "Error allocating memory";
1815 return (NULL);
1817 data.data = cert_buf;
1818 data.size = bytes_read;
1819 if (gnutls_x509_crt_list_import(certs, &max_certs, &data,
1820 GNUTLS_X509_FMT_PEM, 0) < 0) {
1821 gnutls_free(certs);
1822 *error_str = "Error reading local cert chain";
1823 return (NULL);
1826 *ncerts = max_certs;
1827 return (certs);
1831 * This uses the pem-encoded cert chain saved in t->pem instead of
1832 * grabbing the remote cert. We save it beforehand and read it here
1833 * so as to not open a side channel that ignores proxy settings.
1835 gnutls_x509_crt_t *
1836 get_chain_for_pem(char *pem, size_t *ncerts, const char **error_str)
1838 gnutls_datum_t data;
1839 unsigned int max_certs = XT_MAX_CERTS;
1840 gnutls_x509_crt_t *certs;
1842 if (pem == NULL) {
1843 *error_str = "Error reading remote cert chain";
1844 return (NULL);
1847 certs = gnutls_malloc(sizeof(*certs) * max_certs);
1848 if (certs == NULL) {
1849 *error_str = "Error allocating memory";
1850 return (NULL);
1852 data.data = (unsigned char *)pem;
1853 data.size = strlen(pem);
1854 if (gnutls_x509_crt_list_import(certs, &max_certs, &data,
1855 GNUTLS_X509_FMT_PEM, 0) < 0) {
1856 gnutls_free(certs);
1857 *error_str = "Error reading remote cert chain";
1858 return (NULL);
1861 *ncerts = max_certs;
1862 return (certs);
1867 cert_cmd(struct tab *t, struct karg *args)
1869 const gchar *uri, *error_str = NULL;
1870 size_t cert_count;
1871 gnutls_x509_crt_t *certs;
1872 SoupURI *su;
1873 char *host;
1874 #if !GTK_CHECK_VERSION(3, 0, 0)
1875 GdkColor color;
1876 #endif
1878 if (t == NULL)
1879 return (1);
1881 if (args->s != NULL) {
1882 uri = args->s;
1883 } else if ((uri = get_uri(t)) == NULL) {
1884 show_oops(t, "Invalid URI");
1885 return (1);
1887 if ((su = soup_uri_new(uri)) == NULL) {
1888 show_oops(t, "Invalid URI");
1889 return (1);
1893 * if we're only showing the local certs, don't open a socket and get
1894 * the remote certs
1896 if (args->i & XT_SHOW && args->i & XT_CACHE) {
1897 certs = get_local_cert_chain(uri, &cert_count, &error_str,
1898 certs_cache_dir);
1899 if (error_str == NULL) {
1900 t->about_cert_host = g_strdup(su->host);
1901 show_certs(t, certs, cert_count, "Certificate Chain");
1902 free_connection_certs(certs, cert_count);
1903 } else {
1904 show_oops(t, "%s", error_str);
1905 soup_uri_free(su);
1906 return (1);
1908 soup_uri_free(su);
1909 return (0);
1912 certs = get_chain_for_pem(t->pem, &cert_count, &error_str);
1913 if (error_str)
1914 goto done;
1916 if (args->i & XT_SHOW) {
1917 t->about_cert_host = g_strdup(su->host);
1918 show_certs(t, certs, cert_count, "Certificate Chain");
1919 } else if (args->i & XT_SAVE) {
1920 host = t->about_cert_host ? t->about_cert_host : su->host;
1921 save_certs(t, certs, cert_count, host, certs_dir);
1922 #if GTK_CHECK_VERSION(3, 0, 0)
1923 gtk_widget_set_name(t->uri_entry, XT_CSS_BLUE);
1924 statusbar_modify_attr(t, XT_CSS_BLUE);
1925 #else
1926 gdk_color_parse(XT_COLOR_BLUE, &color);
1927 gtk_widget_modify_base(t->uri_entry, GTK_STATE_NORMAL, &color);
1928 statusbar_modify_attr(t, XT_COLOR_BLACK, XT_COLOR_BLUE);
1929 #endif
1930 } else if (args->i & XT_CACHE)
1931 save_certs(t, certs, cert_count, su->host, certs_cache_dir);
1933 free_connection_certs(certs, cert_count);
1935 done:
1936 soup_uri_free(su);
1938 if (error_str && strlen(error_str)) {
1939 show_oops(t, "%s", error_str);
1940 return (1);
1942 return (0);
1946 * Checks whether the remote cert is identical to the local saved
1947 * cert. Returns CERT_LOCAL if unchanged, CERT_UNTRUSTED if local
1948 * cert does not exist, and CERT_BAD if different.
1950 * Saves entire cert chain in pem encoding to chain for it to be
1951 * cached later, if needed.
1953 enum cert_trust
1954 check_local_certs(const char *file, GTlsCertificate *cert, char **chain)
1956 char r_cert_buf[64 * 1024];
1957 FILE *f;
1958 GTlsCertificate *tmpcert = NULL;
1959 GTlsCertificate *issuer = NULL;
1960 char *pem = NULL;
1961 char *tmp = NULL;
1962 enum cert_trust rv = CERT_LOCAL;
1963 int i;
1965 if ((f = fopen(file, "r")) == NULL) {
1966 /* no local cert to check */
1967 rv = CERT_UNTRUSTED;
1970 for (i = 0;;) {
1971 if (i == 0) {
1972 g_object_get(G_OBJECT(cert), "certificate-pem", &pem,
1973 NULL);
1974 g_object_get(G_OBJECT(cert), "issuer", &issuer, NULL);
1975 } else {
1976 if (issuer == NULL)
1977 break;
1978 g_object_get(G_OBJECT(tmpcert), "issuer", &issuer,
1979 NULL);
1980 if (issuer == NULL)
1981 break;
1983 g_object_get(G_OBJECT(tmpcert), "certificate-pem", &pem,
1984 NULL);
1986 i++;
1988 if (tmpcert != NULL)
1989 g_object_unref(G_OBJECT(tmpcert));
1990 tmpcert = issuer;
1991 if (f) {
1992 if (fread(r_cert_buf, strlen(pem), 1, f) != 1 && !feof(f))
1993 rv = CERT_BAD;
1994 if (bcmp(r_cert_buf, pem, strlen(pem)))
1995 rv = CERT_BAD;
1997 tmp = g_strdup_printf("%s%s", *chain, pem);
1998 g_free(pem);
1999 g_free(*chain);
2000 *chain = tmp;
2003 if (issuer != NULL)
2004 g_object_unref(G_OBJECT(issuer));
2005 if (f != NULL)
2006 fclose(f);
2007 return (rv);
2011 check_cert_changes(struct tab *t, GTlsCertificate *cert, const char *file, const char *uri)
2013 SoupURI *soupuri = NULL;
2014 struct karg args = {0};
2015 struct wl_entry *w = NULL;
2016 char *chain = NULL;
2017 int ret = 0;
2019 chain = g_strdup("");
2020 switch(check_local_certs(file, cert, &chain)) {
2021 case CERT_LOCAL:
2022 /* The cached certificate is identical */
2023 break;
2024 case CERT_TRUSTED: /* FALLTHROUGH */
2025 case CERT_UNTRUSTED:
2026 /* cache new certificate */
2027 args.i = XT_CACHE;
2028 cert_cmd(t, &args);
2029 break;
2030 case CERT_BAD:
2031 if ((soupuri = soup_uri_new(uri)) == NULL ||
2032 soupuri->host == NULL)
2033 break;
2034 if ((w = wl_find(soupuri->host, &svil)) != NULL)
2035 break;
2036 set_xtp_meaning(t, XT_XTP_TAB_MEANING_SV);
2037 args.s = g_strdup((char *)uri);
2038 xtp_page_sv(t, &args);
2039 ret = 1;
2040 break;
2043 if (soupuri)
2044 soup_uri_free(soupuri);
2045 if (chain)
2046 g_free(chain);
2047 return (ret);
2051 remove_cookie(int index)
2053 int i, rv = 1;
2054 GSList *cf;
2055 SoupCookie *c;
2057 DNPRINTF(XT_D_COOKIE, "remove_cookie: %d\n", index);
2059 cf = soup_cookie_jar_all_cookies(s_cookiejar);
2061 for (i = 1; cf; cf = cf->next, i++) {
2062 if (i != index)
2063 continue;
2064 c = cf->data;
2065 print_cookie("remove cookie", c);
2066 soup_cookie_jar_delete_cookie(s_cookiejar, c);
2067 rv = 0;
2068 break;
2071 soup_cookies_free(cf);
2073 return (rv);
2077 remove_cookie_domain(int domain_id)
2079 int domain_count, rv = 1;
2080 GSList *cf;
2081 SoupCookie *c;
2082 char *last_domain;
2084 DNPRINTF(XT_D_COOKIE, "remove_cookie_domain: %d\n", domain_id);
2086 last_domain = "";
2087 cf = soup_cookie_jar_all_cookies(s_cookiejar);
2089 for (domain_count = 0; cf; cf = cf->next) {
2090 c = cf->data;
2092 if (strcmp(last_domain, c->domain) != 0) {
2093 domain_count++;
2094 last_domain = c->domain;
2097 if (domain_count < domain_id)
2098 continue;
2099 else if (domain_count > domain_id)
2100 break;
2102 print_cookie("remove cookie", c);
2103 soup_cookie_jar_delete_cookie(s_cookiejar, c);
2104 rv = 0;
2107 soup_cookies_free(cf);
2109 return (rv);
2113 remove_cookie_all()
2115 int rv = 1;
2116 GSList *cf;
2117 SoupCookie *c;
2119 DNPRINTF(XT_D_COOKIE, "remove_cookie_all\n");
2121 cf = soup_cookie_jar_all_cookies(s_cookiejar);
2123 for (; cf; cf = cf->next) {
2124 c = cf->data;
2126 print_cookie("remove cookie", c);
2127 soup_cookie_jar_delete_cookie(s_cookiejar, c);
2128 rv = 0;
2131 soup_cookies_free(cf);
2133 return (rv);
2137 toplevel_cmd(struct tab *t, struct karg *args)
2139 js_toggle_cb(t->js_toggle, t);
2141 return (0);
2145 can_go_back_for_real(struct tab *t)
2147 int i;
2148 WebKitWebHistoryItem *item;
2149 const gchar *uri;
2151 if (t == NULL)
2152 return (FALSE);
2154 if (t->item != NULL)
2155 return (TRUE);
2157 /* rely on webkit to make sure we can go backward when on an about page */
2158 uri = get_uri(t);
2159 if (uri == NULL || g_str_has_prefix(uri, "about:") ||
2160 g_str_has_prefix(uri, "xxxt://"))
2161 return (webkit_web_view_can_go_back(t->wv));
2163 /* the back/forward list is stupid so help determine if we can go back */
2164 for (i = 0, item = webkit_web_back_forward_list_get_current_item(t->bfl);
2165 item != NULL;
2166 i--, item = webkit_web_back_forward_list_get_nth_item(t->bfl, i)) {
2167 if (strcmp(webkit_web_history_item_get_uri(item), uri))
2168 return (TRUE);
2171 return (FALSE);
2175 can_go_forward_for_real(struct tab *t)
2177 int i;
2178 WebKitWebHistoryItem *item;
2179 const gchar *uri;
2181 if (t == NULL)
2182 return (FALSE);
2184 /* rely on webkit to make sure we can go forward when on an about page */
2185 uri = get_uri(t);
2186 if (uri == NULL || g_str_has_prefix(uri, "about:") ||
2187 g_str_has_prefix(uri, "xxxt://"))
2188 return (webkit_web_view_can_go_forward(t->wv));
2190 /* the back/forwars list is stupid so help selecting a different item */
2191 for (i = 0, item = webkit_web_back_forward_list_get_current_item(t->bfl);
2192 item != NULL;
2193 i++, item = webkit_web_back_forward_list_get_nth_item(t->bfl, i)) {
2194 if (strcmp(webkit_web_history_item_get_uri(item), uri))
2195 return (TRUE);
2198 return (FALSE);
2201 void
2202 go_back_for_real(struct tab *t)
2204 int i;
2205 WebKitWebHistoryItem *item;
2206 const gchar *uri;
2208 if (t == NULL)
2209 return;
2211 uri = get_uri(t);
2212 if (uri == NULL || g_str_has_prefix(uri, "about:") ||
2213 g_str_has_prefix(uri, "xxxt://")) {
2214 webkit_web_view_go_back(t->wv);
2215 return;
2217 /* the back/forwars list is stupid so help selecting a different item */
2218 for (i = 0, item = webkit_web_back_forward_list_get_current_item(t->bfl);
2219 item != NULL;
2220 i--, item = webkit_web_back_forward_list_get_nth_item(t->bfl, i)) {
2221 if (strcmp(webkit_web_history_item_get_uri(item), uri)) {
2222 webkit_web_view_go_to_back_forward_item(t->wv, item);
2223 break;
2228 void
2229 go_forward_for_real(struct tab *t)
2231 int i;
2232 WebKitWebHistoryItem *item;
2233 const gchar *uri;
2235 if (t == NULL)
2236 return;
2238 uri = get_uri(t);
2239 if (uri == NULL || g_str_has_prefix(uri, "about:") ||
2240 g_str_has_prefix(uri, "xxxt://")) {
2241 webkit_web_view_go_forward(t->wv);
2242 return;
2244 /* the back/forwars list is stupid so help selecting a different item */
2245 for (i = 0, item = webkit_web_back_forward_list_get_current_item(t->bfl);
2246 item != NULL;
2247 i++, item = webkit_web_back_forward_list_get_nth_item(t->bfl, i)) {
2248 if (strcmp(webkit_web_history_item_get_uri(item), uri)) {
2249 webkit_web_view_go_to_back_forward_item(t->wv, item);
2250 break;
2256 navaction(struct tab *t, struct karg *args)
2258 WebKitWebHistoryItem *item = NULL;
2259 WebKitWebFrame *frame;
2261 DNPRINTF(XT_D_NAV, "navaction: tab %d opcode %d\n",
2262 t->tab_id, args->i);
2264 hide_oops(t);
2265 set_normal_tab_meaning(t);
2266 if (t->item) {
2267 if (args->i == XT_NAV_BACK)
2268 item = webkit_web_back_forward_list_get_current_item(t->bfl);
2269 else
2270 item = webkit_web_back_forward_list_get_forward_item(t->bfl);
2273 switch (args->i) {
2274 case XT_NAV_BACK:
2275 if (t->item) {
2276 if (item == NULL)
2277 return (XT_CB_PASSTHROUGH);
2278 webkit_web_view_go_to_back_forward_item(t->wv, item);
2279 t->item = NULL;
2280 return (XT_CB_PASSTHROUGH);
2282 marks_clear(t);
2283 go_back_for_real(t);
2284 break;
2285 case XT_NAV_FORWARD:
2286 if (t->item) {
2287 if (item == NULL)
2288 return (XT_CB_PASSTHROUGH);
2289 webkit_web_view_go_to_back_forward_item(t->wv, item);
2290 t->item = NULL;
2291 return (XT_CB_PASSTHROUGH);
2293 marks_clear(t);
2294 go_forward_for_real(t);
2295 break;
2296 case XT_NAV_RELOAD:
2297 frame = webkit_web_view_get_main_frame(t->wv);
2298 webkit_web_frame_reload(frame);
2299 break;
2300 case XT_NAV_STOP:
2301 frame = webkit_web_view_get_main_frame(t->wv);
2302 webkit_web_frame_stop_loading(frame);
2303 break;
2305 return (XT_CB_PASSTHROUGH);
2309 move(struct tab *t, struct karg *args)
2311 GtkAdjustment *adjust;
2312 double pi, si, pos, ps, upper, lower, max;
2313 double percent;
2315 switch (args->i) {
2316 case XT_MOVE_DOWN:
2317 case XT_MOVE_UP:
2318 case XT_MOVE_BOTTOM:
2319 case XT_MOVE_TOP:
2320 case XT_MOVE_PAGEDOWN:
2321 case XT_MOVE_PAGEUP:
2322 case XT_MOVE_HALFDOWN:
2323 case XT_MOVE_HALFUP:
2324 case XT_MOVE_PERCENT:
2325 case XT_MOVE_CENTER:
2326 adjust = t->adjust_v;
2327 break;
2328 default:
2329 adjust = t->adjust_h;
2330 break;
2333 pos = gtk_adjustment_get_value(adjust);
2334 ps = gtk_adjustment_get_page_size(adjust);
2335 upper = gtk_adjustment_get_upper(adjust);
2336 lower = gtk_adjustment_get_lower(adjust);
2337 si = gtk_adjustment_get_step_increment(adjust);
2338 pi = gtk_adjustment_get_page_increment(adjust);
2339 max = upper - ps;
2341 DNPRINTF(XT_D_MOVE, "move: opcode %d %s pos %f ps %f upper %f lower %f "
2342 "max %f si %f pi %f\n",
2343 args->i, adjust == t->adjust_h ? "horizontal" : "vertical",
2344 pos, ps, upper, lower, max, si, pi);
2346 switch (args->i) {
2347 case XT_MOVE_DOWN:
2348 case XT_MOVE_RIGHT:
2349 pos += si;
2350 gtk_adjustment_set_value(adjust, MIN(pos, max));
2351 break;
2352 case XT_MOVE_UP:
2353 case XT_MOVE_LEFT:
2354 pos -= si;
2355 gtk_adjustment_set_value(adjust, MAX(pos, lower));
2356 break;
2357 case XT_MOVE_BOTTOM:
2358 case XT_MOVE_FARRIGHT:
2359 t->mark[marktoindex('\'')] = gtk_adjustment_get_value(t->adjust_v);
2360 gtk_adjustment_set_value(adjust, max);
2361 break;
2362 case XT_MOVE_TOP:
2363 case XT_MOVE_FARLEFT:
2364 t->mark[marktoindex('\'')] = gtk_adjustment_get_value(t->adjust_v);
2365 gtk_adjustment_set_value(adjust, lower);
2366 break;
2367 case XT_MOVE_PAGEDOWN:
2368 pos += pi;
2369 gtk_adjustment_set_value(adjust, MIN(pos, max));
2370 break;
2371 case XT_MOVE_PAGEUP:
2372 pos -= pi;
2373 gtk_adjustment_set_value(adjust, MAX(pos, lower));
2374 break;
2375 case XT_MOVE_HALFDOWN:
2376 pos += pi / 2;
2377 gtk_adjustment_set_value(adjust, MIN(pos, max));
2378 break;
2379 case XT_MOVE_HALFUP:
2380 pos -= pi / 2;
2381 gtk_adjustment_set_value(adjust, MAX(pos, lower));
2382 break;
2383 case XT_MOVE_CENTER:
2384 t->mark[marktoindex('\'')] = gtk_adjustment_get_value(t->adjust_v);
2385 args->s = g_strdup("50.0");
2386 /* FALLTHROUGH */
2387 case XT_MOVE_PERCENT:
2388 t->mark[marktoindex('\'')] = gtk_adjustment_get_value(t->adjust_v);
2389 percent = atoi(args->s) / 100.0;
2390 pos = max * percent;
2391 if (pos < 0.0 || pos > max)
2392 break;
2393 gtk_adjustment_set_value(adjust, pos);
2394 break;
2395 default:
2396 return (XT_CB_PASSTHROUGH);
2399 DNPRINTF(XT_D_MOVE, "move: new pos %f %f\n", pos, MIN(pos, max));
2401 return (XT_CB_HANDLED);
2404 void
2405 url_set_visibility(void)
2407 struct tab *t;
2409 TAILQ_FOREACH(t, &tabs, entry)
2410 if (show_url == 0) {
2411 gtk_widget_hide(t->toolbar);
2412 focus_webview(t);
2413 } else
2414 gtk_widget_show(t->toolbar);
2417 void
2418 notebook_tab_set_visibility(void)
2420 if (show_tabs == 0) {
2421 gtk_widget_hide(tab_bar);
2422 gtk_notebook_set_show_tabs(notebook, FALSE);
2423 } else {
2424 if (tab_style == XT_TABS_NORMAL) {
2425 gtk_widget_hide(tab_bar);
2426 gtk_notebook_set_show_tabs(notebook, TRUE);
2427 } else if (tab_style == XT_TABS_COMPACT) {
2428 gtk_widget_show(tab_bar);
2429 gtk_notebook_set_show_tabs(notebook, FALSE);
2434 void
2435 statusbar_set_visibility(void)
2437 struct tab *t;
2439 TAILQ_FOREACH(t, &tabs, entry){
2440 if (show_statusbar == 0)
2441 gtk_widget_hide(t->statusbar);
2442 else
2443 gtk_widget_show(t->statusbar);
2445 focus_webview(t);
2449 void
2450 url_set(struct tab *t, int enable_url_entry)
2452 GdkPixbuf *pixbuf;
2453 int progress;
2455 show_url = enable_url_entry;
2457 if (enable_url_entry) {
2458 gtk_entry_set_icon_from_icon_name(GTK_ENTRY(t->sbe.uri),
2459 GTK_ENTRY_ICON_PRIMARY, NULL);
2460 gtk_entry_set_progress_fraction(GTK_ENTRY(t->sbe.uri), 0);
2461 } else {
2462 pixbuf = gtk_entry_get_icon_pixbuf(GTK_ENTRY(t->uri_entry),
2463 GTK_ENTRY_ICON_PRIMARY);
2464 progress =
2465 gtk_entry_get_progress_fraction(GTK_ENTRY(t->uri_entry));
2466 gtk_entry_set_icon_from_pixbuf(GTK_ENTRY(t->sbe.uri),
2467 GTK_ENTRY_ICON_PRIMARY, pixbuf);
2468 gtk_entry_set_progress_fraction(GTK_ENTRY(t->sbe.uri),
2469 progress);
2474 fullscreen(struct tab *t, struct karg *args)
2476 DNPRINTF(XT_D_TAB, "%s: %p %d\n", __func__, t, args->i);
2478 if (t == NULL)
2479 return (XT_CB_PASSTHROUGH);
2481 if (show_url == 0) {
2482 url_set(t, 1);
2483 show_tabs = 1;
2484 } else {
2485 url_set(t, 0);
2486 show_tabs = 0;
2489 url_set_visibility();
2490 notebook_tab_set_visibility();
2492 return (XT_CB_HANDLED);
2496 statustoggle(struct tab *t, struct karg *args)
2498 DNPRINTF(XT_D_TAB, "%s: %p %d\n", __func__, t, args->i);
2500 if (show_statusbar == 1) {
2501 show_statusbar = 0;
2502 statusbar_set_visibility();
2503 } else if (show_statusbar == 0) {
2504 show_statusbar = 1;
2505 statusbar_set_visibility();
2507 return (XT_CB_HANDLED);
2511 urlaction(struct tab *t, struct karg *args)
2513 int rv = XT_CB_HANDLED;
2515 DNPRINTF(XT_D_TAB, "%s: %p %d\n", __func__, t, args->i);
2517 if (t == NULL)
2518 return (XT_CB_PASSTHROUGH);
2520 switch (args->i) {
2521 case XT_URL_SHOW:
2522 if (show_url == 0) {
2523 url_set(t, 1);
2524 url_set_visibility();
2526 break;
2527 case XT_URL_HIDE:
2528 if (show_url == 1) {
2529 url_set(t, 0);
2530 url_set_visibility();
2532 break;
2534 return (rv);
2538 tabaction(struct tab *t, struct karg *args)
2540 int rv = XT_CB_HANDLED;
2541 char *url = args->s;
2542 struct undo *u;
2543 struct tab *tt, *tv;
2545 DNPRINTF(XT_D_TAB, "tabaction: %p %d\n", t, args->i);
2547 if (t == NULL)
2548 return (XT_CB_PASSTHROUGH);
2550 switch (args->i) {
2551 case XT_TAB_NEW:
2552 if (strlen(url) > 0)
2553 create_new_tab(url, NULL, 1, args->precount);
2554 else
2555 create_new_tab(NULL, NULL, 1, args->precount);
2556 break;
2557 case XT_TAB_DELETE:
2558 if (args->precount < 0)
2559 delete_tab(t);
2560 else
2561 TAILQ_FOREACH(tt, &tabs, entry)
2562 if (tt->tab_id == args->precount - 1) {
2563 delete_tab(tt);
2564 break;
2566 break;
2567 case XT_TAB_DELQUIT:
2568 if (gtk_notebook_get_n_pages(notebook) > 1)
2569 delete_tab(t);
2570 else
2571 quit(t, args);
2572 break;
2573 case XT_TAB_ONLY:
2574 TAILQ_FOREACH_SAFE(tt, &tabs, entry, tv)
2575 if (t != tt)
2576 delete_tab(tt);
2577 break;
2578 case XT_TAB_OPEN:
2579 if (strlen(url) > 0)
2581 else {
2582 rv = XT_CB_PASSTHROUGH;
2583 goto done;
2585 load_uri(t, url);
2586 break;
2587 case XT_TAB_SHOW:
2588 if (show_tabs == 0) {
2589 show_tabs = 1;
2590 notebook_tab_set_visibility();
2592 break;
2593 case XT_TAB_HIDE:
2594 if (show_tabs == 1) {
2595 show_tabs = 0;
2596 notebook_tab_set_visibility();
2598 break;
2599 case XT_TAB_NEXTSTYLE:
2600 if (tab_style == XT_TABS_NORMAL) {
2601 tab_style = XT_TABS_COMPACT;
2602 recolor_compact_tabs();
2604 else
2605 tab_style = XT_TABS_NORMAL;
2606 notebook_tab_set_visibility();
2607 break;
2608 case XT_TAB_UNDO_CLOSE:
2609 if (undo_count == 0) {
2610 DNPRINTF(XT_D_TAB, "%s: no tabs to undo close",
2611 __func__);
2612 goto done;
2613 } else {
2614 undo_count--;
2615 u = TAILQ_FIRST(&undos);
2616 create_new_tab(u->uri, u, 1, -1);
2618 TAILQ_REMOVE(&undos, u, entry);
2619 g_free(u->uri);
2620 /* u->history is freed in create_new_tab() */
2621 g_free(u);
2623 break;
2624 case XT_TAB_LOAD_IMAGES:
2626 if (!auto_load_images) {
2628 /* Enable auto-load images (this will load all
2629 * previously unloaded images). */
2630 g_object_set(G_OBJECT(t->settings),
2631 "auto-load-images", TRUE, (char *)NULL);
2632 webkit_web_view_set_settings(t->wv, t->settings);
2634 webkit_web_view_reload(t->wv);
2636 /* Webkit triggers an event when we change the setting,
2637 * so we can't disable the auto-loading at once.
2639 * Unfortunately, webkit does not tell us when it's done.
2640 * Instead, we wait until the next request, and then
2641 * disable autoloading again.
2643 t->load_images = TRUE;
2645 break;
2646 default:
2647 rv = XT_CB_PASSTHROUGH;
2648 goto done;
2651 done:
2652 if (args->s) {
2653 g_free(args->s);
2654 args->s = NULL;
2657 return (rv);
2661 resizetab(struct tab *t, struct karg *args)
2663 if (t == NULL || args == NULL) {
2664 show_oops(NULL, "resizetab invalid parameters");
2665 return (XT_CB_PASSTHROUGH);
2668 DNPRINTF(XT_D_TAB, "resizetab: tab %d %d\n",
2669 t->tab_id, args->i);
2671 setzoom_webkit(t, args->i);
2673 return (XT_CB_HANDLED);
2677 movetab(struct tab *t, struct karg *args)
2679 int n, dest;
2681 if (t == NULL || args == NULL) {
2682 show_oops(NULL, "movetab invalid parameters");
2683 return (XT_CB_PASSTHROUGH);
2686 DNPRINTF(XT_D_TAB, "movetab: tab %d opcode %d\n",
2687 t->tab_id, args->i);
2689 if (args->i >= XT_TAB_INVALID)
2690 return (XT_CB_PASSTHROUGH);
2692 if (TAILQ_EMPTY(&tabs))
2693 return (XT_CB_PASSTHROUGH);
2695 n = gtk_notebook_get_n_pages(notebook);
2696 dest = gtk_notebook_get_current_page(notebook);
2698 switch (args->i) {
2699 case XT_TAB_NEXT:
2700 if (args->precount < 0)
2701 dest = dest == n - 1 ? 0 : dest + 1;
2702 else
2703 dest = args->precount - 1;
2705 break;
2706 case XT_TAB_PREV:
2707 if (args->precount < 0)
2708 dest -= 1;
2709 else
2710 dest -= args->precount % n;
2712 if (dest < 0)
2713 dest += n;
2715 break;
2716 case XT_TAB_FIRST:
2717 dest = 0;
2718 break;
2719 case XT_TAB_LAST:
2720 dest = n - 1;
2721 break;
2722 default:
2723 return (XT_CB_PASSTHROUGH);
2726 if (dest < 0 || dest >= n)
2727 return (XT_CB_PASSTHROUGH);
2728 if (t->tab_id == dest) {
2729 DNPRINTF(XT_D_TAB, "movetab: do nothing\n");
2730 return (XT_CB_HANDLED);
2733 set_current_tab(dest);
2735 return (XT_CB_HANDLED);
2738 int cmd_prefix = 0;
2740 struct prompt_sub {
2741 const char *s;
2742 const char *(*f)(struct tab *);
2743 } subs[] = {
2744 { "<uri>", get_uri },
2748 command(struct tab *t, struct karg *args)
2750 struct karg a = {0};
2751 int i, cmd_setup = 0;
2752 char *s = NULL, *sp = NULL, *sl = NULL;
2753 gchar **sv;
2755 if (t == NULL || args == NULL) {
2756 show_oops(NULL, "command invalid parameters");
2757 return (XT_CB_PASSTHROUGH);
2760 switch (args->i) {
2761 case '/':
2762 s = "/";
2763 break;
2764 case '?':
2765 s = "?";
2766 break;
2767 case ':':
2768 if (cmd_prefix == 0) {
2769 if (args->s != NULL && strlen(args->s) != 0) {
2770 sp = g_strdup_printf(":%s", args->s);
2771 s = sp;
2772 } else
2773 s = ":";
2774 } else {
2775 sp = g_strdup_printf(":%d", cmd_prefix);
2776 s = sp;
2777 cmd_prefix = 0;
2779 sl = g_strdup(s);
2780 if (sp) {
2781 g_free(sp);
2782 sp = NULL;
2784 s = sl;
2785 for (i = 0; i < LENGTH(subs); ++i) {
2786 sv = g_strsplit(sl, subs[i].s, -1);
2787 if (sl)
2788 g_free(sl);
2789 sl = g_strjoinv(subs[i].f(t), sv);
2790 g_strfreev(sv);
2791 s = sl;
2793 break;
2794 case '.':
2795 t->mode = XT_MODE_HINT;
2796 a.i = 0;
2797 s = ".";
2799 * js code will auto fire() if a single link is visible,
2800 * causing the focus-out-event cb function to be called. Setup
2801 * the cmd _before_ triggering hinting code so the cmd can get
2802 * killed by the cb in this case.
2804 show_cmd(t, s);
2805 cmd_setup = 1;
2806 hint(t, &a);
2807 break;
2808 case ',':
2809 t->mode = XT_MODE_HINT;
2810 a.i = XT_HINT_NEWTAB;
2811 s = ",";
2812 show_cmd(t, s);
2813 cmd_setup = 1;
2814 hint(t, &a);
2815 break;
2816 default:
2817 show_oops(t, "command: invalid opcode %d", args->i);
2818 return (XT_CB_PASSTHROUGH);
2821 DNPRINTF(XT_D_CMD, "%s: tab %d type %s\n", __func__, t->tab_id, s);
2823 if (!cmd_setup)
2824 show_cmd(t, s);
2826 if (sp)
2827 g_free(sp);
2828 if (sl)
2829 g_free(sl);
2831 return (XT_CB_HANDLED);
2835 search(struct tab *t, struct karg *args)
2837 gboolean d;
2839 if (t == NULL || args == NULL) {
2840 show_oops(NULL, "search invalid parameters");
2841 return (1);
2844 switch (args->i) {
2845 case XT_SEARCH_NEXT:
2846 d = t->search_forward;
2847 break;
2848 case XT_SEARCH_PREV:
2849 d = !t->search_forward;
2850 break;
2851 default:
2852 return (XT_CB_PASSTHROUGH);
2855 if (t->search_text == NULL) {
2856 if (global_search == NULL)
2857 return (XT_CB_PASSTHROUGH);
2858 else {
2859 d = t->search_forward = TRUE;
2860 t->search_text = g_strdup(global_search);
2861 webkit_web_view_mark_text_matches(t->wv, global_search, FALSE, 0);
2862 webkit_web_view_set_highlight_text_matches(t->wv, TRUE);
2866 DNPRINTF(XT_D_CMD, "search: tab %d opc %d forw %d text %s\n",
2867 t->tab_id, args->i, t->search_forward, t->search_text);
2869 webkit_web_view_search_text(t->wv, t->search_text, FALSE, d, TRUE);
2871 return (XT_CB_HANDLED);
2875 session_save(struct tab *t, char *filename)
2877 struct karg a;
2878 int rv = 1;
2879 struct session *s;
2881 if (strlen(filename) == 0)
2882 goto done;
2884 if (filename[0] == '.' || filename[0] == '/')
2885 goto done;
2887 a.s = filename;
2888 if (save_tabs(t, &a))
2889 goto done;
2890 strlcpy(named_session, filename, sizeof named_session);
2892 /* add the new session to the list of sessions */
2893 s = g_malloc(sizeof(struct session));
2894 s->name = g_strdup(filename);
2895 TAILQ_INSERT_TAIL(&sessions, s, entry);
2897 rv = 0;
2898 done:
2899 return (rv);
2903 session_open(struct tab *t, char *filename)
2905 struct karg a;
2906 int rv = 1;
2908 if (strlen(filename) == 0)
2909 goto done;
2911 if (filename[0] == '.' || filename[0] == '/')
2912 goto done;
2914 a.s = filename;
2915 a.i = XT_SES_CLOSETABS;
2916 if (open_tabs(t, &a))
2917 goto done;
2919 strlcpy(named_session, filename, sizeof named_session);
2921 rv = 0;
2922 done:
2923 return (rv);
2927 session_delete(struct tab *t, char *filename)
2929 char file[PATH_MAX];
2930 int rv = 1;
2931 struct session *s;
2933 if (strlen(filename) == 0)
2934 goto done;
2936 if (filename[0] == '.' || filename[0] == '/')
2937 goto done;
2939 snprintf(file, sizeof file, "%s" PS "%s", sessions_dir, filename);
2940 if (unlink(file))
2941 goto done;
2943 if (!strcmp(filename, named_session))
2944 strlcpy(named_session, XT_SAVED_TABS_FILE,
2945 sizeof named_session);
2947 /* remove session from sessions list */
2948 TAILQ_FOREACH(s, &sessions, entry) {
2949 if (!strcmp(s->name, filename))
2950 break;
2952 if (s == NULL)
2953 goto done;
2954 TAILQ_REMOVE(&sessions, s, entry);
2955 g_free((gpointer) s->name);
2956 g_free(s);
2958 rv = 0;
2959 done:
2960 return (rv);
2964 session_cmd(struct tab *t, struct karg *args)
2966 char *filename = args->s;
2968 if (t == NULL)
2969 return (1);
2971 if (args->i & XT_SHOW)
2972 show_oops(t, "Current session: %s", named_session[0] == '\0' ?
2973 XT_SAVED_TABS_FILE : named_session);
2974 else if (args->i & XT_SAVE) {
2975 if (session_save(t, filename)) {
2976 show_oops(t, "Can't save session: %s",
2977 filename ? filename : "INVALID");
2978 goto done;
2980 } else if (args->i & XT_OPEN) {
2981 if (session_open(t, filename)) {
2982 show_oops(t, "Can't open session: %s",
2983 filename ? filename : "INVALID");
2984 goto done;
2986 } else if (args->i & XT_DELETE) {
2987 if (session_delete(t, filename)) {
2988 show_oops(t, "Can't delete session: %s",
2989 filename ? filename : "INVALID");
2990 goto done;
2993 done:
2994 return (XT_CB_PASSTHROUGH);
2998 script_cmd(struct tab *t, struct karg *args)
3000 struct stat sb;
3001 FILE *f = NULL;
3002 char *buf = NULL;
3004 if (t == NULL)
3005 goto done;
3007 if ((f = fopen(args->s, "r")) == NULL) {
3008 show_oops(t, "Can't open script file: %s", args->s);
3009 goto done;
3012 if (fstat(fileno(f), &sb) == -1) {
3013 show_oops(t, "Can't stat script file: %s", args->s);
3014 goto done;
3017 buf = g_malloc0(sb.st_size + 1);
3018 if (fread(buf, 1, sb.st_size, f) != sb.st_size) {
3019 show_oops(t, "Can't read script file: %s", args->s);
3020 goto done;
3023 DNPRINTF(XT_D_JS, "%s: about to run script\n", __func__);
3024 run_script(t, buf);
3026 done:
3027 if (f)
3028 fclose(f);
3029 if (buf)
3030 g_free(buf);
3032 return (XT_CB_PASSTHROUGH);
3036 * Make a hardcopy of the page
3039 print_page(struct tab *t, struct karg *args)
3041 WebKitWebFrame *frame;
3042 GtkPageSetup *ps;
3043 GtkPrintOperation *op;
3044 GtkPrintOperationAction action;
3045 GtkPrintOperationResult print_res;
3046 GError *g_err = NULL;
3047 int marg_l, marg_r, marg_t, marg_b;
3048 int ret = 0;
3050 DNPRINTF(XT_D_PRINTING, "%s:", __func__);
3052 ps = gtk_page_setup_new();
3053 op = gtk_print_operation_new();
3054 action = GTK_PRINT_OPERATION_ACTION_PRINT_DIALOG;
3055 frame = webkit_web_view_get_main_frame(t->wv);
3057 /* the default margins are too small, so we will bump them */
3058 marg_l = gtk_page_setup_get_left_margin(ps, GTK_UNIT_MM) +
3059 XT_PRINT_EXTRA_MARGIN;
3060 marg_r = gtk_page_setup_get_right_margin(ps, GTK_UNIT_MM) +
3061 XT_PRINT_EXTRA_MARGIN;
3062 marg_t = gtk_page_setup_get_top_margin(ps, GTK_UNIT_MM) +
3063 XT_PRINT_EXTRA_MARGIN;
3064 marg_b = gtk_page_setup_get_bottom_margin(ps, GTK_UNIT_MM) +
3065 XT_PRINT_EXTRA_MARGIN;
3067 /* set margins */
3068 gtk_page_setup_set_left_margin(ps, marg_l, GTK_UNIT_MM);
3069 gtk_page_setup_set_right_margin(ps, marg_r, GTK_UNIT_MM);
3070 gtk_page_setup_set_top_margin(ps, marg_t, GTK_UNIT_MM);
3071 gtk_page_setup_set_bottom_margin(ps, marg_b, GTK_UNIT_MM);
3073 gtk_print_operation_set_default_page_setup(op, ps);
3075 print_res = webkit_web_frame_print_full(frame, op, action, &g_err);
3077 /* check it worked */
3078 if (print_res == GTK_PRINT_OPERATION_RESULT_ERROR) {
3079 show_oops(NULL, "can't print: %s", g_err->message);
3080 g_error_free (g_err);
3081 ret = 1;
3084 g_object_unref(G_OBJECT(ps));
3085 g_object_unref(G_OBJECT(op));
3086 return (ret);
3090 go_home(struct tab *t, struct karg *args)
3092 load_uri(t, home);
3093 return (0);
3097 set_encoding(struct tab *t, struct karg *args)
3099 const gchar *e;
3101 if (args->s && strlen(g_strstrip(args->s)) == 0) {
3102 e = webkit_web_view_get_custom_encoding(t->wv);
3103 if (e == NULL)
3104 e = webkit_web_view_get_encoding(t->wv);
3105 show_oops(t, "encoding: %s", e ? e : "N/A");
3106 } else
3107 webkit_web_view_set_custom_encoding(t->wv, args->s);
3109 return (0);
3113 restart(struct tab *t, struct karg *args)
3115 struct karg a;
3117 a.s = XT_RESTART_TABS_FILE;
3118 save_tabs(t, &a);
3119 execvp(start_argv[0], start_argv);
3120 /* NOTREACHED */
3122 return (0);
3125 char *http_proxy_save; /* not a setting, used to toggle */
3128 proxy_cmd(struct tab *t, struct karg *args)
3130 struct tab *tt;
3132 DNPRINTF(XT_D_CMD, "%s: tab %d\n", __func__, t->tab_id);
3134 if (t == NULL)
3135 return (1);
3137 /* setup */
3138 if (http_proxy) {
3139 TAILQ_FOREACH(tt, &tabs, entry)
3140 gtk_widget_show(t->proxy_toggle);
3141 if (http_proxy_save)
3142 g_free(http_proxy_save);
3143 http_proxy_save = g_strdup(http_proxy);
3146 if (args->i & XT_PRXY_SHOW) {
3147 if (http_proxy)
3148 show_oops(t, "http_proxy = %s", http_proxy);
3149 else
3150 show_oops(t, "proxy is currently disabled");
3151 } else if (args->i & XT_PRXY_TOGGLE) {
3152 if (http_proxy_save == NULL && http_proxy == NULL) {
3153 show_oops(t, "can't toggle proxy");
3154 goto done;
3156 TAILQ_FOREACH(tt, &tabs, entry)
3157 gtk_widget_show(t->proxy_toggle);
3158 if (http_proxy) {
3159 if (setup_proxy(NULL) == 0)
3160 button_set_file(t->proxy_toggle,
3161 "tordisabled.ico");
3162 show_oops(t, "http proxy disabled");
3163 } else {
3164 if (setup_proxy(http_proxy_save) == 0 && http_proxy) {
3165 button_set_file(t->proxy_toggle,
3166 "torenabled.ico");
3167 show_oops(t, "http_proxy = %s", http_proxy);
3168 } else
3169 show_oops(t, "invalid proxy: %s", http_proxy_save);
3172 done:
3173 return (XT_CB_PASSTHROUGH);
3177 * If you can read this functionthen you are a sick and twisted individual.
3178 * I hope we never meet, it'll be violent.
3180 gboolean
3181 eval_cb(const GMatchInfo *info, GString *res, gpointer data)
3183 gchar *match, *num;
3184 gint start = -1, end = -1, i;
3185 struct karg *args = data;
3188 * match contains the string UP TO the match.
3190 * res is what is returned, note that whatever remains in the sent in
3191 * string is appended on the way out.
3193 * for example /123/456/789/moo came in
3194 * match contains /123/456/789/
3195 * we assign that to res and replace /789/ with the replacement text
3196 * then g_regex_replace_eval on the way out has /123/456/replacement/moo
3199 match = g_match_info_fetch(info, 0);
3200 if (match == NULL)
3201 goto done;
3203 if (g_match_info_fetch_pos(info, 1, &start, &end) == FALSE)
3204 goto freeit;
3206 g_string_assign(res, match);
3208 i = atoi(&match[start + 1]);
3209 if (args->i == XT_URL_PLUS)
3210 i++;
3211 else
3212 i--;
3214 /* preserve whitespace when likely */
3215 num = g_strdup_printf("%0*d", end - start - 2, i);
3216 g_string_overwrite_len(res, start + 1, num, end - start - 2);
3217 g_free(num);
3219 freeit:
3220 g_free(match);
3221 done:
3222 return (FALSE); /* doesn't matter */
3226 urlmod_cmd(struct tab *t, struct karg *args)
3228 const gchar *uri;
3229 GRegex *reg;
3230 gchar *res;
3232 if (t == NULL)
3233 goto done;
3234 if ((uri = gtk_entry_get_text(GTK_ENTRY(t->uri_entry))) == NULL)
3235 goto done;
3236 if (strlen(uri) == 0)
3237 goto done;
3239 reg = g_regex_new(".*(/[0-9]+/)", 0, 0, NULL);
3240 if (reg == NULL)
3241 goto done;
3242 res = g_regex_replace_eval(reg, uri, -1, 0, 0, eval_cb, args, NULL);
3243 if (res == NULL)
3244 goto free_reg;
3246 if (!strcmp(res, uri))
3247 goto free_res;
3249 gtk_entry_set_text(GTK_ENTRY(t->uri_entry), res);
3250 activate_uri_entry_cb(t->uri_entry, t);
3252 free_res:
3253 g_free(res);
3254 free_reg:
3255 g_regex_unref(reg);
3256 done:
3257 return (XT_CB_PASSTHROUGH);
3260 struct cmd {
3261 char *cmd;
3262 int level;
3263 int (*func)(struct tab *, struct karg *);
3264 int arg;
3265 int type;
3266 } cmds[] = {
3267 { "command_mode", 0, command_mode, XT_MODE_COMMAND, 0 },
3268 { "insert_mode", 0, command_mode, XT_MODE_INSERT, 0 },
3269 { "command", 0, command, ':', 0 },
3270 { "search", 0, command, '/', 0 },
3271 { "searchb", 0, command, '?', 0 },
3272 { "hinting", 0, command, '.', 0 },
3273 { "hinting_newtab", 0, command, ',', 0 },
3274 { "togglesrc", 0, toggle_src, 0, 0 },
3275 { "editsrc", 0, edit_src, 0, 0 },
3276 { "editelement", 0, edit_element, 0, 0 },
3277 { "passthrough", 0, passthrough, 0, 0 },
3278 { "modurl", 0, modurl, 0, 0 },
3279 { "modsearchentry", 0, modsearchentry, 0, 0 },
3281 /* yanking and pasting */
3282 { "yankuri", 0, yank_uri, 0, 0 },
3283 { "pasteuricur", 0, paste_uri, XT_PASTE_CURRENT_TAB, 0 },
3284 { "pasteurinew", 0, paste_uri, XT_PASTE_NEW_TAB, 0 },
3286 /* search */
3287 { "searchnext", 0, search, XT_SEARCH_NEXT, 0 },
3288 { "searchprevious", 0, search, XT_SEARCH_PREV, 0 },
3290 /* focus */
3291 { "focusaddress", 0, focus, XT_FOCUS_URI, 0 },
3292 { "focussearch", 0, focus, XT_FOCUS_SEARCH, 0 },
3294 /* hinting */
3295 { "hinting", 0, hint, 0, 0 },
3296 { "hinting_newtab", 0, hint, XT_HINT_NEWTAB, 0 },
3298 /* custom stylesheet */
3299 { "userstyle", 0, userstyle_cmd, XT_STYLE_CURRENT_TAB, XT_USERARG },
3300 { "userstyle_global", 0, userstyle_cmd, XT_STYLE_GLOBAL, XT_USERARG },
3302 /* navigation */
3303 { "goback", 0, navaction, XT_NAV_BACK, 0 },
3304 { "goforward", 0, navaction, XT_NAV_FORWARD, 0 },
3305 { "reload", 0, navaction, XT_NAV_RELOAD, 0 },
3306 { "stop", 0, navaction, XT_NAV_STOP, 0 },
3308 /* vertical movement */
3309 { "scrolldown", 0, move, XT_MOVE_DOWN, 0 },
3310 { "scrollup", 0, move, XT_MOVE_UP, 0 },
3311 { "scrollbottom", 0, move, XT_MOVE_BOTTOM, 0 },
3312 { "scrolltop", 0, move, XT_MOVE_TOP, 0 },
3313 { "1", 0, move, XT_MOVE_TOP, 0 },
3314 { "scrollhalfdown", 0, move, XT_MOVE_HALFDOWN, 0 },
3315 { "scrollhalfup", 0, move, XT_MOVE_HALFUP, 0 },
3316 { "scrollpagedown", 0, move, XT_MOVE_PAGEDOWN, 0 },
3317 { "scrollpageup", 0, move, XT_MOVE_PAGEUP, 0 },
3318 /* horizontal movement */
3319 { "scrollright", 0, move, XT_MOVE_RIGHT, 0 },
3320 { "scrollleft", 0, move, XT_MOVE_LEFT, 0 },
3321 { "scrollfarright", 0, move, XT_MOVE_FARRIGHT, 0 },
3322 { "scrollfarleft", 0, move, XT_MOVE_FARLEFT, 0 },
3324 { "favorites", 0, xtp_page_fl, XT_SHOW, 0 },
3325 { "fav", 0, xtp_page_fl, XT_SHOW, 0 },
3326 { "favedit", 0, xtp_page_fl, XT_SHOW|XT_DELETE, 0 },
3327 { "favadd", 0, add_favorite, 0, XT_USERARG },
3329 { "qall", 0, quit, 0, 0 },
3330 { "quitall", 0, quit, 0, 0 },
3331 { "w", 0, save_tabs, 0, 0 },
3332 { "wq", 0, save_tabs_and_quit, 0, 0 },
3333 { "help", 0, help, 0, 0 },
3334 { "about", 0, xtp_page_ab, 0, 0 },
3335 { "stats", 0, stats, 0, 0 },
3336 { "version", 0, xtp_page_ab, 0, 0 },
3338 /* js command */
3339 { "js", 0, js_cmd, XT_SHOW | XT_WL_PERSISTENT | XT_WL_SESSION, 0 },
3340 { "save", 1, js_cmd, XT_SAVE | XT_WL_FQDN, 0 },
3341 { "domain", 2, js_cmd, XT_SAVE | XT_WL_TOPLEVEL, 0 },
3342 { "fqdn", 2, js_cmd, XT_SAVE | XT_WL_FQDN, 0 },
3343 { "show", 1, js_cmd, XT_SHOW | XT_WL_PERSISTENT | XT_WL_SESSION, 0 },
3344 { "all", 2, js_cmd, XT_SHOW | XT_WL_PERSISTENT | XT_WL_SESSION, 0 },
3345 { "persistent", 2, js_cmd, XT_SHOW | XT_WL_PERSISTENT, 0 },
3346 { "session", 2, js_cmd, XT_SHOW | XT_WL_SESSION, 0 },
3347 { "toggle", 1, js_cmd, XT_WL_TOGGLE | XT_WL_FQDN, 0 },
3348 { "domain", 2, js_cmd, XT_WL_TOGGLE | XT_WL_TOPLEVEL, 0 },
3349 { "fqdn", 2, js_cmd, XT_WL_TOGGLE | XT_WL_FQDN, 0 },
3351 /* cookie command */
3352 { "cookie", 0, cookie_cmd, XT_SHOW | XT_WL_PERSISTENT | XT_WL_SESSION, 0 },
3353 { "save", 1, cookie_cmd, XT_SAVE | XT_WL_FQDN, 0 },
3354 { "domain", 2, cookie_cmd, XT_SAVE | XT_WL_TOPLEVEL, 0 },
3355 { "fqdn", 2, cookie_cmd, XT_SAVE | XT_WL_FQDN, 0 },
3356 { "show", 1, cookie_cmd, XT_SHOW | XT_WL_PERSISTENT | XT_WL_SESSION, 0 },
3357 { "all", 2, cookie_cmd, XT_SHOW | XT_WL_PERSISTENT | XT_WL_SESSION, 0 },
3358 { "persistent", 2, cookie_cmd, XT_SHOW | XT_WL_PERSISTENT, 0 },
3359 { "session", 2, cookie_cmd, XT_SHOW | XT_WL_SESSION, 0 },
3360 { "toggle", 1, cookie_cmd, XT_WL_TOGGLE | XT_WL_FQDN, 0 },
3361 { "domain", 2, cookie_cmd, XT_WL_TOGGLE | XT_WL_TOPLEVEL, 0 },
3362 { "fqdn", 2, cookie_cmd, XT_WL_TOGGLE | XT_WL_FQDN, 0 },
3363 { "purge", 1, cookie_cmd, XT_DELETE, 0 },
3365 /* plugin command */
3366 { "plugin", 0, pl_cmd, XT_SHOW | XT_WL_PERSISTENT | XT_WL_SESSION, 0 },
3367 { "save", 1, pl_cmd, XT_SAVE | XT_WL_FQDN, 0 },
3368 { "domain", 2, pl_cmd, XT_SAVE | XT_WL_TOPLEVEL, 0 },
3369 { "fqdn", 2, pl_cmd, XT_SAVE | XT_WL_FQDN, 0 },
3370 { "show", 1, pl_cmd, XT_SHOW | XT_WL_PERSISTENT | XT_WL_SESSION, 0 },
3371 { "all", 2, pl_cmd, XT_SHOW | XT_WL_PERSISTENT | XT_WL_SESSION, 0 },
3372 { "persistent", 2, pl_cmd, XT_SHOW | XT_WL_PERSISTENT, 0 },
3373 { "session", 2, pl_cmd, XT_SHOW | XT_WL_SESSION, 0 },
3374 { "toggle", 1, pl_cmd, XT_WL_TOGGLE | XT_WL_FQDN, 0 },
3375 { "domain", 2, pl_cmd, XT_WL_TOGGLE | XT_WL_TOPLEVEL, 0 },
3376 { "fqdn", 2, pl_cmd, XT_WL_TOGGLE | XT_WL_FQDN, 0 },
3378 /* https command */
3379 { "https", 0, https_cmd, XT_SHOW | XT_WL_PERSISTENT | XT_WL_SESSION, 0 },
3380 { "save", 1, https_cmd, XT_SAVE | XT_WL_FQDN, 0 },
3381 { "domain", 2, https_cmd, XT_SAVE | XT_WL_TOPLEVEL, 0 },
3382 { "fqdn", 2, https_cmd, XT_SAVE | XT_WL_FQDN, 0 },
3383 { "show", 1, https_cmd, XT_SHOW | XT_WL_PERSISTENT | XT_WL_SESSION, 0 },
3384 { "all", 2, https_cmd, XT_SHOW | XT_WL_PERSISTENT | XT_WL_SESSION, 0 },
3385 { "persistent", 2, https_cmd, XT_SHOW | XT_WL_PERSISTENT, 0 },
3386 { "session", 2, https_cmd, XT_SHOW | XT_WL_SESSION, 0 },
3387 { "toggle", 1, https_cmd, XT_WL_TOGGLE | XT_WL_FQDN, 0 },
3388 { "domain", 2, https_cmd, XT_WL_TOGGLE | XT_WL_TOPLEVEL, 0 },
3389 { "fqdn", 2, https_cmd, XT_WL_TOGGLE | XT_WL_FQDN, 0 },
3391 /* toplevel (domain) command */
3392 { "toplevel", 0, toplevel_cmd, XT_WL_TOGGLE | XT_WL_TOPLEVEL | XT_WL_RELOAD, 0 },
3393 { "toggle", 1, toplevel_cmd, XT_WL_TOGGLE | XT_WL_TOPLEVEL | XT_WL_RELOAD, 0 },
3395 /* cookie jar */
3396 { "cookiejar", 0, xtp_page_cl, 0, 0 },
3398 /* cert command */
3399 { "cert", 0, cert_cmd, XT_SHOW, 0 },
3400 { "save", 1, cert_cmd, XT_SAVE, 0 },
3401 { "show", 1, cert_cmd, XT_SHOW, 0 },
3403 { "ca", 0, ca_cmd, 0, 0 },
3404 { "downloadmgr", 0, xtp_page_dl, 0, 0 },
3405 { "dl", 0, xtp_page_dl, 0, 0 },
3406 { "h", 0, xtp_page_hl, 0, 0 },
3407 { "history", 0, xtp_page_hl, 0, 0 },
3408 { "home", 0, go_home, 0, 0 },
3409 { "restart", 0, restart, 0, 0 },
3410 { "urlhide", 0, urlaction, XT_URL_HIDE, 0 },
3411 { "urlshow", 0, urlaction, XT_URL_SHOW, 0 },
3412 { "statustoggle", 0, statustoggle, 0, 0 },
3413 { "run_script", 0, run_page_script, 0, XT_USERARG },
3415 { "print", 0, print_page, 0, 0 },
3417 /* tabs */
3418 { "focusin", 0, resizetab, XT_ZOOM_IN, 0 },
3419 { "focusout", 0, resizetab, XT_ZOOM_OUT, 0 },
3420 { "focusreset", 0, resizetab, XT_ZOOM_NORMAL, 0 },
3421 { "q", 0, tabaction, XT_TAB_DELQUIT, 0 },
3422 { "quit", 0, tabaction, XT_TAB_DELQUIT, 0 },
3423 { "open", 0, tabaction, XT_TAB_OPEN, XT_URLARG },
3424 { "tabclose", 0, tabaction, XT_TAB_DELETE, XT_PREFIX | XT_INTARG},
3425 { "tabedit", 0, tabaction, XT_TAB_NEW, XT_PREFIX | XT_URLARG },
3426 { "tabfirst", 0, movetab, XT_TAB_FIRST, 0 },
3427 { "tabhide", 0, tabaction, XT_TAB_HIDE, 0 },
3428 { "tablast", 0, movetab, XT_TAB_LAST, 0 },
3429 { "tabnew", 0, tabaction, XT_TAB_NEW, XT_PREFIX | XT_URLARG },
3430 { "tabnext", 0, movetab, XT_TAB_NEXT, XT_PREFIX | XT_INTARG},
3431 { "tabnextstyle", 0, tabaction, XT_TAB_NEXTSTYLE, 0 },
3432 { "tabonly", 0, tabaction, XT_TAB_ONLY, 0 },
3433 { "tabprevious", 0, movetab, XT_TAB_PREV, XT_PREFIX | XT_INTARG},
3434 { "tabrewind", 0, movetab, XT_TAB_FIRST, 0 },
3435 { "tabshow", 0, tabaction, XT_TAB_SHOW, 0 },
3436 { "tabs", 0, buffers, 0, 0 },
3437 { "tabundoclose", 0, tabaction, XT_TAB_UNDO_CLOSE, 0 },
3438 { "buffers", 0, buffers, 0, 0 },
3439 { "ls", 0, buffers, 0, 0 },
3440 { "encoding", 0, set_encoding, 0, XT_USERARG },
3441 { "loadimages", 0, tabaction, XT_TAB_LOAD_IMAGES, 0 },
3443 /* settings */
3444 { "set", 0, set, 0, XT_SETARG },
3445 { "runtime", 0, xtp_page_rt, 0, 0 },
3447 { "fullscreen", 0, fullscreen, 0, 0 },
3448 { "f", 0, fullscreen, 0, 0 },
3450 /* sessions */
3451 { "session", 0, session_cmd, XT_SHOW, 0 },
3452 { "delete", 1, session_cmd, XT_DELETE, XT_SESSARG },
3453 { "open", 1, session_cmd, XT_OPEN, XT_SESSARG },
3454 { "save", 1, session_cmd, XT_SAVE, XT_USERARG },
3455 { "show", 1, session_cmd, XT_SHOW, 0 },
3457 /* external javascript */
3458 { "script", 0, script_cmd, XT_EJS_SHOW, XT_USERARG },
3460 /* inspector */
3461 { "inspector", 0, inspector_cmd, XT_INS_SHOW, 0 },
3462 { "show", 1, inspector_cmd, XT_INS_SHOW, 0 },
3463 { "hide", 1, inspector_cmd, XT_INS_HIDE, 0 },
3465 /* proxy */
3466 { "proxy", 0, proxy_cmd, XT_PRXY_SHOW, 0 },
3467 { "show", 1, proxy_cmd, XT_PRXY_SHOW, 0 },
3468 { "toggle", 1, proxy_cmd, XT_PRXY_TOGGLE, 0 },
3470 /* url mod */
3471 { "urlmod", 0, urlmod_cmd, XT_URL, 0 },
3472 { "plus", 1, urlmod_cmd, XT_URL_PLUS, 0 },
3473 { "min", 1, urlmod_cmd, XT_URL_MIN, 0 },
3476 struct {
3477 int index;
3478 int len;
3479 gchar *list[256];
3480 } cmd_status = {-1, 0};
3482 gboolean
3483 wv_release_button_cb(GtkWidget *btn, GdkEventButton *e, struct tab *t)
3486 if (e->type == GDK_BUTTON_RELEASE && e->button == 1)
3487 btn_down = 0;
3489 return (FALSE);
3492 gboolean
3493 wv_button_cb(GtkWidget *btn, GdkEventButton *e, struct tab *t)
3495 struct karg a;
3496 WebKitHitTestResult *hit_test_result;
3497 guint context;
3499 hit_test_result = webkit_web_view_get_hit_test_result(t->wv, e);
3500 g_object_get(hit_test_result, "context", &context, NULL);
3501 g_object_unref(G_OBJECT(hit_test_result));
3503 hide_oops(t);
3504 hide_buffers(t);
3506 if (context & WEBKIT_HIT_TEST_RESULT_CONTEXT_EDITABLE)
3507 t->mode = XT_MODE_INSERT;
3508 else
3509 t->mode = XT_MODE_COMMAND;
3511 if (e->type == GDK_BUTTON_PRESS && e->button == 1)
3512 btn_down = 1;
3513 else if (e->type == GDK_BUTTON_PRESS && e->button == 8 /* btn 4 */) {
3514 /* go backward */
3515 a.i = XT_NAV_BACK;
3516 navaction(t, &a);
3518 return (TRUE);
3519 } else if (e->type == GDK_BUTTON_PRESS && e->button == 9 /* btn 5 */) {
3520 /* go forward */
3521 a.i = XT_NAV_FORWARD;
3522 navaction(t, &a);
3524 return (TRUE);
3527 return (FALSE);
3530 void
3531 tab_close_cb(GtkWidget *btn, struct tab *t)
3533 DNPRINTF(XT_D_TAB, "tab_close_cb: tab %d\n", t->tab_id);
3535 delete_tab(t);
3539 parse_custom_uri(struct tab *t, const char *uri)
3541 struct custom_uri *u;
3542 int handled = 0;
3543 char *sv[3];
3545 TAILQ_FOREACH(u, &cul, entry) {
3546 if (strncmp(uri, u->uri, strlen(u->uri)))
3547 continue;
3549 handled = 1;
3550 sv[0] = u->cmd;
3551 sv[1] = (char *)uri;
3552 sv[2] = NULL;
3553 if (!g_spawn_async(NULL, sv, NULL, G_SPAWN_SEARCH_PATH, NULL,
3554 NULL, NULL, NULL))
3555 show_oops(t, "%s: could not spawn process", __func__);
3558 return (handled);
3561 void
3562 activate_uri_entry_cb(GtkWidget* entry, struct tab *t)
3564 const gchar *uri = gtk_entry_get_text(GTK_ENTRY(entry));
3566 DNPRINTF(XT_D_URL, "activate_uri_entry_cb: %s\n", uri);
3568 if (t == NULL) {
3569 show_oops(NULL, "activate_uri_entry_cb invalid parameters");
3570 return;
3573 if (uri == NULL) {
3574 show_oops(t, "activate_uri_entry_cb no uri");
3575 return;
3578 uri += strspn(uri, "\t ");
3580 if (parse_custom_uri(t, uri))
3581 return;
3583 /* otherwise continue to load page normally */
3584 load_uri(t, (gchar *)uri);
3585 focus_webview(t);
3588 void
3589 activate_search_entry_cb(GtkWidget* entry, struct tab *t)
3591 const gchar *search = gtk_entry_get_text(GTK_ENTRY(entry));
3592 char *newuri = NULL;
3593 gchar *enc_search;
3594 char **sv;
3596 DNPRINTF(XT_D_URL, "activate_search_entry_cb: %s\n", search);
3598 if (t == NULL) {
3599 show_oops(NULL, "activate_search_entry_cb invalid parameters");
3600 return;
3603 if (search_string == NULL || strlen(search_string) == 0) {
3604 show_oops(t, "no search_string");
3605 return;
3608 set_normal_tab_meaning(t);
3610 enc_search = soup_uri_encode(search, XT_RESERVED_CHARS);
3611 sv = g_strsplit(search_string, "%s", 2);
3612 newuri = g_strjoinv(enc_search, sv);
3613 g_free(enc_search);
3614 g_strfreev(sv);
3616 marks_clear(t);
3617 load_uri(t, newuri);
3618 focus_webview(t);
3620 if (newuri)
3621 g_free(newuri);
3624 void
3625 check_and_set_cookie(const gchar *uri, struct tab *t)
3627 struct wl_entry *w = NULL;
3628 int es = 0;
3630 if (uri == NULL || t == NULL)
3631 return;
3633 if ((w = wl_find_uri(uri, &c_wl)) == NULL)
3634 es = 0;
3635 else
3636 es = 1;
3638 DNPRINTF(XT_D_COOKIE, "check_and_set_cookie: %s %s\n",
3639 es ? "enable" : "disable", uri);
3641 g_object_set(G_OBJECT(t->settings),
3642 "enable-html5-local-storage", es, (char *)NULL);
3643 webkit_web_view_set_settings(t->wv, t->settings);
3646 void
3647 check_and_set_js(const gchar *uri, struct tab *t)
3649 struct wl_entry *w = NULL;
3650 int es = 0;
3652 if (uri == NULL || t == NULL)
3653 return;
3655 if ((w = wl_find_uri(uri, &js_wl)) == NULL)
3656 es = 0;
3657 else
3658 es = 1;
3660 DNPRINTF(XT_D_JS, "check_and_set_js: %s %s\n",
3661 es ? "enable" : "disable", uri);
3663 g_object_set(G_OBJECT(t->settings),
3664 "enable-scripts", es, (char *)NULL);
3665 webkit_web_view_set_settings(t->wv, t->settings);
3667 button_set_icon_name(t->js_toggle,
3668 es ? "media-playback-start" : "media-playback-pause");
3671 void
3672 check_and_set_pl(const gchar *uri, struct tab *t)
3674 struct wl_entry *w = NULL;
3675 int es = 0;
3677 if (uri == NULL || t == NULL)
3678 return;
3680 if ((w = wl_find_uri(uri, &pl_wl)) == NULL)
3681 es = 0;
3682 else
3683 es = 1;
3685 DNPRINTF(XT_D_JS, "check_and_set_pl: %s %s\n",
3686 es ? "enable" : "disable", uri);
3688 g_object_set(G_OBJECT(t->settings),
3689 "enable-plugins", es, (char *)NULL);
3690 webkit_web_view_set_settings(t->wv, t->settings);
3693 #if GTK_CHECK_VERSION(3, 0, 0)
3694 /* A lot of this can be removed when gtk2 is dropped on the floor */
3695 char *
3696 get_css_name(const char *col_str)
3698 char *name = NULL;
3700 if (!strcmp(col_str, XT_COLOR_WHITE))
3701 name = g_strdup(XT_CSS_NORMAL);
3702 else if (!strcmp(col_str, XT_COLOR_RED))
3703 name = g_strdup(XT_CSS_RED);
3704 else if (!strcmp(col_str, XT_COLOR_YELLOW))
3705 name = g_strdup(XT_CSS_YELLOW);
3706 else if (!strcmp(col_str, XT_COLOR_GREEN))
3707 name = g_strdup(XT_CSS_GREEN);
3708 else if (!strcmp(col_str, XT_COLOR_BLUE))
3709 name = g_strdup(XT_CSS_BLUE);
3710 return (name);
3712 #endif
3714 void
3715 show_ca_status(struct tab *t, const char *uri)
3717 char domain[8182], file[PATH_MAX];
3718 SoupMessage *msg = NULL;
3719 GTlsCertificate *cert = NULL;
3720 GTlsCertificateFlags flags = 0;
3721 gchar *col_str = XT_COLOR_RED;
3722 char *cut_uri;
3723 char *chain;
3724 char *s;
3725 #if GTK_CHECK_VERSION(3, 0, 0)
3726 char *name;
3727 #else
3728 GdkColor color;
3729 gchar *text, *base;
3730 #endif
3731 enum cert_trust trust;
3732 int nocolor = 0;
3733 int i;
3735 DNPRINTF(XT_D_URL, "show_ca_status: %d %s %s\n",
3736 ssl_strict_certs, ssl_ca_file, uri);
3738 if (t == NULL)
3739 return;
3741 if (uri == NULL || g_str_has_prefix(uri, "http://") ||
3742 !g_str_has_prefix(uri, "https://"))
3743 return;
3746 * Cut the uri to get the certs off the homepage. We can't use the
3747 * full URI here since it may include arguments and we don't want to make
3748 * these requests multiple times.
3750 cut_uri = g_strdup(uri);
3751 s = cut_uri;
3752 for (i = 0; i < 3; ++i)
3753 s = strchr(&(s[1]), '/');
3754 s[1] = '\0';
3756 msg = soup_message_new("HEAD", cut_uri);
3757 g_free(cut_uri);
3758 if (msg == NULL)
3759 return;
3760 soup_message_set_flags(msg, SOUP_MESSAGE_NO_REDIRECT);
3761 soup_session_send_message(session, msg);
3762 if (msg->status_code == SOUP_STATUS_SSL_FAILED ||
3763 msg->status_code == SOUP_STATUS_TLS_FAILED) {
3764 DNPRINTF(XT_D_URL, "%s: status not ok: %d\n", uri,
3765 msg->status_code);
3766 goto done;
3768 if (!soup_message_get_https_status(msg, &cert, &flags)) {
3769 DNPRINTF(XT_D_URL, "%s: invalid response\n", uri);
3770 goto done;
3772 if (!G_IS_TLS_CERTIFICATE(cert)) {
3773 DNPRINTF(XT_D_URL, "%s: no cert\n", uri);
3774 goto done;
3777 if (flags == 0)
3778 col_str = XT_COLOR_GREEN;
3779 else
3780 col_str = XT_COLOR_YELLOW;
3782 strlcpy(domain, uri + strlen("https://"), sizeof domain);
3783 for (i = 0; i < strlen(domain); i++)
3784 if (domain[i] == '/') {
3785 domain[i] = '\0';
3786 break;
3789 snprintf(file, sizeof file, "%s" PS "%s", certs_dir, domain);
3790 chain = g_strdup("");
3791 if ((trust = check_local_certs(file, cert, &chain)) == CERT_LOCAL)
3792 col_str = XT_COLOR_BLUE;
3793 if (t->pem)
3794 g_free(t->pem);
3795 t->pem = chain;
3797 snprintf(file, sizeof file, "%s" PS "%s", certs_cache_dir, domain);
3798 if (warn_cert_changes) {
3799 if (check_cert_changes(t, cert, file, uri))
3800 nocolor = 1;
3803 done:
3804 g_object_unref(msg);
3805 if (!strcmp(col_str, XT_COLOR_WHITE) || nocolor) {
3806 #if GTK_CHECK_VERSION(3, 0, 0)
3807 gtk_widget_set_name(t->uri_entry, XT_CSS_NORMAL);
3808 statusbar_modify_attr(t, XT_CSS_NORMAL);
3809 #else
3810 text = gdk_color_to_string(
3811 &t->default_style->text[GTK_STATE_NORMAL]);
3812 base = gdk_color_to_string(
3813 &t->default_style->base[GTK_STATE_NORMAL]);
3814 gtk_widget_modify_base(t->uri_entry, GTK_STATE_NORMAL,
3815 &t->default_style->base[GTK_STATE_NORMAL]);
3816 statusbar_modify_attr(t, text, base);
3817 g_free(text);
3818 g_free(base);
3819 #endif
3820 } else {
3821 #if GTK_CHECK_VERSION(3, 0, 0)
3822 name = get_css_name(col_str);
3823 gtk_widget_set_name(t->uri_entry, name);
3824 statusbar_modify_attr(t, name);
3825 g_free(name);
3826 #else
3827 gdk_color_parse(col_str, &color);
3828 gtk_widget_modify_base(t->uri_entry, GTK_STATE_NORMAL, &color);
3829 statusbar_modify_attr(t, XT_COLOR_BLACK, col_str);
3830 #endif
3834 void
3835 free_favicon(struct tab *t)
3837 DNPRINTF(XT_D_DOWNLOAD, "%s: down %p req %p\n",
3838 __func__, t->icon_download, t->icon_request);
3840 if (t->icon_request)
3841 g_object_unref(t->icon_request);
3842 if (t->icon_dest_uri)
3843 g_free(t->icon_dest_uri);
3845 t->icon_request = NULL;
3846 t->icon_dest_uri = NULL;
3849 void
3850 xt_icon_from_name(struct tab *t, gchar *name)
3852 if (!enable_favicon_entry)
3853 return;
3855 gtk_entry_set_icon_from_icon_name(GTK_ENTRY(t->uri_entry),
3856 GTK_ENTRY_ICON_PRIMARY, "text-html");
3857 if (show_url == 0)
3858 gtk_entry_set_icon_from_icon_name(GTK_ENTRY(t->sbe.uri),
3859 GTK_ENTRY_ICON_PRIMARY, "text-html");
3860 else
3861 gtk_entry_set_icon_from_icon_name(GTK_ENTRY(t->sbe.uri),
3862 GTK_ENTRY_ICON_PRIMARY, NULL);
3865 void
3866 xt_icon_from_pixbuf(struct tab *t, GdkPixbuf *pb)
3868 GdkPixbuf *pb_scaled;
3870 if (gdk_pixbuf_get_width(pb) > 16 || gdk_pixbuf_get_height(pb) > 16)
3871 pb_scaled = gdk_pixbuf_scale_simple(pb, 16, 16,
3872 GDK_INTERP_BILINEAR);
3873 else
3874 pb_scaled = pb;
3876 if (enable_favicon_entry) {
3878 /* Classic tabs. */
3879 gtk_entry_set_icon_from_pixbuf(GTK_ENTRY(t->uri_entry),
3880 GTK_ENTRY_ICON_PRIMARY, pb_scaled);
3882 /* Minimal tabs. */
3883 if (show_url == 0) {
3884 gtk_entry_set_icon_from_pixbuf(GTK_ENTRY(t->sbe.uri),
3885 GTK_ENTRY_ICON_PRIMARY, pb_scaled);
3886 } else
3887 gtk_entry_set_icon_from_icon_name(GTK_ENTRY(t->sbe.uri),
3888 GTK_ENTRY_ICON_PRIMARY, NULL);
3891 /* XXX: Only supports the minimal tabs atm. */
3892 if (enable_favicon_tabs)
3893 gtk_image_set_from_pixbuf(GTK_IMAGE(t->tab_elems.favicon),
3894 pb_scaled);
3896 if (pb_scaled != pb)
3897 g_object_unref(pb_scaled);
3900 void
3901 xt_icon_from_file(struct tab *t, char *uri)
3903 GdkPixbuf *pb;
3904 char *file;
3906 if (g_str_has_prefix(uri, "file://"))
3907 file = g_filename_from_uri(uri, NULL, NULL);
3908 else
3909 file = g_strdup(uri);
3911 if (file == NULL)
3912 return;
3914 pb = gdk_pixbuf_new_from_file(file, NULL);
3915 if (pb) {
3916 xt_icon_from_pixbuf(t, pb);
3917 g_object_unref(pb);
3918 } else
3919 xt_icon_from_name(t, "text-html");
3921 g_free(file);
3924 gboolean
3925 is_valid_icon(char *file)
3927 gboolean valid = 0;
3928 const char *mime_type;
3929 GFileInfo *fi;
3930 GFile *gf;
3932 gf = g_file_new_for_path(file);
3933 fi = g_file_query_info(gf, G_FILE_ATTRIBUTE_STANDARD_CONTENT_TYPE, 0,
3934 NULL, NULL);
3935 mime_type = g_file_info_get_content_type(fi);
3936 valid = g_strcmp0(mime_type, "image/x-ico") == 0 ||
3937 g_strcmp0(mime_type, "image/vnd.microsoft.icon") == 0 ||
3938 g_strcmp0(mime_type, "image/png") == 0 ||
3939 g_strcmp0(mime_type, "image/gif") == 0 ||
3940 g_strcmp0(mime_type, "application/octet-stream") == 0;
3941 g_object_unref(fi);
3942 g_object_unref(gf);
3944 return (valid);
3947 void
3948 set_favicon_from_file(struct tab *t, char *uri)
3950 struct stat sb;
3951 char *file;
3953 if (t == NULL || uri == NULL)
3954 return;
3956 if (g_str_has_prefix(uri, "file://"))
3957 file = g_filename_from_uri(uri, NULL, NULL);
3958 else
3959 file = g_strdup(uri);
3961 if (file == NULL)
3962 return;
3964 DNPRINTF(XT_D_DOWNLOAD, "%s: loading %s\n", __func__, file);
3966 if (!stat(file, &sb)) {
3967 if (sb.st_size == 0 || !is_valid_icon(file)) {
3968 /* corrupt icon so trash it */
3969 DNPRINTF(XT_D_DOWNLOAD, "%s: corrupt icon %s\n",
3970 __func__, file);
3971 unlink(file);
3972 /* no need to set icon to default here */
3973 goto done;
3976 xt_icon_from_file(t, file);
3977 done:
3978 g_free(file);
3981 void
3982 favicon_download_status_changed_cb(WebKitDownload *download, GParamSpec *spec,
3983 WebKitWebView *wv)
3985 WebKitDownloadStatus status = webkit_download_get_status(download);
3986 struct tab *tt = NULL, *t = NULL;
3989 * find the webview instead of passing in the tab as it could have been
3990 * deleted from underneath us.
3992 TAILQ_FOREACH(tt, &tabs, entry) {
3993 if (tt->wv == wv) {
3994 t = tt;
3995 break;
3998 if (t == NULL)
3999 return;
4001 DNPRINTF(XT_D_DOWNLOAD, "%s: tab %d status %d\n",
4002 __func__, t->tab_id, status);
4004 switch (status) {
4005 case WEBKIT_DOWNLOAD_STATUS_ERROR:
4006 /* -1 */
4007 t->icon_download = NULL;
4008 free_favicon(t);
4009 break;
4010 case WEBKIT_DOWNLOAD_STATUS_CREATED:
4011 /* 0 */
4012 break;
4013 case WEBKIT_DOWNLOAD_STATUS_STARTED:
4014 /* 1 */
4015 break;
4016 case WEBKIT_DOWNLOAD_STATUS_CANCELLED:
4017 /* 2 */
4018 DNPRINTF(XT_D_DOWNLOAD, "%s: freeing favicon %d\n",
4019 __func__, t->tab_id);
4020 t->icon_download = NULL;
4021 free_favicon(t);
4022 break;
4023 case WEBKIT_DOWNLOAD_STATUS_FINISHED:
4024 /* 3 */
4026 DNPRINTF(XT_D_DOWNLOAD, "%s: setting icon to %s\n",
4027 __func__, t->icon_dest_uri);
4028 set_favicon_from_file(t, t->icon_dest_uri);
4029 /* these will be freed post callback */
4030 t->icon_request = NULL;
4031 t->icon_download = NULL;
4032 break;
4033 default:
4034 break;
4038 void
4039 abort_favicon_download(struct tab *t)
4041 DNPRINTF(XT_D_DOWNLOAD, "%s: down %p\n", __func__, t->icon_download);
4043 #if !WEBKIT_CHECK_VERSION(1, 4, 0)
4044 if (t->icon_download) {
4045 g_signal_handlers_disconnect_by_func(G_OBJECT(t->icon_download),
4046 G_CALLBACK(favicon_download_status_changed_cb), t->wv);
4047 webkit_download_cancel(t->icon_download);
4048 t->icon_download = NULL;
4049 } else
4050 free_favicon(t);
4051 #endif
4053 xt_icon_from_name(t, "text-html");
4056 void
4057 notify_icon_loaded_cb(WebKitWebView *wv, gchar *uri, struct tab *t)
4059 DNPRINTF(XT_D_DOWNLOAD, "%s %s\n", __func__, uri);
4061 if (uri == NULL || t == NULL)
4062 return;
4064 #if WEBKIT_CHECK_VERSION(1, 4, 0)
4065 /* take icon from WebKitIconDatabase */
4066 GdkPixbuf *pb = NULL;
4068 /* webkit_web_view_get_icon_pixbuf is depreciated in 1.8 */
4069 #if WEBKIT_CHECK_VERSION(1, 8, 0)
4071 * If the page was not loaded (for example, via ssl_strict_certs), do
4072 * not attempt to get the webview's pixbuf. This prevents a CRITICAL
4073 * glib warning.
4075 if (wv && webkit_web_view_get_uri(wv))
4076 pb = webkit_web_view_try_get_favicon_pixbuf(wv, 0, 0);
4077 #else
4078 if (wv && webkit_web_view_get_uri(wv))
4079 pb = webkit_web_view_get_icon_pixbuf(wv);
4080 #endif
4081 if (pb) {
4082 xt_icon_from_pixbuf(t, pb);
4083 g_object_unref(pb);
4084 } else
4085 xt_icon_from_name(t, "text-html");
4086 #elif WEBKIT_CHECK_VERSION(1, 1, 18)
4087 /* download icon to cache dir */
4088 gchar *name_hash, file[PATH_MAX];
4089 struct stat sb;
4091 if (t->icon_request) {
4092 DNPRINTF(XT_D_DOWNLOAD, "%s: download in progress\n", __func__);
4093 return;
4096 /* check to see if we got the icon in cache */
4097 name_hash = g_compute_checksum_for_string(G_CHECKSUM_SHA256, uri, -1);
4098 snprintf(file, sizeof file, "%s" PS "%s.ico", cache_dir, name_hash);
4099 g_free(name_hash);
4101 if (!stat(file, &sb)) {
4102 if (sb.st_size > 0) {
4103 DNPRINTF(XT_D_DOWNLOAD, "%s: loading from cache %s\n",
4104 __func__, file);
4105 set_favicon_from_file(t, file);
4106 return;
4109 /* corrupt icon so trash it */
4110 DNPRINTF(XT_D_DOWNLOAD, "%s: corrupt icon %s\n",
4111 __func__, file);
4112 unlink(file);
4115 /* create download for icon */
4116 t->icon_request = webkit_network_request_new(uri);
4117 if (t->icon_request == NULL) {
4118 DNPRINTF(XT_D_DOWNLOAD, "%s: invalid uri %s\n",
4119 __func__, uri);
4120 return;
4123 t->icon_download = webkit_download_new(t->icon_request);
4124 if (t->icon_download == NULL)
4125 return;
4127 /* we have to free icon_dest_uri later */
4128 if ((t->icon_dest_uri = g_filename_to_uri(file, NULL, NULL)) == NULL)
4129 return;
4130 webkit_download_set_destination_uri(t->icon_download,
4131 t->icon_dest_uri);
4133 if (webkit_download_get_status(t->icon_download) ==
4134 WEBKIT_DOWNLOAD_STATUS_ERROR) {
4135 g_object_unref(t->icon_request);
4136 g_free(t->icon_dest_uri);
4137 t->icon_request = NULL;
4138 t->icon_dest_uri = NULL;
4139 return;
4142 g_signal_connect(G_OBJECT(t->icon_download), "notify::status",
4143 G_CALLBACK(favicon_download_status_changed_cb), t->wv);
4145 webkit_download_start(t->icon_download);
4146 #endif
4149 void
4150 notify_load_status_cb(WebKitWebView* wview, GParamSpec* pspec, struct tab *t)
4152 const gchar *uri = NULL;
4153 struct history *h, find;
4154 struct karg a;
4155 #if !GTK_CHECK_VERSION(3, 0, 0)
4156 gchar *text, *base;
4157 #endif
4159 DNPRINTF(XT_D_URL, "notify_load_status_cb: %d %s\n",
4160 webkit_web_view_get_load_status(wview),
4161 get_uri(t) ? get_uri(t) : "NOTHING");
4163 if (t == NULL) {
4164 show_oops(NULL, "notify_load_status_cb invalid parameters");
4165 return;
4168 switch (webkit_web_view_get_load_status(wview)) {
4169 case WEBKIT_LOAD_PROVISIONAL:
4170 /* 0 */
4171 abort_favicon_download(t);
4172 #if GTK_CHECK_VERSION(2, 20, 0)
4173 gtk_widget_show(t->spinner);
4174 gtk_spinner_start(GTK_SPINNER(t->spinner));
4175 #endif
4176 t->download_requested = 0;
4178 gtk_widget_set_sensitive(GTK_WIDGET(t->stop), TRUE);
4180 /* assume we are a new address */
4181 #if GTK_CHECK_VERSION(3, 0, 0)
4182 gtk_widget_set_name(t->uri_entry, XT_CSS_NORMAL);
4183 statusbar_modify_attr(t, XT_CSS_NORMAL);
4184 #else
4185 text = gdk_color_to_string(
4186 &t->default_style->text[GTK_STATE_NORMAL]);
4187 base = gdk_color_to_string(
4188 &t->default_style->base[GTK_STATE_NORMAL]);
4189 gtk_widget_modify_base(t->uri_entry, GTK_STATE_NORMAL,
4190 &t->default_style->base[GTK_STATE_NORMAL]);
4191 statusbar_modify_attr(t, text, base);
4192 g_free(text);
4193 g_free(base);
4194 #endif
4196 /* DOM is changing, unreference the previous focused element */
4197 #if WEBKIT_CHECK_VERSION(1, 5, 0)
4198 if (t->active)
4199 g_object_unref(t->active);
4200 t->active = NULL;
4201 if (t->active_text) {
4202 g_free(t->active_text);
4203 t->active_text = NULL;
4205 #endif
4207 /* take focus if we are visible */
4208 focus_webview(t);
4209 t->focus_wv = 1;
4211 marks_clear(t);
4212 break;
4214 case WEBKIT_LOAD_COMMITTED:
4215 /* 1 */
4216 uri = get_uri(t);
4217 if (uri == NULL)
4218 return;
4219 gtk_entry_set_text(GTK_ENTRY(t->uri_entry), uri);
4221 if (t->status) {
4222 g_free(t->status);
4223 t->status = NULL;
4225 set_status(t, "Loading: %s", (char *)uri);
4227 /* clear t->item, except if we're switching to an about: page */
4228 if (t->item && !g_str_has_prefix(uri, "xxxt://") &&
4229 !g_str_has_prefix(uri, "about:")) {
4230 g_object_unref(t->item);
4231 t->item = NULL;
4234 /* check if js white listing is enabled */
4235 if (enable_plugin_whitelist)
4236 check_and_set_pl(uri, t);
4237 if (enable_cookie_whitelist)
4238 check_and_set_cookie(uri, t);
4239 if (enable_js_whitelist)
4240 check_and_set_js(uri, t);
4242 if (t->styled)
4243 apply_style(t);
4246 /* we know enough to autosave the session */
4247 if (session_autosave) {
4248 a.s = NULL;
4249 save_tabs(t, &a);
4252 show_ca_status(t, uri);
4253 run_script(t, JS_HINTING);
4254 if (enable_autoscroll)
4255 run_script(t, JS_AUTOSCROLL);
4256 break;
4258 case WEBKIT_LOAD_FIRST_VISUALLY_NON_EMPTY_LAYOUT:
4259 /* 3 */
4260 if (color_visited_uris) {
4261 color_visited(t, color_visited_helper());
4264 * This colors the links you middle-click (open in new
4265 * tab) in the current tab.
4267 if (t->tab_id != gtk_notebook_get_current_page(notebook) &&
4268 (uri = get_uri(t)) != NULL)
4269 color_visited(get_current_tab(),
4270 g_strdup_printf("{'%s' : 'dummy'}", uri));
4272 break;
4274 case WEBKIT_LOAD_FINISHED:
4275 /* 2 */
4276 if ((uri = get_uri(t)) == NULL)
4277 return;
4279 /* autorun some js if enabled */
4280 js_autorun(t);
4282 input_autofocus(t);
4284 if (!strncmp(uri, "http://", strlen("http://")) ||
4285 !strncmp(uri, "https://", strlen("https://")) ||
4286 !strncmp(uri, "file://", strlen("file://"))) {
4287 find.uri = (gchar *)uri;
4288 h = RB_FIND(history_list, &hl, &find);
4289 if (!h)
4290 insert_history_item(uri,
4291 get_title(t, FALSE), time(NULL));
4292 else
4293 h->time = time(NULL);
4296 if (statusbar_style == XT_STATUSBAR_URL)
4297 set_status(t, "%s", (char *)uri);
4298 else
4299 set_status(t, "%s", get_title(t, FALSE));
4300 gtk_widget_set_sensitive(GTK_WIDGET(t->stop), FALSE);
4301 #if GTK_CHECK_VERSION(2, 20, 0)
4302 gtk_spinner_stop(GTK_SPINNER(t->spinner));
4303 gtk_widget_hide(t->spinner);
4304 #endif
4305 break;
4307 #if WEBKIT_CHECK_VERSION(1, 1, 18)
4308 case WEBKIT_LOAD_FAILED:
4309 /* 4 */
4310 if (!t->download_requested) {
4311 gtk_label_set_text(GTK_LABEL(t->label),
4312 get_title(t, FALSE));
4313 gtk_label_set_text(GTK_LABEL(t->tab_elems.label),
4314 get_title(t, FALSE));
4315 set_status(t, "%s", (char *)get_title(t, FALSE));
4316 gtk_window_set_title(GTK_WINDOW(main_window),
4317 get_title(t, TRUE));
4318 } else {
4321 #endif
4322 default:
4323 #if GTK_CHECK_VERSION(2, 20, 0)
4324 gtk_spinner_stop(GTK_SPINNER(t->spinner));
4325 gtk_widget_hide(t->spinner);
4326 #endif
4327 gtk_widget_set_sensitive(GTK_WIDGET(t->stop), FALSE);
4328 break;
4331 gtk_widget_set_sensitive(GTK_WIDGET(t->backward),
4332 can_go_back_for_real(t));
4334 gtk_widget_set_sensitive(GTK_WIDGET(t->forward),
4335 can_go_forward_for_real(t));
4338 void
4339 notify_title_cb(WebKitWebView* wview, GParamSpec* pspec, struct tab *t)
4341 const gchar *title = NULL, *win_title = NULL;
4343 title = get_title(t, FALSE);
4344 win_title = get_title(t, TRUE);
4345 if (title) {
4346 gtk_label_set_text(GTK_LABEL(t->label), title);
4347 gtk_label_set_text(GTK_LABEL(t->tab_elems.label), title);
4350 if (win_title && t->tab_id == gtk_notebook_get_current_page(notebook))
4351 gtk_window_set_title(GTK_WINDOW(main_window), win_title);
4354 char *
4355 get_domain(const gchar *host)
4357 size_t x;
4358 char *p;
4360 /* handle silly domains like .co.uk */
4362 if ((x = strlen(host)) <= 6)
4363 return (g_strdup(host));
4365 if (host[x - 3] == '.' && host[x - 6] == '.') {
4366 x = x - 7;
4367 while (x > 0)
4368 if (host[x] != '.')
4369 x--;
4370 else
4371 return (g_strdup(&host[x + 1]));
4374 /* find first . */
4375 p = g_strrstr(host, ".");
4376 if (p == NULL)
4377 return (g_strdup(""));
4378 p--;
4379 while (p > host)
4380 if (*p != '.')
4381 p--;
4382 else
4383 return (g_strdup(p + 1));
4385 return (g_strdup(host));
4388 void
4389 js_autorun(struct tab *t)
4391 SoupURI *su = NULL;
4392 const gchar *uri;
4393 size_t got_default = 0, got_host = 0;
4394 struct stat sb;
4395 char deff[PATH_MAX], hostf[PATH_MAX];
4396 char *js = NULL, *jsat, *domain = NULL;
4397 FILE *deffile = NULL, *hostfile = NULL;
4399 if (enable_js_autorun == 0)
4400 return;
4402 uri = get_uri(t);
4403 if (uri &&
4404 !(g_str_has_prefix(uri, "http://") ||
4405 g_str_has_prefix(uri, "https://")))
4406 goto done;
4408 su = soup_uri_new(uri);
4409 if (su == NULL)
4410 goto done;
4411 if (!SOUP_URI_VALID_FOR_HTTP(su))
4412 goto done;
4414 DNPRINTF(XT_D_JS, "%s: host: %s domain: %s\n", __func__,
4415 su->host, domain);
4416 domain = get_domain(su->host);
4418 snprintf(deff, sizeof deff, "%s" PS "default.js", js_dir);
4419 if ((deffile = fopen(deff, "r")) != NULL) {
4420 if (fstat(fileno(deffile), &sb) == -1) {
4421 show_oops(t, "can't stat default JS file");
4422 goto done;
4424 got_default = sb.st_size;
4427 /* try host first followed by domain */
4428 snprintf(hostf, sizeof hostf, "%s" PS "%s.js", js_dir, su->host);
4429 DNPRINTF(XT_D_JS, "trying file: %s\n", hostf);
4430 if ((hostfile = fopen(hostf, "r")) == NULL) {
4431 snprintf(hostf, sizeof hostf, "%s" PS "%s.js", js_dir, domain);
4432 DNPRINTF(XT_D_JS, "trying file: %s\n", hostf);
4433 if ((hostfile = fopen(hostf, "r")) == NULL)
4434 goto nofile;
4436 DNPRINTF(XT_D_JS, "file: %s\n", hostf);
4437 if (fstat(fileno(hostfile), &sb) == -1) {
4438 show_oops(t, "can't stat %s JS file", hostf);
4439 goto done;
4441 got_host = sb.st_size;
4443 nofile:
4444 if (got_default + got_host == 0)
4445 goto done;
4447 js = g_malloc0(got_default + got_host + 1);
4448 jsat = js;
4450 if (got_default) {
4451 if (fread(js, got_default, 1, deffile) != 1) {
4452 show_oops(t, "default file read error");
4453 goto done;
4455 jsat = js + got_default;
4458 if (got_host) {
4459 if (fread(jsat, got_host, 1, hostfile) != 1) {
4460 show_oops(t, "host file read error");
4461 goto done;
4465 DNPRINTF(XT_D_JS, "%s: about to run script\n", __func__);
4466 run_script(t, js);
4468 done:
4469 if (su)
4470 soup_uri_free(su);
4471 if (js)
4472 g_free(js);
4473 if (deffile)
4474 fclose(deffile);
4475 if (hostfile)
4476 fclose(hostfile);
4477 if (domain)
4478 g_free(domain);
4481 void
4482 webview_progress_changed_cb(WebKitWebView *wv, GParamSpec *pspec, struct tab *t)
4484 gdouble progress;
4486 progress = webkit_web_view_get_progress(wv);
4487 gtk_entry_set_progress_fraction(GTK_ENTRY(t->sbe.uri),
4488 progress > (1.0 - 0.0001) ? 0 : progress);
4489 gtk_entry_set_progress_fraction(GTK_ENTRY(t->uri_entry),
4490 progress > (1.0 - 0.0001) ? 0 : progress);
4492 update_statusbar_position(NULL, NULL);
4496 strict_transport_rb_cmp(struct strict_transport *a, struct strict_transport *b)
4498 char *p1, *p2;
4499 int l1, l2;
4501 /* compare strings from the end */
4502 l1 = strlen(a->host);
4503 l2 = strlen(b->host);
4505 p1 = a->host + l1;
4506 p2 = b->host + l2;
4507 for (; *p1 == *p2 && p1 > a->host && p2 > b->host;
4508 p1--, p2--)
4512 * Check if we need to do pattern expansion,
4513 * or if we're just keeping the tree in order
4515 if (a->flags & XT_STS_FLAGS_EXPAND &&
4516 b->flags & XT_STS_FLAGS_INCLUDE_SUBDOMAINS) {
4517 /* Check if we're matching the
4518 * 'host.xyz' part in '*.host.xyz'
4520 if (p2 == b->host && (p1 == a->host || *(p1-1) == '.')) {
4521 return (0);
4525 if (p1 == a->host && p2 == b->host)
4526 return (0);
4527 if (p1 == a->host)
4528 return (1);
4529 if (p2 == b->host)
4530 return (-1);
4532 if (*p1 < *p2)
4533 return (-1);
4534 if (*p1 > *p2)
4535 return (1);
4537 return (0);
4539 RB_GENERATE(strict_transport_tree, strict_transport, entry,
4540 strict_transport_rb_cmp);
4543 strict_transport_add(const char *domain, time_t timeout, int subdomains)
4545 struct strict_transport *d, find;
4546 time_t now;
4547 FILE *f;
4549 if (enable_strict_transport == FALSE)
4550 return (0);
4552 DPRINTF("strict_transport_add(%s,%" PRIi64 ",%d)\n", domain,
4553 (uint64_t)timeout, subdomains);
4555 now = time(NULL);
4556 if (timeout < now)
4557 return (0);
4559 find.host = (char *)domain;
4560 find.flags = 0;
4561 d = RB_FIND(strict_transport_tree, &st_tree, &find);
4563 /* update flags */
4564 if (d) {
4565 /* check if update is needed */
4566 if (d->timeout == timeout &&
4567 (d->flags & XT_STS_FLAGS_INCLUDE_SUBDOMAINS) == subdomains)
4568 return (0);
4570 d->timeout = timeout;
4571 if (subdomains)
4572 d->flags |= XT_STS_FLAGS_INCLUDE_SUBDOMAINS;
4574 /* We're still initializing */
4575 if (strict_transport_file == NULL)
4576 return (0);
4578 if ((f = fopen(strict_transport_file, "w")) == NULL) {
4579 show_oops(NULL,
4580 "can't open strict-transport rules file");
4581 return (1);
4584 fprintf(f, "# Generated file - do not update unless you know "
4585 "what you're doing\n");
4586 RB_FOREACH(d, strict_transport_tree, &st_tree) {
4587 if (d->timeout < now)
4588 continue;
4589 fprintf(f, "%s\t%" PRIi64 "\t%d\n", d->host,
4590 (uint64_t)d->timeout,
4591 d->flags & XT_STS_FLAGS_INCLUDE_SUBDOMAINS);
4593 fclose(f);
4594 } else {
4595 d = g_malloc(sizeof *d);
4596 d->host= g_strdup(domain);
4597 d->timeout = timeout;
4598 if (subdomains)
4599 d->flags = XT_STS_FLAGS_INCLUDE_SUBDOMAINS;
4600 else
4601 d->flags = 0;
4602 RB_INSERT(strict_transport_tree, &st_tree, d);
4604 /* We're still initializing */
4605 if (strict_transport_file == NULL)
4606 return (0);
4608 if ((f = fopen(strict_transport_file, "a+")) == NULL) {
4609 show_oops(NULL,
4610 "can't open strict-transport rules file");
4611 return (1);
4614 fseek(f, 0, SEEK_END);
4615 fprintf(f,"%s\t%" PRIi64 "\t%d\n", d->host, (uint64_t)timeout,
4616 subdomains);
4617 fclose(f);
4619 return (0);
4623 strict_transport_check(const char *host)
4625 static struct strict_transport *d = NULL;
4626 struct strict_transport find;
4628 if (enable_strict_transport == FALSE)
4629 return (0);
4631 find.host = (char *)host;
4633 /* match for domains that include subdomains */
4634 find.flags = XT_STS_FLAGS_EXPAND;
4636 /* First, check if we're already at the right node */
4637 if (d != NULL && strict_transport_rb_cmp(&find, d) == 0) {
4638 return (1);
4641 d = RB_FIND(strict_transport_tree, &st_tree, &find);
4642 if (d != NULL)
4643 return (1);
4645 return (0);
4649 strict_transport_init()
4651 char file[PATH_MAX];
4652 char delim[3];
4653 char *rule;
4654 char *ptr;
4655 FILE *f;
4656 size_t len;
4657 time_t timeout, now;
4658 int subdomains;
4660 snprintf(file, sizeof file, "%s" PS "%s", work_dir, XT_STS_FILE);
4661 if ((f = fopen(file, "r")) == NULL) {
4662 strict_transport_file = g_strdup(file);
4663 return (0);
4666 delim[0] = '\\';
4667 delim[1] = '\\';
4668 delim[2] = '#';
4669 rule = NULL;
4670 now = time(NULL);
4672 for (;;) {
4673 if ((rule = fparseln(f, &len, NULL, delim, 0)) == NULL) {
4674 if (!feof(f) || ferror(f))
4675 goto corrupt_file;
4676 else
4677 break;
4680 /* get second entry */
4681 if ((ptr = strpbrk(rule, " \t")) == NULL)
4682 goto corrupt_file;
4684 *ptr++ = '\0';
4685 timeout = atoi(ptr);
4687 /* get third entry */
4688 if ((ptr = strpbrk(ptr, " \t")) == NULL)
4689 goto corrupt_file;
4691 ptr ++;
4692 subdomains = atoi(ptr);
4694 if (timeout > now)
4695 strict_transport_add(rule, timeout, subdomains);
4696 free(rule);
4699 fclose(f);
4700 strict_transport_file = g_strdup(file);
4701 return (0);
4703 corrupt_file:
4704 startpage_add("strict-transport rules file ('%s') is corrupt", file);
4705 if (rule)
4706 free(rule);
4707 fclose(f);
4708 return (1);
4712 force_https_check(const char *uri)
4714 struct wl_entry *w = NULL;
4716 if (uri == NULL)
4717 return (0);
4719 if ((w = wl_find_uri(uri, &force_https)) == NULL)
4720 return (0);
4721 else
4722 return (1);
4725 void
4726 strict_transport_security_cb(SoupMessage *msg, gpointer data)
4728 SoupURI *uri;
4729 const char *sts;
4730 char *ptr;
4731 time_t timeout = 0;
4732 int subdomains = FALSE;
4734 if (msg == NULL)
4735 return;
4737 sts = soup_message_headers_get_one(msg->response_headers,
4738 "Strict-Transport-Security");
4739 uri = soup_message_get_uri(msg);
4741 if (sts == NULL || uri == NULL)
4742 return;
4744 if ((ptr = strcasestr(sts, "max-age="))) {
4745 ptr += strlen("max-age=");
4746 timeout = atoll(ptr);
4747 } else
4748 return; /* malformed header - max-age must be included */
4750 if ((ptr = strcasestr(sts, "includeSubDomains")))
4751 subdomains = TRUE;
4753 strict_transport_add(uri->host, timeout + time(NULL), subdomains);
4756 void
4757 session_rq_cb(SoupSession *s, SoupMessage *msg, SoupSocket *socket,
4758 gpointer data)
4760 SoupURI *dest;
4761 SoupURI *ref_uri;
4762 const char *ref;
4764 char *ref_suffix;
4765 char *dest_suffix;
4767 if (s == NULL || msg == NULL)
4768 return;
4770 if (enable_strict_transport) {
4771 soup_message_add_header_handler(msg, "finished",
4772 "Strict-Transport-Security",
4773 G_CALLBACK(strict_transport_security_cb), NULL);
4776 if (referer_mode == XT_REFERER_ALWAYS)
4777 return;
4779 /* Check if referer is set - and what the user requested for referers */
4780 ref = soup_message_headers_get_one(msg->request_headers, "Referer");
4781 if (ref) {
4782 DNPRINTF(XT_D_NAV, "session_rq_cb: Referer: %s\n", ref);
4783 switch (referer_mode) {
4784 case XT_REFERER_NEVER:
4785 DNPRINTF(XT_D_NAV, "session_rq_cb: removing referer\n");
4786 soup_message_headers_remove(msg->request_headers,
4787 "Referer");
4788 break;
4789 case XT_REFERER_SAME_DOMAIN:
4790 ref_uri = soup_uri_new(ref);
4791 dest = soup_message_get_uri(msg);
4793 if (ref_uri == NULL || dest == NULL)
4794 return;
4796 ref_suffix = tld_get_suffix(ref_uri->host);
4797 dest_suffix = tld_get_suffix(dest->host);
4799 if (ref_suffix && dest_suffix &&
4800 strcmp(ref_suffix, dest_suffix) != 0) {
4801 soup_message_headers_remove(msg->request_headers,
4802 "Referer");
4803 DNPRINTF(XT_D_NAV, "session_rq_cb: removing "
4804 "referer (not same domain) (suffixes: %s - %s)\n",
4805 ref_suffix, dest_suffix);
4807 soup_uri_free(ref_uri);
4808 break;
4809 case XT_REFERER_SAME_FQDN:
4810 ref_uri = soup_uri_new(ref);
4811 dest = soup_message_get_uri(msg);
4813 if (ref_uri == NULL || dest == NULL)
4814 return;
4816 if (strcmp(ref_uri->host, dest->host) != 0) {
4817 soup_message_headers_remove(msg->request_headers,
4818 "Referer");
4819 DNPRINTF(XT_D_NAV, "session_rq_cb: removing "
4820 "referer (not same fqdn) (should be %s)\n",
4821 dest->host);
4823 soup_uri_free(ref_uri);
4824 break;
4825 case XT_REFERER_CUSTOM:
4826 DNPRINTF(XT_D_NAV, "session_rq_cb: setting referer "
4827 "to %s\n", referer_custom);
4828 soup_message_headers_replace(msg->request_headers,
4829 "Referer", referer_custom);
4830 break;
4836 webview_npd_cb(WebKitWebView *wv, WebKitWebFrame *wf,
4837 WebKitNetworkRequest *request, WebKitWebNavigationAction *na,
4838 WebKitWebPolicyDecision *pd, struct tab *t)
4840 WebKitWebNavigationReason reason;
4841 char *uri;
4843 if (t == NULL) {
4844 show_oops(NULL, "webview_npd_cb invalid parameters");
4845 return (FALSE);
4848 DNPRINTF(XT_D_NAV, "webview_npd_cb: ctrl_click %d %s\n",
4849 t->ctrl_click,
4850 webkit_network_request_get_uri(request));
4852 uri = (char *)webkit_network_request_get_uri(request);
4854 if (!auto_load_images && t->load_images) {
4856 /* Disable autoloading of images, now that we're done loading
4857 * them. */
4858 g_object_set(G_OBJECT(t->settings),
4859 "auto-load-images", FALSE, (char *)NULL);
4860 webkit_web_view_set_settings(t->wv, t->settings);
4862 t->load_images = FALSE;
4865 /* If this is an xtp url, we don't load anything else. */
4866 if (parse_xtp_url(t, uri)) {
4867 webkit_web_policy_decision_ignore(pd);
4868 return (TRUE);
4871 if (parse_custom_uri(t, uri)) {
4872 webkit_web_policy_decision_ignore(pd);
4873 return (TRUE);
4876 if (valid_url_type(uri)) {
4877 show_oops(t, "Stopping attempt to load an invalid URI (possible"
4878 " bait and switch attack)");
4879 webkit_web_policy_decision_ignore(pd);
4880 return (TRUE);
4883 if ((t->mode == XT_MODE_HINT && t->new_tab) || t->ctrl_click) {
4884 t->ctrl_click = 0;
4885 create_new_tab(uri, NULL, ctrl_click_focus, -1);
4886 webkit_web_policy_decision_ignore(pd);
4887 return (TRUE); /* we made the decission */
4891 * This is a little hairy but it comes down to this:
4892 * when we run in whitelist mode we have to assist the browser in
4893 * opening the URL that it would have opened in a new tab.
4895 reason = webkit_web_navigation_action_get_reason(na);
4896 if (reason == WEBKIT_WEB_NAVIGATION_REASON_LINK_CLICKED) {
4897 set_normal_tab_meaning(t);
4898 if (enable_scripts == 0 && enable_cookie_whitelist == 1)
4899 load_uri(t, uri);
4900 webkit_web_policy_decision_use(pd);
4901 return (TRUE); /* we made the decision */
4904 return (FALSE);
4907 void
4908 webview_rrs_cb(WebKitWebView *wv, WebKitWebFrame *wf, WebKitWebResource *res,
4909 WebKitNetworkRequest *request, WebKitNetworkResponse *response,
4910 struct tab *t)
4912 SoupMessage *msg = NULL;
4913 SoupURI *uri = NULL;
4914 struct http_accept ha_find, *ha = NULL;
4915 struct user_agent ua_find, *ua = NULL;
4916 struct domain_id di_find, *di = NULL;
4917 char *uri_s = NULL;
4919 msg = webkit_network_request_get_message(request);
4920 if (!msg)
4921 return;
4923 uri = soup_message_get_uri(msg);
4924 if (!uri)
4925 return;
4926 uri_s = soup_uri_to_string(uri, FALSE);
4928 if (strcmp(uri->scheme, SOUP_URI_SCHEME_HTTP) == 0) {
4929 if (strict_transport_check(uri->host) ||
4930 force_https_check(uri_s)) {
4931 DNPRINTF(XT_D_NAV, "webview_rrs_cb: force https for %s\n",
4932 uri->host);
4933 soup_uri_set_scheme(uri, SOUP_URI_SCHEME_HTTPS);
4937 if (do_not_track)
4938 soup_message_headers_append(msg->request_headers, "DNT", "1");
4941 * Check if resources on this domain have been loaded before. If
4942 * not, add the current tab's http-accept and user-agent id's to a
4943 * new domain_id and insert into the RB tree. Use these http headers
4944 * for all resources loaded from this domain for the lifetime of the
4945 * browser.
4947 if ((di_find.domain = uri->host) == NULL)
4948 goto done;
4949 if ((di = RB_FIND(domain_id_list, &di_list, &di_find)) == NULL) {
4950 di = g_malloc(sizeof *di);
4951 di->domain = g_strdup(uri->host);
4952 di->ua_id = t->user_agent_id++;
4953 di->ha_id = t->http_accept_id++;
4954 RB_INSERT(domain_id_list, &di_list, di);
4956 ua_find.id = t->user_agent_id;
4957 ua = RB_FIND(user_agent_list, &ua_list, &ua_find);
4958 if (ua == NULL)
4959 t->user_agent_id = 0;
4961 ha_find.id = t->http_accept_id;
4962 ha = RB_FIND(http_accept_list, &ha_list, &ha_find);
4963 if (ha == NULL)
4964 t->http_accept_id = 0;
4967 ua_find.id = di->ua_id;
4968 ua = RB_FIND(user_agent_list, &ua_list, &ua_find);
4969 ha_find.id = di->ha_id;
4970 ha = RB_FIND(http_accept_list, &ha_list, &ha_find);
4972 if (ua != NULL)
4973 soup_message_headers_replace(msg->request_headers,
4974 "User-Agent", ua->value);
4975 if (ha != NULL)
4976 soup_message_headers_replace(msg->request_headers,
4977 "Accept", ha->value);
4979 done:
4980 if (uri_s)
4981 g_free(uri_s);
4984 WebKitWebView *
4985 webview_cwv_cb(WebKitWebView *wv, WebKitWebFrame *wf, struct tab *t)
4987 struct tab *tt;
4988 struct wl_entry *w = NULL;
4989 const gchar *uri;
4990 WebKitWebView *webview = NULL;
4991 int x = 1;
4993 DNPRINTF(XT_D_NAV, "webview_cwv_cb: %s\n",
4994 webkit_web_view_get_uri(wv));
4996 if (tabless) {
4997 /* open in current tab */
4998 webview = t->wv;
4999 } else if (enable_scripts == 0 && enable_js_whitelist == 1) {
5000 uri = webkit_web_view_get_uri(wv);
5001 if (uri && (w = wl_find_uri(uri, &js_wl)) == NULL)
5002 return (NULL);
5004 if (t->ctrl_click) {
5005 x = ctrl_click_focus;
5006 t->ctrl_click = 0;
5008 tt = create_new_tab(NULL, NULL, x, -1);
5009 webview = tt->wv;
5010 } else if (enable_scripts == 1) {
5011 if (t->ctrl_click) {
5012 x = ctrl_click_focus;
5013 t->ctrl_click = 0;
5015 tt = create_new_tab(NULL, NULL, x, -1);
5016 webview = tt->wv;
5019 return (webview);
5022 gboolean
5023 webview_closewv_cb(WebKitWebView *wv, struct tab *t)
5025 const gchar *uri;
5026 struct wl_entry *w = NULL;
5028 DNPRINTF(XT_D_NAV, "webview_close_cb: %d\n", t->tab_id);
5030 if (enable_scripts == 0 && enable_cookie_whitelist == 1) {
5031 uri = webkit_web_view_get_uri(wv);
5032 if (uri && (w = wl_find_uri(uri, &js_wl)) == NULL)
5033 return (FALSE);
5035 delete_tab(t);
5036 } else if (enable_scripts == 1)
5037 delete_tab(t);
5039 return (TRUE);
5043 webview_event_cb(GtkWidget *w, GdkEventButton *e, struct tab *t)
5045 /* we can not eat the event without throwing gtk off so defer it */
5047 /* catch middle click */
5048 if (e->type == GDK_BUTTON_RELEASE && e->button == 2) {
5049 t->ctrl_click = 1;
5050 goto done;
5053 /* catch ctrl click */
5054 if (e->type == GDK_BUTTON_RELEASE &&
5055 CLEAN(e->state) == GDK_CONTROL_MASK)
5056 t->ctrl_click = 1;
5057 else
5058 t->ctrl_click = 0;
5059 done:
5060 return (XT_CB_PASSTHROUGH);
5064 run_mimehandler(struct tab *t, char *mime_type, WebKitNetworkRequest *request)
5066 struct mime_type *m;
5067 char *sv[3];
5068 GError *gerr = NULL;
5070 m = find_mime_type(mime_type);
5071 if (m == NULL)
5072 return (1);
5073 if (m->mt_download)
5074 return (1);
5076 sv[0] = m->mt_action;
5077 sv[1] = (char *)webkit_network_request_get_uri(request);
5078 sv[2] = NULL;
5080 /* ignore donothing from example config */
5081 if (m->mt_action && !strcmp(m->mt_action, "donothing"))
5082 return (0);
5084 if (!g_spawn_async(NULL, sv, NULL, G_SPAWN_SEARCH_PATH, NULL, NULL,
5085 NULL, &gerr))
5086 show_oops(t, "%s: could not spawn process (%s)", __func__,
5087 gerr ? gerr->message : "N/A");
5088 return (0);
5091 char *
5092 get_mime_type(const char *uri)
5094 GFileInfo *fi;
5095 GFile *gf;
5096 const gchar *m;
5097 char *mime_type = NULL;
5098 char *file;
5100 if (uri == NULL) {
5101 show_oops(NULL, "%s: invalid parameters", __func__);
5102 return (NULL);
5105 if (g_str_has_prefix(uri, "file://"))
5106 file = g_filename_from_uri(uri, NULL, NULL);
5107 else
5108 file = g_strdup(uri);
5110 if (file == NULL)
5111 return (NULL);
5113 gf = g_file_new_for_path(file);
5114 fi = g_file_query_info(gf, G_FILE_ATTRIBUTE_STANDARD_CONTENT_TYPE, 0,
5115 NULL, NULL);
5116 if ((m = g_file_info_get_content_type(fi)) != NULL)
5117 mime_type = g_strdup(m);
5118 g_object_unref(fi);
5119 g_object_unref(gf);
5120 g_free(file);
5122 return (mime_type);
5126 run_download_mimehandler(char *mime_type, char *file)
5128 struct mime_type *m;
5129 char *sv[3];
5131 m = find_mime_type(mime_type);
5132 if (m == NULL)
5133 return (1);
5135 sv[0] = m->mt_action;
5136 sv[1] = file;
5137 sv[2] = NULL;
5138 if (!g_spawn_async(NULL, sv, NULL, G_SPAWN_SEARCH_PATH, NULL, NULL,
5139 NULL, NULL)) {
5140 show_oops(NULL, "%s: could not spawn process: %s %s", __func__,
5141 sv[0], sv[1]);
5142 return (1);
5144 return (0);
5147 void
5148 download_status_changed_cb(WebKitDownload *download, GParamSpec *spec,
5149 WebKitWebView *wv)
5151 WebKitDownloadStatus status;
5152 const char *uri;
5153 char *file = NULL;
5154 char *mime = NULL;
5155 char *destination;
5157 if (download == NULL)
5158 return;
5159 status = webkit_download_get_status(download);
5160 if (status != WEBKIT_DOWNLOAD_STATUS_FINISHED)
5161 return;
5163 if (download_notifications) {
5164 /* because basename() takes a char * on linux */
5165 destination = g_strdup(
5166 webkit_download_get_destination_uri(download));
5167 show_oops(NULL, "Download of '%s' finished",
5168 basename(destination));
5169 g_free(destination);
5171 uri = webkit_download_get_destination_uri(download);
5172 if (uri == NULL)
5173 return;
5174 mime = get_mime_type(uri);
5175 if (mime == NULL)
5176 return;
5178 if (g_str_has_prefix(uri, "file://"))
5179 file = g_filename_from_uri(uri, NULL, NULL);
5180 else
5181 file = g_strdup(uri);
5183 if (file == NULL)
5184 goto done;
5186 run_download_mimehandler((char *)mime, file);
5188 done:
5189 g_free(mime);
5193 webview_mimetype_cb(WebKitWebView *wv, WebKitWebFrame *frame,
5194 WebKitNetworkRequest *request, char *mime_type,
5195 WebKitWebPolicyDecision *decision, struct tab *t)
5197 if (t == NULL) {
5198 show_oops(NULL, "webview_mimetype_cb invalid parameters");
5199 return (FALSE);
5202 DNPRINTF(XT_D_DOWNLOAD, "webview_mimetype_cb: tab %d mime %s\n",
5203 t->tab_id, mime_type);
5205 if (run_mimehandler(t, mime_type, request) == 0) {
5206 webkit_web_policy_decision_ignore(decision);
5207 focus_webview(t);
5208 return (TRUE);
5211 if (webkit_web_view_can_show_mime_type(wv, mime_type) == FALSE) {
5212 webkit_web_policy_decision_download(decision);
5213 return (TRUE);
5216 return (FALSE);
5220 download_start(struct tab *t, struct download *d, int flag)
5222 WebKitNetworkRequest *req;
5223 struct stat sb;
5224 const gchar *suggested_name;
5225 gchar *filename = NULL;
5226 char *uri = NULL;
5227 char *path = NULL;
5228 char *destination;
5229 int ret = TRUE;
5230 int i;
5232 if (d == NULL || t == NULL) {
5233 show_oops(NULL, "%s invalid parameters", __func__);
5234 return (FALSE);
5237 suggested_name = webkit_download_get_suggested_filename(d->download);
5238 if (suggested_name == NULL)
5239 return (FALSE); /* abort download */
5241 i = 0;
5242 do {
5243 if (filename) {
5244 g_free(filename);
5245 filename = NULL;
5247 if (i) {
5248 g_free(uri);
5249 uri = NULL;
5250 filename = g_strdup_printf("%d%s", i, suggested_name);
5252 #ifdef __MINGW32__
5253 /* XXX using urls doesn't work properly in windows? */
5254 uri = g_strdup_printf("%s\\%s", download_dir, i ?
5255 filename : suggested_name);
5256 #else
5257 path = g_strdup_printf("%s" PS "%s", download_dir, i ?
5258 filename : suggested_name);
5259 if ((uri = g_filename_to_uri(path, NULL, NULL)) == NULL)
5260 break; /* XXX */
5261 #endif
5262 i++;
5263 #ifdef __MINGW32__
5264 } while (!stat(uri, &sb));
5265 #else
5266 } while (!stat(path, &sb));
5267 #endif
5269 DNPRINTF(XT_D_DOWNLOAD, "%s: tab %d filename %s "
5270 "local %s\n", __func__, t->tab_id, filename, uri);
5272 /* if we're restarting the download, or starting
5273 * it after doing something else, we need to recreate
5274 * the download request.
5276 if (flag == XT_DL_RESTART) {
5277 req = webkit_network_request_new(webkit_download_get_uri(d->download));
5278 webkit_download_cancel(d->download);
5279 g_object_unref(d->download);
5280 d->download = webkit_download_new(req);
5281 g_object_unref(req);
5284 webkit_download_set_destination_uri(d->download, uri);
5286 if (webkit_download_get_status(d->download) ==
5287 WEBKIT_DOWNLOAD_STATUS_ERROR) {
5288 show_oops(t, "%s: download failed to start", __func__);
5289 ret = FALSE;
5290 show_oops(t, "Download Failed");
5291 } else {
5292 /* connect "download first" mime handler */
5293 g_signal_connect(G_OBJECT(d->download), "notify::status",
5294 G_CALLBACK(download_status_changed_cb), NULL);
5296 /* get from history */
5297 g_object_ref(d->download);
5298 /* because basename() takes a char * on linux */
5299 destination = g_strdup(
5300 webkit_download_get_destination_uri(d->download));
5301 show_oops(t, "Download of '%s' started...",
5302 basename(destination));
5303 g_free(destination);
5306 if (flag != XT_DL_START)
5307 webkit_download_start(d->download);
5309 DNPRINTF(XT_D_DOWNLOAD, "download status : %d",
5310 webkit_download_get_status(d->download));
5312 /* sync other download manager tabs */
5313 update_download_tabs(NULL);
5315 if (uri)
5316 g_free(uri);
5317 if (path)
5318 g_free(path);
5319 if (filename)
5320 g_free(filename);
5322 return (ret);
5326 download_ask_cb(struct tab *t, GdkEventKey *e, gpointer data)
5328 struct download *d = data;
5330 /* unset mode */
5331 t->mode_cb = NULL;
5332 t->mode_cb_data = NULL;
5334 if (d == NULL) {
5335 if (e != NULL)
5336 e->keyval = GDK_Escape;
5337 return (XT_CB_PASSTHROUGH);
5340 DPRINTF("download_ask_cb: User pressed %c\n", e->keyval);
5341 if (e->keyval == 'y' || e->keyval == 'Y' || e->keyval == GDK_Return)
5342 /* We need to do a RESTART, because we're not calling from
5343 * webview_download_cb
5345 download_start(t, d, XT_DL_RESTART);
5347 /* for all other keyvals, we just let the download be */
5348 e->keyval = GDK_Escape;
5349 return (XT_CB_HANDLED);
5353 download_ask(struct tab *t, struct download *d)
5355 const gchar *suggested_name;
5357 suggested_name = webkit_download_get_suggested_filename(d->download);
5358 if (suggested_name == NULL)
5359 return (FALSE); /* abort download */
5361 show_oops(t, "download file %s [y/n] ?", suggested_name);
5362 t->mode_cb = download_ask_cb;
5363 t->mode_cb_data = d;
5365 return (TRUE);
5369 webview_download_cb(WebKitWebView *wv, WebKitDownload *wk_download,
5370 struct tab *t)
5372 const gchar *suggested_name;
5373 struct download *download_entry;
5374 int ret = TRUE;
5376 if (wk_download == NULL || t == NULL) {
5377 show_oops(NULL, "%s invalid parameters", __func__);
5378 return (FALSE);
5381 suggested_name = webkit_download_get_suggested_filename(wk_download);
5382 if (suggested_name == NULL)
5383 return (FALSE); /* abort download */
5385 download_entry = g_malloc(sizeof(struct download));
5386 download_entry->download = wk_download;
5387 download_entry->tab = t;
5388 download_entry->id = next_download_id++;
5389 RB_INSERT(download_list, &downloads, download_entry);
5390 t->download_requested = 1;
5392 if (download_mode == XT_DM_START)
5393 ret = download_start(t, download_entry, XT_DL_START);
5394 else if (download_mode == XT_DM_ASK)
5395 ret = download_ask(t, download_entry);
5396 else if (download_mode == XT_DM_ADD)
5397 show_oops(t, "added %s to download manager",
5398 suggested_name);
5400 /* sync other download manager tabs */
5401 update_download_tabs(NULL);
5404 * NOTE: never redirect/render the current tab before this
5405 * function returns. This will cause the download to never start.
5407 return (ret); /* start download */
5410 void
5411 webview_hover_cb(WebKitWebView *wv, gchar *title, gchar *uri, struct tab *t)
5413 DNPRINTF(XT_D_KEY, "webview_hover_cb: %s %s\n", title, uri);
5415 if (t == NULL) {
5416 show_oops(NULL, "webview_hover_cb");
5417 return;
5420 if (uri)
5421 set_status(t, "Link: %s", uri);
5422 else {
5423 if (statusbar_style == XT_STATUSBAR_URL) {
5424 const gchar *page_uri;
5426 if ((page_uri = get_uri(t)) != NULL)
5427 set_status(t, "%s", page_uri);
5428 } else
5429 set_status(t, "%s", (char *)get_title(t, FALSE));
5434 mark(struct tab *t, struct karg *arg)
5436 char mark;
5437 int index;
5438 double pos;
5440 mark = arg->s[1];
5441 if ((index = marktoindex(mark)) == -1)
5442 return (-1);
5444 if (arg->i == XT_MARK_SET)
5445 t->mark[index] = gtk_adjustment_get_value(t->adjust_v);
5446 else if (arg->i == XT_MARK_GOTO) {
5447 if (t->mark[index] > (XT_INVALID_MARK - 0.001) &&
5448 t->mark[index] < (XT_INVALID_MARK + 0.001)) {
5449 show_oops(t, "mark '%c' does not exist", mark);
5450 return (-1);
5452 /* XXX t->mark[index] can be bigger than the maximum if ajax or
5453 something changes the document size */
5454 pos = gtk_adjustment_get_value(t->adjust_v);
5455 gtk_adjustment_set_value(t->adjust_v, t->mark[index]);
5456 t->mark[marktoindex('\'')] = pos;
5459 return (0);
5462 void
5463 marks_clear(struct tab *t)
5465 int i;
5467 for (i = 0; i < LENGTH(t->mark); i++)
5468 t->mark[i] = XT_INVALID_MARK;
5472 qmarks_load(void)
5474 char file[PATH_MAX];
5475 char *line = NULL, *p;
5476 int index, i;
5477 FILE *f;
5478 size_t linelen;
5480 snprintf(file, sizeof file, "%s" PS "%s", work_dir, XT_QMARKS_FILE);
5481 if ((f = fopen(file, "r+")) == NULL) {
5482 show_oops(NULL, "Can't open quickmarks file: %s", strerror(errno));
5483 return (1);
5486 for (i = 1; ; i++) {
5487 if ((line = fparseln(f, &linelen, NULL, NULL, 0)) == NULL)
5488 break;
5489 if (strlen(line) == 0 || line[0] == '#') {
5490 free(line);
5491 line = NULL;
5492 continue;
5495 p = strtok(line, " \t");
5497 if (p == NULL || strlen(p) != 1 ||
5498 (index = qmarktoindex(*p)) == -1) {
5499 warnx("corrupt quickmarks file, line %d", i);
5500 break;
5503 p = strtok(NULL, " \t");
5504 if (qmarks[index] != NULL)
5505 g_free(qmarks[index]);
5506 qmarks[index] = g_strdup(p);
5509 fclose(f);
5511 return (0);
5515 qmarks_save(void)
5517 char file[PATH_MAX];
5518 int i;
5519 FILE *f;
5521 snprintf(file, sizeof file, "%s" PS "%s", work_dir, XT_QMARKS_FILE);
5522 if ((f = fopen(file, "r+")) == NULL) {
5523 show_oops(NULL, "Can't open quickmarks file: %s", strerror(errno));
5524 return (1);
5527 for (i = 0; i < XT_NOQMARKS; i++)
5528 if (qmarks[i] != NULL)
5529 fprintf(f, "%c %s\n", indextoqmark(i), qmarks[i]);
5531 fclose(f);
5533 return (0);
5537 qmark(struct tab *t, struct karg *arg)
5539 char mark;
5540 int index;
5542 mark = arg->s[strlen(arg->s)-1];
5543 index = qmarktoindex(mark);
5544 if (index == -1)
5545 return (-1);
5547 switch (arg->i) {
5548 case XT_QMARK_SET:
5549 if (qmarks[index] != NULL) {
5550 g_free(qmarks[index]);
5551 qmarks[index] = NULL;
5554 qmarks_load(); /* sync if multiple instances */
5555 qmarks[index] = g_strdup(get_uri(t));
5556 qmarks_save();
5557 break;
5558 case XT_QMARK_OPEN:
5559 if (qmarks[index] != NULL)
5560 load_uri(t, qmarks[index]);
5561 else {
5562 show_oops(t, "quickmark \"%c\" does not exist",
5563 mark);
5564 return (-1);
5566 break;
5567 case XT_QMARK_TAB:
5568 if (qmarks[index] != NULL)
5569 create_new_tab(qmarks[index], NULL, 1, -1);
5570 else {
5571 show_oops(t, "quickmark \"%c\" does not exist",
5572 mark);
5573 return (-1);
5575 break;
5578 return (0);
5582 go_up(struct tab *t, struct karg *args)
5584 int levels;
5585 int lastidx;
5586 char *uri;
5587 char *tmp;
5588 char *p;
5590 if (args->i == XT_GO_UP_ROOT)
5591 levels = XT_GO_UP_ROOT;
5592 else if ((levels = atoi(args->s)) == 0)
5593 levels = 1;
5595 uri = g_strdup(get_uri(t));
5596 if (uri == NULL)
5597 return (1);
5599 if ((tmp = strstr(uri, XT_PROTO_DELIM)) == NULL)
5600 return (1);
5602 tmp += strlen(XT_PROTO_DELIM);
5604 /* it makes no sense to strip the last slash from ".../dir/", skip it */
5605 lastidx = strlen(tmp) - 1;
5606 if (lastidx > 0) {
5607 if (tmp[lastidx] == '/')
5608 tmp[lastidx] = '\0';
5611 while (levels--) {
5612 p = strrchr(tmp, '/');
5613 if (p == tmp) { /* Are we at the root of a file://-path? */
5614 p[1] = '\0';
5615 break;
5616 } else if (p != NULL)
5617 *p = '\0';
5618 else
5619 break;
5622 load_uri(t, uri);
5623 g_free(uri);
5625 return (0);
5629 gototab(struct tab *t, struct karg *args)
5631 int tab;
5632 struct karg arg = {0, NULL, -1};
5634 tab = atoi(args->s);
5636 if (args->i == 0)
5637 arg.i = XT_TAB_NEXT;
5638 else
5639 arg.i = args->i;
5641 arg.precount = tab;
5643 movetab(t, &arg);
5645 return (0);
5649 zoom_amount(struct tab *t, struct karg *arg)
5651 struct karg narg = {0, NULL, -1};
5653 narg.i = atoi(arg->s);
5654 resizetab(t, &narg);
5656 return (0);
5660 flip_colon(struct tab *t, struct karg *arg)
5662 struct karg narg = {0, NULL, -1};
5663 char *p;
5665 if (t == NULL || arg == NULL)
5666 return (1);
5668 p = strstr(arg->s, ":");
5669 if (p == NULL)
5670 return (1);
5671 *p = '\0';
5673 narg.i = ':';
5674 narg.s = arg->s;
5675 command(t, &narg);
5677 return (0);
5680 /* buffer commands receive the regex that triggered them in arg.s */
5681 char bcmd[XT_BUFCMD_SZ];
5682 struct buffercmd {
5683 char *regex;
5684 int precount;
5685 #define XT_PRE_NO (0)
5686 #define XT_PRE_YES (1)
5687 #define XT_PRE_MAYBE (2)
5688 char *cmd;
5689 int (*func)(struct tab *, struct karg *);
5690 int arg;
5691 regex_t cregex;
5692 } buffercmds[] = {
5693 { "^[0-9]*gu$", XT_PRE_MAYBE, "gu", go_up, 0 },
5694 { "^gU$", XT_PRE_NO, "gU", go_up, XT_GO_UP_ROOT },
5695 { "^gg$", XT_PRE_NO, "gg", move, XT_MOVE_TOP },
5696 { "^gG$", XT_PRE_NO, "gG", move, XT_MOVE_BOTTOM },
5697 { "^[0-9]+%$", XT_PRE_YES, "%", move, XT_MOVE_PERCENT },
5698 { "^zz$", XT_PRE_NO, "zz", move, XT_MOVE_CENTER },
5699 { "^gh$", XT_PRE_NO, "gh", go_home, 0 },
5700 { "^m[a-zA-Z0-9]$", XT_PRE_NO, "m", mark, XT_MARK_SET },
5701 { "^['][a-zA-Z0-9']$", XT_PRE_NO, "'", mark, XT_MARK_GOTO },
5702 { "^[0-9]+t$", XT_PRE_YES, "t", gototab, 0 },
5703 { "^g0$", XT_PRE_YES, "g0", movetab, XT_TAB_FIRST },
5704 { "^g[$]$", XT_PRE_YES, "g$", movetab, XT_TAB_LAST },
5705 { "^[0-9]*gt$", XT_PRE_YES, "t", movetab, XT_TAB_NEXT },
5706 { "^[0-9]*gT$", XT_PRE_YES, "T", movetab, XT_TAB_PREV },
5707 { "^M[a-zA-Z0-9]$", XT_PRE_NO, "M", qmark, XT_QMARK_SET },
5708 { "^go[a-zA-Z0-9]$", XT_PRE_NO, "go", qmark, XT_QMARK_OPEN },
5709 { "^gn[a-zA-Z0-9]$", XT_PRE_NO, "gn", qmark, XT_QMARK_TAB },
5710 { "^ZR$", XT_PRE_NO, "ZR", restart, 0 },
5711 { "^ZZ$", XT_PRE_NO, "ZZ", quit, 0 },
5712 { "^zi$", XT_PRE_NO, "zi", resizetab, XT_ZOOM_IN },
5713 { "^zo$", XT_PRE_NO, "zo", resizetab, XT_ZOOM_OUT },
5714 { "^z0$", XT_PRE_NO, "z0", resizetab, XT_ZOOM_NORMAL },
5715 { "^[0-9]+Z$", XT_PRE_YES, "Z", zoom_amount, 0 },
5716 { "^[0-9]+:$", XT_PRE_YES, ":", flip_colon, 0 },
5719 void
5720 buffercmd_init(void)
5722 int i;
5724 for (i = 0; i < LENGTH(buffercmds); i++)
5725 if (regcomp(&buffercmds[i].cregex, buffercmds[i].regex,
5726 REG_EXTENDED | REG_NOSUB))
5727 startpage_add("invalid buffercmd regex %s",
5728 buffercmds[i].regex);
5731 void
5732 buffercmd_abort(struct tab *t)
5734 int i;
5736 if (t == NULL)
5737 return;
5739 DNPRINTF(XT_D_BUFFERCMD, "%s: clearing buffer\n", __func__);
5741 for (i = 0; i < LENGTH(bcmd); i++)
5742 bcmd[i] = '\0';
5744 cmd_prefix = 0; /* clear prefix for non-buffer commands */
5745 if (t->sbe.buffercmd)
5746 gtk_label_set_text(GTK_LABEL(t->sbe.buffercmd), bcmd);
5749 void
5750 buffercmd_execute(struct tab *t, struct buffercmd *cmd)
5752 struct karg arg = {0, NULL, -1};
5754 arg.i = cmd->arg;
5755 arg.s = g_strdup(bcmd);
5757 DNPRINTF(XT_D_BUFFERCMD, "buffercmd_execute: buffer \"%s\" "
5758 "matches regex \"%s\", executing\n", bcmd, cmd->regex);
5759 cmd->func(t, &arg);
5761 if (arg.s)
5762 g_free(arg.s);
5764 buffercmd_abort(t);
5767 gboolean
5768 buffercmd_addkey(struct tab *t, guint keyval)
5770 int i, c, match ;
5771 char s[XT_BUFCMD_SZ];
5773 if (gtk_widget_get_visible(GTK_WIDGET(t->buffers))) {
5774 buffercmd_abort(t);
5775 return (XT_CB_PASSTHROUGH);
5778 if (keyval == GDK_Escape) {
5779 buffercmd_abort(t);
5780 return (XT_CB_HANDLED);
5783 /* key with modifier or non-ascii character */
5784 if (!isascii(keyval)) {
5786 * XXX this looks wrong but fixes some sites like
5787 * http://www.seslisozluk.com/
5788 * that eat a shift or ctrl and end putting default focus in js
5789 * instead of ignoring the keystroke
5790 * so instead of return (XT_CB_PASSTHROUGH); eat the key
5792 return (XT_CB_HANDLED);
5795 DNPRINTF(XT_D_BUFFERCMD, "buffercmd_addkey: adding key \"%c\" "
5796 "to buffer \"%s\"\n", keyval, bcmd);
5798 for (i = 0; i < LENGTH(bcmd); i++)
5799 if (bcmd[i] == '\0') {
5800 bcmd[i] = keyval;
5801 break;
5804 /* buffer full, ignore input */
5805 if (i >= LENGTH(bcmd) -1) {
5806 DNPRINTF(XT_D_BUFFERCMD, "buffercmd_addkey: buffer full\n");
5807 buffercmd_abort(t);
5808 return (XT_CB_HANDLED);
5811 if (t->sbe.buffercmd != NULL)
5812 gtk_label_set_text(GTK_LABEL(t->sbe.buffercmd), bcmd);
5814 /* find exact match */
5815 for (i = 0; i < LENGTH(buffercmds); i++)
5816 if (regexec(&buffercmds[i].cregex, bcmd,
5817 (size_t) 0, NULL, 0) == 0) {
5818 buffercmd_execute(t, &buffercmds[i]);
5819 goto done;
5822 /* find non exact matches to see if we need to abort ot not */
5823 for (i = 0, match = 0; i < LENGTH(buffercmds); i++) {
5824 DNPRINTF(XT_D_BUFFERCMD, "trying: %s\n", bcmd);
5825 c = -1;
5826 s[0] = '\0';
5827 if (buffercmds[i].precount == XT_PRE_MAYBE) {
5828 if (isdigit((unsigned char)bcmd[0])) {
5829 if (sscanf(bcmd, "%d%s", &c, s) == 0)
5830 continue;
5831 } else {
5832 c = 0;
5833 if (sscanf(bcmd, "%s", s) == 0)
5834 continue;
5836 } else if (buffercmds[i].precount == XT_PRE_YES) {
5837 if (sscanf(bcmd, "%d%s", &c, s) == 0)
5838 continue;
5839 } else {
5840 if (sscanf(bcmd, "%s", s) == 0)
5841 continue;
5843 if (c == -1 && buffercmds[i].precount)
5844 continue;
5845 if (!strncmp(s, buffercmds[i].cmd, strlen(s)))
5846 match++;
5848 DNPRINTF(XT_D_BUFFERCMD, "got[%d] %d <%s>: %d %s\n",
5849 i, match, buffercmds[i].cmd, c, s);
5851 if (match == 0) {
5852 DNPRINTF(XT_D_BUFFERCMD, "aborting: %s\n", bcmd);
5853 buffercmd_abort(t);
5856 done:
5857 return (XT_CB_HANDLED);
5861 * XXX we were seeing a bunch of focus issues with the toplevel
5862 * main_window losing its is-active and has-toplevel-focus properties.
5863 * This is the most correct and portable solution we could come up with
5864 * without relying on calling internal GTK functions (which we
5865 * couldn't link to in Linux).
5867 #if GTK_CHECK_VERSION(3, 0, 0)
5868 void
5869 fake_focus_in(GtkWidget *w)
5871 if (fevent == NULL) {
5872 fevent = gdk_event_new(GDK_FOCUS_CHANGE);
5873 fevent->focus_change.window =
5874 gtk_widget_get_window(main_window);
5875 fevent->focus_change.type = GDK_FOCUS_CHANGE;
5876 fevent->focus_change.in = TRUE;
5878 gtk_widget_send_focus_change(main_window, fevent);
5880 #endif
5882 gboolean
5883 handle_keypress(struct tab *t, GdkEventKey *e, int entry)
5885 struct karg args;
5886 struct key_binding *k;
5889 * This sometimes gets randomly unset for whatever reason in GTK3.
5890 * If we're handling a keypress, the main window's is-active propery
5891 * *must* be true, or else many things will break.
5893 #if GTK_CHECK_VERSION(3, 0, 0)
5894 fake_focus_in(main_window);
5895 #endif
5897 /* handle keybindings if buffercmd is empty.
5898 if not empty, allow commands like C-n */
5899 if (bcmd[0] == '\0' || ((e->state & (CTRL | MOD1)) != 0))
5900 TAILQ_FOREACH(k, &kbl, entry)
5901 if (e->keyval == k->key
5902 && (entry ? k->use_in_entry : 1)) {
5903 /* when we are edditing eat ctrl/mod keys */
5904 if (edit_mode == XT_EM_VI &&
5905 t->mode == XT_MODE_INSERT &&
5906 (e->state & CTRL || e->state & MOD1))
5907 return (XT_CB_PASSTHROUGH);
5909 if (k->mask == 0) {
5910 if ((e->state & (CTRL | MOD1)) == 0)
5911 goto runcmd;
5912 } else if ((e->state & k->mask) == k->mask) {
5913 goto runcmd;
5917 if (!entry && ((e->state & (CTRL | MOD1)) == 0))
5918 return (buffercmd_addkey(t, e->keyval));
5920 return (XT_CB_PASSTHROUGH);
5922 runcmd:
5923 if (k->cmd[0] == ':') {
5924 args.i = ':';
5925 args.s = &k->cmd[1];
5926 return (command(t, &args));
5927 } else
5928 return (cmd_execute(t, k->cmd));
5932 wv_keypress_cb(GtkEntry *w, GdkEventKey *e, struct tab *t)
5934 char s[2];
5936 /* don't use w directly; use t->whatever instead */
5938 if (t == NULL) {
5939 show_oops(NULL, "wv_keypress_cb");
5940 return (XT_CB_PASSTHROUGH);
5943 hide_oops(t);
5945 if (t->mode_cb)
5946 return (t->mode_cb(t, e, t->mode_cb_data));
5948 DNPRINTF(XT_D_KEY, "wv_keypress_cb: mode %d keyval 0x%x mask "
5949 "0x%x tab %d\n", t->mode, e->keyval, e->state, t->tab_id);
5951 /* Hide buffers, if they are visible, with escape. */
5952 if (gtk_widget_get_visible(GTK_WIDGET(t->buffers)) &&
5953 CLEAN(e->state) == 0 && e->keyval == GDK_Escape) {
5954 gtk_widget_grab_focus(GTK_WIDGET(t->wv));
5955 hide_buffers(t);
5956 return (XT_CB_HANDLED);
5959 if ((CLEAN(e->state) == 0 && e->keyval == GDK_Tab) ||
5960 (CLEAN(e->state) == SHFT && e->keyval == GDK_Tab))
5961 /* something focussy is about to happen */
5962 return (XT_CB_PASSTHROUGH);
5964 /* check if we are some sort of text input thing in the dom */
5965 input_check_mode(t);
5967 if (t->mode == XT_MODE_PASSTHROUGH) {
5968 if (CLEAN(e->state) == 0 && e->keyval == GDK_Escape)
5969 t->mode = XT_MODE_COMMAND;
5970 return (XT_CB_PASSTHROUGH);
5971 } else if (t->mode == XT_MODE_COMMAND || t->mode == XT_MODE_HINT) {
5972 /* prefix input */
5973 snprintf(s, sizeof s, "%c", e->keyval);
5974 if (CLEAN(e->state) == 0 && isdigit((unsigned char)s[0]))
5975 cmd_prefix = 10 * cmd_prefix + atoi(s);
5976 return (handle_keypress(t, e, 0));
5977 } else {
5978 /* insert mode */
5979 return (handle_keypress(t, e, 1));
5982 /* NOTREACHED */
5983 return (XT_CB_PASSTHROUGH);
5986 gboolean
5987 hint_continue(struct tab *t)
5989 const gchar *c = gtk_entry_get_text(GTK_ENTRY(t->cmd));
5990 char *s;
5991 const gchar *errstr = NULL;
5992 gboolean rv = TRUE;
5993 int i;
5995 if (!(c[0] == '.' || c[0] == ','))
5996 goto done;
5997 if (strlen(c) == 1) {
5998 /* XXX should not happen */
5999 rv = TRUE;
6000 goto done;
6003 if (isdigit((unsigned char)c[1])) {
6004 /* numeric input */
6005 i = strtonum(&c[1], 1, 4096, &errstr);
6006 if (errstr) {
6007 show_oops(t, "invalid numerical hint %s", &c[1]);
6008 goto done;
6010 s = g_strdup_printf("hints.updateHints(%d);", i);
6011 run_script(t, s);
6012 g_free(s);
6013 } else {
6014 /* alphanumeric input */
6015 s = g_strdup_printf("hints.createHints('%s', '%c');",
6016 &c[1], c[0] == '.' ? 'f' : 'F');
6017 run_script(t, s);
6018 g_free(s);
6021 rv = FALSE;
6022 done:
6023 return (rv);
6026 gboolean
6027 search_continue(struct tab *t)
6029 const gchar *c = gtk_entry_get_text(GTK_ENTRY(t->cmd));
6030 gboolean rv = FALSE;
6032 if (c[0] == ':' || c[0] == '.' || c[0] == ',')
6033 goto done;
6034 if (strlen(c) == 1) {
6035 webkit_web_view_unmark_text_matches(t->wv);
6036 goto done;
6039 if (c[0] == '/')
6040 t->search_forward = TRUE;
6041 else if (c[0] == '?')
6042 t->search_forward = FALSE;
6043 else
6044 goto done;
6046 rv = TRUE;
6047 done:
6048 return (rv);
6051 gboolean
6052 search_cb(struct tab *t)
6054 const gchar *c = gtk_entry_get_text(GTK_ENTRY(t->cmd));
6055 #if !GTK_CHECK_VERSION(3, 0, 0)
6056 GdkColor color;
6057 #endif
6059 if (search_continue(t) == FALSE)
6060 goto done;
6062 /* search */
6063 if (webkit_web_view_search_text(t->wv, &c[1], FALSE, t->search_forward,
6064 TRUE) == FALSE) {
6065 /* not found, mark red */
6066 #if GTK_CHECK_VERSION(3, 0, 0)
6067 gtk_widget_set_name(t->cmd, XT_CSS_RED);
6068 #else
6069 gdk_color_parse(XT_COLOR_RED, &color);
6070 gtk_widget_modify_base(t->cmd, GTK_STATE_NORMAL, &color);
6071 #endif
6072 /* unmark and remove selection */
6073 webkit_web_view_unmark_text_matches(t->wv);
6074 /* my kingdom for a way to unselect text in webview */
6075 } else {
6076 /* found, highlight all */
6077 webkit_web_view_unmark_text_matches(t->wv);
6078 webkit_web_view_mark_text_matches(t->wv, &c[1], FALSE, 0);
6079 webkit_web_view_set_highlight_text_matches(t->wv, TRUE);
6080 #if GTK_CHECK_VERSION(3, 0, 0)
6081 gtk_widget_set_name(t->cmd, XT_CSS_NORMAL);
6082 #else
6083 gtk_widget_modify_base(t->cmd, GTK_STATE_NORMAL,
6084 &t->default_style->base[GTK_STATE_NORMAL]);
6085 #endif
6087 done:
6088 t->search_id = 0;
6089 return (FALSE);
6093 cmd_keyrelease_cb(GtkEntry *w, GdkEventKey *e, struct tab *t)
6095 const gchar *c = gtk_entry_get_text(w);
6097 if (t == NULL) {
6098 show_oops(NULL, "cmd_keyrelease_cb invalid parameters");
6099 return (XT_CB_PASSTHROUGH);
6102 DNPRINTF(XT_D_CMD, "cmd_keyrelease_cb: keyval 0x%x mask 0x%x tab %d\n",
6103 e->keyval, e->state, t->tab_id);
6105 /* hinting */
6106 if (!(e->keyval == GDK_Tab || e->keyval == GDK_ISO_Left_Tab)) {
6107 if (hint_continue(t) == FALSE)
6108 goto done;
6111 /* search */
6112 if (search_continue(t) == FALSE)
6113 goto done;
6115 /* if search length is > 4 then no longer play timeout games */
6116 if (strlen(c) > 4) {
6117 if (t->search_id) {
6118 g_source_remove(t->search_id);
6119 t->search_id = 0;
6121 search_cb(t);
6122 goto done;
6125 /* reestablish a new timer if the user types fast */
6126 if (t->search_id)
6127 g_source_remove(t->search_id);
6128 t->search_id = g_timeout_add(250, (GSourceFunc)search_cb, (gpointer)t);
6130 done:
6131 return (XT_CB_PASSTHROUGH);
6134 gboolean
6135 match_uri(const gchar *uri, const gchar *key) {
6136 gchar *voffset;
6137 size_t len;
6138 gboolean match = FALSE;
6140 len = strlen(key);
6142 if (!strncmp(key, uri, len))
6143 match = TRUE;
6144 else {
6145 voffset = strstr(uri, "/") + 2;
6146 if (!strncmp(key, voffset, len))
6147 match = TRUE;
6148 else if (g_str_has_prefix(voffset, "www.")) {
6149 voffset = voffset + strlen("www.");
6150 if (!strncmp(key, voffset, len))
6151 match = TRUE;
6155 return (match);
6158 gboolean
6159 match_session(const gchar *name, const gchar *key) {
6160 char *sub;
6162 sub = strcasestr(name, key);
6164 return sub == name;
6167 void
6168 cmd_getlist(int id, char *key)
6170 int i, dep, c = 0;
6171 struct history *h;
6172 struct session *s;
6174 if (key == NULL)
6175 return;
6177 if (id >= 0) {
6178 if (cmds[id].type & XT_URLARG) {
6179 RB_FOREACH_REVERSE(h, history_list, &hl)
6180 if (match_uri(h->uri, key)) {
6181 cmd_status.list[c] = (char *)h->uri;
6182 if (++c > 255)
6183 break;
6185 cmd_status.len = c;
6186 return;
6187 } else if (cmds[id].type & XT_SESSARG) {
6188 TAILQ_FOREACH(s, &sessions, entry)
6189 if (match_session(s->name, key)) {
6190 cmd_status.list[c] = (char *)s->name;
6191 if (++c > 255)
6192 break;
6194 cmd_status.len = c;
6195 return;
6196 } else if (cmds[id].type & XT_SETARG) {
6197 for (i = 0; i < get_settings_size(); i++)
6198 if (!strncmp(key, get_setting_name(i),
6199 strlen(key)))
6200 cmd_status.list[c++] =
6201 get_setting_name(i);
6202 cmd_status.len = c;
6203 return;
6207 dep = (id == -1) ? 0 : cmds[id].level + 1;
6209 for (i = id + 1; i < LENGTH(cmds); i++) {
6210 if (cmds[i].level < dep)
6211 break;
6212 if (cmds[i].level == dep && !strncmp(key, cmds[i].cmd,
6213 strlen(key)) && !isdigit((unsigned char)cmds[i].cmd[0]))
6214 cmd_status.list[c++] = cmds[i].cmd;
6218 cmd_status.len = c;
6221 char *
6222 cmd_getnext(int dir)
6224 cmd_status.index += dir;
6226 if (cmd_status.index < 0)
6227 cmd_status.index = cmd_status.len - 1;
6228 else if (cmd_status.index >= cmd_status.len)
6229 cmd_status.index = 0;
6231 return cmd_status.list[cmd_status.index];
6235 cmd_tokenize(char *s, char *tokens[])
6237 int i = 0;
6238 char *tok, *last = NULL;
6239 size_t len = strlen(s);
6240 bool blank;
6242 blank = len == 0 || (len > 0 && s[len - 1] == ' ');
6243 for (tok = strtok_r(s, " ", &last); tok && i < 3;
6244 tok = strtok_r(NULL, " ", &last), i++)
6245 tokens[i] = tok;
6247 if (blank && i < 3)
6248 tokens[i++] = "";
6250 return (i);
6253 void
6254 cmd_complete(struct tab *t, char *str, int dir)
6256 GtkEntry *w = GTK_ENTRY(t->cmd);
6257 int i, j, levels, c = 0, dep = 0, parent = -1;
6258 int matchcount = 0;
6259 char *tok, *match, *s = g_strdup(str);
6260 char *tokens[3] = {0};
6261 char res[XT_MAX_URL_LENGTH + 32] = ":";
6262 char *sc = s;
6264 DNPRINTF(XT_D_CMD, "%s: complete %s\n", __func__, str);
6266 /* copy prefix*/
6267 for (i = 0; isdigit((unsigned char)s[i]); i++)
6268 res[i + 1] = s[i];
6270 for (; isspace((unsigned char)s[i]); i++)
6271 res[i + 1] = s[i];
6273 s += i;
6275 levels = cmd_tokenize(s, tokens);
6277 for (i = 0; i < levels - 1; i++) {
6278 tok = tokens[i];
6279 matchcount = 0;
6280 for (j = c; j < LENGTH(cmds); j++) {
6281 if (cmds[j].level < dep)
6282 break;
6283 if (cmds[j].level == dep && !strncmp(tok, cmds[j].cmd,
6284 strlen(tok))) {
6285 matchcount++;
6286 c = j + 1;
6287 if (strlen(tok) == strlen(cmds[j].cmd)) {
6288 matchcount = 1;
6289 break;
6294 if (matchcount == 1) {
6295 strlcat(res, tok, sizeof res);
6296 strlcat(res, " ", sizeof res);
6297 dep++;
6298 } else {
6299 g_free(sc);
6300 return;
6303 parent = c - 1;
6306 if (cmd_status.index == -1)
6307 cmd_getlist(parent, tokens[i]);
6309 if (cmd_status.len > 0) {
6310 match = cmd_getnext(dir);
6311 strlcat(res, match, sizeof res);
6312 gtk_entry_set_text(w, res);
6313 gtk_editable_set_position(GTK_EDITABLE(w), -1);
6316 g_free(sc);
6319 char *
6320 parse_prefix_and_alias(const char *str, int *prefix)
6322 struct cmd_alias *c;
6323 char *s = g_strdup(str), *sc;
6325 g_strstrip(s);
6326 sc = s;
6328 if (isdigit((unsigned char)s[0])) {
6329 sscanf(s, "%d", prefix);
6330 while (isdigit((unsigned char)s[0]) ||
6331 isspace((unsigned char)s[0]))
6332 ++s;
6335 TAILQ_FOREACH(c, &cal, entry) {
6336 if (strncmp(s, c->alias, strlen(c->alias)))
6337 continue;
6339 if (strlen(s) == strlen(c->alias)) {
6340 g_free(sc);
6341 return (g_strdup(c->cmd));
6344 if (!isspace((unsigned char)s[strlen(c->alias)]))
6345 continue;
6347 s = g_strdup_printf("%s %s", c->cmd, &s[strlen(c->alias) + 1]);
6348 g_free(sc);
6349 return (s);
6351 s = g_strdup(s);
6352 g_free(sc);
6353 return (s);
6356 gboolean
6357 cmd_execute(struct tab *t, char *str)
6359 struct cmd *cmd = NULL;
6360 char *tok, *last = NULL, *s = str;
6361 int j = 0, len, c = 0, dep = 0, matchcount = 0;
6362 int prefix = -1, rv = XT_CB_PASSTHROUGH;
6363 struct karg arg = {0, NULL, -1};
6365 s = parse_prefix_and_alias(s, &prefix);
6367 for (tok = strtok_r(s, " ", &last); tok;
6368 tok = strtok_r(NULL, " ", &last)) {
6369 matchcount = 0;
6370 for (j = c; j < LENGTH(cmds); j++) {
6371 if (cmds[j].level < dep)
6372 break;
6373 len = (tok[strlen(tok) - 1] == '!') ? strlen(tok) - 1 :
6374 strlen(tok);
6375 if (cmds[j].level == dep &&
6376 !strncmp(tok, cmds[j].cmd, len)) {
6377 matchcount++;
6378 c = j + 1;
6379 cmd = &cmds[j];
6380 if (len == strlen(cmds[j].cmd)) {
6381 matchcount = 1;
6382 break;
6386 if (matchcount == 1) {
6387 if (cmd->type > 0)
6388 goto execute_cmd;
6389 dep++;
6390 } else {
6391 show_oops(t, "Invalid command: %s", str);
6392 goto done;
6395 execute_cmd:
6396 if (cmd == NULL) {
6397 show_oops(t, "Empty command");
6398 goto done;
6400 arg.i = cmd->arg;
6402 if (prefix != -1)
6403 arg.precount = prefix;
6404 else if (cmd_prefix > 0)
6405 arg.precount = cmd_prefix;
6407 if (j > 0 && !(cmd->type & XT_PREFIX) && arg.precount > -1) {
6408 show_oops(t, "No prefix allowed: %s", str);
6409 goto done;
6411 if (cmd->type > 1)
6412 arg.s = last ? g_strdup(last) : g_strdup("");
6413 if (cmd->type & XT_INTARG && last && strlen(last) > 0) {
6414 if (arg.s == NULL) {
6415 show_oops(t, "Invalid command");
6416 goto done;
6418 arg.precount = atoi(arg.s);
6419 if (arg.precount <= 0) {
6420 if (arg.s[0] == '0')
6421 show_oops(t, "Zero count");
6422 else
6423 show_oops(t, "Trailing characters");
6424 goto done;
6428 DNPRINTF(XT_D_CMD, "%s: prefix %d arg %s\n",
6429 __func__, arg.precount, arg.s);
6431 cmd->func(t, &arg);
6433 rv = XT_CB_HANDLED;
6434 done:
6435 if (j > 0)
6436 cmd_prefix = 0;
6437 g_free(s);
6438 if (arg.s)
6439 g_free(arg.s);
6441 return (rv);
6445 save_runtime_setting(const char *name, const char *val)
6447 struct stat sb;
6448 FILE *f;
6449 size_t linelen;
6450 int found = 0;
6451 char file[PATH_MAX];
6452 char delim[3] = { '\0', '\0', '\0' };
6453 char *line, *lt, *start;
6454 char *contents, *tmp;
6456 if (runtime_settings == NULL || strlen(runtime_settings) == 0)
6457 return (-1);
6459 snprintf(file, sizeof file, "%s" PS "%s", work_dir, runtime_settings);
6460 if (stat(file, &sb) || (f = fopen(file, "r+")) == NULL)
6461 return (-1);
6462 lt = g_strdup_printf("%s=%s", name, val);
6463 contents = g_strdup("");
6464 while (!feof(f)) {
6465 line = fparseln(f, &linelen, NULL, delim, 0);
6466 if (line == NULL || linelen == 0)
6467 continue;
6468 tmp = contents;
6469 start = g_strdup_printf("%s=", name);
6470 if (strstr(line, start) == NULL)
6471 contents = g_strdup_printf("%s%s\n", contents, line);
6472 else {
6473 found = 1;
6474 contents = g_strdup_printf("%s%s\n", contents, lt);
6476 g_free(tmp);
6477 g_free(start);
6478 free(line);
6479 line = NULL;
6481 if (found == 0) {
6482 tmp = contents;
6483 contents = g_strdup_printf("%s%s\n", contents, lt);
6484 g_free(tmp);
6486 if ((f = freopen(file, "w", f)) == NULL)
6487 return (-1);
6488 else {
6489 fputs(contents, f);
6490 fclose(f);
6492 g_free(lt);
6493 g_free(contents);
6495 return (0);
6499 entry_focus_cb(GtkWidget *w, GdkEvent e, struct tab *t)
6502 * This sometimes gets randomly unset for whatever reason in GTK3,
6503 * causing a GtkEntry's text cursor becomes invisible. When we focus
6504 * a GtkEntry, be sure to manually reset the main window's is-active
6505 * property so the cursor is shown correctly.
6507 #if GTK_CHECK_VERSION(3, 0, 0)
6508 fake_focus_in(main_window);
6509 #endif
6510 return (XT_CB_PASSTHROUGH);
6514 entry_key_cb(GtkEntry *w, GdkEventKey *e, struct tab *t)
6516 if (t == NULL) {
6517 show_oops(NULL, "entry_key_cb invalid parameters");
6518 return (XT_CB_PASSTHROUGH);
6521 DNPRINTF(XT_D_CMD, "entry_key_cb: keyval 0x%x mask 0x%x tab %d\n",
6522 e->keyval, e->state, t->tab_id);
6524 hide_oops(t);
6526 if (e->keyval == GDK_Escape) {
6527 /* don't use focus_webview(t) because we want to type :cmds */
6528 gtk_widget_grab_focus(GTK_WIDGET(t->wv));
6531 return (handle_keypress(t, e, 1));
6534 struct command_entry *
6535 history_prev(struct command_list *l, struct command_entry *at)
6537 if (at == NULL)
6538 at = TAILQ_LAST(l, command_list);
6539 else {
6540 at = TAILQ_PREV(at, command_list, entry);
6541 if (at == NULL)
6542 at = TAILQ_LAST(l, command_list);
6545 return (at);
6548 struct command_entry *
6549 history_next(struct command_list *l, struct command_entry *at)
6551 if (at == NULL)
6552 at = TAILQ_FIRST(l);
6553 else {
6554 at = TAILQ_NEXT(at, entry);
6555 if (at == NULL)
6556 at = TAILQ_FIRST(l);
6559 return (at);
6563 cmd_keypress_cb(GtkEntry *w, GdkEventKey *e, struct tab *t)
6565 int rv = XT_CB_HANDLED;
6566 const gchar *c = gtk_entry_get_text(w);
6567 char *s;
6569 if (t == NULL) {
6570 show_oops(NULL, "cmd_keypress_cb parameters");
6571 return (XT_CB_PASSTHROUGH);
6574 DNPRINTF(XT_D_CMD, "cmd_keypress_cb: keyval 0x%x mask 0x%x tab %d\n",
6575 e->keyval, e->state, t->tab_id);
6577 /* sanity */
6578 if (c == NULL)
6579 e->keyval = GDK_Escape;
6580 else if (!(c[0] == ':' || c[0] == '/' || c[0] == '?' ||
6581 c[0] == '.' || c[0] == ','))
6582 e->keyval = GDK_Escape;
6584 if (e->keyval != GDK_Tab && e->keyval != GDK_Shift_L &&
6585 e->keyval != GDK_ISO_Left_Tab)
6586 cmd_status.index = -1;
6588 switch (e->keyval) {
6589 case GDK_Tab:
6590 if (c[0] == ':')
6591 cmd_complete(t, (char *)&c[1], 1);
6592 else if (c[0] == '.' || c[0] == ',')
6593 run_script(t, "hints.focusNextHint();");
6594 goto done;
6595 case GDK_ISO_Left_Tab:
6596 if (c[0] == ':')
6597 cmd_complete(t, (char *)&c[1], -1);
6598 else if (c[0] == '.' || c[0] == ',')
6599 run_script(t, "hints.focusPreviousHint();");
6600 goto done;
6601 case GDK_Down:
6602 if (c[0] == '?') {
6603 if ((search_at = history_next(&shl, search_at))) {
6604 search_at->line[0] = c[0];
6605 gtk_entry_set_text(w, search_at->line);
6606 gtk_editable_set_position(GTK_EDITABLE(w), -1);
6608 } else if (c[0] == '/') {
6609 if ((search_at = history_prev(&shl, search_at))) {
6610 search_at->line[0] = c[0];
6611 gtk_entry_set_text(w, search_at->line);
6612 gtk_editable_set_position(GTK_EDITABLE(w), -1);
6614 } else if (c[0] == ':') {
6615 if ((history_at = history_prev(&chl, history_at))) {
6616 history_at->line[0] = c[0];
6617 gtk_entry_set_text(w, history_at->line);
6618 gtk_editable_set_position(GTK_EDITABLE(w), -1);
6621 goto done;
6622 case GDK_Up:
6623 if (c[0] == '/') {
6624 if ((search_at = history_next(&shl, search_at))) {
6625 search_at->line[0] = c[0];
6626 gtk_entry_set_text(w, search_at->line);
6627 gtk_editable_set_position(GTK_EDITABLE(w), -1);
6629 } else if (c[0] == '?') {
6630 if ((search_at = history_prev(&shl, search_at))) {
6631 search_at->line[0] = c[0];
6632 gtk_entry_set_text(w, search_at->line);
6633 gtk_editable_set_position(GTK_EDITABLE(w), -1);
6635 } if (c[0] == ':') {
6636 if ((history_at = history_next(&chl, history_at))) {
6637 history_at->line[0] = c[0];
6638 gtk_entry_set_text(w, history_at->line);
6639 gtk_editable_set_position(GTK_EDITABLE(w), -1);
6642 goto done;
6643 case GDK_Home:
6644 if (c[0] == ':' || c[0] == '/' || c[0] == '?')
6645 gtk_editable_set_position(GTK_EDITABLE(w), 1);
6646 goto done;
6647 case GDK_BackSpace:
6648 if (!(!strcmp(c, ":") || !strcmp(c, "/") || !strcmp(c, "?") ||
6649 !strcmp(c, ".") || !strcmp(c, ","))) {
6650 /* see if we are doing hinting and reset it */
6651 if (c[0] == '.' || c[0] == ',') {
6652 /* recreate hints */
6653 s = g_strdup_printf("hints.createHints('', "
6654 "'%c');", c[0] == '.' ? 'f' : 'F');
6655 run_script(t, s);
6656 g_free(s);
6658 break;
6661 /* FALLTHROUGH */
6662 case GDK_Escape:
6663 hide_cmd(t);
6665 /* cancel search */
6666 if (c != NULL && (c[0] == '/' || c[0] == '?'))
6667 webkit_web_view_unmark_text_matches(t->wv);
6669 /* no need to cancel hints */
6670 goto done;
6673 rv = XT_CB_PASSTHROUGH;
6674 done:
6675 return (rv);
6678 void
6679 wv_popup_activ_cb(GtkMenuItem *menu, struct tab *t)
6681 GtkClipboard *clipboard, *primary;
6682 const gchar *name, *uri;
6683 #if !GTK_CHECK_VERSION(3, 4, 0)
6684 GtkAction *a;
6686 a = gtk_activatable_get_related_action(GTK_ACTIVATABLE(menu));
6687 if (a == NULL)
6688 return;
6689 name = gtk_action_get_name(a);
6690 #else
6691 name = gtk_actionable_get_action_name(GTK_ACTIONABLE(menu));
6692 #endif
6693 if (name == NULL)
6694 return;
6696 DNPRINTF(XT_D_CMD, "wv_popup_activ_cb: tab %d action %s\n",
6697 t->tab_id, name);
6700 * context-menu-action-3 copy link location
6701 * context-menu-action-7 copy image address
6702 * context-menu-action-2030 copy video link location
6705 /* copy actions */
6706 if ((g_strcmp0(name, "context-menu-action-3") == 0) ||
6707 (g_strcmp0(name, "context-menu-action-7") == 0) ||
6708 (g_strcmp0(name, "context-menu-action-2030") == 0)) {
6709 clipboard = gtk_clipboard_get(GDK_SELECTION_CLIPBOARD);
6710 primary = gtk_clipboard_get(GDK_SELECTION_PRIMARY);
6711 uri = gtk_clipboard_wait_for_text(clipboard);
6712 if (uri == NULL)
6713 return;
6714 gtk_clipboard_set_text(primary, uri, -1);
6718 void
6719 wv_popup_cb(WebKitWebView *wview, GtkMenu *menu, struct tab *t)
6721 GList *items, *l;
6723 DNPRINTF(XT_D_CMD, "wv_popup_cb: tab %d\n", t->tab_id);
6725 items = gtk_container_get_children(GTK_CONTAINER(menu));
6726 for (l = items; l; l = l->next)
6727 g_signal_connect(l->data, "activate",
6728 G_CALLBACK(wv_popup_activ_cb), t);
6729 g_list_free(items);
6732 void
6733 wv_deny_location_cb(WebKitWebView *wv, WebKitWebFrame *frame,
6734 WebKitGeolocationPolicyDecision *pd, struct tab *t)
6736 webkit_geolocation_policy_deny(pd);
6739 void
6740 cmd_popup_cb(GtkEntry *entry, GtkMenu *menu, struct tab *t)
6742 /* popup menu enabled */
6743 t->popup = 1;
6747 cmd_focusout_cb(GtkWidget *w, GdkEventFocus *e, struct tab *t)
6749 if (t == NULL) {
6750 show_oops(NULL, "cmd_focusout_cb invalid parameters");
6751 return (XT_CB_PASSTHROUGH);
6754 DNPRINTF(XT_D_CMD, "cmd_focusout_cb: tab %d popup %d\n",
6755 t->tab_id, t->popup);
6757 /* if popup is enabled don't lose focus */
6758 if (t->popup) {
6759 t->popup = 0;
6760 return (XT_CB_PASSTHROUGH);
6763 hide_cmd(t);
6764 hide_oops(t);
6765 disable_hints(t);
6767 return (XT_CB_PASSTHROUGH);
6770 void
6771 cmd_hide_cb(GtkWidget *w, struct tab *t)
6773 if (t == NULL) {
6774 show_oops(NULL, "%s: invalid parameters", __func__);
6775 return;
6778 if (show_url == 0 || t->focus_wv)
6779 focus_webview(t);
6780 else
6781 gtk_widget_grab_focus(GTK_WIDGET(t->uri_entry));
6784 void
6785 cmd_activate_cb(GtkEntry *entry, struct tab *t)
6787 char *s;
6788 const gchar *c = gtk_entry_get_text(entry);
6790 if (t == NULL) {
6791 show_oops(NULL, "cmd_activate_cb invalid parameters");
6792 return;
6795 DNPRINTF(XT_D_CMD, "cmd_activate_cb: tab %d %s\n", t->tab_id, c);
6797 /* sanity */
6798 if (c == NULL)
6799 goto done;
6800 else if (!(c[0] == ':' || c[0] == '/' || c[0] == '?' ||
6801 c[0] == '.' || c[0] == ','))
6802 goto done;
6803 if (strlen(c) < 1)
6804 goto done;
6805 s = (char *)&c[1];
6807 if (c[0] == '/' || c[0] == '?') {
6808 /* see if there is a timer pending */
6809 if (t->search_id) {
6810 g_source_remove(t->search_id);
6811 t->search_id = 0;
6812 search_cb(t);
6815 if (t->search_text) {
6816 g_free(t->search_text);
6817 t->search_text = NULL;
6820 t->search_text = g_strdup(s);
6821 if (global_search)
6822 g_free(global_search);
6823 global_search = g_strdup(s);
6824 t->search_forward = c[0] == '/';
6826 history_add(&shl, search_file, s, &search_history_count);
6827 } else if (c[0] == '.' || c[0] == ',') {
6828 run_script(t, "hints.fire();");
6829 /* XXX history for link following? */
6830 } else if (c[0] == ':') {
6831 history_add(&chl, command_file, s, &cmd_history_count);
6832 /* can't call hide_cmd after cmd_execute */
6833 hide_cmd(t);
6834 cmd_execute(t, s);
6835 return;
6838 done:
6839 hide_cmd(t);
6842 void
6843 backward_cb(GtkWidget *w, struct tab *t)
6845 struct karg a;
6847 if (t == NULL) {
6848 show_oops(NULL, "backward_cb invalid parameters");
6849 return;
6852 DNPRINTF(XT_D_NAV, "backward_cb: tab %d\n", t->tab_id);
6854 a.i = XT_NAV_BACK;
6855 navaction(t, &a);
6858 void
6859 forward_cb(GtkWidget *w, struct tab *t)
6861 struct karg a;
6863 if (t == NULL) {
6864 show_oops(NULL, "forward_cb invalid parameters");
6865 return;
6868 DNPRINTF(XT_D_NAV, "forward_cb: tab %d\n", t->tab_id);
6870 a.i = XT_NAV_FORWARD;
6871 navaction(t, &a);
6874 void
6875 home_cb(GtkWidget *w, struct tab *t)
6877 if (t == NULL) {
6878 show_oops(NULL, "home_cb invalid parameters");
6879 return;
6882 DNPRINTF(XT_D_NAV, "home_cb: tab %d\n", t->tab_id);
6884 load_uri(t, home);
6887 void
6888 stop_cb(GtkWidget *w, struct tab *t)
6890 WebKitWebFrame *frame;
6892 if (t == NULL) {
6893 show_oops(NULL, "stop_cb invalid parameters");
6894 return;
6897 DNPRINTF(XT_D_NAV, "stop_cb: tab %d\n", t->tab_id);
6899 frame = webkit_web_view_get_main_frame(t->wv);
6900 if (frame == NULL) {
6901 show_oops(t, "stop_cb: no frame");
6902 return;
6905 webkit_web_frame_stop_loading(frame);
6906 abort_favicon_download(t);
6909 void
6910 setup_webkit(struct tab *t)
6912 if (is_g_object_setting(G_OBJECT(t->settings), "enable-dns-prefetching"))
6913 g_object_set(G_OBJECT(t->settings), "enable-dns-prefetching",
6914 FALSE, (char *)NULL);
6915 else
6916 warnx("webkit does not have \"enable-dns-prefetching\" property");
6917 g_object_set(G_OBJECT(t->settings), "default-encoding", encoding,
6918 (char *)NULL);
6919 g_object_set(G_OBJECT(t->settings),
6920 "enable-scripts", enable_scripts, (char *)NULL);
6921 g_object_set(G_OBJECT(t->settings),
6922 "enable-plugins", enable_plugins, (char *)NULL);
6923 g_object_set(G_OBJECT(t->settings),
6924 "javascript-can-open-windows-automatically",
6925 js_auto_open_windows, (char *)NULL);
6926 g_object_set(G_OBJECT(t->settings),
6927 "enable-html5-database", FALSE, (char *)NULL);
6928 g_object_set(G_OBJECT(t->settings),
6929 "enable-html5-local-storage", enable_localstorage, (char *)NULL);
6930 g_object_set(G_OBJECT(t->settings),
6931 "enable_spell_checking", enable_spell_checking, (char *)NULL);
6932 g_object_set(G_OBJECT(t->settings),
6933 "spell_checking_languages", spell_check_languages, (char *)NULL);
6934 g_object_set(G_OBJECT(t->settings),
6935 "enable-developer-extras", TRUE, (char *)NULL);
6936 g_object_set(G_OBJECT(t->wv),
6937 "full-content-zoom", TRUE, (char *)NULL);
6938 g_object_set(G_OBJECT(t->settings),
6939 "auto-load-images", auto_load_images, (char *)NULL);
6940 if (is_g_object_setting(G_OBJECT(t->settings),
6941 "enable-display-of-insecure-content"))
6942 g_object_set(G_OBJECT(t->settings),
6943 "enable-display-of-insecure-content",
6944 allow_insecure_content, (char *)NULL);
6945 if (is_g_object_setting(G_OBJECT(t->settings),
6946 "enable-running-of-insecure-content"))
6947 g_object_set(G_OBJECT(t->settings),
6948 "enable-running-of-insecure-content",
6949 allow_insecure_scripts, (char *)NULL);
6951 webkit_web_view_set_settings(t->wv, t->settings);
6954 gboolean
6955 update_statusbar_position(GtkAdjustment* adjustment, gpointer data)
6957 struct tab *ti, *t = NULL;
6958 gdouble view_size, value, max;
6959 gchar *position;
6961 TAILQ_FOREACH(ti, &tabs, entry)
6962 if (ti->tab_id == gtk_notebook_get_current_page(notebook)) {
6963 t = ti;
6964 break;
6967 if (t == NULL)
6968 return FALSE;
6970 if (adjustment == NULL)
6971 adjustment = gtk_scrolled_window_get_vadjustment(
6972 GTK_SCROLLED_WINDOW(t->browser_win));
6974 view_size = gtk_adjustment_get_page_size(adjustment);
6975 value = gtk_adjustment_get_value(adjustment);
6976 max = gtk_adjustment_get_upper(adjustment) - view_size;
6978 if (max > -0.0001 && max < 0.0001)
6979 position = g_strdup("All");
6980 else if (value > (max - 0.0001) && value < (max + 0.0001))
6981 position = g_strdup("Bot");
6982 else if (value > -0.0001 && value < 0.0001)
6983 position = g_strdup("Top");
6984 else
6985 position = g_strdup_printf("%d%%", (int) ((value / max) * 100));
6987 if (t->sbe.position != NULL)
6988 gtk_label_set_text(GTK_LABEL(t->sbe.position), position);
6989 g_free(position);
6991 return (TRUE);
6994 GtkWidget *
6995 create_window(const gchar *name)
6997 GtkWidget *w;
6999 w = gtk_window_new(GTK_WINDOW_TOPLEVEL);
7000 if (window_maximize)
7001 gtk_window_maximize(GTK_WINDOW(w));
7002 else
7003 gtk_window_set_default_size(GTK_WINDOW(w), window_width, window_height);
7004 gtk_widget_set_name(w, name);
7005 gtk_window_set_wmclass(GTK_WINDOW(w), name, "Xombrero");
7007 return (w);
7010 GtkWidget *
7011 create_browser(struct tab *t)
7013 GtkWidget *w;
7014 GtkAdjustment *adjustment;
7016 if (t == NULL) {
7017 show_oops(NULL, "create_browser invalid parameters");
7018 return (NULL);
7021 w = gtk_scrolled_window_new(NULL, NULL);
7022 gtk_widget_set_can_focus(w, FALSE);
7023 t->adjust_h = gtk_scrolled_window_get_hadjustment(
7024 GTK_SCROLLED_WINDOW(w));
7025 t->adjust_v = gtk_scrolled_window_get_vadjustment(
7026 GTK_SCROLLED_WINDOW(w));
7027 #if !GTK_CHECK_VERSION(3, 0, 0)
7028 gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(w),
7029 GTK_POLICY_AUTOMATIC, GTK_POLICY_AUTOMATIC);
7030 #endif
7033 t->wv = WEBKIT_WEB_VIEW(webkit_web_view_new());
7034 gtk_container_add(GTK_CONTAINER(w), GTK_WIDGET(t->wv));
7036 /* set defaults */
7037 t->settings = webkit_web_view_get_settings(t->wv);
7038 t->stylesheet = g_strdup(stylesheet);
7039 t->load_images = auto_load_images;
7041 adjustment =
7042 gtk_scrolled_window_get_vadjustment(GTK_SCROLLED_WINDOW(w));
7043 g_signal_connect(G_OBJECT(adjustment), "value-changed",
7044 G_CALLBACK(update_statusbar_position), NULL);
7046 setup_webkit(t);
7047 setup_inspector(t);
7049 return (w);
7052 GtkWidget *
7053 create_kiosk_toolbar(struct tab *t)
7055 GtkWidget *toolbar = NULL;
7056 GtkBox *b;
7058 #if GTK_CHECK_VERSION(3, 0, 0)
7059 toolbar = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 1);
7060 gtk_widget_set_name(toolbar, "toolbar");
7061 #else
7062 toolbar = gtk_hbox_new(FALSE, 1);
7063 #endif
7065 b = GTK_BOX(toolbar);
7066 gtk_container_set_border_width(GTK_CONTAINER(toolbar), 0);
7068 /* backward button */
7069 t->backward = create_button("Back", "go-previous", 0);
7070 gtk_widget_set_sensitive(t->backward, FALSE);
7071 g_signal_connect(G_OBJECT(t->backward), "clicked",
7072 G_CALLBACK(backward_cb), t);
7073 gtk_box_pack_start(b, t->backward, TRUE, TRUE, 0);
7075 /* forward button */
7076 t->forward = create_button("Forward", "go-next", 0);
7077 gtk_widget_set_sensitive(t->forward, FALSE);
7078 g_signal_connect(G_OBJECT(t->forward), "clicked",
7079 G_CALLBACK(forward_cb), t);
7080 gtk_box_pack_start(b, t->forward, TRUE, TRUE, 0);
7082 /* home button */
7083 t->gohome = create_button("Home", "go-home", 0);
7084 gtk_widget_set_sensitive(t->gohome, true);
7085 g_signal_connect(G_OBJECT(t->gohome), "clicked",
7086 G_CALLBACK(home_cb), t);
7087 gtk_box_pack_start(b, t->gohome, TRUE, TRUE, 0);
7090 * Create widgets but don't use them. This is just so we don't get
7091 * loads of errors when trying to do stuff with them. Sink the floating
7092 * reference here, and do a manual unreference when the tab is deleted.
7094 t->uri_entry = gtk_entry_new();
7095 g_object_ref_sink(G_OBJECT(t->uri_entry));
7096 g_signal_connect(G_OBJECT(t->uri_entry), "focus-in-event",
7097 G_CALLBACK(entry_focus_cb), t);
7098 t->stop = create_button("Stop", "process-stop", 0);
7099 g_object_ref_sink(G_OBJECT(t->stop));
7100 t->js_toggle = create_button("JS-Toggle", enable_scripts ?
7101 "media-playback-start" : "media-playback-pause", 0);
7102 g_object_ref_sink(G_OBJECT(t->stop));
7104 #if !GTK_CHECK_VERSION(3, 0, 0)
7105 t->default_style = gtk_rc_get_style(t->uri_entry);
7106 #endif
7108 return (toolbar);
7111 GtkWidget *
7112 create_toolbar(struct tab *t)
7114 GtkWidget *toolbar = NULL;
7115 GtkBox *b;
7118 * t->stop, t->js_toggle, and t->uri_entry are shared by the kiosk
7119 * toolbar, but not shown or used. We still create them there so we can
7120 * avoid loads of warnings when trying to use them. Instead, we sink
7121 * the floating reference here, and do the final unreference when
7122 * deleting the tab.
7125 #if GTK_CHECK_VERSION(3, 0, 0)
7126 toolbar = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 1);
7127 gtk_widget_set_name(toolbar, "toolbar");
7128 #else
7129 toolbar = gtk_hbox_new(FALSE, 1);
7130 #endif
7132 b = GTK_BOX(toolbar);
7133 gtk_container_set_border_width(GTK_CONTAINER(toolbar), 0);
7135 /* backward button */
7136 t->backward = create_button("Back", "go-previous", 0);
7137 gtk_widget_set_sensitive(t->backward, FALSE);
7138 g_signal_connect(G_OBJECT(t->backward), "clicked",
7139 G_CALLBACK(backward_cb), t);
7140 gtk_box_pack_start(b, t->backward, FALSE, FALSE, 0);
7142 /* forward button */
7143 t->forward = create_button("Forward", "go-next", 0);
7144 gtk_widget_set_sensitive(t->forward, FALSE);
7145 g_signal_connect(G_OBJECT(t->forward), "clicked",
7146 G_CALLBACK(forward_cb), t);
7147 gtk_box_pack_start(b, t->forward, FALSE, FALSE, 0);
7149 /* stop button */
7150 t->stop = create_button("Stop", "process-stop", 0);
7151 g_object_ref_sink(G_OBJECT(t->stop));
7152 gtk_widget_set_sensitive(t->stop, FALSE);
7153 g_signal_connect(G_OBJECT(t->stop), "clicked", G_CALLBACK(stop_cb), t);
7154 gtk_box_pack_start(b, t->stop, FALSE, FALSE, 0);
7156 /* JS button */
7157 t->js_toggle = create_button("JS-Toggle", enable_scripts ?
7158 "media-playback-start" : "media-playback-pause", 0);
7159 g_object_ref_sink(G_OBJECT(t->js_toggle));
7160 gtk_widget_set_sensitive(t->js_toggle, TRUE);
7161 g_signal_connect(G_OBJECT(t->js_toggle), "clicked",
7162 G_CALLBACK(js_toggle_cb), t);
7163 gtk_box_pack_start(b, t->js_toggle, FALSE, FALSE, 0);
7165 /* toggle proxy button */
7166 t->proxy_toggle = create_button("Proxy-Toggle", proxy_uri ?
7167 "gtk-connect" : "gtk-disconnect", 0);
7168 /* override icons */
7169 if (proxy_uri)
7170 button_set_file(t->proxy_toggle, "torenabled.ico");
7171 else
7172 button_set_file(t->proxy_toggle, "tordisabled.ico");
7173 gtk_widget_set_sensitive(t->proxy_toggle, TRUE);
7174 g_signal_connect(G_OBJECT(t->proxy_toggle), "clicked",
7175 G_CALLBACK(proxy_toggle_cb), t);
7176 gtk_box_pack_start(b, t->proxy_toggle, FALSE, FALSE, 0);
7178 t->uri_entry = gtk_entry_new();
7179 g_object_ref_sink(G_OBJECT(t->uri_entry));
7180 g_signal_connect(G_OBJECT(t->uri_entry), "activate",
7181 G_CALLBACK(activate_uri_entry_cb), t);
7182 g_signal_connect(G_OBJECT(t->uri_entry), "key-press-event",
7183 G_CALLBACK(entry_key_cb), t);
7184 g_signal_connect(G_OBJECT(t->uri_entry), "focus-in-event",
7185 G_CALLBACK(entry_focus_cb), t);
7186 completion_add(t);
7187 gtk_box_pack_start(b, t->uri_entry, TRUE, TRUE, 0);
7189 /* search entry */
7190 t->search_entry = gtk_entry_new();
7191 gtk_entry_set_width_chars(GTK_ENTRY(t->search_entry), 30);
7192 g_signal_connect(G_OBJECT(t->search_entry), "activate",
7193 G_CALLBACK(activate_search_entry_cb), t);
7194 g_signal_connect(G_OBJECT(t->search_entry), "key-press-event",
7195 G_CALLBACK(entry_key_cb), t);
7196 g_signal_connect(G_OBJECT(t->search_entry), "focus-in-event",
7197 G_CALLBACK(entry_focus_cb), t);
7198 gtk_box_pack_start(b, t->search_entry, FALSE, FALSE, 0);
7200 #if !GTK_CHECK_VERSION(3, 0, 0)
7201 t->default_style = gtk_rc_get_style(t->uri_entry);
7202 #endif
7204 return (toolbar);
7207 GtkWidget *
7208 create_buffers(struct tab *t)
7210 GtkCellRenderer *renderer;
7211 GtkWidget *view;
7213 view = gtk_tree_view_new();
7215 gtk_tree_view_set_headers_visible(GTK_TREE_VIEW(view), FALSE);
7217 renderer = gtk_cell_renderer_text_new();
7218 gtk_tree_view_insert_column_with_attributes
7219 (GTK_TREE_VIEW(view), -1, "Id", renderer, "text", COL_ID, (char *)NULL);
7221 renderer = gtk_cell_renderer_pixbuf_new();
7222 gtk_tree_view_insert_column_with_attributes
7223 (GTK_TREE_VIEW(view), -1, "Favicon", renderer, "pixbuf", COL_FAVICON,
7224 (char *)NULL);
7226 renderer = gtk_cell_renderer_text_new();
7227 gtk_tree_view_insert_column_with_attributes
7228 (GTK_TREE_VIEW(view), -1, "Title", renderer, "text", COL_TITLE,
7229 (char *)NULL);
7231 gtk_tree_view_set_model
7232 (GTK_TREE_VIEW(view), GTK_TREE_MODEL(buffers_store));
7234 return (view);
7237 void
7238 row_activated_cb(GtkTreeView *view, GtkTreePath *path,
7239 GtkTreeViewColumn *col, struct tab *t)
7241 GtkTreeIter iter;
7242 guint id;
7244 gtk_widget_grab_focus(GTK_WIDGET(t->wv));
7246 if (gtk_tree_model_get_iter(GTK_TREE_MODEL(buffers_store), &iter,
7247 path)) {
7248 gtk_tree_model_get
7249 (GTK_TREE_MODEL(buffers_store), &iter, COL_ID, &id, -1);
7250 set_current_tab(id - 1);
7253 hide_buffers(t);
7256 /* after tab reordering/creation/removal */
7257 void
7258 recalc_tabs(void)
7260 struct tab *t;
7262 TAILQ_FOREACH(t, &tabs, entry)
7263 t->tab_id = gtk_notebook_page_num(notebook, t->vbox);
7266 void
7267 update_statusbar_tabs(struct tab *t)
7269 int tab_id, max_tab_id;
7270 char s[16];
7272 if (t != NULL)
7273 tab_id = t->tab_id;
7274 else
7275 tab_id = gtk_notebook_get_current_page(notebook);
7277 max_tab_id = gtk_notebook_get_n_pages(notebook);
7278 snprintf(s, sizeof s, "%d/%d", tab_id + 1, max_tab_id);
7280 if (t == NULL)
7281 t = get_current_tab();
7283 if (t != NULL && t->sbe.tabs != NULL)
7284 gtk_label_set_text(GTK_LABEL(t->sbe.tabs), s);
7287 /* after active tab change */
7288 void
7289 recolor_compact_tabs(void)
7291 struct tab *t;
7292 int curid = 0;
7293 #if !GTK_CHECK_VERSION(3, 0, 0)
7294 GdkColor color_active, color_inactive;
7296 gdk_color_parse(XT_COLOR_CT_ACTIVE, &color_active);
7297 gdk_color_parse(XT_COLOR_CT_INACTIVE, &color_inactive);
7298 #endif
7299 curid = gtk_notebook_get_current_page(notebook);
7301 TAILQ_FOREACH(t, &tabs, entry) {
7302 #if GTK_CHECK_VERSION(3, 0, 0)
7303 if (t->tab_id == curid)
7304 gtk_widget_set_name(t->tab_elems.label, XT_CSS_ACTIVE);
7305 else
7306 gtk_widget_set_name(t->tab_elems.label, "");
7307 #else
7308 if (t->tab_id == curid)
7309 gtk_widget_modify_fg(t->tab_elems.label,
7310 GTK_STATE_NORMAL, &color_active);
7311 else
7312 gtk_widget_modify_fg(t->tab_elems.label,
7313 GTK_STATE_NORMAL, &color_inactive);
7314 #endif
7318 void
7319 set_current_tab(int page_num)
7321 buffercmd_abort(get_current_tab());
7322 gtk_notebook_set_current_page(notebook, page_num);
7323 recolor_compact_tabs();
7324 update_statusbar_tabs(NULL);
7328 undo_close_tab_save(struct tab *t)
7330 int m, n;
7331 const gchar *uri;
7332 struct undo *u1, *u2;
7333 GList *items;
7334 GList *item;
7335 WebKitWebHistoryItem *el;
7337 if ((uri = get_uri(t)) == NULL)
7338 return (1);
7340 u1 = g_malloc0(sizeof(struct undo));
7341 u1->uri = g_strdup(uri);
7343 t->bfl = webkit_web_view_get_back_forward_list(t->wv);
7345 m = webkit_web_back_forward_list_get_forward_length(t->bfl);
7346 n = webkit_web_back_forward_list_get_back_length(t->bfl);
7347 u1->back = n;
7349 /* forward history */
7350 items = webkit_web_back_forward_list_get_forward_list_with_limit(t->bfl, m);
7351 for (item = g_list_first(items); item; item = item->next) {
7352 u1->history = g_list_prepend(u1->history,
7353 webkit_web_history_item_copy(item->data));
7355 g_list_free(items);
7357 /* current item */
7358 if (m) {
7359 el = webkit_web_back_forward_list_get_current_item(t->bfl);
7360 u1->history = g_list_prepend(u1->history,
7361 webkit_web_history_item_copy(el));
7364 /* back history */
7365 items = webkit_web_back_forward_list_get_back_list_with_limit(t->bfl, n);
7366 for (item = g_list_first(items); item; item = item->next) {
7367 u1->history = g_list_prepend(u1->history,
7368 webkit_web_history_item_copy(item->data));
7370 g_list_free(items);
7372 TAILQ_INSERT_HEAD(&undos, u1, entry);
7374 if (undo_count > XT_MAX_UNDO_CLOSE_TAB) {
7375 u2 = TAILQ_LAST(&undos, undo_tailq);
7376 TAILQ_REMOVE(&undos, u2, entry);
7377 g_free(u2->uri);
7378 g_list_free(u2->history);
7379 g_free(u2);
7380 } else
7381 undo_count++;
7383 return (0);
7386 void
7387 delete_tab(struct tab *t)
7389 struct karg a;
7391 DNPRINTF(XT_D_TAB, "delete_tab: %p\n", t);
7393 if (t == NULL)
7394 return;
7396 TAILQ_REMOVE(&tabs, t, entry);
7397 buffercmd_abort(t);
7399 /* Halt all webkit activity. */
7400 abort_favicon_download(t);
7401 webkit_web_view_stop_loading(t->wv);
7403 /* Save the tab, so we can undo the close. */
7404 undo_close_tab_save(t);
7406 /* just in case */
7407 if (t->search_id)
7408 g_source_remove(t->search_id);
7410 /* session key */
7411 if (t->session_key)
7412 g_free(t->session_key);
7414 /* inspector */
7415 bzero(&a, sizeof a);
7416 a.i = XT_INS_CLOSE;
7417 inspector_cmd(t, &a);
7419 if (browser_mode == XT_BM_KIOSK) {
7420 gtk_widget_destroy(t->uri_entry);
7421 gtk_widget_destroy(t->stop);
7422 gtk_widget_destroy(t->js_toggle);
7425 /* widgets not shown in the kiosk toolbar */
7426 gtk_widget_destroy(t->stop);
7427 g_object_unref(G_OBJECT(t->stop));
7428 gtk_widget_destroy(t->js_toggle);
7429 g_object_unref(G_OBJECT(t->js_toggle));
7430 gtk_widget_destroy(t->uri_entry);
7431 g_object_unref(G_OBJECT(t->uri_entry));
7433 g_object_unref(G_OBJECT(t->completion));
7434 if (t->item)
7435 g_object_unref(t->item);
7437 gtk_widget_destroy(t->tab_elems.eventbox);
7438 gtk_widget_destroy(t->vbox);
7440 g_free(t->stylesheet);
7441 g_free(t->tmp_uri);
7442 g_free(t->status);
7443 g_free(t);
7444 t = NULL;
7446 if (TAILQ_EMPTY(&tabs)) {
7447 if (browser_mode == XT_BM_KIOSK)
7448 create_new_tab(home, NULL, 1, -1);
7449 else
7450 create_new_tab(NULL, NULL, 1, -1);
7453 /* recreate session */
7454 if (session_autosave) {
7455 bzero(&a, sizeof a);
7456 a.s = NULL;
7457 save_tabs(NULL, &a);
7460 recalc_tabs();
7461 recolor_compact_tabs();
7464 void
7465 update_statusbar_zoom(struct tab *t)
7467 gfloat zoom;
7468 char s[16] = { '\0' };
7470 g_object_get(G_OBJECT(t->wv), "zoom-level", &zoom, (char *)NULL);
7471 if ((zoom <= 0.99 || zoom >= 1.01))
7472 snprintf(s, sizeof s, "%d%%", (int)(zoom * 100));
7473 if (t->sbe.zoom != NULL)
7474 gtk_label_set_text(GTK_LABEL(t->sbe.zoom), s);
7477 void
7478 setzoom_webkit(struct tab *t, int adjust)
7480 #define XT_ZOOMPERCENT 0.04
7482 gfloat zoom;
7484 if (t == NULL) {
7485 show_oops(NULL, "setzoom_webkit invalid parameters");
7486 return;
7489 g_object_get(G_OBJECT(t->wv), "zoom-level", &zoom, (char *)NULL);
7490 if (adjust == XT_ZOOM_IN)
7491 zoom += XT_ZOOMPERCENT;
7492 else if (adjust == XT_ZOOM_OUT)
7493 zoom -= XT_ZOOMPERCENT;
7494 else if (adjust > 0)
7495 zoom = default_zoom_level + adjust / 100.0 - 1.0;
7496 else {
7497 show_oops(t, "setzoom_webkit invalid zoom value");
7498 return;
7501 if (zoom < XT_ZOOMPERCENT)
7502 zoom = XT_ZOOMPERCENT;
7503 g_object_set(G_OBJECT(t->wv), "zoom-level", zoom, (char *)NULL);
7504 update_statusbar_zoom(t);
7507 gboolean
7508 tab_clicked_cb(GtkWidget *widget, GdkEventButton *event, gpointer data)
7510 struct tab *t = (struct tab *) data;
7512 DNPRINTF(XT_D_TAB, "tab_clicked_cb: tab: %d\n", t->tab_id);
7514 switch (event->button) {
7515 case 1:
7516 set_current_tab(t->tab_id);
7517 break;
7518 case 2:
7519 delete_tab(t);
7520 break;
7523 return TRUE;
7526 void
7527 append_tab(struct tab *t)
7529 if (t == NULL)
7530 return;
7532 TAILQ_INSERT_TAIL(&tabs, t, entry);
7533 t->tab_id = gtk_notebook_append_page(notebook, t->vbox, t->tab_content);
7536 GtkWidget *
7537 create_sbe(void)
7539 GtkWidget *sbe;
7541 sbe = gtk_label_new(NULL);
7542 gtk_widget_set_can_focus(GTK_WIDGET(sbe), FALSE);
7543 modify_font(GTK_WIDGET(sbe), statusbar_font);
7544 return (sbe);
7548 statusbar_create(struct tab *t)
7550 GtkWidget *box; /* container for statusbar elems */
7551 GtkWidget *sep;
7552 GtkBox *b;
7553 char *p;
7554 #if !GTK_CHECK_VERSION(3, 0, 0)
7555 GdkColor color;
7556 #endif
7558 if (t == NULL) {
7559 DPRINTF("%s: invalid parameters", __func__);
7560 return (1);
7563 #if GTK_CHECK_VERSION(3, 0, 0)
7564 t->statusbar = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 0);
7565 box = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 0);
7566 gtk_widget_set_name(GTK_WIDGET(t->statusbar), "statusbar");
7567 #else
7568 t->statusbar = gtk_hbox_new(FALSE, 0);
7569 box = gtk_hbox_new(FALSE, 0);
7570 #endif
7571 t->sbe.ebox = gtk_event_box_new();
7573 gtk_widget_set_can_focus(GTK_WIDGET(t->statusbar), FALSE);
7574 gtk_widget_set_can_focus(GTK_WIDGET(t->sbe.ebox), FALSE);
7575 gtk_widget_set_can_focus(GTK_WIDGET(box), FALSE);
7577 gtk_box_set_spacing(GTK_BOX(box), 10);
7578 gtk_box_pack_start(GTK_BOX(t->statusbar), t->sbe.ebox, TRUE, TRUE, 0);
7579 gtk_container_add(GTK_CONTAINER(t->sbe.ebox), box);
7581 t->sbe.uri = gtk_entry_new();
7582 gtk_widget_set_can_focus(GTK_WIDGET(t->sbe.uri), FALSE);
7583 modify_font(GTK_WIDGET(t->sbe.uri), statusbar_font);
7584 #if !GTK_CHECK_VERSION(3, 0, 0)
7585 gtk_entry_set_inner_border(GTK_ENTRY(t->sbe.uri), NULL);
7586 gtk_entry_set_has_frame(GTK_ENTRY(t->sbe.uri), FALSE);
7587 #endif
7589 #if GTK_CHECK_VERSION(3, 0, 0)
7590 statusbar_modify_attr(t, XT_CSS_NORMAL);
7591 #else
7592 statusbar_modify_attr(t, XT_COLOR_WHITE, XT_COLOR_BLACK);
7593 #endif
7595 b = GTK_BOX(box);
7596 gtk_box_pack_start(b, t->sbe.uri, TRUE, TRUE, 0);
7598 for (p = statusbar_elems; *p != '\0'; p++) {
7599 switch (*p) {
7600 case '|':
7601 #if GTK_CHECK_VERSION(3, 0, 0)
7602 sep = gtk_separator_new(GTK_ORIENTATION_VERTICAL);
7603 #else
7604 sep = gtk_vseparator_new();
7605 gdk_color_parse(XT_COLOR_SB_SEPARATOR, &color);
7606 gtk_widget_modify_bg(sep, GTK_STATE_NORMAL, &color);
7607 #endif
7608 gtk_box_pack_start(b, sep, FALSE, FALSE, 0);
7609 break;
7610 case 'P':
7611 if (t->sbe.position == NULL) {
7612 t->sbe.position = create_sbe();
7613 gtk_box_pack_start(b, t->sbe.position, FALSE,
7614 FALSE, 0);
7616 break;
7617 case 'B':
7618 if (t->sbe.buffercmd == NULL) {
7619 t->sbe.buffercmd = create_sbe();
7620 gtk_box_pack_start(b, t->sbe.buffercmd, FALSE,
7621 FALSE, 0);
7623 break;
7624 case 'Z':
7625 if (t->sbe.zoom == NULL) {
7626 t->sbe.zoom = create_sbe();
7627 gtk_box_pack_start(b, t->sbe.zoom, FALSE, FALSE,
7630 break;
7631 case 'T':
7632 if (t->sbe.tabs == NULL) {
7633 t->sbe.tabs = create_sbe();
7634 gtk_box_pack_start(b, t->sbe.tabs, FALSE, FALSE,
7637 break;
7638 case 'p':
7639 if (t->sbe.proxy == NULL) {
7640 t->sbe.proxy = create_sbe();
7641 gtk_box_pack_start(b, t->sbe.proxy, FALSE,
7642 FALSE, 0);
7643 if (proxy_uri)
7644 gtk_label_set_text(
7645 GTK_LABEL(t->sbe.proxy), "proxy");
7647 break;
7648 default:
7649 warnx("illegal flag \"%c\" in statusbar_elems\n", *p);
7650 break;
7654 gtk_box_pack_end(GTK_BOX(t->vbox), t->statusbar, FALSE, FALSE, 0);
7656 return (0);
7659 struct tab *
7660 create_new_tab(const char *title, struct undo *u, int focus, int position)
7662 struct tab *t;
7663 int load = 1, id;
7664 GtkWidget *b, *bb;
7665 WebKitWebHistoryItem *item;
7666 GList *items;
7667 char *sv[3];
7668 #if !GTK_CHECK_VERSION(3, 0, 0)
7669 GdkColor color;
7670 #endif
7672 DNPRINTF(XT_D_TAB, "create_new_tab: title %s focus %d\n", title, focus);
7674 if (tabless && !TAILQ_EMPTY(&tabs)) {
7675 if (single_instance) {
7676 DNPRINTF(XT_D_TAB,
7677 "create_new_tab: new tab rejected\n");
7678 return (NULL);
7680 sv[0] = start_argv[0];
7681 sv[1] = (char *)title;
7682 sv[2] = (char *)NULL;
7683 if (!g_spawn_async(NULL, sv, NULL, G_SPAWN_SEARCH_PATH,
7684 NULL, NULL, NULL, NULL))
7685 show_oops(NULL, "%s: could not spawn process",
7686 __func__);
7687 return (NULL);
7690 t = g_malloc0(sizeof *t);
7692 if (title == NULL) {
7693 title = "(untitled)";
7694 load = 0;
7697 #if GTK_CHECK_VERSION(3, 0, 0)
7698 t->vbox = gtk_box_new(GTK_ORIENTATION_VERTICAL, 0);
7699 b = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 0);
7700 gtk_widget_set_name(t->vbox, "vbox");
7701 #else
7702 t->vbox = gtk_vbox_new(FALSE, 0);
7703 b = gtk_hbox_new(FALSE, 0);
7704 #endif
7705 gtk_widget_set_can_focus(t->vbox, FALSE);
7707 /* label + button for tab */
7708 t->tab_content = b;
7709 gtk_widget_set_can_focus(t->tab_content, FALSE);
7711 t->user_agent_id = 0;
7712 t->http_accept_id = 0;
7714 #if WEBKIT_CHECK_VERSION(1, 5, 0)
7715 t->active = NULL;
7716 #endif
7718 #if GTK_CHECK_VERSION(2, 20, 0)
7719 t->spinner = gtk_spinner_new();
7720 #endif
7721 t->label = gtk_label_new(title);
7722 bb = create_button("Close", "window-close", 1);
7723 gtk_label_set_max_width_chars(GTK_LABEL(t->label), 20);
7724 gtk_label_set_ellipsize(GTK_LABEL(t->label), PANGO_ELLIPSIZE_END);
7725 gtk_label_set_line_wrap(GTK_LABEL(t->label), FALSE);
7726 gtk_widget_set_size_request(t->tab_content, 130, 0);
7729 * this is a total hack and most likely breaks with other styles but
7730 * is necessary so the text doesn't bounce around when the spinner is
7731 * shown/hidden
7733 #if GTK_CHECK_VERSION(3, 0, 0)
7734 gtk_widget_set_size_request(t->label, 95, 0);
7735 #else
7736 gtk_widget_set_size_request(t->label, 100, 0);
7737 #endif
7739 gtk_box_pack_start(GTK_BOX(t->tab_content), bb, FALSE, FALSE, 0);
7740 gtk_box_pack_start(GTK_BOX(t->tab_content), t->label, FALSE, FALSE, 0);
7741 #if GTK_CHECK_VERSION(2, 20, 0)
7742 gtk_box_pack_end(GTK_BOX(b), t->spinner, FALSE, FALSE, 0);
7743 #endif
7745 /* toolbar */
7746 if (browser_mode == XT_BM_KIOSK) {
7747 t->toolbar = create_kiosk_toolbar(t);
7748 gtk_box_pack_start(GTK_BOX(t->vbox), t->toolbar, FALSE, FALSE,
7750 } else {
7751 t->toolbar = create_toolbar(t);
7752 gtk_box_pack_start(GTK_BOX(t->vbox), t->toolbar, FALSE, FALSE,
7756 /* marks */
7757 marks_clear(t);
7759 /* browser */
7760 t->browser_win = create_browser(t);
7761 set_scrollbar_visibility(t, show_scrollbars);
7762 gtk_box_pack_start(GTK_BOX(t->vbox), t->browser_win, TRUE, TRUE, 0);
7764 /* oops message for user feedback */
7765 t->oops = gtk_entry_new();
7766 gtk_entry_set_inner_border(GTK_ENTRY(t->oops), NULL);
7767 gtk_entry_set_has_frame(GTK_ENTRY(t->oops), FALSE);
7768 gtk_widget_set_can_focus(GTK_WIDGET(t->oops), FALSE);
7769 #if GTK_CHECK_VERSION(3, 0, 0)
7770 gtk_widget_set_name(t->oops, XT_CSS_RED);
7771 #else
7772 gdk_color_parse(XT_COLOR_RED, &color);
7773 gtk_widget_modify_base(t->oops, GTK_STATE_NORMAL, &color);
7774 #endif
7775 gtk_box_pack_end(GTK_BOX(t->vbox), t->oops, FALSE, FALSE, 0);
7776 modify_font(GTK_WIDGET(t->oops), oops_font);
7778 /* command entry */
7779 t->cmd = gtk_entry_new();
7780 g_signal_connect(G_OBJECT(t->cmd), "focus-in-event",
7781 G_CALLBACK(entry_focus_cb), t);
7782 gtk_entry_set_inner_border(GTK_ENTRY(t->cmd), NULL);
7783 gtk_entry_set_has_frame(GTK_ENTRY(t->cmd), FALSE);
7784 gtk_box_pack_end(GTK_BOX(t->vbox), t->cmd, FALSE, FALSE, 0);
7785 modify_font(GTK_WIDGET(t->cmd), cmd_font);
7787 /* status bar */
7788 statusbar_create(t);
7790 /* buffer list */
7791 t->buffers = create_buffers(t);
7792 gtk_box_pack_end(GTK_BOX(t->vbox), t->buffers, FALSE, FALSE, 0);
7794 /* xtp meaning is normal by default */
7795 set_normal_tab_meaning(t);
7797 /* set empty favicon */
7798 xt_icon_from_name(t, "text-html");
7800 /* and show it all */
7801 gtk_widget_show_all(b);
7802 gtk_widget_show_all(t->vbox);
7804 if (!fancy_bar) {
7805 gtk_widget_hide(t->backward);
7806 gtk_widget_hide(t->forward);
7807 gtk_widget_hide(t->stop);
7808 gtk_widget_hide(t->js_toggle);
7810 if (!fancy_bar || (search_string == NULL || strlen(search_string) == 0))
7811 gtk_widget_hide(t->search_entry);
7812 if (http_proxy == NULL && http_proxy_save == NULL)
7813 gtk_widget_hide(t->proxy_toggle);
7815 /* compact tab bar */
7816 t->tab_elems.label = gtk_label_new(title);
7817 t->tab_elems.favicon = gtk_image_new();
7819 t->tab_elems.eventbox = gtk_event_box_new();
7820 gtk_widget_set_name(t->tab_elems.eventbox, "compact_tab");
7821 #if GTK_CHECK_VERSION(3, 0, 0)
7822 t->tab_elems.box = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 0);
7824 gtk_label_set_ellipsize(GTK_LABEL(t->tab_elems.label),
7825 PANGO_ELLIPSIZE_END);
7826 gtk_widget_override_font(t->tab_elems.label, tabbar_font);
7827 gtk_widget_set_halign(t->tab_elems.label, GTK_ALIGN_START);
7828 gtk_widget_set_valign(t->tab_elems.label, GTK_ALIGN_START);
7829 #else
7830 t->tab_elems.box = gtk_hbox_new(FALSE, 0);
7832 gtk_label_set_width_chars(GTK_LABEL(t->tab_elems.label), 1);
7833 gtk_misc_set_alignment(GTK_MISC(t->tab_elems.label), 0.0, 0.0);
7834 gtk_misc_set_padding(GTK_MISC(t->tab_elems.label), 4.0, 4.0);
7835 modify_font(GTK_WIDGET(t->tab_elems.label), tabbar_font);
7837 gdk_color_parse(XT_COLOR_CT_BACKGROUND, &color);
7838 gtk_widget_modify_bg(t->tab_elems.eventbox, GTK_STATE_NORMAL, &color);
7839 gdk_color_parse(XT_COLOR_CT_INACTIVE, &color);
7840 gtk_widget_modify_fg(t->tab_elems.label, GTK_STATE_NORMAL, &color);
7841 #endif
7843 gtk_box_pack_start(GTK_BOX(t->tab_elems.box), t->tab_elems.favicon, FALSE,
7844 FALSE, 0);
7845 gtk_box_pack_start(GTK_BOX(t->tab_elems.box), t->tab_elems.label, TRUE,
7846 TRUE, 0);
7847 gtk_container_add(GTK_CONTAINER(t->tab_elems.eventbox),
7848 t->tab_elems.box);
7850 gtk_box_pack_start(GTK_BOX(tab_bar_box), t->tab_elems.eventbox, TRUE,
7851 TRUE, 0);
7852 gtk_widget_show_all(t->tab_elems.eventbox);
7854 if (append_next == 0 || gtk_notebook_get_n_pages(notebook) == 0)
7855 append_tab(t);
7856 else {
7857 id = position >= 0 ? position :
7858 gtk_notebook_get_current_page(notebook) + 1;
7859 if (id > gtk_notebook_get_n_pages(notebook))
7860 append_tab(t);
7861 else {
7862 TAILQ_INSERT_TAIL(&tabs, t, entry);
7863 gtk_notebook_insert_page(notebook, t->vbox, t->tab_content,
7864 id);
7865 gtk_box_reorder_child(GTK_BOX(tab_bar_box),
7866 t->tab_elems.eventbox, id);
7867 recalc_tabs();
7871 #if GTK_CHECK_VERSION(2, 20, 0)
7872 /* turn spinner off if we are a new tab without uri */
7873 if (!load) {
7874 gtk_spinner_stop(GTK_SPINNER(t->spinner));
7875 gtk_widget_hide(t->spinner);
7877 #endif
7878 /* make notebook tabs reorderable */
7879 gtk_notebook_set_tab_reorderable(notebook, t->vbox, TRUE);
7881 /* compact tabs clickable */
7882 g_signal_connect(G_OBJECT(t->tab_elems.eventbox),
7883 "button_press_event", G_CALLBACK(tab_clicked_cb), t);
7885 g_object_connect(G_OBJECT(t->cmd),
7886 "signal::button-release-event", G_CALLBACK(cmd_keyrelease_cb), t,
7887 "signal::key-press-event", G_CALLBACK(cmd_keypress_cb), t,
7888 "signal::key-release-event", G_CALLBACK(cmd_keyrelease_cb), t,
7889 "signal::focus-out-event", G_CALLBACK(cmd_focusout_cb), t,
7890 "signal::activate", G_CALLBACK(cmd_activate_cb), t,
7891 "signal::populate-popup", G_CALLBACK(cmd_popup_cb), t,
7892 "signal::hide", G_CALLBACK(cmd_hide_cb), t,
7893 (char *)NULL);
7895 /* reuse wv_button_cb to hide oops */
7896 g_object_connect(G_OBJECT(t->oops),
7897 "signal::button_press_event", G_CALLBACK(wv_button_cb), t,
7898 (char *)NULL);
7900 g_signal_connect(t->buffers,
7901 "row-activated", G_CALLBACK(row_activated_cb), t);
7902 g_object_connect(G_OBJECT(t->buffers),
7903 "signal::key-press-event", G_CALLBACK(wv_keypress_cb), t, (char *)NULL);
7905 g_object_connect(G_OBJECT(t->wv),
7906 "signal::key-press-event", G_CALLBACK(wv_keypress_cb), t,
7907 "signal::hovering-over-link", G_CALLBACK(webview_hover_cb), t,
7908 "signal::download-requested", G_CALLBACK(webview_download_cb), t,
7909 "signal::mime-type-policy-decision-requested", G_CALLBACK(webview_mimetype_cb), t,
7910 "signal::navigation-policy-decision-requested", G_CALLBACK(webview_npd_cb), t,
7911 "signal::new-window-policy-decision-requested", G_CALLBACK(webview_npd_cb), t,
7912 "signal::resource-request-starting", G_CALLBACK(webview_rrs_cb), t,
7913 "signal::create-web-view", G_CALLBACK(webview_cwv_cb), t,
7914 "signal::close-web-view", G_CALLBACK(webview_closewv_cb), t,
7915 "signal::event", G_CALLBACK(webview_event_cb), t,
7916 "signal::icon-loaded", G_CALLBACK(notify_icon_loaded_cb), t,
7917 "signal::button_press_event", G_CALLBACK(wv_button_cb), t,
7918 "signal::button_release_event", G_CALLBACK(wv_release_button_cb), t,
7919 "signal::populate-popup", G_CALLBACK(wv_popup_cb), t,
7920 "signal::geolocation-policy-decision-requested", G_CALLBACK(wv_deny_location_cb), t,
7921 (char *)NULL);
7922 g_signal_connect(t->wv,
7923 "notify::load-status", G_CALLBACK(notify_load_status_cb), t);
7924 g_signal_connect(t->wv,
7925 "notify::title", G_CALLBACK(notify_title_cb), t);
7926 t->progress_handle = g_signal_connect(t->wv,
7927 "notify::progress", G_CALLBACK(webview_progress_changed_cb), t);
7929 /* hijack the unused keys as if we were the browser */
7930 //g_object_connect(G_OBJECT(t->toolbar),
7931 // "signal-after::key-press-event", G_CALLBACK(wv_keypress_after_cb), t,
7932 // (char *)NULL);
7934 g_signal_connect(G_OBJECT(bb), "clicked", G_CALLBACK(tab_close_cb), t);
7936 /* setup history */
7937 t->bfl = webkit_web_view_get_back_forward_list(t->wv);
7938 /* restore the tab's history */
7939 if (u && u->history) {
7940 items = u->history;
7941 while (items) {
7942 item = items->data;
7943 webkit_web_back_forward_list_add_item(t->bfl, item);
7944 items = g_list_next(items);
7947 item = g_list_nth_data(u->history, u->back);
7948 if (item)
7949 webkit_web_view_go_to_back_forward_item(t->wv, item);
7951 g_list_free(items);
7952 g_list_free(u->history);
7953 } else
7954 webkit_web_back_forward_list_clear(t->bfl);
7956 /* check and show url and statusbar */
7957 url_set_visibility();
7958 statusbar_set_visibility();
7960 if (focus) {
7961 set_current_tab(t->tab_id);
7962 DNPRINTF(XT_D_TAB, "create_new_tab: going to tab: %d\n",
7963 t->tab_id);
7965 if (load) {
7966 gtk_entry_set_text(GTK_ENTRY(t->uri_entry), title);
7967 load_uri(t, title);
7968 } else {
7969 if (show_url == 1)
7970 gtk_widget_grab_focus(GTK_WIDGET(t->uri_entry));
7971 else
7972 focus_webview(t);
7974 } else if (load)
7975 load_uri(t, title);
7977 if (userstyle_global)
7978 apply_style(t);
7980 recolor_compact_tabs();
7981 setzoom_webkit(t, XT_ZOOM_NORMAL);
7982 return (t);
7985 void
7986 notebook_switchpage_cb(GtkNotebook *nb, GtkWidget *nbp, guint pn,
7987 gpointer *udata)
7989 struct tab *t;
7990 const gchar *uri;
7992 DNPRINTF(XT_D_TAB, "notebook_switchpage_cb: tab: %d\n", pn);
7994 if (gtk_notebook_get_current_page(notebook) == -1)
7995 recalc_tabs();
7997 TAILQ_FOREACH(t, &tabs, entry) {
7998 if (t->tab_id == pn) {
7999 DNPRINTF(XT_D_TAB, "notebook_switchpage_cb: going to "
8000 "%d\n", pn);
8002 uri = get_title(t, TRUE);
8003 gtk_window_set_title(GTK_WINDOW(main_window), uri);
8005 hide_cmd(t);
8006 hide_oops(t);
8007 hide_buffers(t);
8009 if (t->focus_wv) {
8010 /* can't use focus_webview here */
8011 gtk_widget_grab_focus(GTK_WIDGET(t->wv));
8013 update_statusbar_tabs(t);
8014 break;
8019 void
8020 notebook_pagereordered_cb(GtkNotebook *nb, GtkWidget *nbp, guint pn,
8021 gpointer *udata)
8023 struct tab *t = NULL, *tt;
8025 recalc_tabs();
8027 TAILQ_FOREACH(tt, &tabs, entry)
8028 if (tt->tab_id == pn) {
8029 t = tt;
8030 break;
8032 if (t == NULL)
8033 return;
8034 DNPRINTF(XT_D_TAB, "page_reordered_cb: tab: %d\n", t->tab_id);
8036 gtk_box_reorder_child(GTK_BOX(tab_bar_box), t->tab_elems.eventbox,
8037 t->tab_id);
8039 update_statusbar_tabs(t);
8042 void
8043 menuitem_response(struct tab *t)
8045 gtk_notebook_set_current_page(notebook, t->tab_id);
8049 destroy_menu(GtkMenuShell *m, void *notused)
8051 gtk_widget_destroy(GTK_WIDGET(m));
8052 g_object_unref(G_OBJECT(m));
8053 return (XT_CB_PASSTHROUGH);
8056 gboolean
8057 arrow_cb(GtkWidget *w, GdkEventButton *event, gpointer user_data)
8059 GtkWidget *menu = NULL, *menu_items;
8060 GdkEventButton *bevent;
8061 struct tab **stabs = NULL;
8062 int i, num_tabs;
8063 const gchar *uri;
8065 if (event->type == GDK_BUTTON_PRESS) {
8066 bevent = (GdkEventButton *) event;
8067 menu = gtk_menu_new();
8068 g_object_ref_sink(G_OBJECT(menu));
8070 num_tabs = sort_tabs_by_page_num(&stabs);
8071 for (i = 0; i < num_tabs; ++i) {
8072 if (stabs[i] == NULL)
8073 continue;
8074 if ((uri = get_uri(stabs[i])) == NULL)
8075 /* XXX make sure there is something to print */
8076 /* XXX add gui pages in here to look purdy */
8077 uri = "(untitled)";
8078 menu_items = gtk_menu_item_new_with_label(uri);
8079 gtk_menu_shell_append(GTK_MENU_SHELL(menu), menu_items);
8080 gtk_widget_show(menu_items);
8082 g_signal_connect_swapped(menu_items,
8083 "activate", G_CALLBACK(menuitem_response),
8084 (gpointer)stabs[i]);
8086 g_free(stabs);
8088 gtk_menu_popup(GTK_MENU(menu), NULL, NULL, NULL, NULL,
8089 bevent->button, bevent->time);
8091 g_object_connect(G_OBJECT(menu),
8092 "signal::selection-done", G_CALLBACK(destroy_menu), NULL,
8093 (char *)NULL);
8095 return (TRUE /* eat event */);
8098 return (FALSE /* propagate */);
8102 icon_size_map(int iconsz)
8104 if (iconsz <= GTK_ICON_SIZE_INVALID ||
8105 iconsz > GTK_ICON_SIZE_DIALOG)
8106 return (GTK_ICON_SIZE_SMALL_TOOLBAR);
8108 return (iconsz);
8111 GtkWidget *
8112 create_button(const char *name, const char *icon_name, int size)
8114 GtkWidget *button, *image;
8115 int gtk_icon_size;
8116 #if !GTK_CHECK_VERSION(3, 0, 0)
8117 gchar *newstyle;
8118 #endif
8120 #if !GTK_CHECK_VERSION(3, 0, 0)
8121 newstyle = g_strdup_printf(
8122 "style \"%s-style\"\n"
8123 "{\n"
8124 " GtkWidget::focus-padding = 0\n"
8125 " GtkWidget::focus-line-width = 0\n"
8126 " xthickness = 0\n"
8127 " ythickness = 0\n"
8128 "}\n"
8129 "widget \"*.%s\" style \"%s-style\"", name, name, name);
8130 gtk_rc_parse_string(newstyle);
8131 g_free(newstyle);
8132 #endif
8133 button = gtk_button_new();
8134 gtk_widget_set_can_focus(button, FALSE);
8135 gtk_button_set_focus_on_click(GTK_BUTTON(button), FALSE);
8136 gtk_icon_size = icon_size_map(size ? size : icon_size);
8138 image = gtk_image_new_from_icon_name(icon_name, gtk_icon_size);
8139 gtk_container_set_border_width(GTK_CONTAINER(button), 0);
8140 gtk_button_set_image(GTK_BUTTON(button), GTK_WIDGET(image));
8141 gtk_widget_set_name(button, name);
8142 gtk_button_set_relief(GTK_BUTTON(button), GTK_RELIEF_NONE);
8144 return (button);
8147 void
8148 button_set_file(GtkWidget *button, char *filename)
8150 GtkWidget *image;
8151 char file[PATH_MAX];
8153 snprintf(file, sizeof file, "%s" PS "%s", resource_dir, filename);
8154 image = gtk_image_new_from_file(file);
8155 gtk_button_set_image(GTK_BUTTON(button), image);
8158 void
8159 button_set_icon_name(GtkWidget *button, char *icon_name)
8161 GtkWidget *image = NULL;
8163 image = gtk_image_new_from_icon_name(icon_name,
8164 icon_size_map(icon_size));
8165 gtk_button_set_image(GTK_BUTTON(button), image);
8168 void
8169 create_canvas(void)
8171 GtkWidget *vbox;
8172 GList *l = NULL;
8173 GdkPixbuf *pb;
8174 char file[PATH_MAX];
8175 int i;
8176 #if !GTK_CHECK_VERSION(3, 0, 0)
8177 GdkColor color;
8178 #endif
8180 #if GTK_CHECK_VERSION(3, 0, 0)
8181 vbox = gtk_box_new(GTK_ORIENTATION_VERTICAL, 0);
8182 #else
8183 vbox = gtk_vbox_new(FALSE, 0);
8184 #endif
8185 gtk_box_set_spacing(GTK_BOX(vbox), 0);
8186 gtk_widget_set_can_focus(vbox, FALSE);
8187 notebook = GTK_NOTEBOOK(gtk_notebook_new());
8188 #if !GTK_CHECK_VERSION(3, 0, 0)
8189 /* XXX seems to be needed with gtk+2 */
8190 g_object_set(G_OBJECT(notebook), "tab-border", 0, NULL);
8191 #endif
8192 gtk_notebook_set_scrollable(notebook, TRUE);
8193 gtk_notebook_set_show_border(notebook, FALSE);
8194 gtk_widget_set_can_focus(GTK_WIDGET(notebook), FALSE);
8196 abtn = gtk_button_new();
8197 gtk_widget_set_can_focus(abtn, FALSE);
8198 arrow = gtk_image_new_from_icon_name("pan-down-symbolic",
8199 icon_size_map(icon_size));
8200 gtk_widget_set_name(abtn, "Arrow");
8201 gtk_button_set_image(GTK_BUTTON(abtn), arrow);
8202 gtk_widget_set_size_request(abtn, -1, 20);
8204 #if GTK_CHECK_VERSION(2, 20, 0)
8205 gtk_notebook_set_action_widget(notebook, abtn, GTK_PACK_END);
8206 #endif
8207 /* compact tab bar */
8208 tab_bar = gtk_event_box_new();
8209 #if GTK_CHECK_VERSION(3, 0, 0)
8210 gtk_widget_set_name(tab_bar, "tab_bar");
8211 tab_bar_box = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 0);
8212 #else
8213 gdk_color_parse(XT_COLOR_CT_SEPARATOR, &color);
8214 gtk_widget_modify_bg(tab_bar, GTK_STATE_NORMAL, &color);
8215 tab_bar_box = gtk_hbox_new(TRUE, 0);
8216 #endif
8217 gtk_container_add(GTK_CONTAINER(tab_bar), tab_bar_box);
8218 gtk_box_set_homogeneous(GTK_BOX(tab_bar_box), TRUE);
8219 gtk_box_set_spacing(GTK_BOX(tab_bar_box), 2);
8221 gtk_box_pack_start(GTK_BOX(vbox), tab_bar, FALSE, FALSE, 0);
8222 gtk_box_pack_start(GTK_BOX(vbox), GTK_WIDGET(notebook), TRUE, TRUE, 0);
8224 g_object_connect(G_OBJECT(notebook),
8225 "signal::switch-page", G_CALLBACK(notebook_switchpage_cb), NULL,
8226 (char *)NULL);
8227 g_object_connect(G_OBJECT(notebook),
8228 "signal::page-reordered", G_CALLBACK(notebook_pagereordered_cb),
8229 NULL, (char *)NULL);
8230 g_signal_connect(G_OBJECT(abtn), "button_press_event",
8231 G_CALLBACK(arrow_cb), NULL);
8233 main_window = create_window("xombrero");
8234 gtk_container_add(GTK_CONTAINER(main_window), vbox);
8235 g_signal_connect(G_OBJECT(main_window), "delete_event",
8236 G_CALLBACK(gtk_main_quit), NULL);
8237 #if GTK_CHECK_VERSION(3, 0, 0)
8238 gtk_window_set_has_resize_grip(GTK_WINDOW(main_window), FALSE);
8239 #endif
8241 /* icons */
8242 for (i = 0; i < LENGTH(icons); i++) {
8243 snprintf(file, sizeof file, "%s" PS "%s", resource_dir, icons[i]);
8244 pb = gdk_pixbuf_new_from_file(file, NULL);
8245 l = g_list_append(l, pb);
8247 gtk_window_set_default_icon_list(l);
8249 for (; l; l = l->next)
8250 g_object_unref(G_OBJECT(l->data));
8252 gtk_widget_show_all(abtn);
8253 gtk_widget_show_all(main_window);
8254 notebook_tab_set_visibility();
8257 #ifndef XT_SOCKET_DISABLE
8259 send_cmd_to_socket(char *cmd)
8261 int s, len, rv = 1;
8262 struct sockaddr_un sa;
8264 if ((s = socket(AF_UNIX, SOCK_STREAM, 0)) == -1) {
8265 warnx("%s: socket", __func__);
8266 return (rv);
8269 sa.sun_family = AF_UNIX;
8270 snprintf(sa.sun_path, sizeof(sa.sun_path), "%s" PS "%s",
8271 work_dir, XT_SOCKET_FILE);
8272 len = SUN_LEN(&sa);
8274 if (connect(s, (struct sockaddr *)&sa, len) == -1) {
8275 warnx("%s: connect", __func__);
8276 goto done;
8279 if (send(s, cmd, strlen(cmd) + 1, 0) == -1) {
8280 warnx("%s: send", __func__);
8281 goto done;
8284 rv = 0;
8285 done:
8286 close(s);
8287 return (rv);
8290 gboolean
8291 socket_watcher(GIOChannel *source, GIOCondition condition, gpointer data)
8293 int s, n;
8294 char str[XT_MAX_URL_LENGTH];
8295 socklen_t t = sizeof(struct sockaddr_un);
8296 struct sockaddr_un sa;
8297 struct passwd *p;
8298 uid_t uid;
8299 gid_t gid;
8300 struct tab *tt;
8301 gint fd = g_io_channel_unix_get_fd(source);
8303 if ((s = accept(fd, (struct sockaddr *)&sa, &t)) == -1) {
8304 warn("accept");
8305 return (FALSE);
8308 if (getpeereid(s, &uid, &gid) == -1) {
8309 warn("getpeereid");
8310 return (FALSE);
8312 if (uid != getuid() || gid != getgid()) {
8313 warnx("unauthorized user");
8314 return (FALSE);
8317 p = getpwuid(uid);
8318 if (p == NULL) {
8319 warnx("not a valid user");
8320 return (FALSE);
8323 n = recv(s, str, sizeof(str), 0);
8324 if (n <= 0)
8325 return (TRUE);
8327 tt = get_current_tab();
8328 cmd_execute(tt, str);
8329 return (TRUE);
8333 is_running(void)
8335 int s, len, rv = 1;
8336 struct sockaddr_un sa;
8338 if ((s = socket(AF_UNIX, SOCK_STREAM, 0)) == -1) {
8339 warn("is_running: socket");
8340 return (-1);
8343 sa.sun_family = AF_UNIX;
8344 snprintf(sa.sun_path, sizeof(sa.sun_path), "%s" PS "%s",
8345 work_dir, XT_SOCKET_FILE);
8346 len = SUN_LEN(&sa);
8348 /* connect to see if there is a listener */
8349 if (connect(s, (struct sockaddr *)&sa, len) == -1)
8350 rv = 0; /* not running */
8351 else
8352 rv = 1; /* already running */
8354 close(s);
8356 return (rv);
8360 build_socket(void)
8362 int s, len;
8363 struct sockaddr_un sa;
8365 if ((s = socket(AF_UNIX, SOCK_STREAM, 0)) == -1) {
8366 warn("build_socket: socket");
8367 return (-1);
8370 sa.sun_family = AF_UNIX;
8371 snprintf(sa.sun_path, sizeof(sa.sun_path), "%s" PS "%s",
8372 work_dir, XT_SOCKET_FILE);
8373 len = SUN_LEN(&sa);
8375 /* connect to see if there is a listener */
8376 if (connect(s, (struct sockaddr *)&sa, len) == -1) {
8377 /* no listener so we will */
8378 unlink(sa.sun_path);
8380 if (bind(s, (struct sockaddr *)&sa, len) == -1) {
8381 warn("build_socket: bind");
8382 goto done;
8385 if (listen(s, 1) == -1) {
8386 warn("build_socket: listen");
8387 goto done;
8390 return (s);
8393 done:
8394 close(s);
8395 return (-1);
8397 #endif
8399 void
8400 xxx_dir(char *dir)
8402 struct stat sb;
8404 if (stat(dir, &sb)) {
8405 #if defined __MINGW32__
8406 if (mkdir(dir) == -1)
8407 #else
8408 if (mkdir(dir, S_IRWXU) == -1)
8409 #endif
8410 err(1, "mkdir %s", dir);
8411 if (stat(dir, &sb))
8412 err(1, "stat %s", dir);
8414 if (S_ISDIR(sb.st_mode) == 0)
8415 errx(1, "%s not a dir", dir);
8416 #if !defined __MINGW32__
8417 if (((sb.st_mode & (S_IRWXU | S_IRWXG | S_IRWXO))) != S_IRWXU) {
8418 warnx("fixing invalid permissions on %s", dir);
8419 if (chmod(dir, S_IRWXU) == -1)
8420 err(1, "chmod %s", dir);
8422 #endif
8425 void
8426 usage(void)
8428 fprintf(stderr,
8429 "%s [-nSTVt][-f file][-s session] url ...\n", __progname);
8430 exit(0);
8433 #if GTK_CHECK_VERSION(3, 0, 0)
8434 void
8435 setup_css(void)
8437 GtkCssProvider *provider;
8438 GdkDisplay *display;
8439 GdkScreen *screen;
8440 GFile *file;
8441 char path[PATH_MAX];
8442 #if defined __MINGW32__
8443 GtkCssProvider *windows_hacks;
8444 #endif
8446 provider = gtk_css_provider_new();
8447 display = gdk_display_get_default();
8448 screen = gdk_display_get_default_screen(display);
8449 snprintf(path, sizeof path, "%s" PS "%s", resource_dir, XT_CSS_FILE);
8450 file = g_file_new_for_path(path);
8451 gtk_css_provider_load_from_file(provider, file, NULL);
8452 gtk_style_context_add_provider_for_screen(screen,
8453 GTK_STYLE_PROVIDER(provider),
8454 GTK_STYLE_PROVIDER_PRIORITY_APPLICATION);
8455 g_object_unref(G_OBJECT(provider));
8456 #if defined __MINGW32__
8457 windows_hacks = gtk_css_provider_new();
8458 gtk_css_provider_load_from_data(windows_hacks,
8459 ".notebook tab {\n"
8460 " border-width: 0px;\n"
8461 "}", -1, NULL);
8462 gtk_style_context_add_provider_for_screen(screen,
8463 GTK_STYLE_PROVIDER(windows_hacks),
8464 GTK_STYLE_PROVIDER_PRIORITY_APPLICATION);
8465 g_object_unref(G_OBJECT(windows_hacks));
8466 #endif
8467 g_object_unref(G_OBJECT(file));
8469 #endif
8471 void
8472 welcome(void)
8474 startpage_add("<b>Welcome to xombrero %s!</b><p>", version);
8475 startpage_add("Details at "
8476 "<a href=https://opensource.conformal.com/wiki/xombrero>xombrero "
8477 "wiki page</a><p>");
8481 main(int argc, char **argv)
8483 struct stat sb;
8484 int c, optn = 0, opte = 0, focus = 1;
8485 char conf[PATH_MAX] = { '\0' };
8486 char file[PATH_MAX];
8487 char sodversion[32];
8488 char *env_proxy = NULL;
8489 char *path;
8490 FILE *f = NULL;
8491 struct karg a;
8493 start_argv = (char * const *)argv;
8495 if (os_init)
8496 os_init();
8498 /* prepare gtk */
8499 gtk_init(&argc, &argv);
8501 gnutls_global_init();
8503 strlcpy(named_session, XT_SAVED_TABS_FILE, sizeof named_session);
8505 RB_INIT(&hl);
8506 RB_INIT(&downloads);
8507 RB_INIT(&st_tree);
8508 RB_INIT(&svl);
8509 RB_INIT(&ua_list);
8510 RB_INIT(&ha_list);
8511 RB_INIT(&di_list);
8513 TAILQ_INIT(&sessions);
8514 TAILQ_INIT(&tabs);
8515 TAILQ_INIT(&mtl);
8516 TAILQ_INIT(&aliases);
8517 TAILQ_INIT(&undos);
8518 TAILQ_INIT(&kbl);
8519 TAILQ_INIT(&spl);
8520 TAILQ_INIT(&chl);
8521 TAILQ_INIT(&shl);
8522 TAILQ_INIT(&cul);
8523 TAILQ_INIT(&srl);
8524 TAILQ_INIT(&c_wl);
8525 TAILQ_INIT(&js_wl);
8526 TAILQ_INIT(&pl_wl);
8527 TAILQ_INIT(&force_https);
8528 TAILQ_INIT(&svil);
8530 #ifndef XT_RESOURCE_LIMITS_DISABLE
8531 struct rlimit rlp;
8532 char *cmd = NULL;
8533 int s;
8534 GIOChannel *channel;
8536 /* fiddle with ulimits */
8537 if (getrlimit(RLIMIT_NOFILE, &rlp) == -1)
8538 warn("getrlimit");
8539 else {
8540 /* just use them all */
8541 #ifdef __APPLE__
8542 rlp.rlim_cur = OPEN_MAX;
8543 #else
8544 rlp.rlim_cur = rlp.rlim_max;
8545 #endif
8546 if (setrlimit(RLIMIT_NOFILE, &rlp) == -1)
8547 warn("setrlimit");
8548 if (getrlimit(RLIMIT_NOFILE, &rlp) == -1)
8549 warn("getrlimit");
8550 else if (rlp.rlim_cur < 1024)
8551 startpage_add("%s requires at least 1024 "
8552 "(2048 recommended) file " "descriptors, "
8553 "currently it has up to %d available",
8554 __progname, rlp.rlim_cur);
8556 #endif
8558 while ((c = getopt(argc, argv, "STVf:s:tne")) != -1) {
8559 switch (c) {
8560 case 'S':
8561 show_url = 0;
8562 break;
8563 case 'T':
8564 show_tabs = 0;
8565 break;
8566 case 'V':
8567 #ifdef XOMBRERO_BUILDSTR
8568 errx(0 , "Version: %s Build: %s",
8569 version, XOMBRERO_BUILDSTR);
8570 #else
8571 errx(0 , "Version: %s", version);
8572 #endif
8573 break;
8574 case 'f':
8575 strlcpy(conf, optarg, sizeof(conf));
8576 break;
8577 case 's':
8578 strlcpy(named_session, optarg, sizeof(named_session));
8579 break;
8580 case 't':
8581 tabless = 1;
8582 break;
8583 case 'n':
8584 optn = 1;
8585 break;
8586 case 'e':
8587 opte = 1;
8588 break;
8589 default:
8590 usage();
8591 /* NOTREACHED */
8594 argc -= optind;
8595 argv += optind;
8597 init_keybindings();
8599 pwd = getpwuid(getuid());
8600 if (pwd == NULL)
8601 errx(1, "invalid user %d", getuid());
8603 /* set download dir */
8604 if (strlen(download_dir) == 0)
8605 strlcpy(download_dir, pwd->pw_dir, sizeof download_dir);
8607 /* compile buffer command regexes */
8608 buffercmd_init();
8610 /* set default dynamic string settings */
8611 home = g_strdup(XT_DS_HOME);
8612 search_string = g_strdup(XT_DS_SEARCH_STRING);
8613 strlcpy(runtime_settings, "runtime", sizeof runtime_settings);
8614 cmd_font_name = g_strdup(XT_DS_CMD_FONT_NAME);
8615 oops_font_name = g_strdup(XT_DS_OOPS_FONT_NAME);
8616 statusbar_font_name = g_strdup(XT_DS_STATUSBAR_FONT_NAME);
8617 tabbar_font_name = g_strdup(XT_DS_TABBAR_FONT_NAME);
8618 statusbar_elems = g_strdup("BP");
8619 spell_check_languages = g_strdup(XT_DS_SPELL_CHECK_LANGUAGES);
8620 encoding = g_strdup(XT_DS_ENCODING);
8621 spell_check_languages = g_strdup(XT_DS_SPELL_CHECK_LANGUAGES);
8622 path = g_strdup_printf("%s" PS "style.css", resource_dir);
8623 userstyle = g_filename_to_uri(path, NULL, NULL);
8624 g_free(path);
8625 stylesheet = g_strdup(userstyle);
8627 /* set statically allocated (struct special) settings */
8628 if (strlen(default_script) == 0)
8629 expand_tilde(default_script, sizeof default_script,
8630 XT_DS_DEFAULT_SCRIPT);
8631 if (strlen(ssl_ca_file) == 0)
8632 expand_tilde(ssl_ca_file, sizeof ssl_ca_file,
8633 XT_DS_SSL_CA_FILE);
8635 /* soup session */
8636 session = webkit_get_default_session();
8638 /* read config file */
8639 if (strlen(conf) == 0)
8640 snprintf(conf, sizeof conf, "%s" PS ".%s",
8641 pwd->pw_dir, XT_CONF_FILE);
8642 config_parse(conf, 0);
8644 /* read preloaded HSTS list */
8645 if (preload_strict_transport) {
8646 snprintf(conf, sizeof conf, "%s" PS "%s",
8647 resource_dir, XT_HSTS_PRELOAD_FILE);
8648 config_parse(conf, 0);
8651 /* check whether to read in a crapton of additional http headers */
8652 if (anonymize_headers) {
8653 snprintf(conf, sizeof conf, "%s" PS "%s",
8654 resource_dir, XT_USER_AGENT_FILE);
8655 config_parse(conf, 0);
8656 snprintf(conf, sizeof conf, "%s" PS "%s",
8657 resource_dir, XT_HTTP_ACCEPT_FILE);
8658 config_parse(conf, 0);
8661 /* init fonts */
8662 cmd_font = pango_font_description_from_string(cmd_font_name);
8663 oops_font = pango_font_description_from_string(oops_font_name);
8664 statusbar_font = pango_font_description_from_string(statusbar_font_name);
8665 tabbar_font = pango_font_description_from_string(tabbar_font_name);
8667 /* working directory */
8668 if (strlen(work_dir) == 0)
8669 snprintf(work_dir, sizeof work_dir, "%s" PS "%s",
8670 pwd->pw_dir, XT_DIR);
8671 xxx_dir(work_dir);
8673 /* icon cache dir */
8674 snprintf(cache_dir, sizeof cache_dir, "%s" PS "%s", work_dir, XT_CACHE_DIR);
8675 xxx_dir(cache_dir);
8677 /* certs dir */
8678 snprintf(certs_dir, sizeof certs_dir, "%s" PS "%s", work_dir, XT_CERT_DIR);
8679 xxx_dir(certs_dir);
8681 /* cert changes dir */
8682 snprintf(certs_cache_dir, sizeof certs_cache_dir, "%s" PS "%s",
8683 work_dir, XT_CERT_CACHE_DIR);
8684 xxx_dir(certs_cache_dir);
8686 /* sessions dir */
8687 snprintf(sessions_dir, sizeof sessions_dir, "%s" PS "%s",
8688 work_dir, XT_SESSIONS_DIR);
8689 xxx_dir(sessions_dir);
8691 /* js dir */
8692 snprintf(js_dir, sizeof js_dir, "%s" PS "%s", work_dir, XT_JS_DIR);
8693 xxx_dir(js_dir);
8695 /* temp dir */
8696 snprintf(temp_dir, sizeof temp_dir, "%s" PS "%s", work_dir, XT_TEMP_DIR);
8697 xxx_dir(temp_dir);
8699 /* runtime settings that can override config file */
8700 if (runtime_settings[0] != '\0')
8701 config_parse(runtime_settings, 1);
8703 /* download dir */
8704 if (!strcmp(download_dir, pwd->pw_dir))
8705 strlcat(download_dir, PS "downloads", sizeof download_dir);
8706 xxx_dir(download_dir);
8708 /* first start file */
8709 snprintf(file, sizeof file, "%s" PS "%s", work_dir, XT_SOD_FILE);
8710 if (stat(file, &sb)) {
8711 warnx("start of day file doesn't exist, creating it");
8712 if ((f = fopen(file, "w")) == NULL)
8713 err(1, "startofday");
8714 if (fputs(version, f) == EOF)
8715 err(1, "fputs");
8716 fclose(f);
8718 /* welcome user */
8719 welcome();
8720 } else {
8721 if ((f = fopen(file, "r+")) == NULL)
8722 err(1, "startofday");
8723 if (fgets(sodversion, sizeof sodversion, f) == NULL)
8724 err(1, "fgets");
8725 sodversion[strcspn(sodversion, "\n")] = '\0';
8726 if (strcmp(version, sodversion)) {
8727 if ((f = freopen(file, "w", f)) == NULL)
8728 err(1, "startofday");
8729 if (fputs(version, f) == EOF)
8730 err(1, "fputs");
8732 /* upgrade, say something smart */
8733 welcome();
8735 fclose(f);
8738 /* favorites file */
8739 snprintf(file, sizeof file, "%s" PS "%s", work_dir, XT_FAVS_FILE);
8740 if (stat(file, &sb)) {
8741 warnx("favorites file doesn't exist, creating it");
8742 if ((f = fopen(file, "w")) == NULL)
8743 err(1, "favorites");
8744 fclose(f);
8747 /* quickmarks file */
8748 snprintf(file, sizeof file, "%s" PS "%s", work_dir, XT_QMARKS_FILE);
8749 if (stat(file, &sb)) {
8750 warnx("quickmarks file doesn't exist, creating it");
8751 if ((f = fopen(file, "w")) == NULL)
8752 err(1, "quickmarks");
8753 fclose(f);
8756 /* search history */
8757 if (history_autosave) {
8758 snprintf(search_file, sizeof search_file, "%s" PS "%s",
8759 work_dir, XT_SEARCH_FILE);
8760 if (stat(search_file, &sb)) {
8761 warnx("search history file doesn't exist, creating it");
8762 if ((f = fopen(search_file, "w")) == NULL)
8763 err(1, "search_history");
8764 fclose(f);
8766 history_read(&shl, search_file, &search_history_count);
8769 /* command history */
8770 if (history_autosave) {
8771 snprintf(command_file, sizeof command_file, "%s" PS "%s",
8772 work_dir, XT_COMMAND_FILE);
8773 if (stat(command_file, &sb)) {
8774 warnx("command history file doesn't exist, creating it");
8775 if ((f = fopen(command_file, "w")) == NULL)
8776 err(1, "command_history");
8777 fclose(f);
8779 history_read(&chl, command_file, &cmd_history_count);
8782 /* cookies */
8783 setup_cookies();
8785 /* guess_search regex */
8786 if (url_regex == NULL)
8787 url_regex = g_strdup(XT_URL_REGEX);
8788 if (url_regex)
8789 if (regcomp(&url_re, url_regex, REG_EXTENDED | REG_NOSUB))
8790 startpage_add("invalid url regex %s", url_regex);
8792 /* proxy */
8793 env_proxy = getenv("http_proxy");
8794 if (env_proxy)
8795 setup_proxy(env_proxy);
8796 else {
8797 env_proxy = getenv("HTTP_PROXY");
8798 if (env_proxy)
8799 setup_proxy(env_proxy);
8800 else
8801 setup_proxy(http_proxy);
8804 /* the user can optionally have the proxy disabled at startup */
8805 if ((http_proxy_starts_enabled == 0) && (http_proxy != NULL)) {
8806 http_proxy_save = g_strdup(http_proxy);
8807 setup_proxy(NULL);
8810 #ifndef XT_SOCKET_DISABLE
8811 if (opte) {
8812 send_cmd_to_socket(argv[0]);
8813 exit(0);
8815 #else
8816 opte = opte; /* shut mingw up */
8817 #endif
8818 /* set some connection parameters */
8819 g_object_set(session, "max-conns", max_connections, (char *)NULL);
8820 g_object_set(session, "max-conns-per-host", max_host_connections,
8821 (char *)NULL);
8822 g_object_set(session, SOUP_SESSION_SSL_STRICT, ssl_strict_certs,
8823 (char *)NULL);
8825 g_signal_connect(session, "request-queued", G_CALLBACK(session_rq_cb),
8826 NULL);
8828 #ifndef XT_SOCKET_DISABLE
8829 /* see if there is already a xombrero running */
8830 if (single_instance && is_running()) {
8831 optn = 1;
8832 warnx("already running");
8835 if (optn) {
8836 while (argc) {
8837 cmd = g_strdup_printf("%s %s", "tabnew", argv[0]);
8838 send_cmd_to_socket(cmd);
8839 if (cmd)
8840 g_free(cmd);
8842 argc--;
8843 argv++;
8845 exit(0);
8847 #else
8848 optn = optn; /* shut mingw up */
8849 #endif
8850 /* tld list */
8851 tld_tree_init();
8853 /* cache mode */
8854 if (enable_cache)
8855 webkit_set_cache_model(WEBKIT_CACHE_MODEL_WEB_BROWSER);
8856 else
8857 webkit_set_cache_model(WEBKIT_CACHE_MODEL_DOCUMENT_VIEWER);
8859 if (enable_strict_transport)
8860 strict_transport_init();
8862 /* uri completion */
8863 completion_model = gtk_list_store_new(1, G_TYPE_STRING);
8865 /* buffers */
8866 buffers_store = gtk_list_store_new
8867 (NUM_COLS, G_TYPE_UINT, GDK_TYPE_PIXBUF, G_TYPE_STRING);
8869 qmarks_load();
8871 /* go graphical */
8872 create_canvas();
8873 notebook_tab_set_visibility();
8875 if (save_global_history)
8876 restore_global_history();
8878 /* restore session list */
8879 restore_sessions_list();
8881 if (!strcmp(named_session, XT_SAVED_TABS_FILE))
8882 restore_saved_tabs();
8883 else {
8884 a.s = named_session;
8885 a.i = XT_SES_DONOTHING;
8886 open_tabs(NULL, &a);
8889 /* see if we have an exception */
8890 if (!TAILQ_EMPTY(&spl)) {
8891 create_new_tab("about:startpage", NULL, focus, -1);
8892 focus = 0;
8895 while (argc) {
8896 create_new_tab(argv[0], NULL, focus, -1);
8897 focus = 0;
8899 argc--;
8900 argv++;
8903 if (TAILQ_EMPTY(&tabs))
8904 create_new_tab(home, NULL, 1, -1);
8905 #ifndef XT_SOCKET_DISABLE
8906 if (enable_socket)
8907 if ((s = build_socket()) != -1) {
8908 channel = g_io_channel_unix_new(s);
8909 g_io_add_watch(channel, G_IO_IN, socket_watcher, NULL);
8911 #endif
8913 #if GTK_CHECK_VERSION(3, 0, 0)
8914 setup_css();
8915 #endif
8917 gtk_main();
8919 gnutls_global_deinit();
8921 if (url_regex)
8922 regfree(&url_re);
8924 return (0);