deal with deprecated call
[xombrero.git] / xombrero.c
blob11d5c6c2e7c81d8943acb8099d2dc6b1bf508655
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 t->xtp_meaning = XT_XTP_TAB_MEANING_NORMAL;
861 if (t->session_key != NULL) {
862 g_free(t->session_key);
863 t->session_key = NULL;
867 void
868 load_uri(struct tab *t, const gchar *uri)
870 struct karg args;
871 gchar *newuri = NULL;
872 int i;
874 if (uri == NULL)
875 return;
877 /* Strip leading spaces. */
878 while (*uri && isspace((unsigned char)*uri))
879 uri++;
881 if (strlen(uri) == 0) {
882 blank(t, NULL);
883 return;
886 set_normal_tab_meaning(t);
888 if (valid_url_type(uri)) {
889 if ((newuri = guess_url_type(uri)) != NULL)
890 uri = newuri;
891 else
892 uri = "";
895 /* clear :cert show host */
896 if (t->about_cert_host) {
897 g_free(t->about_cert_host);
898 t->about_cert_host = NULL;
901 if (!strncmp(uri, XT_URI_ABOUT, XT_URI_ABOUT_LEN)) {
902 for (i = 0; i < about_list_size(); i++)
903 if (!strcmp(&uri[XT_URI_ABOUT_LEN], about_list[i].name) &&
904 about_list[i].func != NULL) {
905 bzero(&args, sizeof args);
906 about_list[i].func(t, &args);
907 gtk_widget_set_sensitive(GTK_WIDGET(t->stop),
908 FALSE);
909 goto done;
911 show_oops(t, "invalid about page");
912 goto done;
915 /* remove old HTTPS cert chain (if any) */
916 if (t->pem) {
917 g_free(t->pem);
918 t->pem = NULL;
921 set_status(t, "Loading: %s", (char *)uri);
922 marks_clear(t);
923 webkit_web_view_load_uri(t->wv, uri);
924 done:
925 if (newuri)
926 g_free(newuri);
929 const gchar *
930 get_uri(struct tab *t)
932 const gchar *uri = NULL;
934 if (webkit_web_view_get_load_status(t->wv) == WEBKIT_LOAD_FAILED &&
935 !t->download_requested)
936 return (NULL);
937 if (t->xtp_meaning == XT_XTP_TAB_MEANING_NORMAL)
938 uri = webkit_web_view_get_uri(t->wv);
939 else {
940 /* use tmp_uri to make sure it is g_freed */
941 if (t->tmp_uri)
942 g_free(t->tmp_uri);
943 t->tmp_uri = g_strdup_printf("%s%s", XT_URI_ABOUT,
944 about_list[t->xtp_meaning].name);
945 uri = t->tmp_uri;
947 return (uri);
950 const gchar *
951 get_title(struct tab *t, bool window)
953 const gchar *set = NULL, *title = NULL;
954 WebKitLoadStatus status;
956 status = webkit_web_view_get_load_status(t->wv);
957 if (status == WEBKIT_LOAD_PROVISIONAL ||
958 (status == WEBKIT_LOAD_FAILED && !t->download_requested) ||
959 t->xtp_meaning == XT_XTP_TAB_MEANING_BL)
960 goto notitle;
962 title = webkit_web_view_get_title(t->wv);
963 if ((set = title ? title : get_uri(t)))
964 return set;
966 notitle:
967 set = window ? XT_NAME : "(untitled)";
969 return set;
972 struct mime_type *
973 find_mime_type(char *mime_type)
975 struct mime_type *m, *def = NULL, *rv = NULL;
977 TAILQ_FOREACH(m, &mtl, entry) {
978 if (m->mt_default &&
979 !strncmp(mime_type, m->mt_type, strlen(m->mt_type)))
980 def = m;
982 if (m->mt_default == 0 && !strcmp(mime_type, m->mt_type)) {
983 rv = m;
984 break;
988 if (rv == NULL)
989 rv = def;
991 return (rv);
995 * This only escapes the & and < characters, as per the discussion found here:
996 * http://lists.apple.com/archives/Webkitsdk-dev/2007/May/msg00056.html
998 gchar *
999 html_escape(const char *val)
1001 char *s, *sp;
1002 char **sv;
1004 if (val == NULL)
1005 return NULL;
1007 sv = g_strsplit(val, "&", -1);
1008 s = g_strjoinv("&amp;", sv);
1009 g_strfreev(sv);
1010 sp = s;
1011 sv = g_strsplit(val, "<", -1);
1012 s = g_strjoinv("&lt;", sv);
1013 g_strfreev(sv);
1014 g_free(sp);
1015 return (s);
1018 struct wl_entry *
1019 wl_find_uri(const gchar *s, struct wl_list *wl)
1021 int i;
1022 char *ss;
1023 struct wl_entry *w;
1025 if (s == NULL || wl == NULL)
1026 return (NULL);
1028 if (!strncmp(s, "http://", strlen("http://")))
1029 s = &s[strlen("http://")];
1030 else if (!strncmp(s, "https://", strlen("https://")))
1031 s = &s[strlen("https://")];
1033 if (strlen(s) < 2)
1034 return (NULL);
1036 for (i = 0; i < strlen(s) + 1 /* yes er need this */; i++)
1037 /* chop string at first slash */
1038 if (s[i] == '/' || s[i] == ':' || s[i] == '\0') {
1039 ss = g_strdup(s);
1040 ss[i] = '\0';
1041 w = wl_find(ss, wl);
1042 g_free(ss);
1043 return (w);
1046 return (NULL);
1049 char *
1050 js_ref_to_string(JSContextRef context, JSValueRef ref)
1052 char *s = NULL;
1053 size_t l;
1054 JSStringRef jsref;
1056 jsref = JSValueToStringCopy(context, ref, NULL);
1057 if (jsref == NULL)
1058 return (NULL);
1060 l = JSStringGetMaximumUTF8CStringSize(jsref);
1061 s = g_malloc(l);
1062 if (s)
1063 JSStringGetUTF8CString(jsref, s, l);
1064 JSStringRelease(jsref);
1066 return (s);
1069 #define XT_JS_DONE ("done;")
1070 #define XT_JS_DONE_LEN (strlen(XT_JS_DONE))
1071 #define XT_JS_INSERT ("insert;")
1072 #define XT_JS_INSERT_LEN (strlen(XT_JS_INSERT))
1075 run_script(struct tab *t, char *s)
1077 JSGlobalContextRef ctx;
1078 WebKitWebFrame *frame;
1079 JSStringRef str;
1080 JSValueRef val, exception;
1081 char *es;
1083 DNPRINTF(XT_D_JS, "%s: tab %d %s\n", __func__,
1084 t->tab_id, s == (char *)JS_HINTING ? "JS_HINTING" : s);
1086 frame = webkit_web_view_get_main_frame(t->wv);
1087 ctx = webkit_web_frame_get_global_context(frame);
1089 str = JSStringCreateWithUTF8CString(s);
1090 val = JSEvaluateScript(ctx, str, JSContextGetGlobalObject(ctx),
1091 NULL, 0, &exception);
1092 JSStringRelease(str);
1094 DNPRINTF(XT_D_JS, "%s: val %p\n", __func__, val);
1095 if (val == NULL) {
1096 es = js_ref_to_string(ctx, exception);
1097 if (es) {
1098 DNPRINTF(XT_D_JS, "%s: exception %s\n", __func__, es);
1099 g_free(es);
1101 return (1);
1102 } else {
1103 es = js_ref_to_string(ctx, val);
1104 #if 0
1105 /* return values */
1106 if (!strncmp(es, XT_JS_DONE, XT_JS_DONE_LEN))
1107 ; /* do nothing */
1108 if (!strncmp(es, XT_JS_INSERT, XT_JS_INSERT_LEN))
1109 ; /* do nothing */
1110 #endif
1111 if (es) {
1112 DNPRINTF(XT_D_JS, "%s: val %s\n", __func__, es);
1113 g_free(es);
1117 return (0);
1120 void
1121 enable_hints(struct tab *t)
1123 DNPRINTF(XT_D_JS, "%s: tab %d\n", __func__, t->tab_id);
1125 if (t->new_tab)
1126 run_script(t, "hints.createHints('', 'F');");
1127 else
1128 run_script(t, "hints.createHints('', 'f');");
1129 t->mode = XT_MODE_HINT;
1132 void
1133 disable_hints(struct tab *t)
1135 DNPRINTF(XT_D_JS, "%s: tab %d\n", __func__, t->tab_id);
1137 run_script(t, "hints.clearHints();");
1138 t->mode = XT_MODE_COMMAND;
1139 t->new_tab = 0;
1143 passthrough(struct tab *t, struct karg *args)
1145 t->mode = XT_MODE_PASSTHROUGH;
1146 return (0);
1150 modurl(struct tab *t, struct karg *args)
1152 const gchar *uri = NULL;
1153 char *u = NULL;
1155 /* XXX kind of a bad hack, but oh well */
1156 if (gtk_widget_has_focus(t->uri_entry)) {
1157 if ((uri = gtk_entry_get_text(GTK_ENTRY(t->uri_entry))) &&
1158 (strlen(uri))) {
1159 u = g_strdup_printf("www.%s.com", uri);
1160 gtk_entry_set_text(GTK_ENTRY(t->uri_entry), u);
1161 g_free(u);
1162 activate_uri_entry_cb(t->uri_entry, t);
1165 return (0);
1169 modsearchentry(struct tab *t, struct karg *args)
1171 const gchar *s = NULL;
1172 struct tab *tt;
1174 /* XXX kind of a bad hack (in honor of the modurl hack) */
1175 if (gtk_widget_has_focus(t->search_entry)) {
1176 if ((s = gtk_entry_get_text(GTK_ENTRY(t->search_entry))) &&
1177 (strlen(s))) {
1178 tt = create_new_tab(NULL, NULL, 1, -1);
1179 gtk_entry_set_text(GTK_ENTRY(tt->search_entry), s);
1180 activate_search_entry_cb(t->search_entry,tt);
1181 gtk_entry_set_text(GTK_ENTRY(t->search_entry), "");
1184 return (0);
1188 hint(struct tab *t, struct karg *args)
1191 DNPRINTF(XT_D_JS, "hint: tab %d args %d\n", t->tab_id, args->i);
1193 if (t->mode == XT_MODE_HINT) {
1194 if (args->i == XT_HINT_NEWTAB)
1195 t->new_tab = 1;
1196 enable_hints(t);
1197 } else
1198 disable_hints(t);
1200 return (0);
1203 void
1204 apply_style(struct tab *t)
1206 t->styled = 1;
1207 g_object_set(G_OBJECT(t->settings),
1208 "user-stylesheet-uri", t->stylesheet, (char *)NULL);
1211 void
1212 remove_style(struct tab *t)
1214 t->styled = 0;
1215 g_object_set(G_OBJECT(t->settings),
1216 "user-stylesheet-uri", NULL, (char *)NULL);
1220 userstyle_cmd(struct tab *t, struct karg *args)
1222 char script[PATH_MAX] = {'\0'};
1223 char *script_uri;
1224 struct tab *tt;
1226 DNPRINTF(XT_D_JS, "userstyle_cmd: tab %d\n", t->tab_id);
1228 if (args->s != NULL && strlen(args->s)) {
1229 expand_tilde(script, sizeof script, args->s);
1230 script_uri = g_filename_to_uri(script, NULL, NULL);
1231 } else
1232 script_uri = g_strdup(userstyle);
1234 if (script_uri == NULL)
1235 return (1);
1237 switch (args->i) {
1238 case XT_STYLE_CURRENT_TAB:
1239 if (t->styled && !strcmp(script_uri, t->stylesheet))
1240 remove_style(t);
1241 else {
1242 if (t->stylesheet)
1243 g_free(t->stylesheet);
1244 t->stylesheet = g_strdup(script_uri);
1245 apply_style(t);
1247 break;
1248 case XT_STYLE_GLOBAL:
1249 if (userstyle_global && !strcmp(script_uri, t->stylesheet)) {
1250 userstyle_global = 0;
1251 TAILQ_FOREACH(tt, &tabs, entry)
1252 remove_style(tt);
1253 } else {
1254 userstyle_global = 1;
1256 /* need to save this stylesheet for new tabs */
1257 if (stylesheet)
1258 g_free(stylesheet);
1259 stylesheet = g_strdup(script_uri);
1261 TAILQ_FOREACH(tt, &tabs, entry) {
1262 if (tt->stylesheet)
1263 g_free(tt->stylesheet);
1264 tt->stylesheet = g_strdup(script_uri);
1265 apply_style(tt);
1268 break;
1271 g_free(script_uri);
1273 return (0);
1277 quit(struct tab *t, struct karg *args)
1279 if (save_global_history)
1280 save_global_history_to_disk(t);
1282 gtk_main_quit();
1284 return (1);
1287 void
1288 restore_sessions_list(void)
1290 DIR *sdir = NULL;
1291 struct dirent *dp = NULL;
1292 struct session *s;
1293 int reg;
1295 sdir = opendir(sessions_dir);
1296 if (sdir) {
1297 while ((dp = readdir(sdir)) != NULL) {
1298 #if defined __MINGW32__
1299 reg = 1; /* windows only has regular files */
1300 #else
1301 reg = dp->d_type == DT_REG;
1302 #endif
1303 if (dp && reg) {
1304 s = g_malloc(sizeof(struct session));
1305 s->name = g_strdup(dp->d_name);
1306 TAILQ_INSERT_TAIL(&sessions, s, entry);
1309 closedir(sdir);
1314 open_tabs(struct tab *t, struct karg *a)
1316 char file[PATH_MAX];
1317 FILE *f = NULL;
1318 char *uri = NULL;
1319 int rv = 1;
1320 struct tab *ti, *tt;
1322 if (a == NULL)
1323 goto done;
1325 ti = TAILQ_LAST(&tabs, tab_list);
1327 snprintf(file, sizeof file, "%s" PS "%s", sessions_dir, a->s);
1328 if ((f = fopen(file, "r")) == NULL)
1329 goto done;
1331 for (;;) {
1332 if ((uri = fparseln(f, NULL, NULL, "\0\0\0", 0)) == NULL) {
1333 if (feof(f) || ferror(f))
1334 break;
1335 } else {
1336 /* retrieve session name */
1337 if (g_str_has_prefix(uri, XT_SAVE_SESSION_ID)) {
1338 strlcpy(named_session,
1339 &uri[strlen(XT_SAVE_SESSION_ID)],
1340 sizeof named_session);
1341 continue;
1344 if (strlen(uri))
1345 create_new_tab(uri, NULL, 1, -1);
1347 free(uri);
1351 /* close open tabs */
1352 if (a->i == XT_SES_CLOSETABS && ti != NULL) {
1353 for (;;) {
1354 tt = TAILQ_FIRST(&tabs);
1355 if (tt == NULL)
1356 break;
1357 if (tt != ti) {
1358 delete_tab(tt);
1359 continue;
1361 delete_tab(tt);
1362 break;
1366 rv = 0;
1367 done:
1368 if (f)
1369 fclose(f);
1371 return (rv);
1375 restore_saved_tabs(void)
1377 char file[PATH_MAX];
1378 int unlink_file = 0;
1379 struct stat sb;
1380 struct karg a;
1381 int rv = 0;
1383 snprintf(file, sizeof file, "%s" PS "%s",
1384 sessions_dir, XT_RESTART_TABS_FILE);
1385 if (stat(file, &sb) == -1)
1386 a.s = XT_SAVED_TABS_FILE;
1387 else {
1388 unlink_file = 1;
1389 a.s = XT_RESTART_TABS_FILE;
1392 a.i = XT_SES_DONOTHING;
1393 rv = open_tabs(NULL, &a);
1395 if (unlink_file)
1396 unlink(file);
1398 return (rv);
1402 save_tabs(struct tab *t, struct karg *a)
1404 char file[PATH_MAX];
1405 FILE *f;
1406 int num_tabs = 0, i;
1407 struct tab **stabs = NULL;
1409 /* tab may be null here */
1411 if (a == NULL)
1412 return (1);
1413 if (a->s == NULL)
1414 snprintf(file, sizeof file, "%s" PS "%s",
1415 sessions_dir, named_session);
1416 else
1417 snprintf(file, sizeof file, "%s" PS "%s", sessions_dir, a->s);
1419 if ((f = fopen(file, "w")) == NULL) {
1420 show_oops(t, "Can't open save_tabs file: %s", strerror(errno));
1421 return (1);
1424 /* save session name */
1425 fprintf(f, "%s%s\n", XT_SAVE_SESSION_ID, named_session);
1427 /* Save tabs, in the order they are arranged in the notebook. */
1428 num_tabs = sort_tabs_by_page_num(&stabs);
1430 for (i = 0; i < num_tabs; i++)
1431 if (stabs[i]) {
1432 if (get_uri(stabs[i]) != NULL)
1433 fprintf(f, "%s\n", get_uri(stabs[i]));
1434 else if (gtk_entry_get_text(GTK_ENTRY(
1435 stabs[i]->uri_entry)))
1436 fprintf(f, "%s\n", gtk_entry_get_text(GTK_ENTRY(
1437 stabs[i]->uri_entry)));
1440 g_free(stabs);
1442 /* try and make sure this gets to disk NOW. XXX Backup first? */
1443 if (fflush(f) != 0 || fsync(fileno(f)) != 0) {
1444 show_oops(t, "May not have managed to save session: %s",
1445 strerror(errno));
1448 fclose(f);
1450 return (0);
1454 save_tabs_and_quit(struct tab *t, struct karg *args)
1456 struct karg a;
1458 a.s = NULL;
1459 save_tabs(t, &a);
1460 quit(t, NULL);
1462 return (1);
1465 void
1466 expand_tilde(char *path, size_t len, const char *s)
1468 struct passwd *pwd;
1469 int i;
1470 char user[LOGIN_NAME_MAX];
1471 const char *sc = s;
1473 if (path == NULL || s == NULL)
1474 errx(1, "expand_tilde");
1476 if (s[0] != '~') {
1477 strlcpy(path, sc, len);
1478 return;
1481 ++s;
1482 for (i = 0; s[i] != PSC && s[i] != '\0'; ++i)
1483 user[i] = s[i];
1484 user[i] = '\0';
1485 s = &s[i];
1487 pwd = strlen(user) == 0 ? getpwuid(getuid()) : getpwnam(user);
1488 if (pwd == NULL)
1489 strlcpy(path, sc, len);
1490 else
1491 snprintf(path, len, "%s%s", pwd->pw_dir, s);
1495 run_page_script(struct tab *t, struct karg *args)
1497 const gchar *uri;
1498 char *tmp, script[PATH_MAX];
1499 char *sv[3];
1501 tmp = args->s != NULL && strlen(args->s) > 0 ? args->s : default_script;
1502 if (tmp[0] == '\0') {
1503 show_oops(t, "no script specified");
1504 return (1);
1507 if ((uri = get_uri(t)) == NULL) {
1508 show_oops(t, "tab is empty, not running script");
1509 return (1);
1512 expand_tilde(script, sizeof script, tmp);
1514 sv[0] = script;
1515 sv[1] = (char *)uri;
1516 sv[2] = NULL;
1517 if (!g_spawn_async(NULL, sv, NULL, G_SPAWN_SEARCH_PATH, NULL, NULL,
1518 NULL, NULL)) {
1519 show_oops(t, "%s: could not spawn process: %s %s", __func__,
1520 sv[0], sv[1]);
1521 return (1);
1522 } else
1523 show_oops(t, "running: %s %s", sv[0], sv[1]);
1525 return (0);
1529 yank_uri(struct tab *t, struct karg *args)
1531 const gchar *uri;
1532 GtkClipboard *clipboard, *primary;
1534 if ((uri = get_uri(t)) == NULL)
1535 return (1);
1537 primary = gtk_clipboard_get(GDK_SELECTION_PRIMARY);
1538 clipboard = gtk_clipboard_get(GDK_SELECTION_CLIPBOARD);
1539 gtk_clipboard_set_text(primary, uri, -1);
1540 gtk_clipboard_set_text(clipboard, uri, -1);
1542 return (0);
1546 paste_uri(struct tab *t, struct karg *args)
1548 GtkClipboard *clipboard, *primary;
1549 gchar *c = NULL, *p = NULL, *uri;
1550 int i;
1552 clipboard = gtk_clipboard_get(GDK_SELECTION_CLIPBOARD);
1553 primary = gtk_clipboard_get(GDK_SELECTION_PRIMARY);
1554 c = gtk_clipboard_wait_for_text(clipboard);
1555 p = gtk_clipboard_wait_for_text(primary);
1557 if (c || p) {
1558 #ifdef __MINGW32__
1559 /* Windows try clipboard first */
1560 uri = c ? c : p;
1561 #else
1562 /* UNIX try primary first */
1563 uri = p ? p : c;
1564 #endif
1565 /* replace all newlines with spaces */
1566 for (i = 0; uri[i] != '\0'; ++i)
1567 if (uri[i] == '\n')
1568 uri[i] = ' ';
1570 while (*uri && isspace((unsigned char)*uri))
1571 uri++;
1572 if (strlen(uri) == 0) {
1573 show_oops(t, "empty paste buffer");
1574 goto done;
1576 if (guess_search == 0 && valid_url_type(uri)) {
1577 /* we can be clever and paste this in search box */
1578 show_oops(t, "not a valid URL");
1579 goto done;
1582 if (args->i == XT_PASTE_CURRENT_TAB)
1583 load_uri(t, uri);
1584 else if (args->i == XT_PASTE_NEW_TAB)
1585 create_new_tab(uri, NULL, 1, -1);
1588 done:
1589 if (c)
1590 g_free(c);
1591 if (p)
1592 g_free(p);
1594 return (0);
1597 void
1598 js_toggle_cb(GtkWidget *w, struct tab *t)
1600 struct karg a;
1601 int es, set;
1603 g_object_get(G_OBJECT(t->settings),
1604 "enable-scripts", &es, (char *)NULL);
1605 es = !es;
1606 if (es)
1607 set = XT_WL_ENABLE;
1608 else
1609 set = XT_WL_DISABLE;
1611 a.i = set | XT_WL_TOPLEVEL;
1612 toggle_pl(t, &a);
1614 a.i = set | XT_WL_TOPLEVEL;
1615 toggle_cwl(t, &a);
1617 a.i = XT_WL_TOGGLE | XT_WL_TOPLEVEL | XT_WL_RELOAD;
1618 toggle_js(t, &a);
1621 void
1622 proxy_toggle_cb(GtkWidget *w, struct tab *t)
1624 struct karg args = {0};
1626 args.i = XT_PRXY_TOGGLE;
1627 proxy_cmd(t, &args);
1631 toggle_src(struct tab *t, struct karg *args)
1633 gboolean mode;
1635 if (t == NULL)
1636 return (0);
1638 mode = webkit_web_view_get_view_source_mode(t->wv);
1639 webkit_web_view_set_view_source_mode(t->wv, !mode);
1640 webkit_web_view_reload(t->wv);
1642 return (0);
1645 void
1646 focus_webview(struct tab *t)
1648 if (t == NULL)
1649 return;
1651 /* only grab focus if we are visible */
1652 if (gtk_notebook_get_current_page(notebook) == t->tab_id)
1653 gtk_widget_grab_focus(GTK_WIDGET(t->wv));
1657 focus(struct tab *t, struct karg *args)
1659 if (t == NULL || args == NULL)
1660 return (1);
1662 if (show_url == 0)
1663 return (0);
1665 if (args->i == XT_FOCUS_URI)
1666 gtk_widget_grab_focus(GTK_WIDGET(t->uri_entry));
1667 else if (args->i == XT_FOCUS_SEARCH)
1668 gtk_widget_grab_focus(GTK_WIDGET(t->search_entry));
1670 return (0);
1673 void
1674 free_connection_certs(gnutls_x509_crt_t *certs, size_t cert_count)
1676 int i;
1678 for (i = 0; i < cert_count; i++)
1679 gnutls_x509_crt_deinit(certs[i]);
1680 gnutls_free(certs);
1683 #if GTK_CHECK_VERSION(3, 0, 0)
1684 void
1685 statusbar_modify_attr(struct tab *t, const char *css_name)
1687 gtk_widget_set_name(t->sbe.ebox, css_name);
1689 #else
1690 void
1691 statusbar_modify_attr(struct tab *t, const char *text, const char *base)
1693 GdkColor c_text, c_base;
1695 gdk_color_parse(text, &c_text);
1696 gdk_color_parse(base, &c_base);
1698 gtk_widget_modify_bg(t->sbe.ebox, GTK_STATE_NORMAL, &c_base);
1699 gtk_widget_modify_base(t->sbe.uri, GTK_STATE_NORMAL, &c_base);
1700 gtk_widget_modify_text(t->sbe.uri, GTK_STATE_NORMAL, &c_text);
1702 #endif
1704 void
1705 save_certs(struct tab *t, gnutls_x509_crt_t *certs,
1706 size_t cert_count, const char *domain, const char *dir)
1708 size_t cert_buf_sz;
1709 char file[PATH_MAX];
1710 char *cert_buf = NULL;
1711 int rv;
1712 int i;
1713 FILE *f;
1715 if (t == NULL || certs == NULL || cert_count <= 0 || domain == NULL)
1716 return;
1718 snprintf(file, sizeof file, "%s" PS "%s", dir, domain);
1719 if ((f = fopen(file, "w")) == NULL) {
1720 show_oops(t, "Can't create cert file %s %s",
1721 file, strerror(errno));
1722 return;
1725 for (i = 0; i < cert_count; i++) {
1727 * Because we support old crap and can't use
1728 * gnutls_x509_crt_export2(), we intentionally use an empty
1729 * buffer and then make a second call with the known size
1730 * needed.
1732 cert_buf_sz = 0;
1733 gnutls_x509_crt_export(certs[i], GNUTLS_X509_FMT_PEM,
1734 NULL, &cert_buf_sz);
1735 if (cert_buf_sz == 0) {
1736 show_oops(t, "no certs found");
1737 goto done;
1739 cert_buf = gnutls_malloc(cert_buf_sz * sizeof(char));
1740 if (cert_buf == NULL) {
1741 show_oops(t, "gnutls_x509_crt_export failed");
1742 goto done;
1744 rv = gnutls_x509_crt_export(certs[i],
1745 GNUTLS_X509_FMT_PEM, cert_buf, &cert_buf_sz);
1746 if (rv != 0) {
1747 show_oops(t, "gnutls_x509_crt_export failure: %s",
1748 gnutls_strerror(rv));
1749 goto done;
1751 cert_buf[cert_buf_sz] = '\0';
1752 if (fwrite(cert_buf, cert_buf_sz, 1, f) != 1) {
1753 show_oops(t, "Can't write certs: %s", strerror(errno));
1754 goto done;
1756 gnutls_free(cert_buf);
1757 cert_buf = NULL;
1760 done:
1761 if (cert_buf)
1762 gnutls_free(cert_buf);
1763 fclose(f);
1766 enum cert_trust {
1767 CERT_LOCAL,
1768 CERT_TRUSTED,
1769 CERT_UNTRUSTED,
1770 CERT_BAD
1773 gnutls_x509_crt_t *
1774 get_local_cert_chain(const char *uri, size_t *ncerts, const char **error_str,
1775 const char *dir)
1777 SoupURI *su;
1778 unsigned char cert_buf[64 * 1024] = {0};
1779 gnutls_datum_t data;
1780 unsigned int max_certs = XT_MAX_CERTS;
1781 int bytes_read;
1782 char file[PATH_MAX];
1783 FILE *f;
1784 gnutls_x509_crt_t *certs;
1786 if ((su = soup_uri_new(uri)) == NULL) {
1787 *error_str = "Invalid URI";
1788 return (NULL);
1791 snprintf(file, sizeof file, "%s" PS "%s", dir, su->host);
1792 soup_uri_free(su);
1793 if ((f = fopen(file, "r")) == NULL) {
1794 *error_str = "Could not read local cert";
1795 return (NULL);
1798 bytes_read = fread(cert_buf, sizeof *cert_buf, sizeof cert_buf, f);
1799 if (bytes_read == 0) {
1800 *error_str = "Could not read local cert";
1801 return (NULL);
1804 certs = gnutls_malloc(sizeof(*certs) * max_certs);
1805 if (certs == NULL) {
1806 *error_str = "Error allocating memory";
1807 return (NULL);
1809 data.data = cert_buf;
1810 data.size = bytes_read;
1811 if (gnutls_x509_crt_list_import(certs, &max_certs, &data,
1812 GNUTLS_X509_FMT_PEM, 0) < 0) {
1813 gnutls_free(certs);
1814 *error_str = "Error reading local cert chain";
1815 return (NULL);
1818 *ncerts = max_certs;
1819 return (certs);
1823 * This uses the pem-encoded cert chain saved in t->pem instead of
1824 * grabbing the remote cert. We save it beforehand and read it here
1825 * so as to not open a side channel that ignores proxy settings.
1827 gnutls_x509_crt_t *
1828 get_chain_for_pem(char *pem, size_t *ncerts, const char **error_str)
1830 gnutls_datum_t data;
1831 unsigned int max_certs = XT_MAX_CERTS;
1832 gnutls_x509_crt_t *certs;
1834 if (pem == NULL) {
1835 *error_str = "Error reading remote cert chain";
1836 return (NULL);
1839 certs = gnutls_malloc(sizeof(*certs) * max_certs);
1840 if (certs == NULL) {
1841 *error_str = "Error allocating memory";
1842 return (NULL);
1844 data.data = (unsigned char *)pem;
1845 data.size = strlen(pem);
1846 if (gnutls_x509_crt_list_import(certs, &max_certs, &data,
1847 GNUTLS_X509_FMT_PEM, 0) < 0) {
1848 gnutls_free(certs);
1849 *error_str = "Error reading remote cert chain";
1850 return (NULL);
1853 *ncerts = max_certs;
1854 return (certs);
1859 cert_cmd(struct tab *t, struct karg *args)
1861 const gchar *uri, *error_str = NULL;
1862 size_t cert_count;
1863 gnutls_x509_crt_t *certs;
1864 SoupURI *su;
1865 char *host;
1866 #if !GTK_CHECK_VERSION(3, 0, 0)
1867 GdkColor color;
1868 #endif
1870 if (t == NULL)
1871 return (1);
1873 if (args->s != NULL) {
1874 uri = args->s;
1875 } else if ((uri = get_uri(t)) == NULL) {
1876 show_oops(t, "Invalid URI");
1877 return (1);
1879 if ((su = soup_uri_new(uri)) == NULL) {
1880 show_oops(t, "Invalid URI");
1881 return (1);
1885 * if we're only showing the local certs, don't open a socket and get
1886 * the remote certs
1888 if (args->i & XT_SHOW && args->i & XT_CACHE) {
1889 certs = get_local_cert_chain(uri, &cert_count, &error_str,
1890 certs_cache_dir);
1891 if (error_str == NULL) {
1892 t->about_cert_host = g_strdup(su->host);
1893 show_certs(t, certs, cert_count, "Certificate Chain");
1894 free_connection_certs(certs, cert_count);
1895 } else {
1896 show_oops(t, "%s", error_str);
1897 soup_uri_free(su);
1898 return (1);
1900 soup_uri_free(su);
1901 return (0);
1904 certs = get_chain_for_pem(t->pem, &cert_count, &error_str);
1905 if (error_str)
1906 goto done;
1908 if (args->i & XT_SHOW) {
1909 t->about_cert_host = g_strdup(su->host);
1910 show_certs(t, certs, cert_count, "Certificate Chain");
1911 } else if (args->i & XT_SAVE) {
1912 host = t->about_cert_host ? t->about_cert_host : su->host;
1913 save_certs(t, certs, cert_count, host, certs_dir);
1914 #if GTK_CHECK_VERSION(3, 0, 0)
1915 gtk_widget_set_name(t->uri_entry, XT_CSS_BLUE);
1916 statusbar_modify_attr(t, XT_CSS_BLUE);
1917 #else
1918 gdk_color_parse(XT_COLOR_BLUE, &color);
1919 gtk_widget_modify_base(t->uri_entry, GTK_STATE_NORMAL, &color);
1920 statusbar_modify_attr(t, XT_COLOR_BLACK, XT_COLOR_BLUE);
1921 #endif
1922 } else if (args->i & XT_CACHE)
1923 save_certs(t, certs, cert_count, su->host, certs_cache_dir);
1925 free_connection_certs(certs, cert_count);
1927 done:
1928 soup_uri_free(su);
1930 if (error_str && strlen(error_str)) {
1931 show_oops(t, "%s", error_str);
1932 return (1);
1934 return (0);
1938 * Checks whether the remote cert is identical to the local saved
1939 * cert. Returns CERT_LOCAL if unchanged, CERT_UNTRUSTED if local
1940 * cert does not exist, and CERT_BAD if different.
1942 * Saves entire cert chain in pem encoding to chain for it to be
1943 * cached later, if needed.
1945 enum cert_trust
1946 check_local_certs(const char *file, GTlsCertificate *cert, char **chain)
1948 char r_cert_buf[64 * 1024];
1949 FILE *f;
1950 GTlsCertificate *tmpcert = NULL;
1951 GTlsCertificate *issuer = NULL;
1952 char *pem = NULL;
1953 char *tmp = NULL;
1954 enum cert_trust rv = CERT_LOCAL;
1955 int i;
1957 if ((f = fopen(file, "r")) == NULL) {
1958 /* no local cert to check */
1959 rv = CERT_UNTRUSTED;
1962 for (i = 0;;) {
1963 if (i == 0) {
1964 g_object_get(G_OBJECT(cert), "certificate-pem", &pem,
1965 NULL);
1966 g_object_get(G_OBJECT(cert), "issuer", &issuer, NULL);
1967 } else {
1968 if (issuer == NULL)
1969 break;
1970 g_object_get(G_OBJECT(tmpcert), "issuer", &issuer,
1971 NULL);
1972 if (issuer == NULL)
1973 break;
1975 g_object_get(G_OBJECT(tmpcert), "certificate-pem", &pem,
1976 NULL);
1978 i++;
1980 if (tmpcert != NULL)
1981 g_object_unref(G_OBJECT(tmpcert));
1982 tmpcert = issuer;
1983 if (f) {
1984 if (fread(r_cert_buf, strlen(pem), 1, f) != 1 && !feof(f))
1985 rv = CERT_BAD;
1986 if (bcmp(r_cert_buf, pem, strlen(pem)))
1987 rv = CERT_BAD;
1989 tmp = g_strdup_printf("%s%s", *chain, pem);
1990 g_free(pem);
1991 g_free(*chain);
1992 *chain = tmp;
1995 if (issuer != NULL)
1996 g_object_unref(G_OBJECT(issuer));
1997 if (f != NULL)
1998 fclose(f);
1999 return (rv);
2003 check_cert_changes(struct tab *t, GTlsCertificate *cert, const char *file, const char *uri)
2005 SoupURI *soupuri = NULL;
2006 struct karg args = {0};
2007 struct wl_entry *w = NULL;
2008 char *chain = NULL;
2009 int ret = 0;
2011 chain = g_strdup("");
2012 switch(check_local_certs(file, cert, &chain)) {
2013 case CERT_LOCAL:
2014 /* The cached certificate is identical */
2015 break;
2016 case CERT_TRUSTED: /* FALLTHROUGH */
2017 case CERT_UNTRUSTED:
2018 /* cache new certificate */
2019 args.i = XT_CACHE;
2020 cert_cmd(t, &args);
2021 break;
2022 case CERT_BAD:
2023 if ((soupuri = soup_uri_new(uri)) == NULL ||
2024 soupuri->host == NULL)
2025 break;
2026 if ((w = wl_find(soupuri->host, &svil)) != NULL)
2027 break;
2028 t->xtp_meaning = XT_XTP_TAB_MEANING_SV;
2029 args.s = g_strdup((char *)uri);
2030 xtp_page_sv(t, &args);
2031 ret = 1;
2032 break;
2035 if (soupuri)
2036 soup_uri_free(soupuri);
2037 if (chain)
2038 g_free(chain);
2039 return (ret);
2043 remove_cookie(int index)
2045 int i, rv = 1;
2046 GSList *cf;
2047 SoupCookie *c;
2049 DNPRINTF(XT_D_COOKIE, "remove_cookie: %d\n", index);
2051 cf = soup_cookie_jar_all_cookies(s_cookiejar);
2053 for (i = 1; cf; cf = cf->next, i++) {
2054 if (i != index)
2055 continue;
2056 c = cf->data;
2057 print_cookie("remove cookie", c);
2058 soup_cookie_jar_delete_cookie(s_cookiejar, c);
2059 rv = 0;
2060 break;
2063 soup_cookies_free(cf);
2065 return (rv);
2069 remove_cookie_domain(int domain_id)
2071 int domain_count, rv = 1;
2072 GSList *cf;
2073 SoupCookie *c;
2074 char *last_domain;
2076 DNPRINTF(XT_D_COOKIE, "remove_cookie_domain: %d\n", domain_id);
2078 last_domain = "";
2079 cf = soup_cookie_jar_all_cookies(s_cookiejar);
2081 for (domain_count = 0; cf; cf = cf->next) {
2082 c = cf->data;
2084 if (strcmp(last_domain, c->domain) != 0) {
2085 domain_count++;
2086 last_domain = c->domain;
2089 if (domain_count < domain_id)
2090 continue;
2091 else if (domain_count > domain_id)
2092 break;
2094 print_cookie("remove cookie", c);
2095 soup_cookie_jar_delete_cookie(s_cookiejar, c);
2096 rv = 0;
2099 soup_cookies_free(cf);
2101 return (rv);
2105 remove_cookie_all()
2107 int rv = 1;
2108 GSList *cf;
2109 SoupCookie *c;
2111 DNPRINTF(XT_D_COOKIE, "remove_cookie_all\n");
2113 cf = soup_cookie_jar_all_cookies(s_cookiejar);
2115 for (; cf; cf = cf->next) {
2116 c = cf->data;
2118 print_cookie("remove cookie", c);
2119 soup_cookie_jar_delete_cookie(s_cookiejar, c);
2120 rv = 0;
2123 soup_cookies_free(cf);
2125 return (rv);
2129 toplevel_cmd(struct tab *t, struct karg *args)
2131 js_toggle_cb(t->js_toggle, t);
2133 return (0);
2137 can_go_back_for_real(struct tab *t)
2139 int i;
2140 WebKitWebHistoryItem *item;
2141 const gchar *uri;
2143 if (t == NULL)
2144 return (FALSE);
2146 if (t->item != NULL)
2147 return (TRUE);
2149 /* rely on webkit to make sure we can go backward when on an about page */
2150 uri = get_uri(t);
2151 if (uri == NULL || g_str_has_prefix(uri, "about:") ||
2152 g_str_has_prefix(uri, "xxxt://"))
2153 return (webkit_web_view_can_go_back(t->wv));
2155 /* the back/forward list is stupid so help determine if we can go back */
2156 for (i = 0, item = webkit_web_back_forward_list_get_current_item(t->bfl);
2157 item != NULL;
2158 i--, item = webkit_web_back_forward_list_get_nth_item(t->bfl, i)) {
2159 if (strcmp(webkit_web_history_item_get_uri(item), uri))
2160 return (TRUE);
2163 return (FALSE);
2167 can_go_forward_for_real(struct tab *t)
2169 int i;
2170 WebKitWebHistoryItem *item;
2171 const gchar *uri;
2173 if (t == NULL)
2174 return (FALSE);
2176 /* rely on webkit to make sure we can go forward when on an about page */
2177 uri = get_uri(t);
2178 if (uri == NULL || g_str_has_prefix(uri, "about:") ||
2179 g_str_has_prefix(uri, "xxxt://"))
2180 return (webkit_web_view_can_go_forward(t->wv));
2182 /* the back/forwars list is stupid so help selecting a different item */
2183 for (i = 0, item = webkit_web_back_forward_list_get_current_item(t->bfl);
2184 item != NULL;
2185 i++, item = webkit_web_back_forward_list_get_nth_item(t->bfl, i)) {
2186 if (strcmp(webkit_web_history_item_get_uri(item), uri))
2187 return (TRUE);
2190 return (FALSE);
2193 void
2194 go_back_for_real(struct tab *t)
2196 int i;
2197 WebKitWebHistoryItem *item;
2198 const gchar *uri;
2200 if (t == NULL)
2201 return;
2203 uri = get_uri(t);
2204 if (uri == NULL || g_str_has_prefix(uri, "about:") ||
2205 g_str_has_prefix(uri, "xxxt://")) {
2206 webkit_web_view_go_back(t->wv);
2207 return;
2209 /* the back/forwars list is stupid so help selecting a different item */
2210 for (i = 0, item = webkit_web_back_forward_list_get_current_item(t->bfl);
2211 item != NULL;
2212 i--, item = webkit_web_back_forward_list_get_nth_item(t->bfl, i)) {
2213 if (strcmp(webkit_web_history_item_get_uri(item), uri)) {
2214 webkit_web_view_go_to_back_forward_item(t->wv, item);
2215 break;
2220 void
2221 go_forward_for_real(struct tab *t)
2223 int i;
2224 WebKitWebHistoryItem *item;
2225 const gchar *uri;
2227 if (t == NULL)
2228 return;
2230 uri = get_uri(t);
2231 if (uri == NULL || g_str_has_prefix(uri, "about:") ||
2232 g_str_has_prefix(uri, "xxxt://")) {
2233 webkit_web_view_go_forward(t->wv);
2234 return;
2236 /* the back/forwars list is stupid so help selecting a different item */
2237 for (i = 0, item = webkit_web_back_forward_list_get_current_item(t->bfl);
2238 item != NULL;
2239 i++, item = webkit_web_back_forward_list_get_nth_item(t->bfl, i)) {
2240 if (strcmp(webkit_web_history_item_get_uri(item), uri)) {
2241 webkit_web_view_go_to_back_forward_item(t->wv, item);
2242 break;
2248 navaction(struct tab *t, struct karg *args)
2250 WebKitWebHistoryItem *item = NULL;
2251 WebKitWebFrame *frame;
2253 DNPRINTF(XT_D_NAV, "navaction: tab %d opcode %d\n",
2254 t->tab_id, args->i);
2256 hide_oops(t);
2257 set_normal_tab_meaning(t);
2258 if (t->item) {
2259 if (args->i == XT_NAV_BACK)
2260 item = webkit_web_back_forward_list_get_current_item(t->bfl);
2261 else
2262 item = webkit_web_back_forward_list_get_forward_item(t->bfl);
2265 switch (args->i) {
2266 case XT_NAV_BACK:
2267 if (t->item) {
2268 if (item == NULL)
2269 return (XT_CB_PASSTHROUGH);
2270 webkit_web_view_go_to_back_forward_item(t->wv, item);
2271 t->item = NULL;
2272 return (XT_CB_PASSTHROUGH);
2274 marks_clear(t);
2275 go_back_for_real(t);
2276 break;
2277 case XT_NAV_FORWARD:
2278 if (t->item) {
2279 if (item == NULL)
2280 return (XT_CB_PASSTHROUGH);
2281 webkit_web_view_go_to_back_forward_item(t->wv, item);
2282 t->item = NULL;
2283 return (XT_CB_PASSTHROUGH);
2285 marks_clear(t);
2286 go_forward_for_real(t);
2287 break;
2288 case XT_NAV_RELOAD:
2289 frame = webkit_web_view_get_main_frame(t->wv);
2290 webkit_web_frame_reload(frame);
2291 break;
2292 case XT_NAV_STOP:
2293 frame = webkit_web_view_get_main_frame(t->wv);
2294 webkit_web_frame_stop_loading(frame);
2295 break;
2297 return (XT_CB_PASSTHROUGH);
2301 move(struct tab *t, struct karg *args)
2303 GtkAdjustment *adjust;
2304 double pi, si, pos, ps, upper, lower, max;
2305 double percent;
2307 switch (args->i) {
2308 case XT_MOVE_DOWN:
2309 case XT_MOVE_UP:
2310 case XT_MOVE_BOTTOM:
2311 case XT_MOVE_TOP:
2312 case XT_MOVE_PAGEDOWN:
2313 case XT_MOVE_PAGEUP:
2314 case XT_MOVE_HALFDOWN:
2315 case XT_MOVE_HALFUP:
2316 case XT_MOVE_PERCENT:
2317 case XT_MOVE_CENTER:
2318 adjust = t->adjust_v;
2319 break;
2320 default:
2321 adjust = t->adjust_h;
2322 break;
2325 pos = gtk_adjustment_get_value(adjust);
2326 ps = gtk_adjustment_get_page_size(adjust);
2327 upper = gtk_adjustment_get_upper(adjust);
2328 lower = gtk_adjustment_get_lower(adjust);
2329 si = gtk_adjustment_get_step_increment(adjust);
2330 pi = gtk_adjustment_get_page_increment(adjust);
2331 max = upper - ps;
2333 DNPRINTF(XT_D_MOVE, "move: opcode %d %s pos %f ps %f upper %f lower %f "
2334 "max %f si %f pi %f\n",
2335 args->i, adjust == t->adjust_h ? "horizontal" : "vertical",
2336 pos, ps, upper, lower, max, si, pi);
2338 switch (args->i) {
2339 case XT_MOVE_DOWN:
2340 case XT_MOVE_RIGHT:
2341 pos += si;
2342 gtk_adjustment_set_value(adjust, MIN(pos, max));
2343 break;
2344 case XT_MOVE_UP:
2345 case XT_MOVE_LEFT:
2346 pos -= si;
2347 gtk_adjustment_set_value(adjust, MAX(pos, lower));
2348 break;
2349 case XT_MOVE_BOTTOM:
2350 case XT_MOVE_FARRIGHT:
2351 t->mark[marktoindex('\'')] = gtk_adjustment_get_value(t->adjust_v);
2352 gtk_adjustment_set_value(adjust, max);
2353 break;
2354 case XT_MOVE_TOP:
2355 case XT_MOVE_FARLEFT:
2356 t->mark[marktoindex('\'')] = gtk_adjustment_get_value(t->adjust_v);
2357 gtk_adjustment_set_value(adjust, lower);
2358 break;
2359 case XT_MOVE_PAGEDOWN:
2360 pos += pi;
2361 gtk_adjustment_set_value(adjust, MIN(pos, max));
2362 break;
2363 case XT_MOVE_PAGEUP:
2364 pos -= pi;
2365 gtk_adjustment_set_value(adjust, MAX(pos, lower));
2366 break;
2367 case XT_MOVE_HALFDOWN:
2368 pos += pi / 2;
2369 gtk_adjustment_set_value(adjust, MIN(pos, max));
2370 break;
2371 case XT_MOVE_HALFUP:
2372 pos -= pi / 2;
2373 gtk_adjustment_set_value(adjust, MAX(pos, lower));
2374 break;
2375 case XT_MOVE_CENTER:
2376 t->mark[marktoindex('\'')] = gtk_adjustment_get_value(t->adjust_v);
2377 args->s = g_strdup("50.0");
2378 /* FALLTHROUGH */
2379 case XT_MOVE_PERCENT:
2380 t->mark[marktoindex('\'')] = gtk_adjustment_get_value(t->adjust_v);
2381 percent = atoi(args->s) / 100.0;
2382 pos = max * percent;
2383 if (pos < 0.0 || pos > max)
2384 break;
2385 gtk_adjustment_set_value(adjust, pos);
2386 break;
2387 default:
2388 return (XT_CB_PASSTHROUGH);
2391 DNPRINTF(XT_D_MOVE, "move: new pos %f %f\n", pos, MIN(pos, max));
2393 return (XT_CB_HANDLED);
2396 void
2397 url_set_visibility(void)
2399 struct tab *t;
2401 TAILQ_FOREACH(t, &tabs, entry)
2402 if (show_url == 0) {
2403 gtk_widget_hide(t->toolbar);
2404 focus_webview(t);
2405 } else
2406 gtk_widget_show(t->toolbar);
2409 void
2410 notebook_tab_set_visibility(void)
2412 if (show_tabs == 0) {
2413 gtk_widget_hide(tab_bar);
2414 gtk_notebook_set_show_tabs(notebook, FALSE);
2415 } else {
2416 if (tab_style == XT_TABS_NORMAL) {
2417 gtk_widget_hide(tab_bar);
2418 gtk_notebook_set_show_tabs(notebook, TRUE);
2419 } else if (tab_style == XT_TABS_COMPACT) {
2420 gtk_widget_show(tab_bar);
2421 gtk_notebook_set_show_tabs(notebook, FALSE);
2426 void
2427 statusbar_set_visibility(void)
2429 struct tab *t;
2431 TAILQ_FOREACH(t, &tabs, entry){
2432 if (show_statusbar == 0)
2433 gtk_widget_hide(t->statusbar);
2434 else
2435 gtk_widget_show(t->statusbar);
2437 focus_webview(t);
2441 void
2442 url_set(struct tab *t, int enable_url_entry)
2444 GdkPixbuf *pixbuf;
2445 int progress;
2447 show_url = enable_url_entry;
2449 if (enable_url_entry) {
2450 gtk_entry_set_icon_from_icon_name(GTK_ENTRY(t->sbe.uri),
2451 GTK_ENTRY_ICON_PRIMARY, NULL);
2452 gtk_entry_set_progress_fraction(GTK_ENTRY(t->sbe.uri), 0);
2453 } else {
2454 pixbuf = gtk_entry_get_icon_pixbuf(GTK_ENTRY(t->uri_entry),
2455 GTK_ENTRY_ICON_PRIMARY);
2456 progress =
2457 gtk_entry_get_progress_fraction(GTK_ENTRY(t->uri_entry));
2458 gtk_entry_set_icon_from_pixbuf(GTK_ENTRY(t->sbe.uri),
2459 GTK_ENTRY_ICON_PRIMARY, pixbuf);
2460 gtk_entry_set_progress_fraction(GTK_ENTRY(t->sbe.uri),
2461 progress);
2466 fullscreen(struct tab *t, struct karg *args)
2468 DNPRINTF(XT_D_TAB, "%s: %p %d\n", __func__, t, args->i);
2470 if (t == NULL)
2471 return (XT_CB_PASSTHROUGH);
2473 if (show_url == 0) {
2474 url_set(t, 1);
2475 show_tabs = 1;
2476 } else {
2477 url_set(t, 0);
2478 show_tabs = 0;
2481 url_set_visibility();
2482 notebook_tab_set_visibility();
2484 return (XT_CB_HANDLED);
2488 statustoggle(struct tab *t, struct karg *args)
2490 DNPRINTF(XT_D_TAB, "%s: %p %d\n", __func__, t, args->i);
2492 if (show_statusbar == 1) {
2493 show_statusbar = 0;
2494 statusbar_set_visibility();
2495 } else if (show_statusbar == 0) {
2496 show_statusbar = 1;
2497 statusbar_set_visibility();
2499 return (XT_CB_HANDLED);
2503 urlaction(struct tab *t, struct karg *args)
2505 int rv = XT_CB_HANDLED;
2507 DNPRINTF(XT_D_TAB, "%s: %p %d\n", __func__, t, args->i);
2509 if (t == NULL)
2510 return (XT_CB_PASSTHROUGH);
2512 switch (args->i) {
2513 case XT_URL_SHOW:
2514 if (show_url == 0) {
2515 url_set(t, 1);
2516 url_set_visibility();
2518 break;
2519 case XT_URL_HIDE:
2520 if (show_url == 1) {
2521 url_set(t, 0);
2522 url_set_visibility();
2524 break;
2526 return (rv);
2530 tabaction(struct tab *t, struct karg *args)
2532 int rv = XT_CB_HANDLED;
2533 char *url = args->s;
2534 struct undo *u;
2535 struct tab *tt, *tv;
2537 DNPRINTF(XT_D_TAB, "tabaction: %p %d\n", t, args->i);
2539 if (t == NULL)
2540 return (XT_CB_PASSTHROUGH);
2542 switch (args->i) {
2543 case XT_TAB_NEW:
2544 if (strlen(url) > 0)
2545 create_new_tab(url, NULL, 1, args->precount);
2546 else
2547 create_new_tab(NULL, NULL, 1, args->precount);
2548 break;
2549 case XT_TAB_DELETE:
2550 if (args->precount < 0)
2551 delete_tab(t);
2552 else
2553 TAILQ_FOREACH(tt, &tabs, entry)
2554 if (tt->tab_id == args->precount - 1) {
2555 delete_tab(tt);
2556 break;
2558 break;
2559 case XT_TAB_DELQUIT:
2560 if (gtk_notebook_get_n_pages(notebook) > 1)
2561 delete_tab(t);
2562 else
2563 quit(t, args);
2564 break;
2565 case XT_TAB_ONLY:
2566 TAILQ_FOREACH_SAFE(tt, &tabs, entry, tv)
2567 if (t != tt)
2568 delete_tab(tt);
2569 break;
2570 case XT_TAB_OPEN:
2571 if (strlen(url) > 0)
2573 else {
2574 rv = XT_CB_PASSTHROUGH;
2575 goto done;
2577 load_uri(t, url);
2578 break;
2579 case XT_TAB_SHOW:
2580 if (show_tabs == 0) {
2581 show_tabs = 1;
2582 notebook_tab_set_visibility();
2584 break;
2585 case XT_TAB_HIDE:
2586 if (show_tabs == 1) {
2587 show_tabs = 0;
2588 notebook_tab_set_visibility();
2590 break;
2591 case XT_TAB_NEXTSTYLE:
2592 if (tab_style == XT_TABS_NORMAL) {
2593 tab_style = XT_TABS_COMPACT;
2594 recolor_compact_tabs();
2596 else
2597 tab_style = XT_TABS_NORMAL;
2598 notebook_tab_set_visibility();
2599 break;
2600 case XT_TAB_UNDO_CLOSE:
2601 if (undo_count == 0) {
2602 DNPRINTF(XT_D_TAB, "%s: no tabs to undo close",
2603 __func__);
2604 goto done;
2605 } else {
2606 undo_count--;
2607 u = TAILQ_FIRST(&undos);
2608 create_new_tab(u->uri, u, 1, -1);
2610 TAILQ_REMOVE(&undos, u, entry);
2611 g_free(u->uri);
2612 /* u->history is freed in create_new_tab() */
2613 g_free(u);
2615 break;
2616 case XT_TAB_LOAD_IMAGES:
2618 if (!auto_load_images) {
2620 /* Enable auto-load images (this will load all
2621 * previously unloaded images). */
2622 g_object_set(G_OBJECT(t->settings),
2623 "auto-load-images", TRUE, (char *)NULL);
2624 webkit_web_view_set_settings(t->wv, t->settings);
2626 webkit_web_view_reload(t->wv);
2628 /* Webkit triggers an event when we change the setting,
2629 * so we can't disable the auto-loading at once.
2631 * Unfortunately, webkit does not tell us when it's done.
2632 * Instead, we wait until the next request, and then
2633 * disable autoloading again.
2635 t->load_images = TRUE;
2637 break;
2638 default:
2639 rv = XT_CB_PASSTHROUGH;
2640 goto done;
2643 done:
2644 if (args->s) {
2645 g_free(args->s);
2646 args->s = NULL;
2649 return (rv);
2653 resizetab(struct tab *t, struct karg *args)
2655 if (t == NULL || args == NULL) {
2656 show_oops(NULL, "resizetab invalid parameters");
2657 return (XT_CB_PASSTHROUGH);
2660 DNPRINTF(XT_D_TAB, "resizetab: tab %d %d\n",
2661 t->tab_id, args->i);
2663 setzoom_webkit(t, args->i);
2665 return (XT_CB_HANDLED);
2669 movetab(struct tab *t, struct karg *args)
2671 int n, dest;
2673 if (t == NULL || args == NULL) {
2674 show_oops(NULL, "movetab invalid parameters");
2675 return (XT_CB_PASSTHROUGH);
2678 DNPRINTF(XT_D_TAB, "movetab: tab %d opcode %d\n",
2679 t->tab_id, args->i);
2681 if (args->i >= XT_TAB_INVALID)
2682 return (XT_CB_PASSTHROUGH);
2684 if (TAILQ_EMPTY(&tabs))
2685 return (XT_CB_PASSTHROUGH);
2687 n = gtk_notebook_get_n_pages(notebook);
2688 dest = gtk_notebook_get_current_page(notebook);
2690 switch (args->i) {
2691 case XT_TAB_NEXT:
2692 if (args->precount < 0)
2693 dest = dest == n - 1 ? 0 : dest + 1;
2694 else
2695 dest = args->precount - 1;
2697 break;
2698 case XT_TAB_PREV:
2699 if (args->precount < 0)
2700 dest -= 1;
2701 else
2702 dest -= args->precount % n;
2704 if (dest < 0)
2705 dest += n;
2707 break;
2708 case XT_TAB_FIRST:
2709 dest = 0;
2710 break;
2711 case XT_TAB_LAST:
2712 dest = n - 1;
2713 break;
2714 default:
2715 return (XT_CB_PASSTHROUGH);
2718 if (dest < 0 || dest >= n)
2719 return (XT_CB_PASSTHROUGH);
2720 if (t->tab_id == dest) {
2721 DNPRINTF(XT_D_TAB, "movetab: do nothing\n");
2722 return (XT_CB_HANDLED);
2725 set_current_tab(dest);
2727 return (XT_CB_HANDLED);
2730 int cmd_prefix = 0;
2732 struct prompt_sub {
2733 const char *s;
2734 const char *(*f)(struct tab *);
2735 } subs[] = {
2736 { "<uri>", get_uri },
2740 command(struct tab *t, struct karg *args)
2742 struct karg a = {0};
2743 int i, cmd_setup = 0;
2744 char *s = NULL, *sp = NULL, *sl = NULL;
2745 gchar **sv;
2747 if (t == NULL || args == NULL) {
2748 show_oops(NULL, "command invalid parameters");
2749 return (XT_CB_PASSTHROUGH);
2752 switch (args->i) {
2753 case '/':
2754 s = "/";
2755 break;
2756 case '?':
2757 s = "?";
2758 break;
2759 case ':':
2760 if (cmd_prefix == 0) {
2761 if (args->s != NULL && strlen(args->s) != 0) {
2762 sp = g_strdup_printf(":%s", args->s);
2763 s = sp;
2764 } else
2765 s = ":";
2766 } else {
2767 sp = g_strdup_printf(":%d", cmd_prefix);
2768 s = sp;
2769 cmd_prefix = 0;
2771 sl = g_strdup(s);
2772 if (sp) {
2773 g_free(sp);
2774 sp = NULL;
2776 s = sl;
2777 for (i = 0; i < LENGTH(subs); ++i) {
2778 sv = g_strsplit(sl, subs[i].s, -1);
2779 if (sl)
2780 g_free(sl);
2781 sl = g_strjoinv(subs[i].f(t), sv);
2782 g_strfreev(sv);
2783 s = sl;
2785 break;
2786 case '.':
2787 t->mode = XT_MODE_HINT;
2788 a.i = 0;
2789 s = ".";
2791 * js code will auto fire() if a single link is visible,
2792 * causing the focus-out-event cb function to be called. Setup
2793 * the cmd _before_ triggering hinting code so the cmd can get
2794 * killed by the cb in this case.
2796 show_cmd(t, s);
2797 cmd_setup = 1;
2798 hint(t, &a);
2799 break;
2800 case ',':
2801 t->mode = XT_MODE_HINT;
2802 a.i = XT_HINT_NEWTAB;
2803 s = ",";
2804 show_cmd(t, s);
2805 cmd_setup = 1;
2806 hint(t, &a);
2807 break;
2808 default:
2809 show_oops(t, "command: invalid opcode %d", args->i);
2810 return (XT_CB_PASSTHROUGH);
2813 DNPRINTF(XT_D_CMD, "%s: tab %d type %s\n", __func__, t->tab_id, s);
2815 if (!cmd_setup)
2816 show_cmd(t, s);
2818 if (sp)
2819 g_free(sp);
2820 if (sl)
2821 g_free(sl);
2823 return (XT_CB_HANDLED);
2827 search(struct tab *t, struct karg *args)
2829 gboolean d;
2831 if (t == NULL || args == NULL) {
2832 show_oops(NULL, "search invalid parameters");
2833 return (1);
2836 switch (args->i) {
2837 case XT_SEARCH_NEXT:
2838 d = t->search_forward;
2839 break;
2840 case XT_SEARCH_PREV:
2841 d = !t->search_forward;
2842 break;
2843 default:
2844 return (XT_CB_PASSTHROUGH);
2847 if (t->search_text == NULL) {
2848 if (global_search == NULL)
2849 return (XT_CB_PASSTHROUGH);
2850 else {
2851 d = t->search_forward = TRUE;
2852 t->search_text = g_strdup(global_search);
2853 webkit_web_view_mark_text_matches(t->wv, global_search, FALSE, 0);
2854 webkit_web_view_set_highlight_text_matches(t->wv, TRUE);
2858 DNPRINTF(XT_D_CMD, "search: tab %d opc %d forw %d text %s\n",
2859 t->tab_id, args->i, t->search_forward, t->search_text);
2861 webkit_web_view_search_text(t->wv, t->search_text, FALSE, d, TRUE);
2863 return (XT_CB_HANDLED);
2867 session_save(struct tab *t, char *filename)
2869 struct karg a;
2870 int rv = 1;
2871 struct session *s;
2873 if (strlen(filename) == 0)
2874 goto done;
2876 if (filename[0] == '.' || filename[0] == '/')
2877 goto done;
2879 a.s = filename;
2880 if (save_tabs(t, &a))
2881 goto done;
2882 strlcpy(named_session, filename, sizeof named_session);
2884 /* add the new session to the list of sessions */
2885 s = g_malloc(sizeof(struct session));
2886 s->name = g_strdup(filename);
2887 TAILQ_INSERT_TAIL(&sessions, s, entry);
2889 rv = 0;
2890 done:
2891 return (rv);
2895 session_open(struct tab *t, char *filename)
2897 struct karg a;
2898 int rv = 1;
2900 if (strlen(filename) == 0)
2901 goto done;
2903 if (filename[0] == '.' || filename[0] == '/')
2904 goto done;
2906 a.s = filename;
2907 a.i = XT_SES_CLOSETABS;
2908 if (open_tabs(t, &a))
2909 goto done;
2911 strlcpy(named_session, filename, sizeof named_session);
2913 rv = 0;
2914 done:
2915 return (rv);
2919 session_delete(struct tab *t, char *filename)
2921 char file[PATH_MAX];
2922 int rv = 1;
2923 struct session *s;
2925 if (strlen(filename) == 0)
2926 goto done;
2928 if (filename[0] == '.' || filename[0] == '/')
2929 goto done;
2931 snprintf(file, sizeof file, "%s" PS "%s", sessions_dir, filename);
2932 if (unlink(file))
2933 goto done;
2935 if (!strcmp(filename, named_session))
2936 strlcpy(named_session, XT_SAVED_TABS_FILE,
2937 sizeof named_session);
2939 /* remove session from sessions list */
2940 TAILQ_FOREACH(s, &sessions, entry) {
2941 if (!strcmp(s->name, filename))
2942 break;
2944 if (s == NULL)
2945 goto done;
2946 TAILQ_REMOVE(&sessions, s, entry);
2947 g_free((gpointer) s->name);
2948 g_free(s);
2950 rv = 0;
2951 done:
2952 return (rv);
2956 session_cmd(struct tab *t, struct karg *args)
2958 char *filename = args->s;
2960 if (t == NULL)
2961 return (1);
2963 if (args->i & XT_SHOW)
2964 show_oops(t, "Current session: %s", named_session[0] == '\0' ?
2965 XT_SAVED_TABS_FILE : named_session);
2966 else if (args->i & XT_SAVE) {
2967 if (session_save(t, filename)) {
2968 show_oops(t, "Can't save session: %s",
2969 filename ? filename : "INVALID");
2970 goto done;
2972 } else if (args->i & XT_OPEN) {
2973 if (session_open(t, filename)) {
2974 show_oops(t, "Can't open session: %s",
2975 filename ? filename : "INVALID");
2976 goto done;
2978 } else if (args->i & XT_DELETE) {
2979 if (session_delete(t, filename)) {
2980 show_oops(t, "Can't delete session: %s",
2981 filename ? filename : "INVALID");
2982 goto done;
2985 done:
2986 return (XT_CB_PASSTHROUGH);
2990 script_cmd(struct tab *t, struct karg *args)
2992 struct stat sb;
2993 FILE *f = NULL;
2994 char *buf = NULL;
2996 if (t == NULL)
2997 goto done;
2999 if ((f = fopen(args->s, "r")) == NULL) {
3000 show_oops(t, "Can't open script file: %s", args->s);
3001 goto done;
3004 if (fstat(fileno(f), &sb) == -1) {
3005 show_oops(t, "Can't stat script file: %s", args->s);
3006 goto done;
3009 buf = g_malloc0(sb.st_size + 1);
3010 if (fread(buf, 1, sb.st_size, f) != sb.st_size) {
3011 show_oops(t, "Can't read script file: %s", args->s);
3012 goto done;
3015 DNPRINTF(XT_D_JS, "%s: about to run script\n", __func__);
3016 run_script(t, buf);
3018 done:
3019 if (f)
3020 fclose(f);
3021 if (buf)
3022 g_free(buf);
3024 return (XT_CB_PASSTHROUGH);
3028 * Make a hardcopy of the page
3031 print_page(struct tab *t, struct karg *args)
3033 WebKitWebFrame *frame;
3034 GtkPageSetup *ps;
3035 GtkPrintOperation *op;
3036 GtkPrintOperationAction action;
3037 GtkPrintOperationResult print_res;
3038 GError *g_err = NULL;
3039 int marg_l, marg_r, marg_t, marg_b;
3040 int ret = 0;
3042 DNPRINTF(XT_D_PRINTING, "%s:", __func__);
3044 ps = gtk_page_setup_new();
3045 op = gtk_print_operation_new();
3046 action = GTK_PRINT_OPERATION_ACTION_PRINT_DIALOG;
3047 frame = webkit_web_view_get_main_frame(t->wv);
3049 /* the default margins are too small, so we will bump them */
3050 marg_l = gtk_page_setup_get_left_margin(ps, GTK_UNIT_MM) +
3051 XT_PRINT_EXTRA_MARGIN;
3052 marg_r = gtk_page_setup_get_right_margin(ps, GTK_UNIT_MM) +
3053 XT_PRINT_EXTRA_MARGIN;
3054 marg_t = gtk_page_setup_get_top_margin(ps, GTK_UNIT_MM) +
3055 XT_PRINT_EXTRA_MARGIN;
3056 marg_b = gtk_page_setup_get_bottom_margin(ps, GTK_UNIT_MM) +
3057 XT_PRINT_EXTRA_MARGIN;
3059 /* set margins */
3060 gtk_page_setup_set_left_margin(ps, marg_l, GTK_UNIT_MM);
3061 gtk_page_setup_set_right_margin(ps, marg_r, GTK_UNIT_MM);
3062 gtk_page_setup_set_top_margin(ps, marg_t, GTK_UNIT_MM);
3063 gtk_page_setup_set_bottom_margin(ps, marg_b, GTK_UNIT_MM);
3065 gtk_print_operation_set_default_page_setup(op, ps);
3067 print_res = webkit_web_frame_print_full(frame, op, action, &g_err);
3069 /* check it worked */
3070 if (print_res == GTK_PRINT_OPERATION_RESULT_ERROR) {
3071 show_oops(NULL, "can't print: %s", g_err->message);
3072 g_error_free (g_err);
3073 ret = 1;
3076 g_object_unref(G_OBJECT(ps));
3077 g_object_unref(G_OBJECT(op));
3078 return (ret);
3082 go_home(struct tab *t, struct karg *args)
3084 load_uri(t, home);
3085 return (0);
3089 set_encoding(struct tab *t, struct karg *args)
3091 const gchar *e;
3093 if (args->s && strlen(g_strstrip(args->s)) == 0) {
3094 e = webkit_web_view_get_custom_encoding(t->wv);
3095 if (e == NULL)
3096 e = webkit_web_view_get_encoding(t->wv);
3097 show_oops(t, "encoding: %s", e ? e : "N/A");
3098 } else
3099 webkit_web_view_set_custom_encoding(t->wv, args->s);
3101 return (0);
3105 restart(struct tab *t, struct karg *args)
3107 struct karg a;
3109 a.s = XT_RESTART_TABS_FILE;
3110 save_tabs(t, &a);
3111 execvp(start_argv[0], start_argv);
3112 /* NOTREACHED */
3114 return (0);
3117 char *http_proxy_save; /* not a setting, used to toggle */
3120 proxy_cmd(struct tab *t, struct karg *args)
3122 struct tab *tt;
3124 DNPRINTF(XT_D_CMD, "%s: tab %d\n", __func__, t->tab_id);
3126 if (t == NULL)
3127 return (1);
3129 /* setup */
3130 if (http_proxy) {
3131 TAILQ_FOREACH(tt, &tabs, entry)
3132 gtk_widget_show(t->proxy_toggle);
3133 if (http_proxy_save)
3134 g_free(http_proxy_save);
3135 http_proxy_save = g_strdup(http_proxy);
3138 if (args->i & XT_PRXY_SHOW) {
3139 if (http_proxy)
3140 show_oops(t, "http_proxy = %s", http_proxy);
3141 else
3142 show_oops(t, "proxy is currently disabled");
3143 } else if (args->i & XT_PRXY_TOGGLE) {
3144 if (http_proxy_save == NULL && http_proxy == NULL) {
3145 show_oops(t, "can't toggle proxy");
3146 goto done;
3148 TAILQ_FOREACH(tt, &tabs, entry)
3149 gtk_widget_show(t->proxy_toggle);
3150 if (http_proxy) {
3151 if (setup_proxy(NULL) == 0)
3152 button_set_file(t->proxy_toggle,
3153 "tordisabled.ico");
3154 show_oops(t, "http proxy disabled");
3155 } else {
3156 if (setup_proxy(http_proxy_save) == 0 && http_proxy) {
3157 button_set_file(t->proxy_toggle,
3158 "torenabled.ico");
3159 show_oops(t, "http_proxy = %s", http_proxy);
3160 } else
3161 show_oops(t, "invalid proxy: %s", http_proxy_save);
3164 done:
3165 return (XT_CB_PASSTHROUGH);
3169 * If you can read this functionthen you are a sick and twisted individual.
3170 * I hope we never meet, it'll be violent.
3172 gboolean
3173 eval_cb(const GMatchInfo *info, GString *res, gpointer data)
3175 gchar *match, *num;
3176 gint start = -1, end = -1, i;
3177 struct karg *args = data;
3180 * match contains the string UP TO the match.
3182 * res is what is returned, note that whatever remains in the sent in
3183 * string is appended on the way out.
3185 * for example /123/456/789/moo came in
3186 * match contains /123/456/789/
3187 * we assign that to res and replace /789/ with the replacement text
3188 * then g_regex_replace_eval on the way out has /123/456/replacement/moo
3191 match = g_match_info_fetch(info, 0);
3192 if (match == NULL)
3193 goto done;
3195 if (g_match_info_fetch_pos(info, 1, &start, &end) == FALSE)
3196 goto freeit;
3198 g_string_assign(res, match);
3200 i = atoi(&match[start + 1]);
3201 if (args->i == XT_URL_PLUS)
3202 i++;
3203 else
3204 i--;
3206 /* preserve whitespace when likely */
3207 num = g_strdup_printf("%0*d", end - start - 2, i);
3208 g_string_overwrite_len(res, start + 1, num, end - start - 2);
3209 g_free(num);
3211 freeit:
3212 g_free(match);
3213 done:
3214 return (FALSE); /* doesn't matter */
3218 urlmod_cmd(struct tab *t, struct karg *args)
3220 const gchar *uri;
3221 GRegex *reg;
3222 gchar *res;
3224 if (t == NULL)
3225 goto done;
3226 if ((uri = gtk_entry_get_text(GTK_ENTRY(t->uri_entry))) == NULL)
3227 goto done;
3228 if (strlen(uri) == 0)
3229 goto done;
3231 reg = g_regex_new(".*(/[0-9]+/)", 0, 0, NULL);
3232 if (reg == NULL)
3233 goto done;
3234 res = g_regex_replace_eval(reg, uri, -1, 0, 0, eval_cb, args, NULL);
3235 if (res == NULL)
3236 goto free_reg;
3238 if (!strcmp(res, uri))
3239 goto free_res;
3241 gtk_entry_set_text(GTK_ENTRY(t->uri_entry), res);
3242 activate_uri_entry_cb(t->uri_entry, t);
3244 free_res:
3245 g_free(res);
3246 free_reg:
3247 g_regex_unref(reg);
3248 done:
3249 return (XT_CB_PASSTHROUGH);
3252 struct cmd {
3253 char *cmd;
3254 int level;
3255 int (*func)(struct tab *, struct karg *);
3256 int arg;
3257 int type;
3258 } cmds[] = {
3259 { "command_mode", 0, command_mode, XT_MODE_COMMAND, 0 },
3260 { "insert_mode", 0, command_mode, XT_MODE_INSERT, 0 },
3261 { "command", 0, command, ':', 0 },
3262 { "search", 0, command, '/', 0 },
3263 { "searchb", 0, command, '?', 0 },
3264 { "hinting", 0, command, '.', 0 },
3265 { "hinting_newtab", 0, command, ',', 0 },
3266 { "togglesrc", 0, toggle_src, 0, 0 },
3267 { "editsrc", 0, edit_src, 0, 0 },
3268 { "editelement", 0, edit_element, 0, 0 },
3269 { "passthrough", 0, passthrough, 0, 0 },
3270 { "modurl", 0, modurl, 0, 0 },
3271 { "modsearchentry", 0, modsearchentry, 0, 0 },
3273 /* yanking and pasting */
3274 { "yankuri", 0, yank_uri, 0, 0 },
3275 { "pasteuricur", 0, paste_uri, XT_PASTE_CURRENT_TAB, 0 },
3276 { "pasteurinew", 0, paste_uri, XT_PASTE_NEW_TAB, 0 },
3278 /* search */
3279 { "searchnext", 0, search, XT_SEARCH_NEXT, 0 },
3280 { "searchprevious", 0, search, XT_SEARCH_PREV, 0 },
3282 /* focus */
3283 { "focusaddress", 0, focus, XT_FOCUS_URI, 0 },
3284 { "focussearch", 0, focus, XT_FOCUS_SEARCH, 0 },
3286 /* hinting */
3287 { "hinting", 0, hint, 0, 0 },
3288 { "hinting_newtab", 0, hint, XT_HINT_NEWTAB, 0 },
3290 /* custom stylesheet */
3291 { "userstyle", 0, userstyle_cmd, XT_STYLE_CURRENT_TAB, XT_USERARG },
3292 { "userstyle_global", 0, userstyle_cmd, XT_STYLE_GLOBAL, XT_USERARG },
3294 /* navigation */
3295 { "goback", 0, navaction, XT_NAV_BACK, 0 },
3296 { "goforward", 0, navaction, XT_NAV_FORWARD, 0 },
3297 { "reload", 0, navaction, XT_NAV_RELOAD, 0 },
3298 { "stop", 0, navaction, XT_NAV_STOP, 0 },
3300 /* vertical movement */
3301 { "scrolldown", 0, move, XT_MOVE_DOWN, 0 },
3302 { "scrollup", 0, move, XT_MOVE_UP, 0 },
3303 { "scrollbottom", 0, move, XT_MOVE_BOTTOM, 0 },
3304 { "scrolltop", 0, move, XT_MOVE_TOP, 0 },
3305 { "1", 0, move, XT_MOVE_TOP, 0 },
3306 { "scrollhalfdown", 0, move, XT_MOVE_HALFDOWN, 0 },
3307 { "scrollhalfup", 0, move, XT_MOVE_HALFUP, 0 },
3308 { "scrollpagedown", 0, move, XT_MOVE_PAGEDOWN, 0 },
3309 { "scrollpageup", 0, move, XT_MOVE_PAGEUP, 0 },
3310 /* horizontal movement */
3311 { "scrollright", 0, move, XT_MOVE_RIGHT, 0 },
3312 { "scrollleft", 0, move, XT_MOVE_LEFT, 0 },
3313 { "scrollfarright", 0, move, XT_MOVE_FARRIGHT, 0 },
3314 { "scrollfarleft", 0, move, XT_MOVE_FARLEFT, 0 },
3316 { "favorites", 0, xtp_page_fl, XT_SHOW, 0 },
3317 { "fav", 0, xtp_page_fl, XT_SHOW, 0 },
3318 { "favedit", 0, xtp_page_fl, XT_SHOW|XT_DELETE, 0 },
3319 { "favadd", 0, add_favorite, 0, XT_USERARG },
3321 { "qall", 0, quit, 0, 0 },
3322 { "quitall", 0, quit, 0, 0 },
3323 { "w", 0, save_tabs, 0, 0 },
3324 { "wq", 0, save_tabs_and_quit, 0, 0 },
3325 { "help", 0, help, 0, 0 },
3326 { "about", 0, xtp_page_ab, 0, 0 },
3327 { "stats", 0, stats, 0, 0 },
3328 { "version", 0, xtp_page_ab, 0, 0 },
3330 /* js command */
3331 { "js", 0, js_cmd, XT_SHOW | XT_WL_PERSISTENT | XT_WL_SESSION, 0 },
3332 { "save", 1, js_cmd, XT_SAVE | XT_WL_FQDN, 0 },
3333 { "domain", 2, js_cmd, XT_SAVE | XT_WL_TOPLEVEL, 0 },
3334 { "fqdn", 2, js_cmd, XT_SAVE | XT_WL_FQDN, 0 },
3335 { "show", 1, js_cmd, XT_SHOW | XT_WL_PERSISTENT | XT_WL_SESSION, 0 },
3336 { "all", 2, js_cmd, XT_SHOW | XT_WL_PERSISTENT | XT_WL_SESSION, 0 },
3337 { "persistent", 2, js_cmd, XT_SHOW | XT_WL_PERSISTENT, 0 },
3338 { "session", 2, js_cmd, XT_SHOW | XT_WL_SESSION, 0 },
3339 { "toggle", 1, js_cmd, XT_WL_TOGGLE | XT_WL_FQDN, 0 },
3340 { "domain", 2, js_cmd, XT_WL_TOGGLE | XT_WL_TOPLEVEL, 0 },
3341 { "fqdn", 2, js_cmd, XT_WL_TOGGLE | XT_WL_FQDN, 0 },
3343 /* cookie command */
3344 { "cookie", 0, cookie_cmd, XT_SHOW | XT_WL_PERSISTENT | XT_WL_SESSION, 0 },
3345 { "save", 1, cookie_cmd, XT_SAVE | XT_WL_FQDN, 0 },
3346 { "domain", 2, cookie_cmd, XT_SAVE | XT_WL_TOPLEVEL, 0 },
3347 { "fqdn", 2, cookie_cmd, XT_SAVE | XT_WL_FQDN, 0 },
3348 { "show", 1, cookie_cmd, XT_SHOW | XT_WL_PERSISTENT | XT_WL_SESSION, 0 },
3349 { "all", 2, cookie_cmd, XT_SHOW | XT_WL_PERSISTENT | XT_WL_SESSION, 0 },
3350 { "persistent", 2, cookie_cmd, XT_SHOW | XT_WL_PERSISTENT, 0 },
3351 { "session", 2, cookie_cmd, XT_SHOW | XT_WL_SESSION, 0 },
3352 { "toggle", 1, cookie_cmd, XT_WL_TOGGLE | XT_WL_FQDN, 0 },
3353 { "domain", 2, cookie_cmd, XT_WL_TOGGLE | XT_WL_TOPLEVEL, 0 },
3354 { "fqdn", 2, cookie_cmd, XT_WL_TOGGLE | XT_WL_FQDN, 0 },
3355 { "purge", 1, cookie_cmd, XT_DELETE, 0 },
3357 /* plugin command */
3358 { "plugin", 0, pl_cmd, XT_SHOW | XT_WL_PERSISTENT | XT_WL_SESSION, 0 },
3359 { "save", 1, pl_cmd, XT_SAVE | XT_WL_FQDN, 0 },
3360 { "domain", 2, pl_cmd, XT_SAVE | XT_WL_TOPLEVEL, 0 },
3361 { "fqdn", 2, pl_cmd, XT_SAVE | XT_WL_FQDN, 0 },
3362 { "show", 1, pl_cmd, XT_SHOW | XT_WL_PERSISTENT | XT_WL_SESSION, 0 },
3363 { "all", 2, pl_cmd, XT_SHOW | XT_WL_PERSISTENT | XT_WL_SESSION, 0 },
3364 { "persistent", 2, pl_cmd, XT_SHOW | XT_WL_PERSISTENT, 0 },
3365 { "session", 2, pl_cmd, XT_SHOW | XT_WL_SESSION, 0 },
3366 { "toggle", 1, pl_cmd, XT_WL_TOGGLE | XT_WL_FQDN, 0 },
3367 { "domain", 2, pl_cmd, XT_WL_TOGGLE | XT_WL_TOPLEVEL, 0 },
3368 { "fqdn", 2, pl_cmd, XT_WL_TOGGLE | XT_WL_FQDN, 0 },
3370 /* https command */
3371 { "https", 0, https_cmd, XT_SHOW | XT_WL_PERSISTENT | XT_WL_SESSION, 0 },
3372 { "save", 1, https_cmd, XT_SAVE | XT_WL_FQDN, 0 },
3373 { "domain", 2, https_cmd, XT_SAVE | XT_WL_TOPLEVEL, 0 },
3374 { "fqdn", 2, https_cmd, XT_SAVE | XT_WL_FQDN, 0 },
3375 { "show", 1, https_cmd, XT_SHOW | XT_WL_PERSISTENT | XT_WL_SESSION, 0 },
3376 { "all", 2, https_cmd, XT_SHOW | XT_WL_PERSISTENT | XT_WL_SESSION, 0 },
3377 { "persistent", 2, https_cmd, XT_SHOW | XT_WL_PERSISTENT, 0 },
3378 { "session", 2, https_cmd, XT_SHOW | XT_WL_SESSION, 0 },
3379 { "toggle", 1, https_cmd, XT_WL_TOGGLE | XT_WL_FQDN, 0 },
3380 { "domain", 2, https_cmd, XT_WL_TOGGLE | XT_WL_TOPLEVEL, 0 },
3381 { "fqdn", 2, https_cmd, XT_WL_TOGGLE | XT_WL_FQDN, 0 },
3383 /* toplevel (domain) command */
3384 { "toplevel", 0, toplevel_cmd, XT_WL_TOGGLE | XT_WL_TOPLEVEL | XT_WL_RELOAD, 0 },
3385 { "toggle", 1, toplevel_cmd, XT_WL_TOGGLE | XT_WL_TOPLEVEL | XT_WL_RELOAD, 0 },
3387 /* cookie jar */
3388 { "cookiejar", 0, xtp_page_cl, 0, 0 },
3390 /* cert command */
3391 { "cert", 0, cert_cmd, XT_SHOW, 0 },
3392 { "save", 1, cert_cmd, XT_SAVE, 0 },
3393 { "show", 1, cert_cmd, XT_SHOW, 0 },
3395 { "ca", 0, ca_cmd, 0, 0 },
3396 { "downloadmgr", 0, xtp_page_dl, 0, 0 },
3397 { "dl", 0, xtp_page_dl, 0, 0 },
3398 { "h", 0, xtp_page_hl, 0, 0 },
3399 { "history", 0, xtp_page_hl, 0, 0 },
3400 { "home", 0, go_home, 0, 0 },
3401 { "restart", 0, restart, 0, 0 },
3402 { "urlhide", 0, urlaction, XT_URL_HIDE, 0 },
3403 { "urlshow", 0, urlaction, XT_URL_SHOW, 0 },
3404 { "statustoggle", 0, statustoggle, 0, 0 },
3405 { "run_script", 0, run_page_script, 0, XT_USERARG },
3407 { "print", 0, print_page, 0, 0 },
3409 /* tabs */
3410 { "focusin", 0, resizetab, XT_ZOOM_IN, 0 },
3411 { "focusout", 0, resizetab, XT_ZOOM_OUT, 0 },
3412 { "focusreset", 0, resizetab, XT_ZOOM_NORMAL, 0 },
3413 { "q", 0, tabaction, XT_TAB_DELQUIT, 0 },
3414 { "quit", 0, tabaction, XT_TAB_DELQUIT, 0 },
3415 { "open", 0, tabaction, XT_TAB_OPEN, XT_URLARG },
3416 { "tabclose", 0, tabaction, XT_TAB_DELETE, XT_PREFIX | XT_INTARG},
3417 { "tabedit", 0, tabaction, XT_TAB_NEW, XT_PREFIX | XT_URLARG },
3418 { "tabfirst", 0, movetab, XT_TAB_FIRST, 0 },
3419 { "tabhide", 0, tabaction, XT_TAB_HIDE, 0 },
3420 { "tablast", 0, movetab, XT_TAB_LAST, 0 },
3421 { "tabnew", 0, tabaction, XT_TAB_NEW, XT_PREFIX | XT_URLARG },
3422 { "tabnext", 0, movetab, XT_TAB_NEXT, XT_PREFIX | XT_INTARG},
3423 { "tabnextstyle", 0, tabaction, XT_TAB_NEXTSTYLE, 0 },
3424 { "tabonly", 0, tabaction, XT_TAB_ONLY, 0 },
3425 { "tabprevious", 0, movetab, XT_TAB_PREV, XT_PREFIX | XT_INTARG},
3426 { "tabrewind", 0, movetab, XT_TAB_FIRST, 0 },
3427 { "tabshow", 0, tabaction, XT_TAB_SHOW, 0 },
3428 { "tabs", 0, buffers, 0, 0 },
3429 { "tabundoclose", 0, tabaction, XT_TAB_UNDO_CLOSE, 0 },
3430 { "buffers", 0, buffers, 0, 0 },
3431 { "ls", 0, buffers, 0, 0 },
3432 { "encoding", 0, set_encoding, 0, XT_USERARG },
3433 { "loadimages", 0, tabaction, XT_TAB_LOAD_IMAGES, 0 },
3435 /* settings */
3436 { "set", 0, set, 0, XT_SETARG },
3437 { "runtime", 0, xtp_page_rt, 0, 0 },
3439 { "fullscreen", 0, fullscreen, 0, 0 },
3440 { "f", 0, fullscreen, 0, 0 },
3442 /* sessions */
3443 { "session", 0, session_cmd, XT_SHOW, 0 },
3444 { "delete", 1, session_cmd, XT_DELETE, XT_SESSARG },
3445 { "open", 1, session_cmd, XT_OPEN, XT_SESSARG },
3446 { "save", 1, session_cmd, XT_SAVE, XT_USERARG },
3447 { "show", 1, session_cmd, XT_SHOW, 0 },
3449 /* external javascript */
3450 { "script", 0, script_cmd, XT_EJS_SHOW, XT_USERARG },
3452 /* inspector */
3453 { "inspector", 0, inspector_cmd, XT_INS_SHOW, 0 },
3454 { "show", 1, inspector_cmd, XT_INS_SHOW, 0 },
3455 { "hide", 1, inspector_cmd, XT_INS_HIDE, 0 },
3457 /* proxy */
3458 { "proxy", 0, proxy_cmd, XT_PRXY_SHOW, 0 },
3459 { "show", 1, proxy_cmd, XT_PRXY_SHOW, 0 },
3460 { "toggle", 1, proxy_cmd, XT_PRXY_TOGGLE, 0 },
3462 /* url mod */
3463 { "urlmod", 0, urlmod_cmd, XT_URL, 0 },
3464 { "plus", 1, urlmod_cmd, XT_URL_PLUS, 0 },
3465 { "min", 1, urlmod_cmd, XT_URL_MIN, 0 },
3468 struct {
3469 int index;
3470 int len;
3471 gchar *list[256];
3472 } cmd_status = {-1, 0};
3474 gboolean
3475 wv_release_button_cb(GtkWidget *btn, GdkEventButton *e, struct tab *t)
3478 if (e->type == GDK_BUTTON_RELEASE && e->button == 1)
3479 btn_down = 0;
3481 return (FALSE);
3484 gboolean
3485 wv_button_cb(GtkWidget *btn, GdkEventButton *e, struct tab *t)
3487 struct karg a;
3488 WebKitHitTestResult *hit_test_result;
3489 guint context;
3491 hit_test_result = webkit_web_view_get_hit_test_result(t->wv, e);
3492 g_object_get(hit_test_result, "context", &context, NULL);
3493 g_object_unref(G_OBJECT(hit_test_result));
3495 hide_oops(t);
3496 hide_buffers(t);
3498 if (context & WEBKIT_HIT_TEST_RESULT_CONTEXT_EDITABLE)
3499 t->mode = XT_MODE_INSERT;
3500 else
3501 t->mode = XT_MODE_COMMAND;
3503 if (e->type == GDK_BUTTON_PRESS && e->button == 1)
3504 btn_down = 1;
3505 else if (e->type == GDK_BUTTON_PRESS && e->button == 8 /* btn 4 */) {
3506 /* go backward */
3507 a.i = XT_NAV_BACK;
3508 navaction(t, &a);
3510 return (TRUE);
3511 } else if (e->type == GDK_BUTTON_PRESS && e->button == 9 /* btn 5 */) {
3512 /* go forward */
3513 a.i = XT_NAV_FORWARD;
3514 navaction(t, &a);
3516 return (TRUE);
3519 return (FALSE);
3522 void
3523 tab_close_cb(GtkWidget *btn, struct tab *t)
3525 DNPRINTF(XT_D_TAB, "tab_close_cb: tab %d\n", t->tab_id);
3527 delete_tab(t);
3531 parse_custom_uri(struct tab *t, const char *uri)
3533 struct custom_uri *u;
3534 int handled = 0;
3535 char *sv[3];
3537 TAILQ_FOREACH(u, &cul, entry) {
3538 if (strncmp(uri, u->uri, strlen(u->uri)))
3539 continue;
3541 handled = 1;
3542 sv[0] = u->cmd;
3543 sv[1] = (char *)uri;
3544 sv[2] = NULL;
3545 if (!g_spawn_async(NULL, sv, NULL, G_SPAWN_SEARCH_PATH, NULL,
3546 NULL, NULL, NULL))
3547 show_oops(t, "%s: could not spawn process", __func__);
3550 return (handled);
3553 void
3554 activate_uri_entry_cb(GtkWidget* entry, struct tab *t)
3556 const gchar *uri = gtk_entry_get_text(GTK_ENTRY(entry));
3558 DNPRINTF(XT_D_URL, "activate_uri_entry_cb: %s\n", uri);
3560 if (t == NULL) {
3561 show_oops(NULL, "activate_uri_entry_cb invalid parameters");
3562 return;
3565 if (uri == NULL) {
3566 show_oops(t, "activate_uri_entry_cb no uri");
3567 return;
3570 uri += strspn(uri, "\t ");
3572 if (parse_custom_uri(t, uri))
3573 return;
3575 /* otherwise continue to load page normally */
3576 load_uri(t, (gchar *)uri);
3577 focus_webview(t);
3580 void
3581 activate_search_entry_cb(GtkWidget* entry, struct tab *t)
3583 const gchar *search = gtk_entry_get_text(GTK_ENTRY(entry));
3584 char *newuri = NULL;
3585 gchar *enc_search;
3586 char **sv;
3588 DNPRINTF(XT_D_URL, "activate_search_entry_cb: %s\n", search);
3590 if (t == NULL) {
3591 show_oops(NULL, "activate_search_entry_cb invalid parameters");
3592 return;
3595 if (search_string == NULL || strlen(search_string) == 0) {
3596 show_oops(t, "no search_string");
3597 return;
3600 set_normal_tab_meaning(t);
3602 enc_search = soup_uri_encode(search, XT_RESERVED_CHARS);
3603 sv = g_strsplit(search_string, "%s", 2);
3604 newuri = g_strjoinv(enc_search, sv);
3605 g_free(enc_search);
3606 g_strfreev(sv);
3608 marks_clear(t);
3609 load_uri(t, newuri);
3610 focus_webview(t);
3612 if (newuri)
3613 g_free(newuri);
3616 void
3617 check_and_set_cookie(const gchar *uri, struct tab *t)
3619 struct wl_entry *w = NULL;
3620 int es = 0;
3622 if (uri == NULL || t == NULL)
3623 return;
3625 if ((w = wl_find_uri(uri, &c_wl)) == NULL)
3626 es = 0;
3627 else
3628 es = 1;
3630 DNPRINTF(XT_D_COOKIE, "check_and_set_cookie: %s %s\n",
3631 es ? "enable" : "disable", uri);
3633 g_object_set(G_OBJECT(t->settings),
3634 "enable-html5-local-storage", es, (char *)NULL);
3635 webkit_web_view_set_settings(t->wv, t->settings);
3638 void
3639 check_and_set_js(const gchar *uri, struct tab *t)
3641 struct wl_entry *w = NULL;
3642 int es = 0;
3644 if (uri == NULL || t == NULL)
3645 return;
3647 if ((w = wl_find_uri(uri, &js_wl)) == NULL)
3648 es = 0;
3649 else
3650 es = 1;
3652 DNPRINTF(XT_D_JS, "check_and_set_js: %s %s\n",
3653 es ? "enable" : "disable", uri);
3655 g_object_set(G_OBJECT(t->settings),
3656 "enable-scripts", es, (char *)NULL);
3657 webkit_web_view_set_settings(t->wv, t->settings);
3659 button_set_icon_name(t->js_toggle,
3660 es ? "media-playback-start" : "media-playback-pause");
3663 void
3664 check_and_set_pl(const gchar *uri, struct tab *t)
3666 struct wl_entry *w = NULL;
3667 int es = 0;
3669 if (uri == NULL || t == NULL)
3670 return;
3672 if ((w = wl_find_uri(uri, &pl_wl)) == NULL)
3673 es = 0;
3674 else
3675 es = 1;
3677 DNPRINTF(XT_D_JS, "check_and_set_pl: %s %s\n",
3678 es ? "enable" : "disable", uri);
3680 g_object_set(G_OBJECT(t->settings),
3681 "enable-plugins", es, (char *)NULL);
3682 webkit_web_view_set_settings(t->wv, t->settings);
3685 #if GTK_CHECK_VERSION(3, 0, 0)
3686 /* A lot of this can be removed when gtk2 is dropped on the floor */
3687 char *
3688 get_css_name(const char *col_str)
3690 char *name = NULL;
3692 if (!strcmp(col_str, XT_COLOR_WHITE))
3693 name = g_strdup(XT_CSS_NORMAL);
3694 else if (!strcmp(col_str, XT_COLOR_RED))
3695 name = g_strdup(XT_CSS_RED);
3696 else if (!strcmp(col_str, XT_COLOR_YELLOW))
3697 name = g_strdup(XT_CSS_YELLOW);
3698 else if (!strcmp(col_str, XT_COLOR_GREEN))
3699 name = g_strdup(XT_CSS_GREEN);
3700 else if (!strcmp(col_str, XT_COLOR_BLUE))
3701 name = g_strdup(XT_CSS_BLUE);
3702 return (name);
3704 #endif
3706 void
3707 show_ca_status(struct tab *t, const char *uri)
3709 char domain[8182], file[PATH_MAX];
3710 SoupMessage *msg = NULL;
3711 GTlsCertificate *cert = NULL;
3712 GTlsCertificateFlags flags = 0;
3713 gchar *col_str = XT_COLOR_RED;
3714 char *cut_uri;
3715 char *chain;
3716 char *s;
3717 #if GTK_CHECK_VERSION(3, 0, 0)
3718 char *name;
3719 #else
3720 GdkColor color;
3721 gchar *text, *base;
3722 #endif
3723 enum cert_trust trust;
3724 int nocolor = 0;
3725 int i;
3727 DNPRINTF(XT_D_URL, "show_ca_status: %d %s %s\n",
3728 ssl_strict_certs, ssl_ca_file, uri);
3730 if (t == NULL)
3731 return;
3733 if (uri == NULL || g_str_has_prefix(uri, "http://") ||
3734 !g_str_has_prefix(uri, "https://"))
3735 return;
3738 * Cut the uri to get the certs off the homepage. We can't use the
3739 * full URI here since it may include arguments and we don't want to make
3740 * these requests multiple times.
3742 cut_uri = g_strdup(uri);
3743 s = cut_uri;
3744 for (i = 0; i < 3; ++i)
3745 s = strchr(&(s[1]), '/');
3746 s[1] = '\0';
3748 msg = soup_message_new("HEAD", cut_uri);
3749 g_free(cut_uri);
3750 if (msg == NULL)
3751 return;
3752 soup_message_set_flags(msg, SOUP_MESSAGE_NO_REDIRECT);
3753 soup_session_send_message(session, msg);
3754 if (msg->status_code == SOUP_STATUS_SSL_FAILED ||
3755 msg->status_code == SOUP_STATUS_TLS_FAILED) {
3756 DNPRINTF(XT_D_URL, "%s: status not ok: %d\n", uri,
3757 msg->status_code);
3758 goto done;
3760 if (!soup_message_get_https_status(msg, &cert, &flags)) {
3761 DNPRINTF(XT_D_URL, "%s: invalid response\n", uri);
3762 goto done;
3764 if (!G_IS_TLS_CERTIFICATE(cert)) {
3765 DNPRINTF(XT_D_URL, "%s: no cert\n", uri);
3766 goto done;
3769 if (flags == 0)
3770 col_str = XT_COLOR_GREEN;
3771 else
3772 col_str = XT_COLOR_YELLOW;
3774 strlcpy(domain, uri + strlen("https://"), sizeof domain);
3775 for (i = 0; i < strlen(domain); i++)
3776 if (domain[i] == '/') {
3777 domain[i] = '\0';
3778 break;
3781 snprintf(file, sizeof file, "%s" PS "%s", certs_dir, domain);
3782 chain = g_strdup("");
3783 if ((trust = check_local_certs(file, cert, &chain)) == CERT_LOCAL)
3784 col_str = XT_COLOR_BLUE;
3785 if (t->pem)
3786 g_free(t->pem);
3787 t->pem = chain;
3789 snprintf(file, sizeof file, "%s" PS "%s", certs_cache_dir, domain);
3790 if (warn_cert_changes) {
3791 if (check_cert_changes(t, cert, file, uri))
3792 nocolor = 1;
3795 done:
3796 g_object_unref(msg);
3797 if (!strcmp(col_str, XT_COLOR_WHITE) || nocolor) {
3798 #if GTK_CHECK_VERSION(3, 0, 0)
3799 gtk_widget_set_name(t->uri_entry, XT_CSS_NORMAL);
3800 statusbar_modify_attr(t, XT_CSS_NORMAL);
3801 #else
3802 text = gdk_color_to_string(
3803 &t->default_style->text[GTK_STATE_NORMAL]);
3804 base = gdk_color_to_string(
3805 &t->default_style->base[GTK_STATE_NORMAL]);
3806 gtk_widget_modify_base(t->uri_entry, GTK_STATE_NORMAL,
3807 &t->default_style->base[GTK_STATE_NORMAL]);
3808 statusbar_modify_attr(t, text, base);
3809 g_free(text);
3810 g_free(base);
3811 #endif
3812 } else {
3813 #if GTK_CHECK_VERSION(3, 0, 0)
3814 name = get_css_name(col_str);
3815 gtk_widget_set_name(t->uri_entry, name);
3816 statusbar_modify_attr(t, name);
3817 g_free(name);
3818 #else
3819 gdk_color_parse(col_str, &color);
3820 gtk_widget_modify_base(t->uri_entry, GTK_STATE_NORMAL, &color);
3821 statusbar_modify_attr(t, XT_COLOR_BLACK, col_str);
3822 #endif
3826 void
3827 free_favicon(struct tab *t)
3829 DNPRINTF(XT_D_DOWNLOAD, "%s: down %p req %p\n",
3830 __func__, t->icon_download, t->icon_request);
3832 if (t->icon_request)
3833 g_object_unref(t->icon_request);
3834 if (t->icon_dest_uri)
3835 g_free(t->icon_dest_uri);
3837 t->icon_request = NULL;
3838 t->icon_dest_uri = NULL;
3841 void
3842 xt_icon_from_name(struct tab *t, gchar *name)
3844 if (!enable_favicon_entry)
3845 return;
3847 gtk_entry_set_icon_from_icon_name(GTK_ENTRY(t->uri_entry),
3848 GTK_ENTRY_ICON_PRIMARY, "text-html");
3849 if (show_url == 0)
3850 gtk_entry_set_icon_from_icon_name(GTK_ENTRY(t->sbe.uri),
3851 GTK_ENTRY_ICON_PRIMARY, "text-html");
3852 else
3853 gtk_entry_set_icon_from_icon_name(GTK_ENTRY(t->sbe.uri),
3854 GTK_ENTRY_ICON_PRIMARY, NULL);
3857 void
3858 xt_icon_from_pixbuf(struct tab *t, GdkPixbuf *pb)
3860 GdkPixbuf *pb_scaled;
3862 if (gdk_pixbuf_get_width(pb) > 16 || gdk_pixbuf_get_height(pb) > 16)
3863 pb_scaled = gdk_pixbuf_scale_simple(pb, 16, 16,
3864 GDK_INTERP_BILINEAR);
3865 else
3866 pb_scaled = pb;
3868 if (enable_favicon_entry) {
3870 /* Classic tabs. */
3871 gtk_entry_set_icon_from_pixbuf(GTK_ENTRY(t->uri_entry),
3872 GTK_ENTRY_ICON_PRIMARY, pb_scaled);
3874 /* Minimal tabs. */
3875 if (show_url == 0) {
3876 gtk_entry_set_icon_from_pixbuf(GTK_ENTRY(t->sbe.uri),
3877 GTK_ENTRY_ICON_PRIMARY, pb_scaled);
3878 } else
3879 gtk_entry_set_icon_from_icon_name(GTK_ENTRY(t->sbe.uri),
3880 GTK_ENTRY_ICON_PRIMARY, NULL);
3883 /* XXX: Only supports the minimal tabs atm. */
3884 if (enable_favicon_tabs)
3885 gtk_image_set_from_pixbuf(GTK_IMAGE(t->tab_elems.favicon),
3886 pb_scaled);
3888 if (pb_scaled != pb)
3889 g_object_unref(pb_scaled);
3892 void
3893 xt_icon_from_file(struct tab *t, char *uri)
3895 GdkPixbuf *pb;
3896 char *file;
3898 if (g_str_has_prefix(uri, "file://"))
3899 file = g_filename_from_uri(uri, NULL, NULL);
3900 else
3901 file = g_strdup(uri);
3903 if (file == NULL)
3904 return;
3906 pb = gdk_pixbuf_new_from_file(file, NULL);
3907 if (pb) {
3908 xt_icon_from_pixbuf(t, pb);
3909 g_object_unref(pb);
3910 } else
3911 xt_icon_from_name(t, "text-html");
3913 g_free(file);
3916 gboolean
3917 is_valid_icon(char *file)
3919 gboolean valid = 0;
3920 const char *mime_type;
3921 GFileInfo *fi;
3922 GFile *gf;
3924 gf = g_file_new_for_path(file);
3925 fi = g_file_query_info(gf, G_FILE_ATTRIBUTE_STANDARD_CONTENT_TYPE, 0,
3926 NULL, NULL);
3927 mime_type = g_file_info_get_content_type(fi);
3928 valid = g_strcmp0(mime_type, "image/x-ico") == 0 ||
3929 g_strcmp0(mime_type, "image/vnd.microsoft.icon") == 0 ||
3930 g_strcmp0(mime_type, "image/png") == 0 ||
3931 g_strcmp0(mime_type, "image/gif") == 0 ||
3932 g_strcmp0(mime_type, "application/octet-stream") == 0;
3933 g_object_unref(fi);
3934 g_object_unref(gf);
3936 return (valid);
3939 void
3940 set_favicon_from_file(struct tab *t, char *uri)
3942 struct stat sb;
3943 char *file;
3945 if (t == NULL || uri == NULL)
3946 return;
3948 if (g_str_has_prefix(uri, "file://"))
3949 file = g_filename_from_uri(uri, NULL, NULL);
3950 else
3951 file = g_strdup(uri);
3953 if (file == NULL)
3954 return;
3956 DNPRINTF(XT_D_DOWNLOAD, "%s: loading %s\n", __func__, file);
3958 if (!stat(file, &sb)) {
3959 if (sb.st_size == 0 || !is_valid_icon(file)) {
3960 /* corrupt icon so trash it */
3961 DNPRINTF(XT_D_DOWNLOAD, "%s: corrupt icon %s\n",
3962 __func__, file);
3963 unlink(file);
3964 /* no need to set icon to default here */
3965 goto done;
3968 xt_icon_from_file(t, file);
3969 done:
3970 g_free(file);
3973 void
3974 favicon_download_status_changed_cb(WebKitDownload *download, GParamSpec *spec,
3975 WebKitWebView *wv)
3977 WebKitDownloadStatus status = webkit_download_get_status(download);
3978 struct tab *tt = NULL, *t = NULL;
3981 * find the webview instead of passing in the tab as it could have been
3982 * deleted from underneath us.
3984 TAILQ_FOREACH(tt, &tabs, entry) {
3985 if (tt->wv == wv) {
3986 t = tt;
3987 break;
3990 if (t == NULL)
3991 return;
3993 DNPRINTF(XT_D_DOWNLOAD, "%s: tab %d status %d\n",
3994 __func__, t->tab_id, status);
3996 switch (status) {
3997 case WEBKIT_DOWNLOAD_STATUS_ERROR:
3998 /* -1 */
3999 t->icon_download = NULL;
4000 free_favicon(t);
4001 break;
4002 case WEBKIT_DOWNLOAD_STATUS_CREATED:
4003 /* 0 */
4004 break;
4005 case WEBKIT_DOWNLOAD_STATUS_STARTED:
4006 /* 1 */
4007 break;
4008 case WEBKIT_DOWNLOAD_STATUS_CANCELLED:
4009 /* 2 */
4010 DNPRINTF(XT_D_DOWNLOAD, "%s: freeing favicon %d\n",
4011 __func__, t->tab_id);
4012 t->icon_download = NULL;
4013 free_favicon(t);
4014 break;
4015 case WEBKIT_DOWNLOAD_STATUS_FINISHED:
4016 /* 3 */
4018 DNPRINTF(XT_D_DOWNLOAD, "%s: setting icon to %s\n",
4019 __func__, t->icon_dest_uri);
4020 set_favicon_from_file(t, t->icon_dest_uri);
4021 /* these will be freed post callback */
4022 t->icon_request = NULL;
4023 t->icon_download = NULL;
4024 break;
4025 default:
4026 break;
4030 void
4031 abort_favicon_download(struct tab *t)
4033 DNPRINTF(XT_D_DOWNLOAD, "%s: down %p\n", __func__, t->icon_download);
4035 #if !WEBKIT_CHECK_VERSION(1, 4, 0)
4036 if (t->icon_download) {
4037 g_signal_handlers_disconnect_by_func(G_OBJECT(t->icon_download),
4038 G_CALLBACK(favicon_download_status_changed_cb), t->wv);
4039 webkit_download_cancel(t->icon_download);
4040 t->icon_download = NULL;
4041 } else
4042 free_favicon(t);
4043 #endif
4045 xt_icon_from_name(t, "text-html");
4048 void
4049 notify_icon_loaded_cb(WebKitWebView *wv, gchar *uri, struct tab *t)
4051 DNPRINTF(XT_D_DOWNLOAD, "%s %s\n", __func__, uri);
4053 if (uri == NULL || t == NULL)
4054 return;
4056 #if WEBKIT_CHECK_VERSION(1, 4, 0)
4057 /* take icon from WebKitIconDatabase */
4058 GdkPixbuf *pb = NULL;
4060 /* webkit_web_view_get_icon_pixbuf is depreciated in 1.8 */
4061 #if WEBKIT_CHECK_VERSION(1, 8, 0)
4063 * If the page was not loaded (for example, via ssl_strict_certs), do
4064 * not attempt to get the webview's pixbuf. This prevents a CRITICAL
4065 * glib warning.
4067 if (wv && webkit_web_view_get_uri(wv))
4068 pb = webkit_web_view_try_get_favicon_pixbuf(wv, 0, 0);
4069 #else
4070 if (wv && webkit_web_view_get_uri(wv))
4071 pb = webkit_web_view_get_icon_pixbuf(wv);
4072 #endif
4073 if (pb) {
4074 xt_icon_from_pixbuf(t, pb);
4075 g_object_unref(pb);
4076 } else
4077 xt_icon_from_name(t, "text-html");
4078 #elif WEBKIT_CHECK_VERSION(1, 1, 18)
4079 /* download icon to cache dir */
4080 gchar *name_hash, file[PATH_MAX];
4081 struct stat sb;
4083 if (t->icon_request) {
4084 DNPRINTF(XT_D_DOWNLOAD, "%s: download in progress\n", __func__);
4085 return;
4088 /* check to see if we got the icon in cache */
4089 name_hash = g_compute_checksum_for_string(G_CHECKSUM_SHA256, uri, -1);
4090 snprintf(file, sizeof file, "%s" PS "%s.ico", cache_dir, name_hash);
4091 g_free(name_hash);
4093 if (!stat(file, &sb)) {
4094 if (sb.st_size > 0) {
4095 DNPRINTF(XT_D_DOWNLOAD, "%s: loading from cache %s\n",
4096 __func__, file);
4097 set_favicon_from_file(t, file);
4098 return;
4101 /* corrupt icon so trash it */
4102 DNPRINTF(XT_D_DOWNLOAD, "%s: corrupt icon %s\n",
4103 __func__, file);
4104 unlink(file);
4107 /* create download for icon */
4108 t->icon_request = webkit_network_request_new(uri);
4109 if (t->icon_request == NULL) {
4110 DNPRINTF(XT_D_DOWNLOAD, "%s: invalid uri %s\n",
4111 __func__, uri);
4112 return;
4115 t->icon_download = webkit_download_new(t->icon_request);
4116 if (t->icon_download == NULL)
4117 return;
4119 /* we have to free icon_dest_uri later */
4120 if ((t->icon_dest_uri = g_filename_to_uri(file, NULL, NULL)) == NULL)
4121 return;
4122 webkit_download_set_destination_uri(t->icon_download,
4123 t->icon_dest_uri);
4125 if (webkit_download_get_status(t->icon_download) ==
4126 WEBKIT_DOWNLOAD_STATUS_ERROR) {
4127 g_object_unref(t->icon_request);
4128 g_free(t->icon_dest_uri);
4129 t->icon_request = NULL;
4130 t->icon_dest_uri = NULL;
4131 return;
4134 g_signal_connect(G_OBJECT(t->icon_download), "notify::status",
4135 G_CALLBACK(favicon_download_status_changed_cb), t->wv);
4137 webkit_download_start(t->icon_download);
4138 #endif
4141 void
4142 notify_load_status_cb(WebKitWebView* wview, GParamSpec* pspec, struct tab *t)
4144 const gchar *uri = NULL;
4145 struct history *h, find;
4146 struct karg a;
4147 gchar *tmp_uri = NULL;
4148 #if !GTK_CHECK_VERSION(3, 0, 0)
4149 gchar *text, *base;
4150 #endif
4152 DNPRINTF(XT_D_URL, "notify_load_status_cb: %d %s\n",
4153 webkit_web_view_get_load_status(wview),
4154 get_uri(t) ? get_uri(t) : "NOTHING");
4156 if (t == NULL) {
4157 show_oops(NULL, "notify_load_status_cb invalid parameters");
4158 return;
4161 switch (webkit_web_view_get_load_status(wview)) {
4162 case WEBKIT_LOAD_PROVISIONAL:
4163 /* 0 */
4164 abort_favicon_download(t);
4165 #if GTK_CHECK_VERSION(2, 20, 0)
4166 gtk_widget_show(t->spinner);
4167 gtk_spinner_start(GTK_SPINNER(t->spinner));
4168 #endif
4169 t->download_requested = 0;
4171 gtk_widget_set_sensitive(GTK_WIDGET(t->stop), TRUE);
4173 /* assume we are a new address */
4174 #if GTK_CHECK_VERSION(3, 0, 0)
4175 gtk_widget_set_name(t->uri_entry, XT_CSS_NORMAL);
4176 statusbar_modify_attr(t, XT_CSS_NORMAL);
4177 #else
4178 text = gdk_color_to_string(
4179 &t->default_style->text[GTK_STATE_NORMAL]);
4180 base = gdk_color_to_string(
4181 &t->default_style->base[GTK_STATE_NORMAL]);
4182 gtk_widget_modify_base(t->uri_entry, GTK_STATE_NORMAL,
4183 &t->default_style->base[GTK_STATE_NORMAL]);
4184 statusbar_modify_attr(t, text, base);
4185 g_free(text);
4186 g_free(base);
4187 #endif
4189 /* DOM is changing, unreference the previous focused element */
4190 #if WEBKIT_CHECK_VERSION(1, 5, 0)
4191 if (t->active)
4192 g_object_unref(t->active);
4193 t->active = NULL;
4194 if (t->active_text) {
4195 g_free(t->active_text);
4196 t->active_text = NULL;
4198 #endif
4200 /* take focus if we are visible */
4201 focus_webview(t);
4202 t->focus_wv = 1;
4204 marks_clear(t);
4205 break;
4207 case WEBKIT_LOAD_COMMITTED:
4208 /* 1 */
4209 uri = get_uri(t);
4210 if (uri == NULL)
4211 return;
4212 gtk_entry_set_text(GTK_ENTRY(t->uri_entry), uri);
4214 if (t->status) {
4215 g_free(t->status);
4216 t->status = NULL;
4218 set_status(t, "Loading: %s", (char *)uri);
4220 /* clear t->item, except if we're switching to an about: page */
4221 if (t->item && !g_str_has_prefix(uri, "xxxt://") &&
4222 !g_str_has_prefix(uri, "about:")) {
4223 g_object_unref(t->item);
4224 t->item = NULL;
4227 /* check if js white listing is enabled */
4228 if (enable_plugin_whitelist)
4229 check_and_set_pl(uri, t);
4230 if (enable_cookie_whitelist)
4231 check_and_set_cookie(uri, t);
4232 if (enable_js_whitelist)
4233 check_and_set_js(uri, t);
4235 if (t->styled)
4236 apply_style(t);
4239 /* we know enough to autosave the session */
4240 if (session_autosave) {
4241 a.s = NULL;
4242 save_tabs(t, &a);
4245 show_ca_status(t, uri);
4246 run_script(t, JS_HINTING);
4247 if (enable_autoscroll)
4248 run_script(t, JS_AUTOSCROLL);
4249 break;
4251 case WEBKIT_LOAD_FIRST_VISUALLY_NON_EMPTY_LAYOUT:
4252 /* 3 */
4253 if (color_visited_uris) {
4254 color_visited(t, color_visited_helper());
4257 * This colors the links you middle-click (open in new
4258 * tab) in the current tab.
4260 if (t->tab_id != gtk_notebook_get_current_page(notebook) &&
4261 (uri = get_uri(t)) != NULL)
4262 color_visited(get_current_tab(),
4263 g_strdup_printf("{'%s' : 'dummy'}", uri));
4265 break;
4267 case WEBKIT_LOAD_FINISHED:
4268 /* 2 */
4269 if ((uri = get_uri(t)) == NULL)
4270 return;
4272 * js_autorun calls get_uri which frees t->tmp_uri if on an
4273 * "about:" page. On "about:" pages, uri points to t->tmp_uri.
4274 * I.e. we will use freed memory. Prevent that.
4276 tmp_uri = g_strdup(uri);
4278 /* autorun some js if enabled */
4279 js_autorun(t);
4281 input_autofocus(t);
4283 if (!strncmp(tmp_uri, "http://", strlen("http://")) ||
4284 !strncmp(tmp_uri, "https://", strlen("https://")) ||
4285 !strncmp(tmp_uri, "file://", strlen("file://"))) {
4286 find.uri = (gchar *)tmp_uri;
4287 h = RB_FIND(history_list, &hl, &find);
4288 if (!h)
4289 insert_history_item(tmp_uri,
4290 get_title(t, FALSE), time(NULL));
4291 else
4292 h->time = time(NULL);
4295 if (statusbar_style == XT_STATUSBAR_URL)
4296 set_status(t, "%s", (char *)tmp_uri);
4297 else
4298 set_status(t, "%s", get_title(t, FALSE));
4299 gtk_widget_set_sensitive(GTK_WIDGET(t->stop), FALSE);
4300 #if GTK_CHECK_VERSION(2, 20, 0)
4301 gtk_spinner_stop(GTK_SPINNER(t->spinner));
4302 gtk_widget_hide(t->spinner);
4303 #endif
4304 g_free(tmp_uri);
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);