add os_init to generic unix.c file, move it when needed
[xombrero.git] / xombrero.c
blob7f64aa5585277fd0dcc8642b20f22b0d643bf661
1 /*
2 * Copyright (c) 2010, 2011 Marco Peereboom <marco@peereboom.us>
3 * Copyright (c) 2011 Stevan Andjelkovic <stevan@student.chalmers.se>
4 * Copyright (c) 2010, 2011, 2012 Edd Barrett <vext01@gmail.com>
5 * Copyright (c) 2011 Todd T. Fries <todd@fries.net>
6 * Copyright (c) 2011 Raphael Graf <r@undefined.ch>
7 * Copyright (c) 2011 Michal Mazurek <akfaew@jasminek.net>
8 * Copyright (c) 2012 Josh Rickmar <jrick@devio.us>
10 * Permission to use, copy, modify, and distribute this software for any
11 * purpose with or without fee is hereby granted, provided that the above
12 * copyright notice and this permission notice appear in all copies.
14 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
15 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
16 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
17 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
18 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
19 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
20 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
23 #include <xombrero.h>
24 #include "version.h"
26 char *version = XOMBRERO_VERSION;
28 #ifdef XT_DEBUG
29 uint32_t swm_debug = 0
30 | XT_D_MOVE
31 | XT_D_KEY
32 | XT_D_TAB
33 | XT_D_URL
34 | XT_D_CMD
35 | XT_D_NAV
36 | XT_D_DOWNLOAD
37 | XT_D_CONFIG
38 | XT_D_JS
39 | XT_D_FAVORITE
40 | XT_D_PRINTING
41 | XT_D_COOKIE
42 | XT_D_KEYBINDING
43 | XT_D_CLIP
44 | XT_D_BUFFERCMD
45 | XT_D_INSPECTOR
46 | XT_D_VISITED
47 | XT_D_HISTORY
49 #endif
51 #ifdef USE_THREADS
52 GCRY_THREAD_OPTION_PTHREAD_IMPL;
53 #endif
55 char *icons[] = {
56 "xombreroicon16.png",
57 "xombreroicon32.png",
58 "xombreroicon48.png",
59 "xombreroicon64.png",
60 "xombreroicon128.png"
63 struct session {
64 TAILQ_ENTRY(session) entry;
65 const gchar *name;
67 TAILQ_HEAD(session_list, session);
69 struct undo {
70 TAILQ_ENTRY(undo) entry;
71 gchar *uri;
72 GList *history;
73 int back; /* Keeps track of how many back
74 * history items there are. */
76 TAILQ_HEAD(undo_tailq, undo);
78 struct command_entry {
79 char *line;
80 TAILQ_ENTRY(command_entry) entry;
82 TAILQ_HEAD(command_list, command_entry);
84 /* defines */
85 #define XT_DIR (".xombrero")
86 #define XT_CACHE_DIR ("cache")
87 #define XT_CERT_DIR ("certs")
88 #define XT_JS_DIR ("js")
89 #define XT_SESSIONS_DIR ("sessions")
90 #define XT_TEMP_DIR ("tmp")
91 #define XT_CONF_FILE ("xombrero.conf")
92 #define XT_QMARKS_FILE ("quickmarks")
93 #define XT_SAVED_TABS_FILE ("main_session")
94 #define XT_RESTART_TABS_FILE ("restart_tabs")
95 #define XT_SOCKET_FILE ("socket")
96 #define XT_SAVE_SESSION_ID ("SESSION_NAME=")
97 #define XT_SEARCH_FILE ("search_history")
98 #define XT_COMMAND_FILE ("command_history")
99 #define XT_DLMAN_REFRESH "10"
100 #define XT_MAX_URL_LENGTH (4096) /* 1 page is atomic, don't make bigger */
101 #define XT_MAX_UNDO_CLOSE_TAB (32)
102 #define XT_PRINT_EXTRA_MARGIN 10
103 #define XT_URL_REGEX ("^[[:blank:]]*[^[:blank:]]*([[:alnum:]-]+\\.)+[[:alnum:]-][^[:blank:]]*[[:blank:]]*$")
104 #define XT_INVALID_MARK (-1) /* XXX this is a double, maybe use something else, like a nan */
106 /* colors */
107 #define XT_COLOR_RED "#cc0000"
108 #define XT_COLOR_YELLOW "#ffff66"
109 #define XT_COLOR_BLUE "lightblue"
110 #define XT_COLOR_GREEN "#99ff66"
111 #define XT_COLOR_WHITE "white"
112 #define XT_COLOR_BLACK "black"
114 #define XT_COLOR_CT_BACKGROUND "#000000"
115 #define XT_COLOR_CT_INACTIVE "#dddddd"
116 #define XT_COLOR_CT_ACTIVE "#bbbb00"
117 #define XT_COLOR_CT_SEPARATOR "#555555"
119 #define XT_COLOR_SB_SEPARATOR "#555555"
121 #define XT_PROTO_DELIM "://"
123 /* actions */
124 #define XT_MOVE_INVALID (0)
125 #define XT_MOVE_DOWN (1)
126 #define XT_MOVE_UP (2)
127 #define XT_MOVE_BOTTOM (3)
128 #define XT_MOVE_TOP (4)
129 #define XT_MOVE_PAGEDOWN (5)
130 #define XT_MOVE_PAGEUP (6)
131 #define XT_MOVE_HALFDOWN (7)
132 #define XT_MOVE_HALFUP (8)
133 #define XT_MOVE_LEFT (9)
134 #define XT_MOVE_FARLEFT (10)
135 #define XT_MOVE_RIGHT (11)
136 #define XT_MOVE_FARRIGHT (12)
137 #define XT_MOVE_PERCENT (13)
138 #define XT_MOVE_CENTER (14)
140 #define XT_QMARK_SET (0)
141 #define XT_QMARK_OPEN (1)
142 #define XT_QMARK_TAB (2)
144 #define XT_MARK_SET (0)
145 #define XT_MARK_GOTO (1)
147 #define XT_GO_UP_ROOT (999)
149 #define XT_NAV_INVALID (0)
150 #define XT_NAV_BACK (1)
151 #define XT_NAV_FORWARD (2)
152 #define XT_NAV_RELOAD (3)
153 #define XT_NAV_STOP (4)
155 #define XT_FOCUS_INVALID (0)
156 #define XT_FOCUS_URI (1)
157 #define XT_FOCUS_SEARCH (2)
159 #define XT_SEARCH_INVALID (0)
160 #define XT_SEARCH_NEXT (1)
161 #define XT_SEARCH_PREV (2)
163 #define XT_PASTE_CURRENT_TAB (0)
164 #define XT_PASTE_NEW_TAB (1)
166 #define XT_ZOOM_IN (-1)
167 #define XT_ZOOM_OUT (-2)
168 #define XT_ZOOM_NORMAL (100)
170 #define XT_CMD_OPEN (0)
171 #define XT_CMD_OPEN_CURRENT (1)
172 #define XT_CMD_TABNEW (2)
173 #define XT_CMD_TABNEW_CURRENT (3)
175 #define XT_STATUS_NOTHING (0)
176 #define XT_STATUS_LINK (1)
177 #define XT_STATUS_URI (2)
178 #define XT_STATUS_LOADING (3)
180 #define XT_SES_DONOTHING (0)
181 #define XT_SES_CLOSETABS (1)
183 #define XT_PREFIX (1<<0)
184 #define XT_USERARG (1<<1)
185 #define XT_URLARG (1<<2)
186 #define XT_INTARG (1<<3)
187 #define XT_SESSARG (1<<4)
188 #define XT_SETARG (1<<5)
190 #define XT_HINT_NEWTAB (1<<0)
192 #define XT_BUFCMD_SZ (8)
194 #define XT_EJS_SHOW (1<<0)
196 GtkWidget * create_button(char *, char *, int);
198 void recalc_tabs(void);
199 void recolor_compact_tabs(void);
200 void set_current_tab(int page_num);
201 gboolean update_statusbar_position(GtkAdjustment*, gpointer);
202 void marks_clear(struct tab *t);
204 /* globals */
205 extern char *__progname;
206 char * const *start_argv;
207 struct passwd *pwd;
208 GtkWidget *main_window;
209 GtkNotebook *notebook;
210 GtkWidget *tab_bar;
211 GtkWidget *arrow, *abtn;
212 struct tab_list tabs;
213 struct history_list hl;
214 int hl_purge_count = 0;
215 struct session_list sessions;
216 struct domain_list c_wl;
217 struct domain_list js_wl;
218 struct domain_list pl_wl;
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 int user_agent_count = 0;
225 struct command_list chl;
226 struct command_list shl;
227 struct command_entry *history_at;
228 struct command_entry *search_at;
229 int undo_count;
230 int cmd_history_count = 0;
231 int search_history_count = 0;
232 char *global_search;
233 uint64_t blocked_cookies = 0;
234 char named_session[PATH_MAX];
235 GtkListStore *completion_model;
236 GtkListStore *buffers_store;
238 char *qmarks[XT_NOQMARKS];
239 int btn_down; /* M1 down in any wv */
240 regex_t url_re; /* guess_search regex */
242 /* starts from 1 to catch atoi() failures when calling xtp_handle_dl() */
243 int next_download_id = 1;
245 void xxx_dir(char *);
246 int icon_size_map(int);
247 void activate_uri_entry_cb(GtkWidget*, struct tab *);
249 void
250 history_delete(struct command_list *l, int *counter)
252 struct command_entry *c;
254 if (l == NULL || counter == NULL)
255 return;
257 c = TAILQ_LAST(l, command_list);
258 if (c == NULL)
259 return;
261 TAILQ_REMOVE(l, c, entry);
262 *counter -= 1;
263 g_free(c->line);
264 g_free(c);
267 void
268 history_add(struct command_list *list, char *file, char *l, int *counter)
270 struct command_entry *c;
271 FILE *f;
273 if (list == NULL || l == NULL || counter == NULL)
274 return;
276 /* don't add the same line */
277 c = TAILQ_FIRST(list);
278 if (c)
279 if (!strcmp(c->line + 1 /* skip space */, l))
280 return;
282 c = g_malloc0(sizeof *c);
283 c->line = g_strdup_printf(" %s", l);
285 *counter += 1;
286 TAILQ_INSERT_HEAD(list, c, entry);
288 if (*counter > 1000)
289 history_delete(list, counter);
291 if (history_autosave && file) {
292 f = fopen(file, "w");
293 if (f == NULL) {
294 show_oops(NULL, "couldn't write history %s", file);
295 return;
298 TAILQ_FOREACH_REVERSE(c, list, command_list, entry) {
299 c->line[0] = ' ';
300 fprintf(f, "%s\n", c->line);
303 fclose(f);
308 history_read(struct command_list *list, char *file, int *counter)
310 FILE *f;
311 char *s, line[65536];
313 if (list == NULL || file == NULL)
314 return (1);
316 f = fopen(file, "r");
317 if (f == NULL) {
318 startpage_add("couldn't open history file %s", file);
319 return (1);
322 for (;;) {
323 s = fgets(line, sizeof line, f);
324 if (s == NULL || feof(f) || ferror(f))
325 break;
326 if ((s = strchr(line, '\n')) == NULL) {
327 startpage_add("invalid history file %s", file);
328 fclose(f);
329 return (1);
331 *s = '\0';
333 history_add(list, NULL, line + 1, counter);
336 fclose(f);
338 return (0);
341 /* marks array storage. */
342 char
343 indextomark(int i)
345 if (i < 0 || i >= XT_NOMARKS)
346 return (0);
348 return XT_MARKS[i];
352 marktoindex(char m)
354 char *ret;
356 if ((ret = strchr(XT_MARKS, m)) != NULL)
357 return ret - XT_MARKS;
359 return (-1);
362 /* quickmarks array storage. */
363 char
364 indextoqmark(int i)
366 if (i < 0 || i >= XT_NOQMARKS)
367 return (0);
369 return XT_QMARKS[i];
373 qmarktoindex(char m)
375 char *ret;
377 if ((ret = strchr(XT_QMARKS, m)) != NULL)
378 return ret - XT_QMARKS;
380 return (-1);
383 #ifndef XT_SIGNALS_DISABLE
384 void
385 sigchild(int sig)
387 int saved_errno, status;
388 pid_t pid;
390 saved_errno = errno;
392 while ((pid = waitpid(WAIT_ANY, &status, WNOHANG)) != 0) {
393 if (pid == -1) {
394 if (errno == EINTR)
395 continue;
396 if (errno != ECHILD) {
398 clog_warn("sigchild: waitpid:");
401 break;
404 if (WIFEXITED(status)) {
405 if (WEXITSTATUS(status) != 0) {
407 clog_warnx("sigchild: child exit status: %d",
408 WEXITSTATUS(status));
411 } else {
413 clog_warnx("sigchild: child is terminated abnormally");
418 errno = saved_errno;
420 #endif
423 is_g_object_setting(GObject *o, char *str)
425 guint n_props = 0, i;
426 GParamSpec **proplist;
427 int rv = 0;
429 if (!G_IS_OBJECT(o))
430 return (0);
432 proplist = g_object_class_list_properties(G_OBJECT_GET_CLASS(o),
433 &n_props);
435 for (i = 0; i < n_props; i++) {
436 if (! strcmp(proplist[i]->name, str)) {
437 rv = 1;
438 break;
442 g_free(proplist);
443 return (rv);
446 struct tab *
447 get_current_tab(void)
449 struct tab *t;
451 TAILQ_FOREACH(t, &tabs, entry) {
452 if (t->tab_id == gtk_notebook_get_current_page(notebook))
453 return (t);
456 warnx("%s: no current tab", __func__);
458 return (NULL);
462 set_ssl_ca_file(char *file)
464 struct stat sb;
466 if (file == NULL || strlen(file) == 0)
467 return (-1);
468 if (stat(file, &sb)) {
469 warnx("no CA file: %s", file);
470 if (ssl_ca_file == file) { /* check and fix */
471 g_free(ssl_ca_file);
472 ssl_ca_file = NULL;
474 return (-1);
476 if (ssl_ca_file != file) { /* set dynamically */
477 if (ssl_ca_file)
478 g_free(ssl_ca_file);
479 ssl_ca_file = g_strdup(file);
481 g_object_set(session,
482 SOUP_SESSION_SSL_CA_FILE, ssl_ca_file,
483 SOUP_SESSION_SSL_STRICT, ssl_strict_certs,
484 (void *)NULL);
485 return (0);
488 void
489 set_status(struct tab *t, gchar *s, int status)
491 gchar *type = NULL;
493 if (s == NULL)
494 return;
496 switch (status) {
497 case XT_STATUS_LOADING:
498 type = g_strdup_printf("Loading: %s", s);
499 s = type;
500 break;
501 case XT_STATUS_LINK:
502 type = g_strdup_printf("Link: %s", s);
503 if (!t->status)
504 t->status = g_strdup(gtk_entry_get_text(
505 GTK_ENTRY(t->sbe.statusbar)));
506 s = type;
507 break;
508 case XT_STATUS_URI:
509 type = g_strdup_printf("%s", s);
510 if (!t->status) {
511 t->status = g_strdup(type);
513 s = type;
514 if (!t->status)
515 t->status = g_strdup(s);
516 break;
517 case XT_STATUS_NOTHING:
518 /* FALL THROUGH */
519 default:
520 break;
522 gtk_entry_set_text(GTK_ENTRY(t->sbe.statusbar), s);
523 if (type)
524 g_free(type);
527 void
528 hide_cmd(struct tab *t)
530 DNPRINTF(XT_D_CMD, "%s: tab %d\n", __func__, t->tab_id);
532 history_at = NULL; /* just in case */
533 search_at = NULL; /* just in case */
534 gtk_widget_hide(t->cmd);
537 void
538 show_cmd(struct tab *t)
540 DNPRINTF(XT_D_CMD, "%s: tab %d\n", __func__, t->tab_id);
542 history_at = NULL;
543 search_at = NULL;
544 gtk_widget_hide(t->oops);
545 gtk_widget_show(t->cmd);
548 void
549 hide_buffers(struct tab *t)
551 gtk_widget_hide(t->buffers);
552 gtk_list_store_clear(buffers_store);
555 enum {
556 COL_ID = 0,
557 COL_FAVICON,
558 COL_TITLE,
559 NUM_COLS
563 sort_tabs_by_page_num(struct tab ***stabs)
565 int num_tabs = 0;
566 struct tab *t;
568 num_tabs = gtk_notebook_get_n_pages(notebook);
570 *stabs = g_malloc0(num_tabs * sizeof(struct tab *));
572 TAILQ_FOREACH(t, &tabs, entry)
573 (*stabs)[gtk_notebook_page_num(notebook, t->vbox)] = t;
575 return (num_tabs);
578 void
579 buffers_make_list(void)
581 int i, num_tabs;
582 const gchar *title = NULL;
583 GtkTreeIter iter;
584 struct tab **stabs = NULL;
586 num_tabs = sort_tabs_by_page_num(&stabs);
588 for (i = 0; i < num_tabs; i++)
589 if (stabs[i]) {
590 gtk_list_store_append(buffers_store, &iter);
591 title = get_title(stabs[i], FALSE);
592 gtk_list_store_set(buffers_store, &iter,
593 COL_ID, i + 1, /* Enumerate the tabs starting from 1
594 * rather than 0. */
595 COL_FAVICON, gtk_image_get_pixbuf
596 (GTK_IMAGE(stabs[i]->tab_elems.favicon)),
597 COL_TITLE, title,
598 -1);
601 g_free(stabs);
604 void
605 show_buffers(struct tab *t)
607 if (gtk_widget_get_visible(GTK_WIDGET(t->buffers)))
608 return;
610 buffers_make_list();
611 gtk_widget_show(t->buffers);
612 gtk_widget_grab_focus(GTK_WIDGET(t->buffers));
615 void
616 toggle_buffers(struct tab *t)
618 if (gtk_widget_get_visible(t->buffers))
619 hide_buffers(t);
620 else
621 show_buffers(t);
625 buffers(struct tab *t, struct karg *args)
627 show_buffers(t);
629 return (0);
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 (vasprintf(&msg, fmt, ap) == -1)
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 free(msg);
667 char work_dir[PATH_MAX];
668 char certs_dir[PATH_MAX];
669 char js_dir[PATH_MAX];
670 char cache_dir[PATH_MAX];
671 char sessions_dir[PATH_MAX];
672 char temp_dir[PATH_MAX];
673 char cookie_file[PATH_MAX];
674 char *strict_transport_file = NULL;
675 SoupSession *session;
676 SoupCookieJar *s_cookiejar;
677 SoupCookieJar *p_cookiejar;
678 char rc_fname[PATH_MAX];
680 struct mime_type_list mtl;
681 struct alias_list aliases;
683 /* protos */
684 struct tab *create_new_tab(char *, struct undo *, int, int);
685 void delete_tab(struct tab *);
686 void setzoom_webkit(struct tab *, int);
687 int download_rb_cmp(struct download *, struct download *);
688 gboolean cmd_execute(struct tab *t, char *str);
691 history_rb_cmp(struct history *h1, struct history *h2)
693 return (strcmp(h1->uri, h2->uri));
695 RB_GENERATE(history_list, history, entry, history_rb_cmp);
698 domain_rb_cmp(struct domain *d1, struct domain *d2)
700 return (strcmp(d1->d, d2->d));
702 RB_GENERATE(domain_list, domain, entry, domain_rb_cmp);
705 download_rb_cmp(struct download *e1, struct download *e2)
707 return (e1->id < e2->id ? -1 : e1->id > e2->id);
709 RB_GENERATE(download_list, download, entry, download_rb_cmp);
711 struct valid_url_types {
712 char *type;
713 } vut[] = {
714 { "http://" },
715 { "https://" },
716 { "ftp://" },
717 { "file://" },
718 { XT_XTP_STR },
722 valid_url_type(char *url)
724 int i;
726 for (i = 0; i < LENGTH(vut); i++)
727 if (!strncasecmp(vut[i].type, url, strlen(vut[i].type)))
728 return (0);
730 return (1);
733 char *
734 match_alias(char *url_in)
736 struct alias *a;
737 char *arg;
738 char *url_out = NULL, *search, *enc_arg;
740 search = g_strdup(url_in);
741 arg = search;
742 if (strsep(&arg, " \t") == NULL) {
743 show_oops(NULL, "match_alias: NULL URL");
744 goto done;
747 TAILQ_FOREACH(a, &aliases, entry) {
748 if (!strcmp(search, a->a_name))
749 break;
752 if (a != NULL) {
753 DNPRINTF(XT_D_URL, "match_alias: matched alias %s\n",
754 a->a_name);
755 if (arg != NULL) {
756 enc_arg = soup_uri_encode(arg, XT_RESERVED_CHARS);
757 url_out = g_strdup_printf(a->a_uri, enc_arg);
758 g_free(enc_arg);
759 } else
760 url_out = g_strdup_printf(a->a_uri, "");
762 done:
763 g_free(search);
764 return (url_out);
767 char *
768 guess_url_type(char *url_in)
770 struct stat sb;
771 char *url_out = NULL, *enc_search = NULL;
772 int i;
773 char *cwd;
776 /* substitute aliases */
777 url_out = match_alias(url_in);
778 if (url_out != NULL)
779 return (url_out);
781 /* see if we are an about page */
782 if (!strncmp(url_in, XT_URI_ABOUT, XT_URI_ABOUT_LEN))
783 for (i = 0; i < about_list_size(); i++)
784 if (!strcmp(&url_in[XT_URI_ABOUT_LEN],
785 about_list[i].name)) {
786 url_out = g_strdup(url_in);
787 goto done;
790 if (guess_search && url_regex &&
791 !(g_str_has_prefix(url_in, "http://") ||
792 g_str_has_prefix(url_in, "https://"))) {
793 if (regexec(&url_re, url_in, 0, NULL, 0)) {
794 /* invalid URI so search instead */
795 enc_search = soup_uri_encode(url_in, XT_RESERVED_CHARS);
796 url_out = g_strdup_printf(search_string, enc_search);
797 g_free(enc_search);
798 goto done;
802 /* XXX not sure about this heuristic */
803 if (stat(url_in, &sb) == 0) {
804 if (url_in[0] == '/')
805 url_out = g_strdup_printf("file://%s", url_in);
806 else {
807 cwd = malloc(PATH_MAX);
808 if (getcwd(cwd, PATH_MAX) != NULL) {
809 url_out = g_strdup_printf("file://%s/%s",cwd, url_in);
811 free(cwd);
813 } else
814 url_out = g_strdup_printf("http://%s", url_in); /* guess http */
815 done:
816 DNPRINTF(XT_D_URL, "guess_url_type: guessed %s\n", url_out);
818 return (url_out);
821 void
822 load_uri(struct tab *t, gchar *uri)
824 struct karg args;
825 gchar *newuri = NULL;
826 int i;
828 if (uri == NULL)
829 return;
831 /* Strip leading spaces. */
832 while (*uri && isspace(*uri))
833 uri++;
835 if (strlen(uri) == 0) {
836 blank(t, NULL);
837 return;
840 t->xtp_meaning = XT_XTP_TAB_MEANING_NORMAL;
842 if (valid_url_type(uri)) {
843 newuri = guess_url_type(uri);
844 uri = newuri;
847 if (!strncmp(uri, XT_URI_ABOUT, XT_URI_ABOUT_LEN)) {
848 for (i = 0; i < about_list_size(); i++)
849 if (!strcmp(&uri[XT_URI_ABOUT_LEN], about_list[i].name)) {
850 bzero(&args, sizeof args);
851 about_list[i].func(t, &args);
852 gtk_widget_set_sensitive(GTK_WIDGET(t->stop),
853 FALSE);
854 goto done;
856 show_oops(t, "invalid about page");
857 goto done;
860 set_status(t, (char *)uri, XT_STATUS_LOADING);
861 marks_clear(t);
862 webkit_web_view_load_uri(t->wv, uri);
863 done:
864 if (newuri)
865 g_free(newuri);
868 const gchar *
869 get_uri(struct tab *t)
871 const gchar *uri = NULL;
873 if (webkit_web_view_get_load_status(t->wv) == WEBKIT_LOAD_FAILED)
874 return (NULL);
875 if (t->xtp_meaning == XT_XTP_TAB_MEANING_NORMAL) {
876 uri = webkit_web_view_get_uri(t->wv);
877 } else {
878 /* use tmp_uri to make sure it is g_freed */
879 if (t->tmp_uri)
880 g_free(t->tmp_uri);
881 t->tmp_uri =g_strdup_printf("%s%s", XT_URI_ABOUT,
882 about_list[t->xtp_meaning].name);
883 uri = t->tmp_uri;
885 return uri;
888 const gchar *
889 get_title(struct tab *t, bool window)
891 const gchar *set = NULL, *title = NULL;
892 WebKitLoadStatus status = webkit_web_view_get_load_status(t->wv);
894 if (status == WEBKIT_LOAD_PROVISIONAL || status == WEBKIT_LOAD_FAILED ||
895 t->xtp_meaning == XT_XTP_TAB_MEANING_BL)
896 goto notitle;
898 title = webkit_web_view_get_title(t->wv);
899 if ((set = title ? title : get_uri(t)))
900 return set;
902 notitle:
903 set = window ? XT_NAME : "(untitled)";
905 return set;
908 struct mime_type *
909 find_mime_type(char *mime_type)
911 struct mime_type *m, *def = NULL, *rv = NULL;
913 TAILQ_FOREACH(m, &mtl, entry) {
914 if (m->mt_default &&
915 !strncmp(mime_type, m->mt_type, strlen(m->mt_type)))
916 def = m;
918 if (m->mt_default == 0 && !strcmp(mime_type, m->mt_type)) {
919 rv = m;
920 break;
924 if (rv == NULL)
925 rv = def;
927 return (rv);
930 struct domain *
931 wl_find_uri(const gchar *s, struct domain_list *wl)
933 int i;
934 char *ss;
935 struct domain *r;
937 if (s == NULL || wl == NULL)
938 return (NULL);
940 if (!strncmp(s, "http://", strlen("http://")))
941 s = &s[strlen("http://")];
942 else if (!strncmp(s, "https://", strlen("https://")))
943 s = &s[strlen("https://")];
945 if (strlen(s) < 2)
946 return (NULL);
948 for (i = 0; i < strlen(s) + 1 /* yes er need this */; i++)
949 /* chop string at first slash */
950 if (s[i] == '/' || s[i] == ':' || s[i] == '\0') {
951 ss = g_strdup(s);
952 ss[i] = '\0';
953 r = wl_find(ss, wl);
954 g_free(ss);
955 return (r);
958 return (NULL);
961 char *
962 js_ref_to_string(JSContextRef context, JSValueRef ref)
964 char *s = NULL;
965 size_t l;
966 JSStringRef jsref;
968 jsref = JSValueToStringCopy(context, ref, NULL);
969 if (jsref == NULL)
970 return (NULL);
972 l = JSStringGetMaximumUTF8CStringSize(jsref);
973 s = g_malloc(l);
974 if (s)
975 JSStringGetUTF8CString(jsref, s, l);
976 JSStringRelease(jsref);
978 return (s);
981 #define XT_JS_DONE ("done;")
982 #define XT_JS_DONE_LEN (strlen(XT_JS_DONE))
983 #define XT_JS_INSERT ("insert;")
984 #define XT_JS_INSERT_LEN (strlen(XT_JS_INSERT))
987 run_script(struct tab *t, char *s)
989 JSGlobalContextRef ctx;
990 WebKitWebFrame *frame;
991 JSStringRef str;
992 JSValueRef val, exception;
993 char *es;
995 DNPRINTF(XT_D_JS, "%s: tab %d %s\n", __func__,
996 t->tab_id, s == (char *)JS_HINTING ? "JS_HINTING" : s);
998 frame = webkit_web_view_get_main_frame(t->wv);
999 ctx = webkit_web_frame_get_global_context(frame);
1001 str = JSStringCreateWithUTF8CString(s);
1002 val = JSEvaluateScript(ctx, str, JSContextGetGlobalObject(ctx),
1003 NULL, 0, &exception);
1004 JSStringRelease(str);
1006 DNPRINTF(XT_D_JS, "%s: val %p\n", __func__, val);
1007 if (val == NULL) {
1008 es = js_ref_to_string(ctx, exception);
1009 if (es) {
1010 DNPRINTF(XT_D_JS, "%s: exception %s\n", __func__, es);
1011 g_free(es);
1013 return (1);
1014 } else {
1015 es = js_ref_to_string(ctx, val);
1016 #if 0
1017 /* return values */
1018 if (!strncmp(es, XT_JS_DONE, XT_JS_DONE_LEN))
1019 ; /* do nothing */
1020 if (!strncmp(es, XT_JS_INSERT, XT_JS_INSERT_LEN))
1021 ; /* do nothing */
1022 #endif
1023 if (es) {
1024 DNPRINTF(XT_D_JS, "%s: val %s\n", __func__, es);
1025 g_free(es);
1029 return (0);
1033 run_script_locked(struct tab *t, char *s)
1035 int rv;
1036 #ifdef USE_THREADS
1037 gdk_threads_enter();
1038 #endif
1039 rv = run_script(t, s);
1040 #ifdef USE_THREADS
1041 GDK_FLUSH();
1042 gdk_threads_leave();
1043 #endif
1044 return (rv);
1047 void
1048 enable_hints(struct tab *t)
1050 DNPRINTF(XT_D_JS, "%s: tab %d\n", __func__, t->tab_id);
1052 if (t->new_tab)
1053 run_script(t, "hints.createHints('', 'F');");
1054 else
1055 run_script(t, "hints.createHints('', 'f');");
1056 t->mode = XT_MODE_HINT;
1059 void
1060 disable_hints(struct tab *t)
1062 DNPRINTF(XT_D_JS, "%s: tab %d\n", __func__, t->tab_id);
1064 run_script(t, "hints.clearHints();");
1065 t->mode = XT_MODE_COMMAND;
1066 t->new_tab = 0;
1070 passthrough(struct tab *t, struct karg *args)
1072 t->mode = XT_MODE_PASSTHROUGH;
1073 return (0);
1077 modurl(struct tab *t, struct karg *args)
1079 const gchar *uri = NULL;
1080 char *u = NULL;
1082 /* XXX kind of a bad hack, but oh well */
1083 if (GTK_WIDGET_HAS_FOCUS(t->uri_entry)) {
1084 if ((uri = gtk_entry_get_text(GTK_ENTRY(t->uri_entry))) &&
1085 (strlen(uri))) {
1086 u = g_strdup_printf("www.%s.com", uri);
1087 gtk_entry_set_text(GTK_ENTRY(t->uri_entry), u);
1088 g_free(u);
1089 activate_uri_entry_cb(t->uri_entry, t);
1092 return (0);
1096 hint(struct tab *t, struct karg *args)
1099 DNPRINTF(XT_D_JS, "hint: tab %d args %d\n", t->tab_id, args->i);
1101 if (t->mode == XT_MODE_HINT) {
1102 if (args->i == XT_HINT_NEWTAB)
1103 t->new_tab = 1;
1104 enable_hints(t);
1105 } else
1106 disable_hints(t);
1108 return (0);
1111 void
1112 apply_style(struct tab *t)
1114 t->styled = 1;
1115 g_object_set(G_OBJECT(t->settings),
1116 "user-stylesheet-uri", t->stylesheet, (char *)NULL);
1119 void
1120 remove_style(struct tab *t)
1122 t->styled = 0;
1123 g_object_set(G_OBJECT(t->settings),
1124 "user-stylesheet-uri", NULL, (char *)NULL);
1128 userstyle(struct tab *t, struct karg *args)
1130 struct tab *tt;
1132 DNPRINTF(XT_D_JS, "userstyle: tab %d\n", t->tab_id);
1134 switch (args->i) {
1135 case XT_STYLE_CURRENT_TAB:
1136 if (t->styled)
1137 remove_style(t);
1138 else
1139 apply_style(t);
1140 break;
1141 case XT_STYLE_GLOBAL:
1142 if (userstyle_global) {
1143 userstyle_global = 0;
1144 TAILQ_FOREACH(tt, &tabs, entry)
1145 remove_style(tt);
1146 } else {
1147 userstyle_global = 1;
1148 TAILQ_FOREACH(tt, &tabs, entry)
1149 apply_style(tt);
1151 break;
1154 return (0);
1158 quit(struct tab *t, struct karg *args)
1160 if (save_global_history)
1161 save_global_history_to_disk(t);
1163 gtk_main_quit();
1165 return (1);
1168 void
1169 restore_sessions_list(void)
1171 DIR *sdir = NULL;
1172 struct dirent *dp = NULL;
1173 struct session *s;
1174 int reg;
1176 sdir = opendir(sessions_dir);
1177 if (sdir) {
1178 while ((dp = readdir(sdir)) != NULL) {
1179 #if defined __MINGW32__
1180 reg = 1; /* windows only has regular files */
1181 #else
1182 reg = dp->d_type == DT_REG;
1183 #endif
1184 if (dp && reg) {
1185 s = g_malloc(sizeof(struct session));
1186 s->name = g_strdup(dp->d_name);
1187 TAILQ_INSERT_TAIL(&sessions, s, entry);
1190 closedir(sdir);
1195 open_tabs(struct tab *t, struct karg *a)
1197 char file[PATH_MAX];
1198 FILE *f = NULL;
1199 char *uri = NULL;
1200 int rv = 1;
1201 struct tab *ti, *tt;
1203 if (a == NULL)
1204 goto done;
1206 ti = TAILQ_LAST(&tabs, tab_list);
1208 snprintf(file, sizeof file, "%s" PS "%s", sessions_dir, a->s);
1209 if ((f = fopen(file, "r")) == NULL)
1210 goto done;
1212 for (;;) {
1213 if ((uri = fparseln(f, NULL, NULL, "\0\0\0", 0)) == NULL)
1214 if (feof(f) || ferror(f))
1215 break;
1217 /* retrieve session name */
1218 if (uri && g_str_has_prefix(uri, XT_SAVE_SESSION_ID)) {
1219 strlcpy(named_session,
1220 &uri[strlen(XT_SAVE_SESSION_ID)],
1221 sizeof named_session);
1222 continue;
1225 if (uri && strlen(uri))
1226 create_new_tab(uri, NULL, 1, -1);
1228 free(uri);
1229 uri = NULL;
1232 /* close open tabs */
1233 if (a->i == XT_SES_CLOSETABS && ti != NULL) {
1234 for (;;) {
1235 tt = TAILQ_FIRST(&tabs);
1236 if (tt == NULL)
1237 break;
1238 if (tt != ti) {
1239 delete_tab(tt);
1240 continue;
1242 delete_tab(tt);
1243 break;
1247 rv = 0;
1248 done:
1249 if (f)
1250 fclose(f);
1252 return (rv);
1256 restore_saved_tabs(void)
1258 char file[PATH_MAX];
1259 int unlink_file = 0;
1260 struct stat sb;
1261 struct karg a;
1262 int rv = 0;
1264 snprintf(file, sizeof file, "%s" PS "%s",
1265 sessions_dir, XT_RESTART_TABS_FILE);
1266 if (stat(file, &sb) == -1)
1267 a.s = XT_SAVED_TABS_FILE;
1268 else {
1269 unlink_file = 1;
1270 a.s = XT_RESTART_TABS_FILE;
1273 a.i = XT_SES_DONOTHING;
1274 rv = open_tabs(NULL, &a);
1276 if (unlink_file)
1277 unlink(file);
1279 return (rv);
1283 save_tabs(struct tab *t, struct karg *a)
1285 char file[PATH_MAX];
1286 FILE *f;
1287 int num_tabs = 0, i;
1288 struct tab **stabs = NULL;
1290 /* tab may be null here */
1292 if (a == NULL)
1293 return (1);
1294 if (a->s == NULL)
1295 snprintf(file, sizeof file, "%s" PS "%s",
1296 sessions_dir, named_session);
1297 else
1298 snprintf(file, sizeof file, "%s" PS "%s", sessions_dir, a->s);
1300 if ((f = fopen(file, "w")) == NULL) {
1301 show_oops(t, "Can't open save_tabs file: %s", strerror(errno));
1302 return (1);
1305 /* save session name */
1306 fprintf(f, "%s%s\n", XT_SAVE_SESSION_ID, named_session);
1308 /* Save tabs, in the order they are arranged in the notebook. */
1309 num_tabs = sort_tabs_by_page_num(&stabs);
1311 for (i = 0; i < num_tabs; i++)
1312 if (stabs[i]) {
1313 if (get_uri(stabs[i]) != NULL)
1314 fprintf(f, "%s\n", get_uri(stabs[i]));
1315 else if (gtk_entry_get_text(GTK_ENTRY(
1316 stabs[i]->uri_entry)))
1317 fprintf(f, "%s\n", gtk_entry_get_text(GTK_ENTRY(
1318 stabs[i]->uri_entry)));
1321 g_free(stabs);
1323 /* try and make sure this gets to disk NOW. XXX Backup first? */
1324 if (fflush(f) != 0 || fsync(fileno(f)) != 0) {
1325 show_oops(t, "May not have managed to save session: %s",
1326 strerror(errno));
1329 fclose(f);
1331 return (0);
1335 save_tabs_and_quit(struct tab *t, struct karg *args)
1337 struct karg a;
1339 a.s = NULL;
1340 save_tabs(t, &a);
1341 quit(t, NULL);
1343 return (1);
1347 run_page_script(struct tab *t, struct karg *args)
1349 const gchar *uri;
1350 char *tmp, script[PATH_MAX];
1352 tmp = args->s != NULL && strlen(args->s) > 0 ? args->s : default_script;
1353 if (tmp[0] == '\0') {
1354 show_oops(t, "no script specified");
1355 return (1);
1358 if ((uri = get_uri(t)) == NULL) {
1359 show_oops(t, "tab is empty, not running script");
1360 return (1);
1363 if (tmp[0] == '~')
1364 snprintf(script, sizeof script, "%s" PS "%s",
1365 pwd->pw_dir, &tmp[1]);
1366 else
1367 strlcpy(script, tmp, sizeof script);
1369 return (fork_exec(t, script, uri, "can't launch external script", 1));
1373 yank_uri(struct tab *t, struct karg *args)
1375 const gchar *uri;
1376 GtkClipboard *clipboard;
1378 if ((uri = get_uri(t)) == NULL)
1379 return (1);
1381 clipboard = gtk_clipboard_get(GDK_SELECTION_PRIMARY);
1382 gtk_clipboard_set_text(clipboard, uri, -1);
1384 return (0);
1388 paste_uri(struct tab *t, struct karg *args)
1390 GtkClipboard *clipboard;
1391 GdkAtom atom = gdk_atom_intern("CUT_BUFFER0", FALSE);
1392 gint len;
1393 gchar *p = NULL, *uri;
1395 /* try primary clipboard first */
1396 clipboard = gtk_clipboard_get(GDK_SELECTION_PRIMARY);
1397 p = gtk_clipboard_wait_for_text(clipboard);
1399 /* if it failed get whatever text is in cut_buffer0 */
1400 if (p == NULL && xterm_workaround)
1401 if (gdk_property_get(gdk_get_default_root_window(),
1402 atom,
1403 gdk_atom_intern("STRING", FALSE),
1405 1024 * 1024 /* picked out of my butt */,
1406 FALSE,
1407 NULL,
1408 NULL,
1409 &len,
1410 (guchar **)&p)) {
1411 if (p == NULL)
1412 goto done;
1413 /* yes sir, we need to NUL the string */
1414 p[len] = '\0';
1417 if (p) {
1418 uri = p;
1419 while (*uri && isspace(*uri))
1420 uri++;
1421 if (strlen(uri) == 0) {
1422 show_oops(t, "empty paste buffer");
1423 goto done;
1425 if (guess_search == 0 && valid_url_type(uri)) {
1426 /* we can be clever and paste this in search box */
1427 show_oops(t, "not a valid URL");
1428 goto done;
1431 if (args->i == XT_PASTE_CURRENT_TAB)
1432 load_uri(t, uri);
1433 else if (args->i == XT_PASTE_NEW_TAB)
1434 create_new_tab(uri, NULL, 1, -1);
1437 done:
1438 if (p)
1439 g_free(p);
1441 return (0);
1444 void
1445 js_toggle_cb(GtkWidget *w, struct tab *t)
1447 struct karg a;
1448 int es, set;
1450 g_object_get(G_OBJECT(t->settings),
1451 "enable-scripts", &es, (char *)NULL);
1452 es = !es;
1453 if (es)
1454 set = XT_WL_ENABLE;
1455 else
1456 set = XT_WL_DISABLE;
1458 a.i = set | XT_WL_TOPLEVEL;
1459 toggle_pl(t, &a);
1461 a.i = set | XT_WL_TOPLEVEL;
1462 toggle_cwl(t, &a);
1464 a.i = XT_WL_TOGGLE | XT_WL_TOPLEVEL | XT_WL_RELOAD;
1465 toggle_js(t, &a);
1469 toggle_src(struct tab *t, struct karg *args)
1471 gboolean mode;
1473 if (t == NULL)
1474 return (0);
1476 mode = webkit_web_view_get_view_source_mode(t->wv);
1477 webkit_web_view_set_view_source_mode(t->wv, !mode);
1478 webkit_web_view_reload(t->wv);
1480 return (0);
1483 void
1484 focus_webview(struct tab *t)
1486 if (t == NULL)
1487 return;
1489 /* only grab focus if we are visible */
1490 if (gtk_notebook_get_current_page(notebook) == t->tab_id)
1491 gtk_widget_grab_focus(GTK_WIDGET(t->wv));
1495 focus(struct tab *t, struct karg *args)
1497 if (t == NULL || args == NULL)
1498 return (1);
1500 if (show_url == 0)
1501 return (0);
1503 if (args->i == XT_FOCUS_URI)
1504 gtk_widget_grab_focus(GTK_WIDGET(t->uri_entry));
1505 else if (args->i == XT_FOCUS_SEARCH)
1506 gtk_widget_grab_focus(GTK_WIDGET(t->search_entry));
1508 return (0);
1512 connect_socket_from_uri(const gchar *uri, const gchar **error_str, char *domain,
1513 size_t domain_sz)
1515 SoupURI *su = NULL;
1516 struct addrinfo hints, *res = NULL, *ai;
1517 int rv = -1, s = -1, on, error;
1518 char port[8];
1519 static gchar myerror[256]; /* this is not thread safe */
1521 myerror[0] = '\0';
1522 *error_str = myerror;
1523 if (uri && !g_str_has_prefix(uri, "https://")) {
1524 *error_str = "invalid URI";
1525 goto done;
1528 su = soup_uri_new(uri);
1529 if (su == NULL) {
1530 *error_str = "invalid soup URI";
1531 goto done;
1533 if (!SOUP_URI_VALID_FOR_HTTP(su)) {
1534 *error_str = "invalid HTTPS URI";
1535 goto done;
1538 snprintf(port, sizeof port, "%d", su->port);
1539 bzero(&hints, sizeof(struct addrinfo));
1540 hints.ai_flags = AI_CANONNAME;
1541 hints.ai_family = AF_UNSPEC;
1542 hints.ai_socktype = SOCK_STREAM;
1544 if ((error = getaddrinfo(su->host, port, &hints, &res))) {
1545 snprintf(myerror, sizeof myerror, "getaddrinfo failed: %s",
1546 gai_strerror(errno));
1547 goto done;
1550 for (ai = res; ai; ai = ai->ai_next) {
1551 if (s != -1) {
1552 close(s);
1553 s = -1;
1556 if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6)
1557 continue;
1558 s = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
1559 if (s == -1)
1560 continue;
1561 if (setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &on,
1562 sizeof(on)) == -1)
1563 continue;
1564 if (connect(s, ai->ai_addr, ai->ai_addrlen) == 0)
1565 break;
1567 if (s == -1) {
1568 snprintf(myerror, sizeof myerror,
1569 "could not obtain certificates from: %s",
1570 su->host);
1571 goto done;
1574 if (domain)
1575 strlcpy(domain, su->host, domain_sz);
1576 rv = s;
1577 done:
1578 if (su)
1579 soup_uri_free(su);
1580 if (res)
1581 freeaddrinfo(res);
1582 if (rv == -1 && s != -1)
1583 close(s);
1585 return (rv);
1588 #ifdef __MINGW32__
1589 static ssize_t
1590 custom_gnutls_push(void *s, const void *buf, size_t len)
1592 return send((size_t)s, buf, len, 0);
1595 static ssize_t
1596 custom_gnutls_pull(void *s, void *buf, size_t len)
1598 return recv((size_t)s, buf, len, 0);
1600 #endif
1603 stop_tls(gnutls_session_t gsession, gnutls_certificate_credentials_t xcred)
1605 if (gsession)
1606 gnutls_deinit(gsession);
1607 if (xcred)
1608 gnutls_certificate_free_credentials(xcred);
1610 return (0);
1614 start_tls(const gchar **error_str, int s, gnutls_session_t *gs,
1615 gnutls_certificate_credentials_t *xc)
1617 gnutls_certificate_credentials_t xcred;
1618 gnutls_session_t gsession;
1619 int rv = 1;
1620 static gchar myerror[1024]; /* this is not thread safe */
1622 if (gs == NULL || xc == NULL)
1623 goto done;
1625 myerror[0] = '\0';
1626 *gs = NULL;
1627 *xc = NULL;
1629 gnutls_certificate_allocate_credentials(&xcred);
1630 gnutls_certificate_set_x509_trust_file(xcred, ssl_ca_file,
1631 GNUTLS_X509_FMT_PEM);
1633 gnutls_init(&gsession, GNUTLS_CLIENT);
1634 gnutls_priority_set_direct(gsession, "PERFORMANCE", NULL);
1635 gnutls_credentials_set(gsession, GNUTLS_CRD_CERTIFICATE, xcred);
1636 gnutls_transport_set_ptr(gsession, (gnutls_transport_ptr_t)(long)s);
1637 #ifdef __MINGW32__
1638 /* sockets on windows don't use file descriptors */
1639 gnutls_transport_set_push_function(gsession, custom_gnutls_push);
1640 gnutls_transport_set_pull_function(gsession, custom_gnutls_pull);
1641 #endif
1642 if ((rv = gnutls_handshake(gsession)) < 0) {
1643 snprintf(myerror, sizeof myerror,
1644 "gnutls_handshake failed %d fatal %d %s",
1646 gnutls_error_is_fatal(rv),
1647 #if LIBGNUTLS_VERSION_MAJOR >= 2 && LIBGNUTLS_VERSION_MINOR >= 6
1648 gnutls_strerror_name(rv));
1649 #else
1650 "GNUTLS version is too old to provide human readable error");
1651 #endif
1652 stop_tls(gsession, xcred);
1653 goto done;
1656 gnutls_credentials_type_t cred;
1657 cred = gnutls_auth_get_type(gsession);
1658 if (cred != GNUTLS_CRD_CERTIFICATE) {
1659 snprintf(myerror, sizeof myerror,
1660 "gnutls_auth_get_type failed %d",
1661 (int)cred);
1662 stop_tls(gsession, xcred);
1663 goto done;
1666 *gs = gsession;
1667 *xc = xcred;
1668 rv = 0;
1669 done:
1670 *error_str = myerror;
1671 return (rv);
1675 get_connection_certs(gnutls_session_t gsession, gnutls_x509_crt_t **certs,
1676 size_t *cert_count)
1678 unsigned int len;
1679 const gnutls_datum_t *cl;
1680 gnutls_x509_crt_t *all_certs;
1681 int i, rv = 1;
1683 if (certs == NULL || cert_count == NULL)
1684 goto done;
1685 if (gnutls_certificate_type_get(gsession) != GNUTLS_CRT_X509)
1686 goto done;
1687 cl = gnutls_certificate_get_peers(gsession, &len);
1688 if (len == 0)
1689 goto done;
1691 all_certs = g_malloc(sizeof(gnutls_x509_crt_t) * len);
1692 for (i = 0; i < len; i++) {
1693 gnutls_x509_crt_init(&all_certs[i]);
1694 if (gnutls_x509_crt_import(all_certs[i], &cl[i],
1695 GNUTLS_X509_FMT_PEM < 0)) {
1696 g_free(all_certs);
1697 goto done;
1701 *certs = all_certs;
1702 *cert_count = len;
1703 rv = 0;
1704 done:
1705 return (rv);
1708 void
1709 free_connection_certs(gnutls_x509_crt_t *certs, size_t cert_count)
1711 int i;
1713 for (i = 0; i < cert_count; i++)
1714 gnutls_x509_crt_deinit(certs[i]);
1715 g_free(certs);
1718 void
1719 statusbar_modify_attr(struct tab *t, const char *text, const char *base)
1721 GdkColor c_text, c_base;
1723 gdk_color_parse(text, &c_text);
1724 gdk_color_parse(base, &c_base);
1726 gtk_widget_modify_text(t->sbe.statusbar, GTK_STATE_NORMAL, &c_text);
1727 gtk_widget_modify_text(t->sbe.buffercmd, GTK_STATE_NORMAL, &c_text);
1728 gtk_widget_modify_text(t->sbe.zoom, GTK_STATE_NORMAL, &c_text);
1729 gtk_widget_modify_text(t->sbe.position, GTK_STATE_NORMAL, &c_text);
1731 gtk_widget_modify_base(t->sbe.statusbar, GTK_STATE_NORMAL, &c_base);
1732 gtk_widget_modify_base(t->sbe.buffercmd, GTK_STATE_NORMAL, &c_base);
1733 gtk_widget_modify_base(t->sbe.zoom, GTK_STATE_NORMAL, &c_base);
1734 gtk_widget_modify_base(t->sbe.position, GTK_STATE_NORMAL, &c_base);
1737 void
1738 save_certs(struct tab *t, gnutls_x509_crt_t *certs,
1739 size_t cert_count, char *domain)
1741 size_t cert_buf_sz;
1742 char cert_buf[64 * 1024], file[PATH_MAX];
1743 int i;
1744 FILE *f;
1745 GdkColor color;
1747 if (t == NULL || certs == NULL || cert_count <= 0 || domain == NULL)
1748 return;
1750 snprintf(file, sizeof file, "%s" PS "%s", certs_dir, domain);
1751 if ((f = fopen(file, "w")) == NULL) {
1752 show_oops(t, "Can't create cert file %s %s",
1753 file, strerror(errno));
1754 return;
1757 for (i = 0; i < cert_count; i++) {
1758 cert_buf_sz = sizeof cert_buf;
1759 if (gnutls_x509_crt_export(certs[i], GNUTLS_X509_FMT_PEM,
1760 cert_buf, &cert_buf_sz)) {
1761 show_oops(t, "gnutls_x509_crt_export failed");
1762 goto done;
1764 if (fwrite(cert_buf, cert_buf_sz, 1, f) != 1) {
1765 show_oops(t, "Can't write certs: %s", strerror(errno));
1766 goto done;
1770 /* not the best spot but oh well */
1771 gdk_color_parse(XT_COLOR_BLUE, &color);
1772 gtk_widget_modify_base(t->uri_entry, GTK_STATE_NORMAL, &color);
1773 statusbar_modify_attr(t, XT_COLOR_BLACK, XT_COLOR_BLUE);
1774 done:
1775 fclose(f);
1778 enum cert_trust {
1779 CERT_LOCAL,
1780 CERT_TRUSTED,
1781 CERT_UNTRUSTED,
1782 CERT_BAD
1785 enum cert_trust
1786 load_compare_cert(const gchar *uri, const gchar **error_str)
1788 char domain[8182], file[PATH_MAX];
1789 char cert_buf[64 * 1024], r_cert_buf[64 * 1024];
1790 int s = -1, i;
1791 unsigned int error = 0;
1792 FILE *f = NULL;
1793 size_t cert_buf_sz, cert_count;
1794 enum cert_trust rv = CERT_UNTRUSTED;
1795 static gchar serr[80]; /* this isn't thread safe */
1796 gnutls_session_t gsession;
1797 gnutls_x509_crt_t *certs;
1798 gnutls_certificate_credentials_t xcred;
1800 DNPRINTF(XT_D_URL, "%s: %s\n", __func__, uri);
1802 serr[0] = '\0';
1803 *error_str = serr;
1804 if ((s = connect_socket_from_uri(uri, error_str, domain,
1805 sizeof domain)) == -1)
1806 return (rv);
1808 DNPRINTF(XT_D_URL, "%s: fd %d\n", __func__, s);
1810 /* go ssl/tls */
1811 if (start_tls(error_str, s, &gsession, &xcred))
1812 goto done;
1813 DNPRINTF(XT_D_URL, "%s: got tls\n", __func__);
1815 /* verify certs in case cert file doesn't exist */
1816 if (gnutls_certificate_verify_peers2(gsession, &error) !=
1817 GNUTLS_E_SUCCESS) {
1818 *error_str = "Invalid certificates";
1819 goto done;
1822 /* get certs */
1823 if (get_connection_certs(gsession, &certs, &cert_count)) {
1824 *error_str = "Can't get connection certificates";
1825 goto done;
1828 snprintf(file, sizeof file, "%s" PS "%s", certs_dir, domain);
1829 if ((f = fopen(file, "r")) == NULL) {
1830 if (!error)
1831 rv = CERT_TRUSTED;
1832 goto freeit;
1835 for (i = 0; i < cert_count; i++) {
1836 cert_buf_sz = sizeof cert_buf;
1837 if (gnutls_x509_crt_export(certs[i], GNUTLS_X509_FMT_PEM,
1838 cert_buf, &cert_buf_sz)) {
1839 goto freeit;
1841 if (fread(r_cert_buf, cert_buf_sz, 1, f) != 1) {
1842 rv = CERT_BAD; /* critical */
1843 goto freeit;
1845 if (bcmp(r_cert_buf, cert_buf, cert_buf_sz)) {
1846 rv = CERT_BAD; /* critical */
1847 goto freeit;
1849 rv = CERT_LOCAL;
1852 freeit:
1853 if (f)
1854 fclose(f);
1855 free_connection_certs(certs, cert_count);
1856 done:
1857 /* we close the socket first for speed */
1858 if (s != -1)
1859 close(s);
1861 /* only complain if we didn't save it locally */
1862 if (error && rv != CERT_LOCAL) {
1863 strlcpy(serr, "Certificate exception(s): ", sizeof serr);
1864 if (error & GNUTLS_CERT_INVALID)
1865 strlcat(serr, "invalid, ", sizeof serr);
1866 if (error & GNUTLS_CERT_REVOKED)
1867 strlcat(serr, "revoked, ", sizeof serr);
1868 if (error & GNUTLS_CERT_SIGNER_NOT_FOUND)
1869 strlcat(serr, "signer not found, ", sizeof serr);
1870 if (error & GNUTLS_CERT_SIGNER_NOT_CA)
1871 strlcat(serr, "not signed by CA, ", sizeof serr);
1872 if (error & GNUTLS_CERT_INSECURE_ALGORITHM)
1873 strlcat(serr, "insecure algorithm, ", sizeof serr);
1874 #if LIBGNUTLS_VERSION_MAJOR >= 2 && LIBGNUTLS_VERSION_MINOR >= 6
1875 if (error & GNUTLS_CERT_NOT_ACTIVATED)
1876 strlcat(serr, "not activated, ", sizeof serr);
1877 if (error & GNUTLS_CERT_EXPIRED)
1878 strlcat(serr, "expired, ", sizeof serr);
1879 #endif
1880 for (i = strlen(serr) - 1; i > 0; i--)
1881 if (serr[i] == ',') {
1882 serr[i] = '\0';
1883 break;
1885 *error_str = serr;
1888 stop_tls(gsession, xcred);
1890 return (rv);
1894 cert_cmd(struct tab *t, struct karg *args)
1896 const gchar *uri, *error_str = NULL;
1897 char domain[8182];
1898 int s = -1;
1899 size_t cert_count;
1900 gnutls_session_t gsession;
1901 gnutls_x509_crt_t *certs;
1902 gnutls_certificate_credentials_t xcred;
1904 if (t == NULL)
1905 return (1);
1907 if (ssl_ca_file == NULL) {
1908 show_oops(t, "Can't open CA file: %s", ssl_ca_file);
1909 return (1);
1912 if ((uri = get_uri(t)) == NULL) {
1913 show_oops(t, "Invalid URI");
1914 return (1);
1917 if ((s = connect_socket_from_uri(uri, &error_str, domain,
1918 sizeof domain)) == -1) {
1919 show_oops(t, "%s", error_str);
1920 return (1);
1923 /* go ssl/tls */
1924 if (start_tls(&error_str, s, &gsession, &xcred))
1925 goto done;
1927 /* get certs */
1928 if (get_connection_certs(gsession, &certs, &cert_count)) {
1929 show_oops(t, "get_connection_certs failed");
1930 goto done;
1933 if (args->i & XT_SHOW)
1934 show_certs(t, certs, cert_count, "Certificate Chain");
1935 else if (args->i & XT_SAVE)
1936 save_certs(t, certs, cert_count, domain);
1938 free_connection_certs(certs, cert_count);
1939 done:
1940 /* we close the socket first for speed */
1941 if (s != -1)
1942 close(s);
1943 stop_tls(gsession, xcred);
1944 if (error_str && strlen(error_str))
1945 show_oops(t, "%s", error_str);
1946 return (0);
1950 remove_cookie(int index)
1952 int i, rv = 1;
1953 GSList *cf;
1954 SoupCookie *c;
1956 DNPRINTF(XT_D_COOKIE, "remove_cookie: %d\n", index);
1958 cf = soup_cookie_jar_all_cookies(s_cookiejar);
1960 for (i = 1; cf; cf = cf->next, i++) {
1961 if (i != index)
1962 continue;
1963 c = cf->data;
1964 print_cookie("remove cookie", c);
1965 soup_cookie_jar_delete_cookie(s_cookiejar, c);
1966 rv = 0;
1967 break;
1970 soup_cookies_free(cf);
1972 return (rv);
1976 remove_cookie_domain(int domain_id)
1978 int domain_count, rv = 1;
1979 GSList *cf;
1980 SoupCookie *c;
1981 char *last_domain;
1983 DNPRINTF(XT_D_COOKIE, "remove_cookie_domain: %d\n", domain_id);
1985 last_domain = "";
1986 cf = soup_cookie_jar_all_cookies(s_cookiejar);
1988 for (domain_count = 0; cf; cf = cf->next) {
1989 c = cf->data;
1991 if (strcmp(last_domain, c->domain) != 0) {
1992 domain_count++;
1993 last_domain = c->domain;
1996 if (domain_count < domain_id)
1997 continue;
1998 else if (domain_count > domain_id)
1999 break;
2001 print_cookie("remove cookie", c);
2002 soup_cookie_jar_delete_cookie(s_cookiejar, c);
2003 rv = 0;
2006 soup_cookies_free(cf);
2008 return (rv);
2012 remove_cookie_all()
2014 int rv = 1;
2015 GSList *cf;
2016 SoupCookie *c;
2018 DNPRINTF(XT_D_COOKIE, "remove_cookie_all\n");
2020 cf = soup_cookie_jar_all_cookies(s_cookiejar);
2022 for (; cf; cf = cf->next) {
2023 c = cf->data;
2025 print_cookie("remove cookie", c);
2026 soup_cookie_jar_delete_cookie(s_cookiejar, c);
2027 rv = 0;
2030 soup_cookies_free(cf);
2032 return (rv);
2036 toplevel_cmd(struct tab *t, struct karg *args)
2038 js_toggle_cb(t->js_toggle, t);
2040 return (0);
2044 can_go_back_for_real(struct tab *t)
2046 int i;
2047 WebKitWebHistoryItem *item;
2048 const gchar *uri;
2050 if (t == NULL)
2051 return (FALSE);
2053 /* rely on webkit to make sure we can go backward when on an about page */
2054 uri = get_uri(t);
2055 if (uri == NULL || g_str_has_prefix(uri, "about:"))
2056 return (webkit_web_view_can_go_back(t->wv));
2058 /* the back/forwars list is stupid so help determine if we can go back */
2059 for (i = 0, item = webkit_web_back_forward_list_get_current_item(t->bfl);
2060 item != NULL;
2061 i--, item = webkit_web_back_forward_list_get_nth_item(t->bfl, i)) {
2062 if (strcmp(webkit_web_history_item_get_uri(item), uri))
2063 return (TRUE);
2066 return (FALSE);
2070 can_go_forward_for_real(struct tab *t)
2072 int i;
2073 WebKitWebHistoryItem *item;
2074 const gchar *uri;
2076 if (t == NULL)
2077 return (FALSE);
2079 /* rely on webkit to make sure we can go forward when on an about page */
2080 uri = get_uri(t);
2081 if (uri == NULL || g_str_has_prefix(uri, "about:"))
2082 return (webkit_web_view_can_go_forward(t->wv));
2084 /* the back/forwars list is stupid so help selecting a different item */
2085 for (i = 0, item = webkit_web_back_forward_list_get_current_item(t->bfl);
2086 item != NULL;
2087 i++, item = webkit_web_back_forward_list_get_nth_item(t->bfl, i)) {
2088 if (strcmp(webkit_web_history_item_get_uri(item), uri))
2089 return (TRUE);
2092 return (FALSE);
2095 void
2096 go_back_for_real(struct tab *t)
2098 int i;
2099 WebKitWebHistoryItem *item;
2100 const gchar *uri;
2102 if (t == NULL)
2103 return;
2105 uri = get_uri(t);
2106 if (uri == NULL) {
2107 webkit_web_view_go_back(t->wv);
2108 return;
2110 /* the back/forwars list is stupid so help selecting a different item */
2111 for (i = 0, item = webkit_web_back_forward_list_get_current_item(t->bfl);
2112 item != NULL;
2113 i--, item = webkit_web_back_forward_list_get_nth_item(t->bfl, i)) {
2114 if (strcmp(webkit_web_history_item_get_uri(item), uri)) {
2115 webkit_web_view_go_to_back_forward_item(t->wv, item);
2116 break;
2121 void
2122 go_forward_for_real(struct tab *t)
2124 int i;
2125 WebKitWebHistoryItem *item;
2126 const gchar *uri;
2128 if (t == NULL)
2129 return;
2131 uri = get_uri(t);
2132 if (uri == NULL) {
2133 webkit_web_view_go_forward(t->wv);
2134 return;
2136 /* the back/forwars list is stupid so help selecting a different item */
2137 for (i = 0, item = webkit_web_back_forward_list_get_current_item(t->bfl);
2138 item != NULL;
2139 i++, item = webkit_web_back_forward_list_get_nth_item(t->bfl, i)) {
2140 if (strcmp(webkit_web_history_item_get_uri(item), uri)) {
2141 webkit_web_view_go_to_back_forward_item(t->wv, item);
2142 break;
2148 navaction(struct tab *t, struct karg *args)
2150 WebKitWebHistoryItem *item;
2151 WebKitWebFrame *frame;
2153 DNPRINTF(XT_D_NAV, "navaction: tab %d opcode %d\n",
2154 t->tab_id, args->i);
2156 hide_oops(t);
2157 t->xtp_meaning = XT_XTP_TAB_MEANING_NORMAL;
2158 if (t->item) {
2159 if (args->i == XT_NAV_BACK)
2160 item = webkit_web_back_forward_list_get_current_item(t->bfl);
2161 else
2162 item = webkit_web_back_forward_list_get_forward_item(t->bfl);
2163 if (item == NULL)
2164 return (XT_CB_PASSTHROUGH);
2165 webkit_web_view_go_to_back_forward_item(t->wv, item);
2166 t->item = NULL;
2167 return (XT_CB_PASSTHROUGH);
2170 switch (args->i) {
2171 case XT_NAV_BACK:
2172 marks_clear(t);
2173 go_back_for_real(t);
2174 break;
2175 case XT_NAV_FORWARD:
2176 marks_clear(t);
2177 go_forward_for_real(t);
2178 break;
2179 case XT_NAV_RELOAD:
2180 frame = webkit_web_view_get_main_frame(t->wv);
2181 webkit_web_frame_reload(frame);
2182 break;
2183 case XT_NAV_STOP:
2184 frame = webkit_web_view_get_main_frame(t->wv);
2185 webkit_web_frame_stop_loading(frame);
2186 break;
2188 return (XT_CB_PASSTHROUGH);
2192 move(struct tab *t, struct karg *args)
2194 GtkAdjustment *adjust;
2195 double pi, si, pos, ps, upper, lower, max;
2196 double percent;
2198 switch (args->i) {
2199 case XT_MOVE_DOWN:
2200 case XT_MOVE_UP:
2201 case XT_MOVE_BOTTOM:
2202 case XT_MOVE_TOP:
2203 case XT_MOVE_PAGEDOWN:
2204 case XT_MOVE_PAGEUP:
2205 case XT_MOVE_HALFDOWN:
2206 case XT_MOVE_HALFUP:
2207 case XT_MOVE_PERCENT:
2208 case XT_MOVE_CENTER:
2209 adjust = t->adjust_v;
2210 break;
2211 default:
2212 adjust = t->adjust_h;
2213 break;
2216 pos = gtk_adjustment_get_value(adjust);
2217 ps = gtk_adjustment_get_page_size(adjust);
2218 upper = gtk_adjustment_get_upper(adjust);
2219 lower = gtk_adjustment_get_lower(adjust);
2220 si = gtk_adjustment_get_step_increment(adjust);
2221 pi = gtk_adjustment_get_page_increment(adjust);
2222 max = upper - ps;
2224 DNPRINTF(XT_D_MOVE, "move: opcode %d %s pos %f ps %f upper %f lower %f "
2225 "max %f si %f pi %f\n",
2226 args->i, adjust == t->adjust_h ? "horizontal" : "vertical",
2227 pos, ps, upper, lower, max, si, pi);
2229 switch (args->i) {
2230 case XT_MOVE_DOWN:
2231 case XT_MOVE_RIGHT:
2232 pos += si;
2233 gtk_adjustment_set_value(adjust, MIN(pos, max));
2234 break;
2235 case XT_MOVE_UP:
2236 case XT_MOVE_LEFT:
2237 pos -= si;
2238 gtk_adjustment_set_value(adjust, MAX(pos, lower));
2239 break;
2240 case XT_MOVE_BOTTOM:
2241 case XT_MOVE_FARRIGHT:
2242 t->mark[marktoindex('\'')] = gtk_adjustment_get_value(t->adjust_v);
2243 gtk_adjustment_set_value(adjust, max);
2244 break;
2245 case XT_MOVE_TOP:
2246 case XT_MOVE_FARLEFT:
2247 t->mark[marktoindex('\'')] = gtk_adjustment_get_value(t->adjust_v);
2248 gtk_adjustment_set_value(adjust, lower);
2249 break;
2250 case XT_MOVE_PAGEDOWN:
2251 pos += pi;
2252 gtk_adjustment_set_value(adjust, MIN(pos, max));
2253 break;
2254 case XT_MOVE_PAGEUP:
2255 pos -= pi;
2256 gtk_adjustment_set_value(adjust, MAX(pos, lower));
2257 break;
2258 case XT_MOVE_HALFDOWN:
2259 pos += pi / 2;
2260 gtk_adjustment_set_value(adjust, MIN(pos, max));
2261 break;
2262 case XT_MOVE_HALFUP:
2263 pos -= pi / 2;
2264 gtk_adjustment_set_value(adjust, MAX(pos, lower));
2265 break;
2266 case XT_MOVE_CENTER:
2267 t->mark[marktoindex('\'')] = gtk_adjustment_get_value(t->adjust_v);
2268 args->s = g_strdup("50.0");
2269 /* FALLTHROUGH */
2270 case XT_MOVE_PERCENT:
2271 t->mark[marktoindex('\'')] = gtk_adjustment_get_value(t->adjust_v);
2272 percent = atoi(args->s) / 100.0;
2273 pos = max * percent;
2274 if (pos < 0.0 || pos > max)
2275 break;
2276 gtk_adjustment_set_value(adjust, pos);
2277 break;
2278 default:
2279 return (XT_CB_PASSTHROUGH);
2282 DNPRINTF(XT_D_MOVE, "move: new pos %f %f\n", pos, MIN(pos, max));
2284 return (XT_CB_HANDLED);
2287 void
2288 url_set_visibility(void)
2290 struct tab *t;
2292 TAILQ_FOREACH(t, &tabs, entry)
2293 if (show_url == 0) {
2294 gtk_widget_hide(t->toolbar);
2295 focus_webview(t);
2296 } else
2297 gtk_widget_show(t->toolbar);
2300 void
2301 notebook_tab_set_visibility(void)
2303 if (show_tabs == 0) {
2304 gtk_widget_hide(tab_bar);
2305 gtk_notebook_set_show_tabs(notebook, FALSE);
2306 } else {
2307 if (tab_style == XT_TABS_NORMAL) {
2308 gtk_widget_hide(tab_bar);
2309 gtk_notebook_set_show_tabs(notebook, TRUE);
2310 } else if (tab_style == XT_TABS_COMPACT) {
2311 gtk_widget_show(tab_bar);
2312 gtk_notebook_set_show_tabs(notebook, FALSE);
2317 void
2318 statusbar_set_visibility(void)
2320 struct tab *t;
2322 TAILQ_FOREACH(t, &tabs, entry){
2323 if (show_statusbar == 0)
2324 gtk_widget_hide(t->statusbar_box);
2325 else
2326 gtk_widget_show(t->statusbar_box);
2328 focus_webview(t);
2332 void
2333 url_set(struct tab *t, int enable_url_entry)
2335 GdkPixbuf *pixbuf;
2336 int progress;
2338 show_url = enable_url_entry;
2340 if (enable_url_entry) {
2341 gtk_entry_set_icon_from_icon_name(GTK_ENTRY(t->sbe.statusbar),
2342 GTK_ENTRY_ICON_PRIMARY, NULL);
2343 gtk_entry_set_progress_fraction(GTK_ENTRY(t->sbe.statusbar), 0);
2344 } else {
2345 pixbuf = gtk_entry_get_icon_pixbuf(GTK_ENTRY(t->uri_entry),
2346 GTK_ENTRY_ICON_PRIMARY);
2347 progress =
2348 gtk_entry_get_progress_fraction(GTK_ENTRY(t->uri_entry));
2349 gtk_entry_set_icon_from_pixbuf(GTK_ENTRY(t->sbe.statusbar),
2350 GTK_ENTRY_ICON_PRIMARY, pixbuf);
2351 gtk_entry_set_progress_fraction(GTK_ENTRY(t->sbe.statusbar),
2352 progress);
2357 fullscreen(struct tab *t, struct karg *args)
2359 DNPRINTF(XT_D_TAB, "%s: %p %d\n", __func__, t, args->i);
2361 if (t == NULL)
2362 return (XT_CB_PASSTHROUGH);
2364 if (show_url == 0) {
2365 url_set(t, 1);
2366 show_tabs = 1;
2367 } else {
2368 url_set(t, 0);
2369 show_tabs = 0;
2372 url_set_visibility();
2373 notebook_tab_set_visibility();
2375 return (XT_CB_HANDLED);
2379 statustoggle(struct tab *t, struct karg *args)
2381 DNPRINTF(XT_D_TAB, "%s: %p %d\n", __func__, t, args->i);
2383 if (show_statusbar == 1) {
2384 show_statusbar = 0;
2385 statusbar_set_visibility();
2386 } else if (show_statusbar == 0) {
2387 show_statusbar = 1;
2388 statusbar_set_visibility();
2390 return (XT_CB_HANDLED);
2394 urlaction(struct tab *t, struct karg *args)
2396 int rv = XT_CB_HANDLED;
2398 DNPRINTF(XT_D_TAB, "%s: %p %d\n", __func__, t, args->i);
2400 if (t == NULL)
2401 return (XT_CB_PASSTHROUGH);
2403 switch (args->i) {
2404 case XT_URL_SHOW:
2405 if (show_url == 0) {
2406 url_set(t, 1);
2407 url_set_visibility();
2409 break;
2410 case XT_URL_HIDE:
2411 if (show_url == 1) {
2412 url_set(t, 0);
2413 url_set_visibility();
2415 break;
2417 return (rv);
2421 tabaction(struct tab *t, struct karg *args)
2423 int rv = XT_CB_HANDLED;
2424 char *url = args->s;
2425 struct undo *u;
2426 struct tab *tt;
2428 DNPRINTF(XT_D_TAB, "tabaction: %p %d\n", t, args->i);
2430 if (t == NULL)
2431 return (XT_CB_PASSTHROUGH);
2433 switch (args->i) {
2434 case XT_TAB_NEW:
2435 if (strlen(url) > 0)
2436 create_new_tab(url, NULL, 1, args->precount);
2437 else
2438 create_new_tab(NULL, NULL, 1, args->precount);
2439 break;
2440 case XT_TAB_DELETE:
2441 if (args->precount < 0)
2442 delete_tab(t);
2443 else
2444 TAILQ_FOREACH(tt, &tabs, entry)
2445 if (tt->tab_id == args->precount - 1) {
2446 delete_tab(tt);
2447 break;
2449 break;
2450 case XT_TAB_DELQUIT:
2451 if (gtk_notebook_get_n_pages(notebook) > 1)
2452 delete_tab(t);
2453 else
2454 quit(t, args);
2455 break;
2456 case XT_TAB_OPEN:
2457 if (strlen(url) > 0)
2459 else {
2460 rv = XT_CB_PASSTHROUGH;
2461 goto done;
2463 load_uri(t, url);
2464 break;
2465 case XT_TAB_SHOW:
2466 if (show_tabs == 0) {
2467 show_tabs = 1;
2468 notebook_tab_set_visibility();
2470 break;
2471 case XT_TAB_HIDE:
2472 if (show_tabs == 1) {
2473 show_tabs = 0;
2474 notebook_tab_set_visibility();
2476 break;
2477 case XT_TAB_NEXTSTYLE:
2478 if (tab_style == XT_TABS_NORMAL) {
2479 tab_style = XT_TABS_COMPACT;
2480 recolor_compact_tabs();
2482 else
2483 tab_style = XT_TABS_NORMAL;
2484 notebook_tab_set_visibility();
2485 break;
2486 case XT_TAB_UNDO_CLOSE:
2487 if (undo_count == 0) {
2488 DNPRINTF(XT_D_TAB, "%s: no tabs to undo close",
2489 __func__);
2490 goto done;
2491 } else {
2492 undo_count--;
2493 u = TAILQ_FIRST(&undos);
2494 create_new_tab(u->uri, u, 1, -1);
2496 TAILQ_REMOVE(&undos, u, entry);
2497 g_free(u->uri);
2498 /* u->history is freed in create_new_tab() */
2499 g_free(u);
2501 break;
2502 case XT_TAB_LOAD_IMAGES:
2504 if (!auto_load_images) {
2506 /* Enable auto-load images (this will load all
2507 * previously unloaded images). */
2508 g_object_set(G_OBJECT(t->settings),
2509 "auto-load-images", TRUE, (char *)NULL);
2510 webkit_web_view_set_settings(t->wv, t->settings);
2512 webkit_web_view_reload(t->wv);
2514 /* Webkit triggers an event when we change the setting,
2515 * so we can't disable the auto-loading at once.
2517 * Unfortunately, webkit does not tell us when it's done.
2518 * Instead, we wait until the next request, and then
2519 * disable autoloading again.
2521 t->load_images = TRUE;
2523 break;
2524 default:
2525 rv = XT_CB_PASSTHROUGH;
2526 goto done;
2529 done:
2530 if (args->s) {
2531 g_free(args->s);
2532 args->s = NULL;
2535 return (rv);
2539 resizetab(struct tab *t, struct karg *args)
2541 if (t == NULL || args == NULL) {
2542 show_oops(NULL, "resizetab invalid parameters");
2543 return (XT_CB_PASSTHROUGH);
2546 DNPRINTF(XT_D_TAB, "resizetab: tab %d %d\n",
2547 t->tab_id, args->i);
2549 setzoom_webkit(t, args->i);
2551 return (XT_CB_HANDLED);
2555 movetab(struct tab *t, struct karg *args)
2557 int n, dest;
2559 if (t == NULL || args == NULL) {
2560 show_oops(NULL, "movetab invalid parameters");
2561 return (XT_CB_PASSTHROUGH);
2564 DNPRINTF(XT_D_TAB, "movetab: tab %d opcode %d\n",
2565 t->tab_id, args->i);
2567 if (args->i >= XT_TAB_INVALID)
2568 return (XT_CB_PASSTHROUGH);
2570 if (TAILQ_EMPTY(&tabs))
2571 return (XT_CB_PASSTHROUGH);
2573 n = gtk_notebook_get_n_pages(notebook);
2574 dest = gtk_notebook_get_current_page(notebook);
2576 switch (args->i) {
2577 case XT_TAB_NEXT:
2578 if (args->precount < 0)
2579 dest = dest == n - 1 ? 0 : dest + 1;
2580 else
2581 dest = args->precount - 1;
2583 break;
2584 case XT_TAB_PREV:
2585 if (args->precount < 0)
2586 dest -= 1;
2587 else
2588 dest -= args->precount % n;
2590 if (dest < 0)
2591 dest += n;
2593 break;
2594 case XT_TAB_FIRST:
2595 dest = 0;
2596 break;
2597 case XT_TAB_LAST:
2598 dest = n - 1;
2599 break;
2600 default:
2601 return (XT_CB_PASSTHROUGH);
2604 if (dest < 0 || dest >= n)
2605 return (XT_CB_PASSTHROUGH);
2606 if (t->tab_id == dest) {
2607 DNPRINTF(XT_D_TAB, "movetab: do nothing\n");
2608 return (XT_CB_HANDLED);
2611 set_current_tab(dest);
2613 return (XT_CB_HANDLED);
2616 int cmd_prefix = 0;
2620 command(struct tab *t, struct karg *args)
2622 char *s = NULL, *ss = NULL;
2623 gchar *text, *base;
2624 const gchar *uri;
2625 struct karg a;
2627 if (t == NULL || args == NULL) {
2628 show_oops(NULL, "command invalid parameters");
2629 return (XT_CB_PASSTHROUGH);
2632 switch (args->i) {
2633 case '/':
2634 s = "/";
2635 break;
2636 case '?':
2637 s = "?";
2638 break;
2639 case ':':
2640 if (cmd_prefix == 0)
2641 s = ":";
2642 else {
2643 ss = g_strdup_printf(":%d", cmd_prefix);
2644 s = ss;
2645 cmd_prefix = 0;
2647 break;
2648 case '.':
2649 t->mode = XT_MODE_HINT;
2650 bzero(&a, sizeof a);
2651 a.i = 0;
2652 hint(t, &a);
2653 s = ".";
2654 break;
2655 case ',':
2656 t->mode = XT_MODE_HINT;
2657 bzero(&a, sizeof a);
2658 a.i = XT_HINT_NEWTAB;
2659 hint(t, &a);
2660 s = ",";
2661 break;
2662 case XT_CMD_OPEN:
2663 s = ":open ";
2664 break;
2665 case XT_CMD_TABNEW:
2666 s = ":tabnew ";
2667 break;
2668 case XT_CMD_OPEN_CURRENT:
2669 s = ":open ";
2670 /* FALL THROUGH */
2671 case XT_CMD_TABNEW_CURRENT:
2672 if (!s) /* FALL THROUGH? */
2673 s = ":tabnew ";
2674 if ((uri = get_uri(t)) != NULL) {
2675 ss = g_strdup_printf("%s%s", s, uri);
2676 s = ss;
2678 break;
2679 default:
2680 show_oops(t, "command: invalid opcode %d", args->i);
2681 return (XT_CB_PASSTHROUGH);
2684 DNPRINTF(XT_D_CMD, "%s: tab %d type %s\n", __func__, t->tab_id, s);
2686 gtk_entry_set_text(GTK_ENTRY(t->cmd), s);
2687 text = gdk_color_to_string(&t->default_style->text[GTK_STATE_NORMAL]);
2688 base = gdk_color_to_string(&t->default_style->base[GTK_STATE_NORMAL]);
2689 gtk_widget_modify_base(t->cmd, GTK_STATE_NORMAL,
2690 &t->default_style->base[GTK_STATE_NORMAL]);
2691 statusbar_modify_attr(t, text, base);
2692 g_free(text);
2693 g_free(base);
2694 show_cmd(t);
2695 gtk_widget_grab_focus(GTK_WIDGET(t->cmd));
2696 gtk_editable_set_position(GTK_EDITABLE(t->cmd), -1);
2698 if (ss)
2699 g_free(ss);
2701 return (XT_CB_HANDLED);
2705 search(struct tab *t, struct karg *args)
2707 gboolean d;
2709 if (t == NULL || args == NULL) {
2710 show_oops(NULL, "search invalid parameters");
2711 return (1);
2714 switch (args->i) {
2715 case XT_SEARCH_NEXT:
2716 d = t->search_forward;
2717 break;
2718 case XT_SEARCH_PREV:
2719 d = !t->search_forward;
2720 break;
2721 default:
2722 return (XT_CB_PASSTHROUGH);
2725 if (t->search_text == NULL) {
2726 if (global_search == NULL)
2727 return (XT_CB_PASSTHROUGH);
2728 else {
2729 d = t->search_forward = TRUE;
2730 t->search_text = g_strdup(global_search);
2731 webkit_web_view_mark_text_matches(t->wv, global_search, FALSE, 0);
2732 webkit_web_view_set_highlight_text_matches(t->wv, TRUE);
2736 DNPRINTF(XT_D_CMD, "search: tab %d opc %d forw %d text %s\n",
2737 t->tab_id, args->i, t->search_forward, t->search_text);
2739 webkit_web_view_search_text(t->wv, t->search_text, FALSE, d, TRUE);
2741 return (XT_CB_HANDLED);
2745 session_save(struct tab *t, char *filename)
2747 struct karg a;
2748 int rv = 1;
2749 struct session *s;
2751 if (strlen(filename) == 0)
2752 goto done;
2754 if (filename[0] == '.' || filename[0] == '/')
2755 goto done;
2757 a.s = filename;
2758 if (save_tabs(t, &a))
2759 goto done;
2760 strlcpy(named_session, filename, sizeof named_session);
2762 /* add the new session to the list of sessions */
2763 s = g_malloc(sizeof(struct session));
2764 s->name = g_strdup(filename);
2765 TAILQ_INSERT_TAIL(&sessions, s, entry);
2767 rv = 0;
2768 done:
2769 return (rv);
2773 session_open(struct tab *t, char *filename)
2775 struct karg a;
2776 int rv = 1;
2778 if (strlen(filename) == 0)
2779 goto done;
2781 if (filename[0] == '.' || filename[0] == '/')
2782 goto done;
2784 a.s = filename;
2785 a.i = XT_SES_CLOSETABS;
2786 if (open_tabs(t, &a))
2787 goto done;
2789 strlcpy(named_session, filename, sizeof named_session);
2791 rv = 0;
2792 done:
2793 return (rv);
2797 session_delete(struct tab *t, char *filename)
2799 char file[PATH_MAX];
2800 int rv = 1;
2801 struct session *s;
2803 if (strlen(filename) == 0)
2804 goto done;
2806 if (filename[0] == '.' || filename[0] == '/')
2807 goto done;
2809 snprintf(file, sizeof file, "%s" PS "%s", sessions_dir, filename);
2810 if (unlink(file))
2811 goto done;
2813 if (!strcmp(filename, named_session))
2814 strlcpy(named_session, XT_SAVED_TABS_FILE,
2815 sizeof named_session);
2817 /* remove session from sessions list */
2818 TAILQ_FOREACH(s, &sessions, entry) {
2819 if (!strcmp(s->name, filename))
2820 break;
2822 if (s == NULL)
2823 goto done;
2824 TAILQ_REMOVE(&sessions, s, entry);
2825 g_free((gpointer) s->name);
2826 g_free(s);
2828 rv = 0;
2829 done:
2830 return (rv);
2834 session_cmd(struct tab *t, struct karg *args)
2836 char *filename = args->s;
2838 if (t == NULL)
2839 return (1);
2841 if (args->i & XT_SHOW)
2842 show_oops(t, "Current session: %s", named_session[0] == '\0' ?
2843 XT_SAVED_TABS_FILE : named_session);
2844 else if (args->i & XT_SAVE) {
2845 if (session_save(t, filename)) {
2846 show_oops(t, "Can't save session: %s",
2847 filename ? filename : "INVALID");
2848 goto done;
2850 } else if (args->i & XT_OPEN) {
2851 if (session_open(t, filename)) {
2852 show_oops(t, "Can't open session: %s",
2853 filename ? filename : "INVALID");
2854 goto done;
2856 } else if (args->i & XT_DELETE) {
2857 if (session_delete(t, filename)) {
2858 show_oops(t, "Can't delete session: %s",
2859 filename ? filename : "INVALID");
2860 goto done;
2863 done:
2864 return (XT_CB_PASSTHROUGH);
2868 script_cmd(struct tab *t, struct karg *args)
2870 struct stat sb;
2871 FILE *f = NULL;
2872 char *buf = NULL;
2874 if (t == NULL)
2875 goto done;
2877 if ((f = fopen(args->s, "r")) == NULL) {
2878 show_oops(t, "Can't open script file: %s", args->s);
2879 goto done;
2882 if (fstat(fileno(f), &sb) == -1) {
2883 show_oops(t, "Can't stat script file: %s", args->s);
2884 goto done;
2887 buf = g_malloc0(sb.st_size + 1);
2888 if (fread(buf, 1, sb.st_size, f) != sb.st_size) {
2889 show_oops(t, "Can't read script file: %s", args->s);
2890 goto done;
2893 DNPRINTF(XT_D_JS, "%s: about to run script\n", __func__);
2894 run_script(t, buf);
2896 done:
2897 if (f)
2898 fclose(f);
2899 if (buf)
2900 g_free(buf);
2902 return (XT_CB_PASSTHROUGH);
2906 * Make a hardcopy of the page
2909 print_page(struct tab *t, struct karg *args)
2911 WebKitWebFrame *frame;
2912 GtkPageSetup *ps;
2913 GtkPrintOperation *op;
2914 GtkPrintOperationAction action;
2915 GtkPrintOperationResult print_res;
2916 GError *g_err = NULL;
2917 int marg_l, marg_r, marg_t, marg_b;
2919 DNPRINTF(XT_D_PRINTING, "%s:", __func__);
2921 ps = gtk_page_setup_new();
2922 op = gtk_print_operation_new();
2923 action = GTK_PRINT_OPERATION_ACTION_PRINT_DIALOG;
2924 frame = webkit_web_view_get_main_frame(t->wv);
2926 /* the default margins are too small, so we will bump them */
2927 marg_l = gtk_page_setup_get_left_margin(ps, GTK_UNIT_MM) +
2928 XT_PRINT_EXTRA_MARGIN;
2929 marg_r = gtk_page_setup_get_right_margin(ps, GTK_UNIT_MM) +
2930 XT_PRINT_EXTRA_MARGIN;
2931 marg_t = gtk_page_setup_get_top_margin(ps, GTK_UNIT_MM) +
2932 XT_PRINT_EXTRA_MARGIN;
2933 marg_b = gtk_page_setup_get_bottom_margin(ps, GTK_UNIT_MM) +
2934 XT_PRINT_EXTRA_MARGIN;
2936 /* set margins */
2937 gtk_page_setup_set_left_margin(ps, marg_l, GTK_UNIT_MM);
2938 gtk_page_setup_set_right_margin(ps, marg_r, GTK_UNIT_MM);
2939 gtk_page_setup_set_top_margin(ps, marg_t, GTK_UNIT_MM);
2940 gtk_page_setup_set_bottom_margin(ps, marg_b, GTK_UNIT_MM);
2942 gtk_print_operation_set_default_page_setup(op, ps);
2944 /* this appears to free 'op' and 'ps' */
2945 print_res = webkit_web_frame_print_full(frame, op, action, &g_err);
2947 /* check it worked */
2948 if (print_res == GTK_PRINT_OPERATION_RESULT_ERROR) {
2949 show_oops(NULL, "can't print: %s", g_err->message);
2950 g_error_free (g_err);
2951 return (1);
2954 return (0);
2958 go_home(struct tab *t, struct karg *args)
2960 load_uri(t, home);
2961 return (0);
2965 set_encoding(struct tab *t, struct karg *args)
2967 const gchar *e;
2969 if (args->s && strlen(g_strstrip(args->s)) == 0) {
2970 e = webkit_web_view_get_custom_encoding(t->wv);
2971 if (e == NULL)
2972 e = webkit_web_view_get_encoding(t->wv);
2973 show_oops(t, "encoding: %s", e ? e : "N/A");
2974 } else
2975 webkit_web_view_set_custom_encoding(t->wv, args->s);
2977 return (0);
2981 restart(struct tab *t, struct karg *args)
2983 struct karg a;
2985 a.s = XT_RESTART_TABS_FILE;
2986 save_tabs(t, &a);
2987 execvp(start_argv[0], start_argv);
2988 /* NOTREACHED */
2990 return (0);
2993 char *http_proxy_save; /* not a setting, used to toggle */
2996 proxy_cmd(struct tab *t, struct karg *args)
2998 DNPRINTF(XT_D_CMD, "%s: tab %d\n", __func__, t->tab_id);
3000 if (t == NULL)
3001 return (1);
3003 /* setup */
3004 if (http_proxy) {
3005 if (http_proxy_save)
3006 g_free(http_proxy_save);
3007 http_proxy_save = g_strdup(http_proxy);
3010 if (args->i & XT_PRXY_SHOW) {
3011 if (http_proxy)
3012 show_oops(t, "http_proxy = %s", http_proxy);
3013 else
3014 show_oops(t, "proxy is currently disabled");
3015 } else if (args->i & XT_PRXY_TOGGLE) {
3016 if (http_proxy_save == NULL && http_proxy == NULL) {
3017 show_oops(t, "can't toggle proxy");
3018 goto done;
3020 if (http_proxy)
3021 setup_proxy(NULL);
3022 else
3023 setup_proxy(http_proxy_save);
3025 done:
3026 return (XT_CB_PASSTHROUGH);
3028 struct cmd {
3029 char *cmd;
3030 int level;
3031 int (*func)(struct tab *, struct karg *);
3032 int arg;
3033 int type;
3034 } cmds[] = {
3035 { "command_mode", 0, command_mode, XT_MODE_COMMAND, 0 },
3036 { "insert_mode", 0, command_mode, XT_MODE_INSERT, 0 },
3037 { "command", 0, command, ':', 0 },
3038 { "search", 0, command, '/', 0 },
3039 { "searchb", 0, command, '?', 0 },
3040 { "hinting", 0, command, '.', 0 },
3041 { "hinting_newtab", 0, command, ',', 0 },
3042 { "togglesrc", 0, toggle_src, 0, 0 },
3043 { "editsrc", 0, edit_src, 0, 0 },
3044 { "editelement", 0, edit_element, 0, 0 },
3045 { "passthrough", 0, passthrough, 0, 0 },
3046 { "modurl", 0, modurl, 0, 0 },
3048 /* yanking and pasting */
3049 { "yankuri", 0, yank_uri, 0, 0 },
3050 /* XXX: pasteuri{cur,new} do not work from the cmd_entry? */
3051 { "pasteuricur", 0, paste_uri, XT_PASTE_CURRENT_TAB, 0 },
3052 { "pasteurinew", 0, paste_uri, XT_PASTE_NEW_TAB, 0 },
3054 /* search */
3055 { "searchnext", 0, search, XT_SEARCH_NEXT, 0 },
3056 { "searchprevious", 0, search, XT_SEARCH_PREV, 0 },
3058 /* focus */
3059 { "focusaddress", 0, focus, XT_FOCUS_URI, 0 },
3060 { "focussearch", 0, focus, XT_FOCUS_SEARCH, 0 },
3062 /* hinting */
3063 { "hinting", 0, hint, 0, 0 },
3064 { "hinting_newtab", 0, hint, XT_HINT_NEWTAB, 0 },
3066 /* custom stylesheet */
3067 { "userstyle", 0, userstyle, XT_STYLE_CURRENT_TAB, 0 },
3068 { "userstyle_global", 0, userstyle, XT_STYLE_GLOBAL, 0 },
3070 /* navigation */
3071 { "goback", 0, navaction, XT_NAV_BACK, 0 },
3072 { "goforward", 0, navaction, XT_NAV_FORWARD, 0 },
3073 { "reload", 0, navaction, XT_NAV_RELOAD, 0 },
3074 { "stop", 0, navaction, XT_NAV_STOP, 0 },
3076 /* vertical movement */
3077 { "scrolldown", 0, move, XT_MOVE_DOWN, 0 },
3078 { "scrollup", 0, move, XT_MOVE_UP, 0 },
3079 { "scrollbottom", 0, move, XT_MOVE_BOTTOM, 0 },
3080 { "scrolltop", 0, move, XT_MOVE_TOP, 0 },
3081 { "1", 0, move, XT_MOVE_TOP, 0 },
3082 { "scrollhalfdown", 0, move, XT_MOVE_HALFDOWN, 0 },
3083 { "scrollhalfup", 0, move, XT_MOVE_HALFUP, 0 },
3084 { "scrollpagedown", 0, move, XT_MOVE_PAGEDOWN, 0 },
3085 { "scrollpageup", 0, move, XT_MOVE_PAGEUP, 0 },
3086 /* horizontal movement */
3087 { "scrollright", 0, move, XT_MOVE_RIGHT, 0 },
3088 { "scrollleft", 0, move, XT_MOVE_LEFT, 0 },
3089 { "scrollfarright", 0, move, XT_MOVE_FARRIGHT, 0 },
3090 { "scrollfarleft", 0, move, XT_MOVE_FARLEFT, 0 },
3092 { "favorites", 0, xtp_page_fl, 0, 0 },
3093 { "fav", 0, xtp_page_fl, 0, 0 },
3094 { "favadd", 0, add_favorite, 0, 0 },
3096 { "qall", 0, quit, 0, 0 },
3097 { "quitall", 0, quit, 0, 0 },
3098 { "w", 0, save_tabs, 0, 0 },
3099 { "wq", 0, save_tabs_and_quit, 0, 0 },
3100 { "help", 0, help, 0, 0 },
3101 { "about", 0, about, 0, 0 },
3102 { "stats", 0, stats, 0, 0 },
3103 { "version", 0, about, 0, 0 },
3105 /* js command */
3106 { "js", 0, js_cmd, XT_SHOW | XT_WL_PERSISTENT | XT_WL_SESSION, 0 },
3107 { "save", 1, js_cmd, XT_SAVE | XT_WL_FQDN, 0 },
3108 { "domain", 2, js_cmd, XT_SAVE | XT_WL_TOPLEVEL, 0 },
3109 { "fqdn", 2, js_cmd, XT_SAVE | XT_WL_FQDN, 0 },
3110 { "show", 1, js_cmd, XT_SHOW | XT_WL_PERSISTENT | XT_WL_SESSION, 0 },
3111 { "all", 2, js_cmd, XT_SHOW | XT_WL_PERSISTENT | XT_WL_SESSION, 0 },
3112 { "persistent", 2, js_cmd, XT_SHOW | XT_WL_PERSISTENT, 0 },
3113 { "session", 2, js_cmd, XT_SHOW | XT_WL_SESSION, 0 },
3114 { "toggle", 1, js_cmd, XT_WL_TOGGLE | XT_WL_FQDN, 0 },
3115 { "domain", 2, js_cmd, XT_WL_TOGGLE | XT_WL_TOPLEVEL, 0 },
3116 { "fqdn", 2, js_cmd, XT_WL_TOGGLE | XT_WL_FQDN, 0 },
3118 /* cookie command */
3119 { "cookie", 0, cookie_cmd, XT_SHOW | XT_WL_PERSISTENT | XT_WL_SESSION, 0 },
3120 { "save", 1, cookie_cmd, XT_SAVE | XT_WL_FQDN, 0 },
3121 { "domain", 2, cookie_cmd, XT_SAVE | XT_WL_TOPLEVEL, 0 },
3122 { "fqdn", 2, cookie_cmd, XT_SAVE | XT_WL_FQDN, 0 },
3123 { "show", 1, cookie_cmd, XT_SHOW | XT_WL_PERSISTENT | XT_WL_SESSION, 0 },
3124 { "all", 2, cookie_cmd, XT_SHOW | XT_WL_PERSISTENT | XT_WL_SESSION, 0 },
3125 { "persistent", 2, cookie_cmd, XT_SHOW | XT_WL_PERSISTENT, 0 },
3126 { "session", 2, cookie_cmd, XT_SHOW | XT_WL_SESSION, 0 },
3127 { "toggle", 1, cookie_cmd, XT_WL_TOGGLE | XT_WL_FQDN, 0 },
3128 { "domain", 2, cookie_cmd, XT_WL_TOGGLE | XT_WL_TOPLEVEL, 0 },
3129 { "fqdn", 2, cookie_cmd, XT_WL_TOGGLE | XT_WL_FQDN, 0 },
3130 { "purge", 1, cookie_cmd, XT_DELETE, 0 },
3132 /* plugin command */
3133 { "plugin", 0, pl_cmd, XT_SHOW | XT_WL_PERSISTENT | XT_WL_SESSION, 0 },
3134 { "save", 1, pl_cmd, XT_SAVE | XT_WL_FQDN, 0 },
3135 { "domain", 2, pl_cmd, XT_SAVE | XT_WL_TOPLEVEL, 0 },
3136 { "fqdn", 2, pl_cmd, XT_SAVE | XT_WL_FQDN, 0 },
3137 { "show", 1, pl_cmd, XT_SHOW | XT_WL_PERSISTENT | XT_WL_SESSION, 0 },
3138 { "all", 2, pl_cmd, XT_SHOW | XT_WL_PERSISTENT | XT_WL_SESSION, 0 },
3139 { "persistent", 2, pl_cmd, XT_SHOW | XT_WL_PERSISTENT, 0 },
3140 { "session", 2, pl_cmd, XT_SHOW | XT_WL_SESSION, 0 },
3141 { "toggle", 1, pl_cmd, XT_WL_TOGGLE | XT_WL_FQDN, 0 },
3142 { "domain", 2, pl_cmd, XT_WL_TOGGLE | XT_WL_TOPLEVEL, 0 },
3143 { "fqdn", 2, pl_cmd, XT_WL_TOGGLE | XT_WL_FQDN, 0 },
3145 /* toplevel (domain) command */
3146 { "toplevel", 0, toplevel_cmd, XT_WL_TOGGLE | XT_WL_TOPLEVEL | XT_WL_RELOAD, 0 },
3147 { "toggle", 1, toplevel_cmd, XT_WL_TOGGLE | XT_WL_TOPLEVEL | XT_WL_RELOAD, 0 },
3149 /* cookie jar */
3150 { "cookiejar", 0, xtp_page_cl, 0, 0 },
3152 /* cert command */
3153 { "cert", 0, cert_cmd, XT_SHOW, 0 },
3154 { "save", 1, cert_cmd, XT_SAVE, 0 },
3155 { "show", 1, cert_cmd, XT_SHOW, 0 },
3157 { "ca", 0, ca_cmd, 0, 0 },
3158 { "downloadmgr", 0, xtp_page_dl, 0, 0 },
3159 { "dl", 0, xtp_page_dl, 0, 0 },
3160 { "h", 0, xtp_page_hl, 0, 0 },
3161 { "history", 0, xtp_page_hl, 0, 0 },
3162 { "home", 0, go_home, 0, 0 },
3163 { "restart", 0, restart, 0, 0 },
3164 { "urlhide", 0, urlaction, XT_URL_HIDE, 0 },
3165 { "urlshow", 0, urlaction, XT_URL_SHOW, 0 },
3166 { "statustoggle", 0, statustoggle, 0, 0 },
3167 { "run_script", 0, run_page_script, 0, XT_USERARG },
3169 { "print", 0, print_page, 0, 0 },
3171 /* tabs */
3172 { "focusin", 0, resizetab, XT_ZOOM_IN, 0 },
3173 { "focusout", 0, resizetab, XT_ZOOM_OUT, 0 },
3174 { "focusreset", 0, resizetab, XT_ZOOM_NORMAL, 0 },
3175 { "q", 0, tabaction, XT_TAB_DELQUIT, 0 },
3176 { "quit", 0, tabaction, XT_TAB_DELQUIT, 0 },
3177 { "open", 0, tabaction, XT_TAB_OPEN, XT_URLARG },
3178 { "tabclose", 0, tabaction, XT_TAB_DELETE, XT_PREFIX | XT_INTARG},
3179 { "tabedit", 0, tabaction, XT_TAB_NEW, XT_PREFIX | XT_URLARG },
3180 { "tabfirst", 0, movetab, XT_TAB_FIRST, 0 },
3181 { "tabhide", 0, tabaction, XT_TAB_HIDE, 0 },
3182 { "tablast", 0, movetab, XT_TAB_LAST, 0 },
3183 { "tabnew", 0, tabaction, XT_TAB_NEW, XT_PREFIX | XT_URLARG },
3184 { "tabnext", 0, movetab, XT_TAB_NEXT, XT_PREFIX | XT_INTARG},
3185 { "tabnextstyle", 0, tabaction, XT_TAB_NEXTSTYLE, 0 },
3186 { "tabprevious", 0, movetab, XT_TAB_PREV, XT_PREFIX | XT_INTARG},
3187 { "tabrewind", 0, movetab, XT_TAB_FIRST, 0 },
3188 { "tabshow", 0, tabaction, XT_TAB_SHOW, 0 },
3189 { "tabs", 0, buffers, 0, 0 },
3190 { "tabundoclose", 0, tabaction, XT_TAB_UNDO_CLOSE, 0 },
3191 { "buffers", 0, buffers, 0, 0 },
3192 { "ls", 0, buffers, 0, 0 },
3193 { "encoding", 0, set_encoding, 0, XT_USERARG },
3194 { "loadimages", 0, tabaction, XT_TAB_LOAD_IMAGES, 0 },
3196 /* command aliases (handy when -S flag is used) */
3197 { "promptopen", 0, command, XT_CMD_OPEN, 0 },
3198 { "promptopencurrent", 0, command, XT_CMD_OPEN_CURRENT, 0 },
3199 { "prompttabnew", 0, command, XT_CMD_TABNEW, 0 },
3200 { "prompttabnewcurrent",0, command, XT_CMD_TABNEW_CURRENT, 0 },
3202 /* settings */
3203 { "set", 0, set, 0, XT_SETARG },
3205 { "fullscreen", 0, fullscreen, 0, 0 },
3206 { "f", 0, fullscreen, 0, 0 },
3208 /* sessions */
3209 { "session", 0, session_cmd, XT_SHOW, 0 },
3210 { "delete", 1, session_cmd, XT_DELETE, XT_SESSARG },
3211 { "open", 1, session_cmd, XT_OPEN, XT_SESSARG },
3212 { "save", 1, session_cmd, XT_SAVE, XT_USERARG },
3213 { "show", 1, session_cmd, XT_SHOW, 0 },
3215 /* external javascript */
3216 { "script", 0, script_cmd, XT_EJS_SHOW, XT_USERARG },
3218 /* inspector */
3219 { "inspector", 0, inspector_cmd, XT_INS_SHOW, 0 },
3220 { "show", 1, inspector_cmd, XT_INS_SHOW, 0 },
3221 { "hide", 1, inspector_cmd, XT_INS_HIDE, 0 },
3223 /* proxy */
3224 { "proxy", 0, proxy_cmd, XT_PRXY_SHOW, 0 },
3225 { "show", 1, proxy_cmd, XT_PRXY_SHOW, 0 },
3226 { "toggle", 1, proxy_cmd, XT_PRXY_TOGGLE, 0 },
3229 struct {
3230 int index;
3231 int len;
3232 gchar *list[256];
3233 } cmd_status = {-1, 0};
3235 gboolean
3236 wv_release_button_cb(GtkWidget *btn, GdkEventButton *e, struct tab *t)
3239 if (e->type == GDK_BUTTON_RELEASE && e->button == 1)
3240 btn_down = 0;
3242 return (FALSE);
3245 gboolean
3246 wv_button_cb(GtkWidget *btn, GdkEventButton *e, struct tab *t)
3248 struct karg a;
3249 WebKitHitTestResult *hit_test_result;
3250 guint context;
3252 hit_test_result = webkit_web_view_get_hit_test_result(t->wv, e);
3253 g_object_get(hit_test_result, "context", &context, NULL);
3255 hide_oops(t);
3256 hide_buffers(t);
3258 if (context & WEBKIT_HIT_TEST_RESULT_CONTEXT_EDITABLE)
3259 t->mode = XT_MODE_INSERT;
3260 else
3261 t->mode = XT_MODE_COMMAND;
3263 if (e->type == GDK_BUTTON_PRESS && e->button == 1)
3264 btn_down = 1;
3265 else if (e->type == GDK_BUTTON_PRESS && e->button == 8 /* btn 4 */) {
3266 /* go backward */
3267 a.i = XT_NAV_BACK;
3268 navaction(t, &a);
3270 return (TRUE);
3271 } else if (e->type == GDK_BUTTON_PRESS && e->button == 9 /* btn 5 */) {
3272 /* go forward */
3273 a.i = XT_NAV_FORWARD;
3274 navaction(t, &a);
3276 return (TRUE);
3279 return (FALSE);
3282 gboolean
3283 tab_close_cb(GtkWidget *btn, GdkEventButton *e, struct tab *t)
3285 DNPRINTF(XT_D_TAB, "tab_close_cb: tab %d\n", t->tab_id);
3287 if (e->type == GDK_BUTTON_PRESS && e->button == 1)
3288 delete_tab(t);
3290 return (FALSE);
3295 void
3296 activate_uri_entry_cb(GtkWidget* entry, struct tab *t)
3298 const gchar *uri = gtk_entry_get_text(GTK_ENTRY(entry));
3300 DNPRINTF(XT_D_URL, "activate_uri_entry_cb: %s\n", uri);
3302 if (t == NULL) {
3303 show_oops(NULL, "activate_uri_entry_cb invalid parameters");
3304 return;
3307 if (uri == NULL) {
3308 show_oops(t, "activate_uri_entry_cb no uri");
3309 return;
3312 uri += strspn(uri, "\t ");
3314 /* if xxxt:// treat specially */
3315 if (parse_xtp_url(t, uri))
3316 return;
3318 /* otherwise continue to load page normally */
3319 load_uri(t, (gchar *)uri);
3320 focus_webview(t);
3323 void
3324 activate_search_entry_cb(GtkWidget* entry, struct tab *t)
3326 const gchar *search = gtk_entry_get_text(GTK_ENTRY(entry));
3327 char *newuri = NULL;
3328 gchar *enc_search;
3330 DNPRINTF(XT_D_URL, "activate_search_entry_cb: %s\n", search);
3332 if (t == NULL) {
3333 show_oops(NULL, "activate_search_entry_cb invalid parameters");
3334 return;
3337 if (search_string == NULL || strlen(search_string) == 0) {
3338 show_oops(t, "no search_string");
3339 return;
3342 t->xtp_meaning = XT_XTP_TAB_MEANING_NORMAL;
3344 enc_search = soup_uri_encode(search, XT_RESERVED_CHARS);
3345 newuri = g_strdup_printf(search_string, enc_search);
3346 g_free(enc_search);
3348 marks_clear(t);
3349 load_uri(t, newuri);
3350 focus_webview(t);
3352 if (newuri)
3353 g_free(newuri);
3356 void
3357 check_and_set_cookie(const gchar *uri, struct tab *t)
3359 struct domain *d = NULL;
3360 int es = 0;
3362 if (uri == NULL || t == NULL)
3363 return;
3365 if ((d = wl_find_uri(uri, &c_wl)) == NULL)
3366 es = 0;
3367 else
3368 es = 1;
3370 DNPRINTF(XT_D_COOKIE, "check_and_set_cookie: %s %s\n",
3371 es ? "enable" : "disable", uri);
3373 g_object_set(G_OBJECT(t->settings),
3374 "enable-html5-local-storage", es, (char *)NULL);
3375 webkit_web_view_set_settings(t->wv, t->settings);
3378 void
3379 check_and_set_js(const gchar *uri, struct tab *t)
3381 struct domain *d = NULL;
3382 int es = 0;
3384 if (uri == NULL || t == NULL)
3385 return;
3387 if ((d = wl_find_uri(uri, &js_wl)) == NULL)
3388 es = 0;
3389 else
3390 es = 1;
3392 DNPRINTF(XT_D_JS, "check_and_set_js: %s %s\n",
3393 es ? "enable" : "disable", uri);
3395 g_object_set(G_OBJECT(t->settings),
3396 "enable-scripts", es, (char *)NULL);
3397 g_object_set(G_OBJECT(t->settings),
3398 "javascript-can-open-windows-automatically", es, (char *)NULL);
3399 webkit_web_view_set_settings(t->wv, t->settings);
3401 button_set_stockid(t->js_toggle,
3402 es ? GTK_STOCK_MEDIA_PLAY : GTK_STOCK_MEDIA_PAUSE);
3405 void
3406 check_and_set_pl(const gchar *uri, struct tab *t)
3408 struct domain *d = NULL;
3409 int es = 0;
3411 if (uri == NULL || t == NULL)
3412 return;
3414 if ((d = wl_find_uri(uri, &pl_wl)) == NULL)
3415 es = 0;
3416 else
3417 es = 1;
3419 DNPRINTF(XT_D_JS, "check_and_set_pl: %s %s\n",
3420 es ? "enable" : "disable", uri);
3422 g_object_set(G_OBJECT(t->settings),
3423 "enable-plugins", es, (char *)NULL);
3424 webkit_web_view_set_settings(t->wv, t->settings);
3427 void
3428 color_address_bar(gpointer p)
3430 GdkColor color;
3431 struct tab *tt, *t = p;
3432 gchar *col_str = XT_COLOR_WHITE, *text, *base;
3433 const gchar *uri, *u = NULL, *error_str = NULL;
3435 #ifdef USE_THREADS
3436 gdk_threads_enter();
3437 #endif
3438 DNPRINTF(XT_D_URL, "%s:\n", __func__);
3440 /* make sure t still exists */
3441 if (t == NULL)
3442 goto done;
3443 TAILQ_FOREACH(tt, &tabs, entry)
3444 if (t == tt)
3445 break;
3446 if (t != tt)
3447 goto done;
3449 if ((uri = get_uri(t)) == NULL)
3450 goto white;
3451 u = g_strdup(uri);
3453 #ifdef USE_THREADS
3454 GDK_FLUSH();
3455 gdk_threads_leave();
3456 #endif
3458 col_str = XT_COLOR_YELLOW;
3459 switch (load_compare_cert(u, &error_str)) {
3460 case CERT_LOCAL:
3461 col_str = XT_COLOR_BLUE;
3462 break;
3463 case CERT_TRUSTED:
3464 col_str = XT_COLOR_GREEN;
3465 break;
3466 case CERT_UNTRUSTED:
3467 col_str = XT_COLOR_YELLOW;
3468 break;
3469 case CERT_BAD:
3470 col_str = XT_COLOR_RED;
3471 break;
3474 #ifdef USE_THREADS
3475 gdk_threads_enter();
3476 #endif
3477 /* make sure t isn't deleted */
3478 TAILQ_FOREACH(tt, &tabs, entry)
3479 if (t == tt)
3480 break;
3481 if (t != tt)
3482 goto done;
3484 #ifdef USE_THREADS
3485 /* test to see if the user navigated away and canceled the thread */
3486 if (t->thread != g_thread_self())
3487 goto done;
3488 if ((uri = get_uri(t)) == NULL) {
3489 t->thread = NULL;
3490 goto done;
3492 if (strcmp(uri, u)) {
3493 /* make sure we are still the same url */
3494 t->thread = NULL;
3495 goto done;
3497 #endif
3498 white:
3500 if (!strcmp(col_str, XT_COLOR_WHITE)) {
3501 text = gdk_color_to_string(
3502 &t->default_style->text[GTK_STATE_NORMAL]);
3503 base = gdk_color_to_string(
3504 &t->default_style->base[GTK_STATE_NORMAL]);
3505 gtk_widget_modify_base(t->uri_entry, GTK_STATE_NORMAL,
3506 &t->default_style->base[GTK_STATE_NORMAL]);
3507 statusbar_modify_attr(t, text, base);
3508 g_free(text);
3509 g_free(base);
3510 } else {
3511 gdk_color_parse(col_str, &color);
3512 gtk_widget_modify_base(t->uri_entry, GTK_STATE_NORMAL, &color);
3513 statusbar_modify_attr(t, XT_COLOR_BLACK, col_str);
3516 if (error_str && error_str[0] != '\0')
3517 show_oops(t, "%s", error_str);
3518 #ifdef USE_THREADS
3519 t->thread = NULL;
3520 #endif
3521 done:
3522 /* t is invalid at this point */
3523 if (u)
3524 g_free((gpointer)u);
3525 #ifdef USE_THREADS
3526 GDK_FLUSH();
3527 gdk_threads_leave();
3528 #endif
3531 void
3532 show_ca_status(struct tab *t, const char *uri)
3534 GdkColor color;
3535 gchar *col_str = XT_COLOR_WHITE, *text, *base;
3537 DNPRINTF(XT_D_URL, "show_ca_status: %d %s %s\n",
3538 ssl_strict_certs, ssl_ca_file, uri);
3540 if (t == NULL)
3541 return;
3543 if (uri == NULL)
3544 goto done;
3545 if (ssl_ca_file == NULL) {
3546 if (g_str_has_prefix(uri, "http://"))
3547 goto done;
3548 if (g_str_has_prefix(uri, "https://")) {
3549 col_str = XT_COLOR_RED;
3550 goto done;
3552 return;
3554 if (g_str_has_prefix(uri, "http://") ||
3555 !g_str_has_prefix(uri, "https://"))
3556 goto done;
3557 #ifdef USE_THREADS
3559 * It is not necessary to see if the thread is already running.
3560 * If the thread is in progress setting it to something else aborts it
3561 * on the way out.
3564 /* thread the coloring of the address bar */
3565 t->thread = g_thread_create((GThreadFunc)color_address_bar, t, TRUE, NULL);
3566 #else
3567 color_address_bar(t);
3568 #endif
3569 return;
3571 done:
3572 if (col_str) {
3574 if (!strcmp(col_str, XT_COLOR_WHITE)) {
3575 text = gdk_color_to_string(
3576 &t->default_style->text[GTK_STATE_NORMAL]);
3577 base = gdk_color_to_string(
3578 &t->default_style->base[GTK_STATE_NORMAL]);
3579 gtk_widget_modify_base(t->uri_entry, GTK_STATE_NORMAL,
3580 &t->default_style->base[GTK_STATE_NORMAL]);
3581 statusbar_modify_attr(t, text, base);
3582 g_free(text);
3583 g_free(base);
3584 } else {
3585 gdk_color_parse(col_str, &color);
3586 gtk_widget_modify_base(t->uri_entry, GTK_STATE_NORMAL, &color);
3587 statusbar_modify_attr(t, XT_COLOR_BLACK, col_str);
3592 void
3593 free_favicon(struct tab *t)
3595 DNPRINTF(XT_D_DOWNLOAD, "%s: down %p req %p\n",
3596 __func__, t->icon_download, t->icon_request);
3598 if (t->icon_request)
3599 g_object_unref(t->icon_request);
3600 if (t->icon_dest_uri)
3601 g_free(t->icon_dest_uri);
3603 t->icon_request = NULL;
3604 t->icon_dest_uri = NULL;
3607 void
3608 xt_icon_from_name(struct tab *t, gchar *name)
3610 if (!enable_favicon_entry)
3611 return;
3613 gtk_entry_set_icon_from_icon_name(GTK_ENTRY(t->uri_entry),
3614 GTK_ENTRY_ICON_PRIMARY, "text-html");
3615 if (show_url == 0)
3616 gtk_entry_set_icon_from_icon_name(GTK_ENTRY(t->sbe.statusbar),
3617 GTK_ENTRY_ICON_PRIMARY, "text-html");
3618 else
3619 gtk_entry_set_icon_from_icon_name(GTK_ENTRY(t->sbe.statusbar),
3620 GTK_ENTRY_ICON_PRIMARY, NULL);
3623 void
3624 xt_icon_from_pixbuf(struct tab *t, GdkPixbuf *pb)
3626 GdkPixbuf *pb_scaled;
3628 if (gdk_pixbuf_get_width(pb) > 16 || gdk_pixbuf_get_height(pb) > 16)
3629 pb_scaled = gdk_pixbuf_scale_simple(pb, 16, 16,
3630 GDK_INTERP_BILINEAR);
3631 else
3632 pb_scaled = pb;
3634 if (enable_favicon_entry) {
3636 /* Classic tabs. */
3637 gtk_entry_set_icon_from_pixbuf(GTK_ENTRY(t->uri_entry),
3638 GTK_ENTRY_ICON_PRIMARY, pb_scaled);
3640 /* Minimal tabs. */
3641 if (show_url == 0) {
3642 gtk_entry_set_icon_from_pixbuf(GTK_ENTRY(t->sbe.statusbar),
3643 GTK_ENTRY_ICON_PRIMARY, pb_scaled);
3644 } else
3645 gtk_entry_set_icon_from_icon_name(GTK_ENTRY(t->sbe.statusbar),
3646 GTK_ENTRY_ICON_PRIMARY, NULL);
3649 /* XXX: Only supports the minimal tabs atm. */
3650 if (enable_favicon_tabs)
3651 gtk_image_set_from_pixbuf(GTK_IMAGE(t->tab_elems.favicon),
3652 pb_scaled);
3654 if (pb_scaled != pb)
3655 g_object_unref(pb_scaled);
3658 void
3659 xt_icon_from_file(struct tab *t, char *file)
3661 GdkPixbuf *pb;
3663 if (g_str_has_prefix(file, "file://"))
3664 file += strlen("file://");
3666 pb = gdk_pixbuf_new_from_file(file, NULL);
3667 if (pb) {
3668 xt_icon_from_pixbuf(t, pb);
3669 g_object_unref(pb);
3670 } else
3671 xt_icon_from_name(t, "text-html");
3674 gboolean
3675 is_valid_icon(char *file)
3677 gboolean valid = 0;
3678 const char *mime_type;
3679 GFileInfo *fi;
3680 GFile *gf;
3682 gf = g_file_new_for_path(file);
3683 fi = g_file_query_info(gf, G_FILE_ATTRIBUTE_STANDARD_CONTENT_TYPE, 0,
3684 NULL, NULL);
3685 mime_type = g_file_info_get_content_type(fi);
3686 valid = g_strcmp0(mime_type, "image/x-ico") == 0 ||
3687 g_strcmp0(mime_type, "image/vnd.microsoft.icon") == 0 ||
3688 g_strcmp0(mime_type, "image/png") == 0 ||
3689 g_strcmp0(mime_type, "image/gif") == 0 ||
3690 g_strcmp0(mime_type, "application/octet-stream") == 0;
3691 g_object_unref(fi);
3692 g_object_unref(gf);
3694 return (valid);
3697 void
3698 set_favicon_from_file(struct tab *t, char *file)
3700 struct stat sb;
3702 if (t == NULL || file == NULL)
3703 return;
3705 if (g_str_has_prefix(file, "file://"))
3706 file += strlen("file://");
3707 DNPRINTF(XT_D_DOWNLOAD, "%s: loading %s\n", __func__, file);
3709 if (!stat(file, &sb)) {
3710 if (sb.st_size == 0 || !is_valid_icon(file)) {
3711 /* corrupt icon so trash it */
3712 DNPRINTF(XT_D_DOWNLOAD, "%s: corrupt icon %s\n",
3713 __func__, file);
3714 unlink(file);
3715 /* no need to set icon to default here */
3716 return;
3719 xt_icon_from_file(t, file);
3722 void
3723 favicon_download_status_changed_cb(WebKitDownload *download, GParamSpec *spec,
3724 WebKitWebView *wv)
3726 WebKitDownloadStatus status = webkit_download_get_status(download);
3727 struct tab *tt = NULL, *t = NULL;
3730 * find the webview instead of passing in the tab as it could have been
3731 * deleted from underneath us.
3733 TAILQ_FOREACH(tt, &tabs, entry) {
3734 if (tt->wv == wv) {
3735 t = tt;
3736 break;
3739 if (t == NULL)
3740 return;
3742 DNPRINTF(XT_D_DOWNLOAD, "%s: tab %d status %d\n",
3743 __func__, t->tab_id, status);
3745 switch (status) {
3746 case WEBKIT_DOWNLOAD_STATUS_ERROR:
3747 /* -1 */
3748 t->icon_download = NULL;
3749 free_favicon(t);
3750 break;
3751 case WEBKIT_DOWNLOAD_STATUS_CREATED:
3752 /* 0 */
3753 break;
3754 case WEBKIT_DOWNLOAD_STATUS_STARTED:
3755 /* 1 */
3756 break;
3757 case WEBKIT_DOWNLOAD_STATUS_CANCELLED:
3758 /* 2 */
3759 DNPRINTF(XT_D_DOWNLOAD, "%s: freeing favicon %d\n",
3760 __func__, t->tab_id);
3761 t->icon_download = NULL;
3762 free_favicon(t);
3763 break;
3764 case WEBKIT_DOWNLOAD_STATUS_FINISHED:
3765 /* 3 */
3767 DNPRINTF(XT_D_DOWNLOAD, "%s: setting icon to %s\n",
3768 __func__, t->icon_dest_uri);
3769 set_favicon_from_file(t, t->icon_dest_uri);
3770 /* these will be freed post callback */
3771 t->icon_request = NULL;
3772 t->icon_download = NULL;
3773 break;
3774 default:
3775 break;
3779 void
3780 abort_favicon_download(struct tab *t)
3782 DNPRINTF(XT_D_DOWNLOAD, "%s: down %p\n", __func__, t->icon_download);
3784 #if !WEBKIT_CHECK_VERSION(1, 4, 0)
3785 if (t->icon_download) {
3786 g_signal_handlers_disconnect_by_func(G_OBJECT(t->icon_download),
3787 G_CALLBACK(favicon_download_status_changed_cb), t->wv);
3788 webkit_download_cancel(t->icon_download);
3789 t->icon_download = NULL;
3790 } else
3791 free_favicon(t);
3792 #endif
3794 xt_icon_from_name(t, "text-html");
3797 void
3798 notify_icon_loaded_cb(WebKitWebView *wv, gchar *uri, struct tab *t)
3800 DNPRINTF(XT_D_DOWNLOAD, "%s %s\n", __func__, uri);
3802 if (uri == NULL || t == NULL)
3803 return;
3805 #if WEBKIT_CHECK_VERSION(1, 4, 0)
3806 /* take icon from WebKitIconDatabase */
3807 GdkPixbuf *pb;
3809 pb = webkit_web_view_get_icon_pixbuf(wv);
3810 if (pb) {
3811 xt_icon_from_pixbuf(t, pb);
3812 g_object_unref(pb);
3813 } else
3814 xt_icon_from_name(t, "text-html");
3815 #elif WEBKIT_CHECK_VERSION(1, 1, 18)
3816 /* download icon to cache dir */
3817 gchar *name_hash, file[PATH_MAX];
3818 struct stat sb;
3820 if (t->icon_request) {
3821 DNPRINTF(XT_D_DOWNLOAD, "%s: download in progress\n", __func__);
3822 return;
3825 /* check to see if we got the icon in cache */
3826 name_hash = g_compute_checksum_for_string(G_CHECKSUM_SHA256, uri, -1);
3827 snprintf(file, sizeof file, "%s" PS "%s.ico", cache_dir, name_hash);
3828 g_free(name_hash);
3830 if (!stat(file, &sb)) {
3831 if (sb.st_size > 0) {
3832 DNPRINTF(XT_D_DOWNLOAD, "%s: loading from cache %s\n",
3833 __func__, file);
3834 set_favicon_from_file(t, file);
3835 return;
3838 /* corrupt icon so trash it */
3839 DNPRINTF(XT_D_DOWNLOAD, "%s: corrupt icon %s\n",
3840 __func__, file);
3841 unlink(file);
3844 /* create download for icon */
3845 t->icon_request = webkit_network_request_new(uri);
3846 if (t->icon_request == NULL) {
3847 DNPRINTF(XT_D_DOWNLOAD, "%s: invalid uri %s\n",
3848 __func__, uri);
3849 return;
3852 t->icon_download = webkit_download_new(t->icon_request);
3853 if (t->icon_download == NULL)
3854 return;
3856 /* we have to free icon_dest_uri later */
3857 t->icon_dest_uri = g_strdup_printf("file://%s", file);
3858 webkit_download_set_destination_uri(t->icon_download,
3859 t->icon_dest_uri);
3861 if (webkit_download_get_status(t->icon_download) ==
3862 WEBKIT_DOWNLOAD_STATUS_ERROR) {
3863 g_object_unref(t->icon_request);
3864 g_free(t->icon_dest_uri);
3865 t->icon_request = NULL;
3866 t->icon_dest_uri = NULL;
3867 return;
3870 g_signal_connect(G_OBJECT(t->icon_download), "notify::status",
3871 G_CALLBACK(favicon_download_status_changed_cb), t->wv);
3873 webkit_download_start(t->icon_download);
3874 #endif
3877 void
3878 notify_load_status_cb(WebKitWebView* wview, GParamSpec* pspec, struct tab *t)
3880 const gchar *uri = NULL;
3881 struct history *h, find;
3882 struct karg a;
3883 gchar *text, *base;
3885 DNPRINTF(XT_D_URL, "notify_load_status_cb: %d %s\n",
3886 webkit_web_view_get_load_status(wview),
3887 get_uri(t) ? get_uri(t) : "NOTHING");
3889 if (t == NULL) {
3890 show_oops(NULL, "notify_load_status_cb invalid parameters");
3891 return;
3894 switch (webkit_web_view_get_load_status(wview)) {
3895 case WEBKIT_LOAD_PROVISIONAL:
3896 /* 0 */
3897 abort_favicon_download(t);
3898 #if GTK_CHECK_VERSION(2, 20, 0)
3899 gtk_widget_show(t->spinner);
3900 gtk_spinner_start(GTK_SPINNER(t->spinner));
3901 #endif
3902 gtk_label_set_text(GTK_LABEL(t->label), "Loading");
3904 gtk_widget_set_sensitive(GTK_WIDGET(t->stop), TRUE);
3906 /* assume we are a new address */
3907 gtk_widget_modify_base(t->uri_entry, GTK_STATE_NORMAL,
3908 &t->default_style->base[GTK_STATE_NORMAL]);
3909 text = gdk_color_to_string(
3910 &t->default_style->text[GTK_STATE_NORMAL]);
3911 base = gdk_color_to_string(
3912 &t->default_style->base[GTK_STATE_NORMAL]);
3913 statusbar_modify_attr(t, text, base);
3914 g_free(text);
3915 g_free(base);
3917 /* take focus if we are visible */
3918 focus_webview(t);
3919 t->focus_wv = 1;
3921 marks_clear(t);
3922 #ifdef USE_THREAD
3923 /* kill color thread */
3924 t->thread = NULL;
3925 #endif
3926 break;
3928 case WEBKIT_LOAD_COMMITTED:
3929 /* 1 */
3930 uri = get_uri(t);
3931 if (uri == NULL)
3932 return;
3933 gtk_entry_set_text(GTK_ENTRY(t->uri_entry), uri);
3935 if (t->status) {
3936 g_free(t->status);
3937 t->status = NULL;
3939 set_status(t, (char *)uri, XT_STATUS_LOADING);
3941 /* check if js white listing is enabled */
3942 if (enable_plugin_whitelist)
3943 check_and_set_pl(uri, t);
3944 if (enable_cookie_whitelist)
3945 check_and_set_cookie(uri, t);
3946 if (enable_js_whitelist)
3947 check_and_set_js(uri, t);
3949 if (t->styled)
3950 apply_style(t);
3953 /* we know enough to autosave the session */
3954 if (session_autosave) {
3955 a.s = NULL;
3956 save_tabs(t, &a);
3959 show_ca_status(t, uri);
3960 run_script(t, JS_HINTING);
3961 if (enable_autoscroll)
3962 run_script(t, JS_AUTOSCROLL);
3963 break;
3965 case WEBKIT_LOAD_FIRST_VISUALLY_NON_EMPTY_LAYOUT:
3966 /* 3 */
3967 if (color_visited_uris) {
3968 color_visited(t, color_visited_helper());
3970 /* This colors the links you middle-click (open in new
3971 * tab) in the current tab. */
3972 if (t->tab_id != gtk_notebook_get_current_page(notebook) &&
3973 (uri = get_uri(t)) != NULL)
3974 color_visited(get_current_tab(),
3975 g_strdup_printf("{'%s' : 'dummy'}", uri));
3977 break;
3979 case WEBKIT_LOAD_FINISHED:
3980 /* 2 */
3981 if ((uri = get_uri(t)) == NULL)
3982 return;
3984 if (!strncmp(uri, "http://", strlen("http://")) ||
3985 !strncmp(uri, "https://", strlen("https://")) ||
3986 !strncmp(uri, "file://", strlen("file://"))) {
3987 find.uri = (gchar *)uri;
3988 h = RB_FIND(history_list, &hl, &find);
3989 if (!h)
3990 insert_history_item(uri,
3991 get_title(t, FALSE), time(NULL));
3992 else
3993 h->time = time(NULL);
3996 set_status(t, (char *)uri, XT_STATUS_URI);
3997 #if WEBKIT_CHECK_VERSION(1, 1, 18)
3998 case WEBKIT_LOAD_FAILED:
3999 /* 4 */
4000 #endif
4001 #if GTK_CHECK_VERSION(2, 20, 0)
4002 gtk_spinner_stop(GTK_SPINNER(t->spinner));
4003 gtk_widget_hide(t->spinner);
4004 #endif
4005 default:
4006 gtk_widget_set_sensitive(GTK_WIDGET(t->stop), FALSE);
4007 break;
4010 if (t->item)
4011 gtk_widget_set_sensitive(GTK_WIDGET(t->backward), TRUE);
4012 else
4013 gtk_widget_set_sensitive(GTK_WIDGET(t->backward),
4014 can_go_back_for_real(t));
4016 gtk_widget_set_sensitive(GTK_WIDGET(t->forward),
4017 can_go_forward_for_real(t));
4020 void
4021 notify_title_cb(WebKitWebView* wview, GParamSpec* pspec, struct tab *t)
4023 const gchar *title = NULL, *win_title = NULL;
4025 title = get_title(t, FALSE);
4026 win_title = get_title(t, TRUE);
4027 if (title) {
4028 gtk_label_set_text(GTK_LABEL(t->label), title);
4029 gtk_label_set_text(GTK_LABEL(t->tab_elems.label), title);
4032 if (win_title && t->tab_id == gtk_notebook_get_current_page(notebook))
4033 gtk_window_set_title(GTK_WINDOW(main_window), win_title);
4036 char *
4037 get_domain(const gchar *host)
4039 size_t x;
4040 char *p;
4042 /* handle silly domains like .co.uk */
4044 if ((x = strlen(host)) <= 6)
4045 return (g_strdup(host));
4047 if (host[x - 3] == '.' && host[x - 6] == '.') {
4048 x = x - 7;
4049 while (x > 0)
4050 if (host[x] != '.')
4051 x--;
4052 else
4053 return (g_strdup(&host[x + 1]));
4056 /* find first . */
4057 p = g_strrstr(host, ".");
4058 if (p == NULL)
4059 return (g_strdup(""));
4060 p--;
4061 while (p > host)
4062 if (*p != '.')
4063 p--;
4064 else
4065 return (g_strdup(p + 1));
4067 return (g_strdup(host));
4070 void
4071 js_autorun(struct tab *t)
4073 SoupURI *su = NULL;
4074 const gchar *uri;
4075 size_t got_default = 0, got_host = 0;
4076 struct stat sb;
4077 char deff[PATH_MAX], hostf[PATH_MAX];
4078 char *js = NULL, *jsat, *domain = NULL;
4079 FILE *deffile = NULL, *hostfile = NULL;
4081 if (enable_js_autorun == 0)
4082 return;
4084 uri = get_uri(t);
4085 if (uri &&
4086 !(g_str_has_prefix(uri, "http://") ||
4087 g_str_has_prefix(uri, "https://")))
4088 goto done;
4090 su = soup_uri_new(uri);
4091 if (su == NULL)
4092 goto done;
4093 if (!SOUP_URI_VALID_FOR_HTTP(su))
4094 goto done;
4096 DNPRINTF(XT_D_JS, "%s: host: %s domain: %s\n", __func__,
4097 su->host, domain);
4098 domain = get_domain(su->host);
4100 snprintf(deff, sizeof deff, "%s" PS "default.js", js_dir);
4101 if ((deffile = fopen(deff, "r")) != NULL) {
4102 if (fstat(fileno(deffile), &sb) == -1) {
4103 show_oops(t, "can't stat default JS file");
4104 goto done;
4106 got_default = sb.st_size;
4109 /* try host first followed by domain */
4110 snprintf(hostf, sizeof hostf, "%s" PS "%s.js", js_dir, su->host);
4111 DNPRINTF(XT_D_JS, "trying file: %s\n", hostf);
4112 if ((hostfile = fopen(hostf, "r")) == NULL) {
4113 snprintf(hostf, sizeof hostf, "%s" PS "%s.js", js_dir, domain);
4114 DNPRINTF(XT_D_JS, "trying file: %s\n", hostf);
4115 if ((hostfile = fopen(hostf, "r")) == NULL)
4116 goto nofile;
4118 DNPRINTF(XT_D_JS, "file: %s\n", hostf);
4119 if (fstat(fileno(hostfile), &sb) == -1) {
4120 show_oops(t, "can't stat %s JS file", hostf);
4121 goto done;
4123 got_host = sb.st_size;
4125 nofile:
4126 if (got_default + got_host == 0)
4127 goto done;
4129 js = g_malloc0(got_default + got_host + 1);
4130 jsat = js;
4132 if (got_default) {
4133 if (fread(js, got_default, 1, deffile) != 1) {
4134 show_oops(t, "default file read error");
4135 goto done;
4137 jsat = js + got_default;
4140 if (got_host) {
4141 if (fread(jsat, got_host, 1, hostfile) != 1) {
4142 show_oops(t, "host file read error");
4143 goto done;
4147 DNPRINTF(XT_D_JS, "%s: about to run script\n", __func__);
4148 run_script_locked(t, js);
4150 done:
4151 if (su)
4152 soup_uri_free(su);
4153 if (js)
4154 g_free(js);
4155 if (deffile)
4156 fclose(deffile);
4157 if (hostfile)
4158 fclose(hostfile);
4159 if (domain)
4160 g_free(domain);
4163 void
4164 webview_load_finished_cb(WebKitWebView *wv, WebKitWebFrame *wf, struct tab *t)
4166 /* autorun some js if enabled */
4167 js_autorun(t);
4169 input_autofocus(t);
4173 void
4174 webview_progress_changed_cb(WebKitWebView *wv, int progress, struct tab *t)
4176 gtk_entry_set_progress_fraction(GTK_ENTRY(t->uri_entry),
4177 progress == 100 ? 0 : (double)progress / 100);
4178 if (show_url == 0) {
4179 gtk_entry_set_progress_fraction(GTK_ENTRY(t->sbe.statusbar),
4180 progress == 100 ? 0 : (double)progress / 100);
4183 update_statusbar_position(NULL, NULL);
4187 strict_transport_rb_cmp(struct strict_transport *a, struct strict_transport *b)
4189 char *p1, *p2;
4190 int l1, l2;
4192 /* compare strings from the end */
4193 l1 = strlen(a->host);
4194 l2 = strlen(b->host);
4196 p1 = a->host + l1;
4197 p2 = b->host + l2;
4198 for (; *p1 == *p2 && p1 > a->host && p2 > b->host;
4199 p1--, p2--)
4203 * Check if we need to do pattern expansion,
4204 * or if we're just keeping the tree in order
4206 if (a->flags & XT_STS_FLAGS_EXPAND &&
4207 b->flags & XT_STS_FLAGS_INCLUDE_SUBDOMAINS) {
4208 /* Check if we're matching the
4209 * 'host.xyz' part in '*.host.xyz'
4211 if (p2 == b->host && (p1 == a->host || *(p1-1) == '.')) {
4212 return (0);
4216 if (p1 == a->host && p2 == b->host)
4217 return (0);
4218 if (p1 == a->host)
4219 return (1);
4220 if (p2 == b->host)
4221 return (-1);
4223 if (*p1 < *p2)
4224 return (-1);
4225 if (*p1 > *p2)
4226 return (1);
4228 return (0);
4230 RB_GENERATE(strict_transport_tree, strict_transport, entry,
4231 strict_transport_rb_cmp);
4234 strict_transport_add(const char *domain, time_t timeout, int subdomains)
4236 struct strict_transport *d, find;
4237 time_t now;
4238 FILE *f;
4240 if (enable_strict_transport == FALSE)
4241 return (0);
4243 DPRINTF("strict_transport_add(%s,%" PRIi64 ",%d)\n", domain,
4244 (uint64_t)timeout, subdomains);
4246 now = time(NULL);
4247 if (timeout < now)
4248 return (0);
4250 find.host = (char *)domain;
4251 find.flags = 0;
4252 d = RB_FIND(strict_transport_tree, &st_tree, &find);
4254 /* update flags */
4255 if (d) {
4256 /* check if update is needed */
4257 if (d->timeout == timeout &&
4258 (d->flags & XT_STS_FLAGS_INCLUDE_SUBDOMAINS) == subdomains)
4259 return (0);
4261 d->timeout = timeout;
4262 if (subdomains)
4263 d->flags |= XT_STS_FLAGS_INCLUDE_SUBDOMAINS;
4265 /* We're still initializing */
4266 if (strict_transport_file == NULL)
4267 return (0);
4269 if ((f = fopen(strict_transport_file, "w")) == NULL) {
4270 show_oops(NULL,
4271 "can't open strict-transport rules file");
4272 return (1);
4275 fprintf(f, "# Generated file - do not update unless you know "
4276 "what you're doing\n");
4277 RB_FOREACH(d, strict_transport_tree, &st_tree) {
4278 if (d->timeout < now)
4279 continue;
4280 fprintf(f, "%s\t%" PRIi64 "\t%d\n", d->host,
4281 (uint64_t)d->timeout,
4282 d->flags & XT_STS_FLAGS_INCLUDE_SUBDOMAINS);
4284 fclose(f);
4285 } else {
4286 d = g_malloc(sizeof *d);
4287 d->host= g_strdup(domain);
4288 d->timeout = timeout;
4289 if (subdomains)
4290 d->flags = XT_STS_FLAGS_INCLUDE_SUBDOMAINS;
4291 else
4292 d->flags = 0;
4293 RB_INSERT(strict_transport_tree, &st_tree, d);
4295 /* We're still initializing */
4296 if (strict_transport_file == NULL)
4297 return (0);
4299 if ((f = fopen(strict_transport_file, "a+")) == NULL) {
4300 show_oops(NULL,
4301 "can't open strict-transport rules file");
4302 return (1);
4305 fseek(f, 0, SEEK_END);
4306 fprintf(f,"%s\t%" PRIi64 "\t%d\n", d->host, (uint64_t)timeout,
4307 subdomains);
4308 fclose(f);
4310 return (0);
4314 strict_transport_check(const char *host)
4316 static struct strict_transport *d = NULL;
4317 struct strict_transport find;
4319 if (enable_strict_transport == FALSE)
4320 return (0);
4322 find.host = (char *)host;
4324 /* match for domains that include subdomains */
4325 find.flags = XT_STS_FLAGS_EXPAND;
4327 /* First, check if we're already at the right node */
4328 if (d != NULL && strict_transport_rb_cmp(&find, d) == 0) {
4329 return (1);
4332 d = RB_FIND(strict_transport_tree, &st_tree, &find);
4333 if (d != NULL)
4334 return (1);
4336 return (0);
4340 strict_transport_init()
4342 char file[PATH_MAX];
4343 char delim[3];
4344 char *rule;
4345 char *ptr;
4346 FILE *f;
4347 size_t len;
4348 time_t timeout, now;
4349 int subdomains;
4351 snprintf(file, sizeof file, "%s" PS "%s", work_dir, XT_STS_FILE);
4352 if ((f = fopen(file, "r")) == NULL) {
4353 strict_transport_file = g_strdup(file);
4354 return (0);
4357 delim[0] = '\\';
4358 delim[1] = '\\';
4359 delim[2] = '#';
4360 rule = NULL;
4361 now = time(NULL);
4363 for (;;) {
4364 if ((rule = fparseln(f, &len, NULL, delim, 0)) == NULL) {
4365 if (!feof(f) || ferror(f))
4366 goto corrupt_file;
4367 else
4368 break;
4371 /* get second entry */
4372 if ((ptr = strpbrk(rule, " \t")) == NULL)
4373 goto corrupt_file;
4375 *ptr++ = '\0';
4376 timeout = atoi(ptr);
4378 /* get third entry */
4379 if ((ptr = strpbrk(ptr, " \t")) == NULL)
4380 goto corrupt_file;
4382 ptr ++;
4383 subdomains = atoi(ptr);
4385 if (timeout > now)
4386 strict_transport_add(rule, timeout, subdomains);
4387 free(rule);
4390 fclose(f);
4391 strict_transport_file = g_strdup(file);
4392 return (0);
4394 corrupt_file:
4395 startpage_add("strict-transport rules file ('%s') is corrupt", file);
4396 if (rule)
4397 free(rule);
4398 fclose(f);
4399 return (1);
4402 void
4403 strict_transport_security_cb(SoupMessage *msg, gpointer data)
4405 SoupURI *uri;
4406 const char *sts;
4407 char *ptr;
4408 time_t timeout = 0;
4409 int subdomains = FALSE;
4411 if (msg == NULL)
4412 return;
4414 sts = soup_message_headers_get_one(msg->response_headers,
4415 "Strict-Transport-Security");
4416 uri = soup_message_get_uri(msg);
4418 if (sts == NULL || uri == NULL)
4419 return;
4421 if ((ptr = strcasestr(sts, "max-age="))) {
4422 ptr += strlen("max-age=");
4423 timeout = atoll(ptr);
4424 } else
4425 return; /* malformed header - max-age must be included */
4427 if ((ptr = strcasestr(sts, "includeSubDomains")))
4428 subdomains = TRUE;
4430 strict_transport_add(uri->host, timeout + time(NULL), subdomains);
4433 void
4434 session_rq_cb(SoupSession *s, SoupMessage *msg, SoupSocket *socket,
4435 gpointer data)
4437 SoupURI *dest;
4438 SoupURI *ref_uri;
4439 const char *ref;
4441 char *ref_suffix;
4442 char *dest_suffix;
4444 if (s == NULL || msg == NULL)
4445 return;
4447 if (referer_mode == XT_REFERER_ALWAYS)
4448 return;
4450 /* Check if referer is set - and what the user requested for referers */
4451 ref = soup_message_headers_get_one(msg->request_headers, "Referer");
4452 if (ref) {
4453 DNPRINTF(XT_D_NAV, "session_rq_cb: Referer: %s\n", ref);
4454 switch (referer_mode) {
4455 case XT_REFERER_NEVER:
4456 DNPRINTF(XT_D_NAV, "session_rq_cb: removing referer\n");
4457 soup_message_headers_remove(msg->request_headers,
4458 "Referer");
4459 break;
4460 case XT_REFERER_SAME_DOMAIN:
4461 ref_uri = soup_uri_new(ref);
4462 dest = soup_message_get_uri(msg);
4464 ref_suffix = tld_get_suffix(ref_uri->host);
4465 dest_suffix = tld_get_suffix(dest->host);
4467 if (dest && ref_suffix && dest_suffix &&
4468 strcmp(ref_suffix, dest_suffix) != 0) {
4469 soup_message_headers_remove(msg->request_headers,
4470 "Referer");
4471 DNPRINTF(XT_D_NAV, "session_rq_cb: removing "
4472 "referer (not same domain) (suffixes: %s - %s)\n",
4473 ref_suffix, dest_suffix);
4475 soup_uri_free(ref_uri);
4476 break;
4477 case XT_REFERER_SAME_FQDN:
4478 ref_uri = soup_uri_new(ref);
4479 dest = soup_message_get_uri(msg);
4480 if (dest && strcmp(ref_uri->host, dest->host) != 0) {
4481 soup_message_headers_remove(msg->request_headers,
4482 "Referer");
4483 DNPRINTF(XT_D_NAV, "session_rq_cb: removing "
4484 "referer (not same fqdn) (should be %s)\n",
4485 dest->host);
4487 soup_uri_free(ref_uri);
4488 break;
4489 case XT_REFERER_CUSTOM:
4490 DNPRINTF(XT_D_NAV, "session_rq_cb: setting referer "
4491 "to %s\n", referer_custom);
4492 soup_message_headers_replace(msg->request_headers,
4493 "Referer", referer_custom);
4494 break;
4498 if (enable_strict_transport) {
4499 soup_message_add_header_handler(msg, "finished",
4500 "Strict-Transport-Security",
4501 G_CALLBACK(strict_transport_security_cb), NULL);
4506 webview_npd_cb(WebKitWebView *wv, WebKitWebFrame *wf,
4507 WebKitNetworkRequest *request, WebKitWebNavigationAction *na,
4508 WebKitWebPolicyDecision *pd, struct tab *t)
4510 char *uri;
4511 WebKitWebNavigationReason reason;
4512 struct domain *d = NULL;
4514 if (t == NULL) {
4515 show_oops(NULL, "webview_npd_cb invalid parameters");
4516 return (FALSE);
4519 DNPRINTF(XT_D_NAV, "webview_npd_cb: ctrl_click %d %s\n",
4520 t->ctrl_click,
4521 webkit_network_request_get_uri(request));
4523 uri = (char *)webkit_network_request_get_uri(request);
4525 if (!auto_load_images && t->load_images) {
4527 /* Disable autoloading of images, now that we're done loading
4528 * them. */
4529 g_object_set(G_OBJECT(t->settings),
4530 "auto-load-images", FALSE, (char *)NULL);
4531 webkit_web_view_set_settings(t->wv, t->settings);
4533 t->load_images = FALSE;
4536 /* If this is an xtp url, we don't load anything else. */
4537 if (parse_xtp_url(t, uri))
4538 return (TRUE);
4540 if ((t->mode == XT_MODE_HINT && t->new_tab) || t->ctrl_click) {
4541 t->ctrl_click = 0;
4542 create_new_tab(uri, NULL, ctrl_click_focus, -1);
4543 webkit_web_policy_decision_ignore(pd);
4544 return (TRUE); /* we made the decission */
4547 /* Change user agent if more than one has been given. */
4548 if (user_agent_count > 1) {
4549 struct user_agent *ua;
4551 if ((ua = TAILQ_NEXT(user_agent, entry)) == NULL)
4552 user_agent = TAILQ_FIRST(&ua_list);
4553 else
4554 user_agent = ua;
4556 free(t->user_agent);
4557 t->user_agent = g_strdup(user_agent->value);
4559 DNPRINTF(XT_D_NAV, "user-agent: %s\n", t->user_agent);
4561 g_object_set(G_OBJECT(t->settings),
4562 "user-agent", t->user_agent, (char *)NULL);
4564 webkit_web_view_set_settings(wv, t->settings);
4568 * This is a little hairy but it comes down to this:
4569 * when we run in whitelist mode we have to assist the browser in
4570 * opening the URL that it would have opened in a new tab.
4572 reason = webkit_web_navigation_action_get_reason(na);
4573 if (reason == WEBKIT_WEB_NAVIGATION_REASON_LINK_CLICKED) {
4574 t->xtp_meaning = XT_XTP_TAB_MEANING_NORMAL;
4575 if (enable_scripts == 0 && enable_cookie_whitelist == 1)
4576 if (uri && (d = wl_find_uri(uri, &js_wl)) == NULL)
4577 load_uri(t, uri);
4578 webkit_web_policy_decision_use(pd);
4579 return (TRUE); /* we made the decision */
4582 return (FALSE);
4585 void
4586 webview_rrs_cb(WebKitWebView *wv, WebKitWebFrame *wf, WebKitWebResource *res,
4587 WebKitNetworkRequest *request, WebKitNetworkResponse *response,
4588 struct tab *t)
4590 SoupMessage *msg;
4591 SoupURI *uri;
4593 msg = webkit_network_request_get_message(request);
4594 if (!msg) return;
4596 uri = soup_message_get_uri(msg);
4597 if (!uri) return;
4599 if (strcmp(soup_uri_get_scheme(uri), SOUP_URI_SCHEME_HTTP) == 0) {
4600 if (strict_transport_check(uri->host)) {
4601 DNPRINTF(XT_D_NAV, "webview_rrs_cb: force https for %s\n",
4602 uri->host);
4603 soup_uri_set_scheme(uri, SOUP_URI_SCHEME_HTTPS);
4608 WebKitWebView *
4609 webview_cwv_cb(WebKitWebView *wv, WebKitWebFrame *wf, struct tab *t)
4611 struct tab *tt;
4612 struct domain *d = NULL;
4613 const gchar *uri;
4614 WebKitWebView *webview = NULL;
4615 int x = 1;
4617 DNPRINTF(XT_D_NAV, "webview_cwv_cb: %s\n",
4618 webkit_web_view_get_uri(wv));
4620 if (tabless) {
4621 /* open in current tab */
4622 webview = t->wv;
4623 } else if (enable_scripts == 0 && enable_js_whitelist == 1) {
4624 uri = webkit_web_view_get_uri(wv);
4625 if (uri && (d = wl_find_uri(uri, &js_wl)) == NULL)
4626 return (NULL);
4628 if (t->ctrl_click) {
4629 x = ctrl_click_focus;
4630 t->ctrl_click = 0;
4632 tt = create_new_tab(NULL, NULL, x, -1);
4633 webview = tt->wv;
4634 } else if (enable_scripts == 1) {
4635 if (t->ctrl_click) {
4636 x = ctrl_click_focus;
4637 t->ctrl_click = 0;
4639 tt = create_new_tab(NULL, NULL, x, -1);
4640 webview = tt->wv;
4643 return (webview);
4646 gboolean
4647 webview_closewv_cb(WebKitWebView *wv, struct tab *t)
4649 const gchar *uri;
4650 struct domain *d = NULL;
4652 DNPRINTF(XT_D_NAV, "webview_close_cb: %d\n", t->tab_id);
4654 if (enable_scripts == 0 && enable_cookie_whitelist == 1) {
4655 uri = webkit_web_view_get_uri(wv);
4656 if (uri && (d = wl_find_uri(uri, &js_wl)) == NULL)
4657 return (FALSE);
4659 delete_tab(t);
4660 } else if (enable_scripts == 1)
4661 delete_tab(t);
4663 return (TRUE);
4667 webview_event_cb(GtkWidget *w, GdkEventButton *e, struct tab *t)
4669 /* we can not eat the event without throwing gtk off so defer it */
4671 /* catch middle click */
4672 if (e->type == GDK_BUTTON_RELEASE && e->button == 2) {
4673 t->ctrl_click = 1;
4674 goto done;
4677 /* catch ctrl click */
4678 if (e->type == GDK_BUTTON_RELEASE &&
4679 CLEAN(e->state) == GDK_CONTROL_MASK)
4680 t->ctrl_click = 1;
4681 else
4682 t->ctrl_click = 0;
4683 done:
4684 return (XT_CB_PASSTHROUGH);
4688 run_mimehandler(struct tab *t, char *mime_type, WebKitNetworkRequest *request)
4690 struct mime_type *m;
4692 m = find_mime_type(mime_type);
4693 if (m == NULL)
4694 return (1);
4695 if (m->mt_download)
4696 return (1);
4698 return (fork_exec(t, m->mt_action,
4699 webkit_network_request_get_uri(request),
4700 "can't launch MIME handler", 0));
4703 char *
4704 get_mime_type(const char *file)
4706 const gchar *m;
4707 char *mime_type = NULL;
4708 GFileInfo *fi;
4709 GFile *gf;
4711 if (g_str_has_prefix(file, "file://"))
4712 file += strlen("file://");
4714 gf = g_file_new_for_path(file);
4715 fi = g_file_query_info(gf, G_FILE_ATTRIBUTE_STANDARD_CONTENT_TYPE, 0,
4716 NULL, NULL);
4717 if ((m = g_file_info_get_content_type(fi)) != NULL)
4718 mime_type = g_strdup(m);
4719 g_object_unref(fi);
4720 g_object_unref(gf);
4722 return (mime_type);
4726 run_download_mimehandler(char *mime_type, char *file)
4728 struct mime_type *m;
4730 m = find_mime_type(mime_type);
4731 if (m == NULL)
4732 return (1);
4734 return (fork_exec(NULL, m->mt_action, file,
4735 "can't launch download MIME handler", 0));
4738 void
4739 download_status_changed_cb(WebKitDownload *download, GParamSpec *spec,
4740 WebKitWebView *wv)
4742 WebKitDownloadStatus status;
4743 const char *file = NULL;
4744 char *mime = NULL;
4746 if (download == NULL)
4747 return;
4748 status = webkit_download_get_status(download);
4749 if (status != WEBKIT_DOWNLOAD_STATUS_FINISHED)
4750 return;
4752 if (download_notifications)
4753 show_oops(NULL, "Download of '%s' finished",
4754 basename((char *)webkit_download_get_destination_uri(download)));
4755 file = webkit_download_get_destination_uri(download);
4756 if (file == NULL)
4757 return;
4758 mime = get_mime_type(file);
4759 if (mime == NULL)
4760 return;
4762 if (g_str_has_prefix(file, "file://"))
4763 file += strlen("file://");
4764 run_download_mimehandler((char *)mime, (char *)file);
4765 g_free(mime);
4769 webview_mimetype_cb(WebKitWebView *wv, WebKitWebFrame *frame,
4770 WebKitNetworkRequest *request, char *mime_type,
4771 WebKitWebPolicyDecision *decision, struct tab *t)
4773 if (t == NULL) {
4774 show_oops(NULL, "webview_mimetype_cb invalid parameters");
4775 return (FALSE);
4778 DNPRINTF(XT_D_DOWNLOAD, "webview_mimetype_cb: tab %d mime %s\n",
4779 t->tab_id, mime_type);
4781 if (run_mimehandler(t, mime_type, request) == 0) {
4782 webkit_web_policy_decision_ignore(decision);
4783 focus_webview(t);
4784 return (TRUE);
4787 if (webkit_web_view_can_show_mime_type(wv, mime_type) == FALSE) {
4788 webkit_web_policy_decision_download(decision);
4789 return (TRUE);
4792 return (FALSE);
4796 download_start(struct tab *t, struct download *d, int flag)
4798 WebKitNetworkRequest *req;
4799 struct stat sb;
4800 const gchar *suggested_name;
4801 gchar *filename = NULL;
4802 char *uri = NULL;
4803 int ret = TRUE;
4804 int i;
4806 if (d == NULL || t == NULL) {
4807 show_oops(NULL, "%s invalid parameters", __func__);
4808 return (FALSE);
4811 suggested_name = webkit_download_get_suggested_filename(d->download);
4812 if (suggested_name == NULL)
4813 return (FALSE); /* abort download */
4815 i = 0;
4816 do {
4817 if (filename) {
4818 g_free(filename);
4819 filename = NULL;
4821 if (i) {
4822 g_free(uri);
4823 uri = NULL;
4824 filename = g_strdup_printf("%d%s", i, suggested_name);
4826 #ifdef __MINGW32__
4827 uri = g_strdup_printf("%s\\%s", download_dir, i ?
4828 filename : suggested_name);
4829 #else
4830 uri = g_strdup_printf("file://%s/%s", download_dir, i ?
4831 filename : suggested_name);
4832 #endif
4833 i++;
4834 #ifdef __MINGW32__
4835 } while (!stat(uri, &sb));
4836 #else
4837 } while (!stat(uri + strlen("file://"), &sb)); /* XXX is the + strlen right? */
4838 #endif
4840 DNPRINTF(XT_D_DOWNLOAD, "%s: tab %d filename %s "
4841 "local %s\n", __func__, t->tab_id, filename, uri);
4843 /* if we're restarting the download, or starting
4844 * it after doing something else, we need to recreate
4845 * the download request.
4847 if (flag == XT_DL_RESTART) {
4848 req = webkit_network_request_new(webkit_download_get_uri(d->download));
4849 webkit_download_cancel(d->download);
4850 g_object_unref(d->download);
4851 d->download = webkit_download_new(req);
4854 webkit_download_set_destination_uri(d->download, uri);
4856 if (webkit_download_get_status(d->download) ==
4857 WEBKIT_DOWNLOAD_STATUS_ERROR) {
4858 show_oops(t, "%s: download failed to start", __func__);
4859 ret = FALSE;
4860 gtk_label_set_text(GTK_LABEL(t->label), "Download Failed");
4861 } else {
4862 /* connect "download first" mime handler */
4863 g_signal_connect(G_OBJECT(d->download), "notify::status",
4864 G_CALLBACK(download_status_changed_cb), NULL);
4866 /* get from history */
4867 g_object_ref(d->download);
4868 gtk_label_set_text(GTK_LABEL(t->label), "Downloading");
4869 if (download_notifications)
4870 show_oops(t, "Download of '%s' started...",
4871 basename((char *)webkit_download_get_destination_uri(d->download)));
4874 if (flag != XT_DL_START)
4875 webkit_download_start(d->download);
4877 DNPRINTF(XT_D_DOWNLOAD, "download status : %d",
4878 webkit_download_get_status(d->download));
4880 /* sync other download manager tabs */
4881 update_download_tabs(NULL);
4883 if (uri)
4884 g_free(uri);
4886 if (filename)
4887 g_free(filename);
4889 return (ret);
4893 download_ask_cb(struct tab *t, GdkEventKey *e, gpointer data)
4895 struct download *d = data;
4897 /* unset mode */
4898 t->mode_cb = NULL;
4899 t->mode_cb_data = NULL;
4901 if (!e || !d) {
4902 e->keyval = GDK_Escape;
4903 return (XT_CB_PASSTHROUGH);
4906 DPRINTF("download_ask_cb: User pressed %c\n", e->keyval);
4907 if (e->keyval == 'y' || e->keyval == 'Y' || e->keyval == GDK_Return)
4908 /* We need to do a RESTART, because we're not calling from
4909 * webview_download_cb
4911 download_start(t, d, XT_DL_RESTART);
4913 /* for all other keyvals, we just let the download be */
4914 e->keyval = GDK_Escape;
4915 return (XT_CB_HANDLED);
4919 download_ask(struct tab *t, struct download *d)
4921 const gchar *suggested_name;
4923 suggested_name = webkit_download_get_suggested_filename(d->download);
4924 if (suggested_name == NULL)
4925 return (FALSE); /* abort download */
4927 show_oops(t, "download file %s [y/n] ?", suggested_name);
4928 t->mode_cb = download_ask_cb;
4929 t->mode_cb_data = d;
4931 return (TRUE);
4935 webview_download_cb(WebKitWebView *wv, WebKitDownload *wk_download,
4936 struct tab *t)
4938 const gchar *suggested_name;
4939 struct download *download_entry;
4940 int ret = TRUE;
4942 if (wk_download == NULL || t == NULL) {
4943 show_oops(NULL, "%s invalid parameters", __func__);
4944 return (FALSE);
4947 suggested_name = webkit_download_get_suggested_filename(wk_download);
4948 if (suggested_name == NULL)
4949 return (FALSE); /* abort download */
4951 download_entry = g_malloc(sizeof(struct download));
4952 download_entry->download = wk_download;
4953 download_entry->tab = t;
4954 download_entry->id = next_download_id++;
4955 RB_INSERT(download_list, &downloads, download_entry);
4957 if (download_mode == XT_DM_START)
4958 ret = download_start(t, download_entry, XT_DL_START);
4959 else if (download_mode == XT_DM_ASK)
4960 ret = download_ask(t, download_entry);
4961 else if (download_mode == XT_DM_ADD)
4962 show_oops(t, "added %s to download manager",
4963 suggested_name);
4965 /* sync other download manager tabs */
4966 update_download_tabs(NULL);
4969 * NOTE: never redirect/render the current tab before this
4970 * function returns. This will cause the download to never start.
4972 return (ret); /* start download */
4975 void
4976 webview_hover_cb(WebKitWebView *wv, gchar *title, gchar *uri, struct tab *t)
4978 DNPRINTF(XT_D_KEY, "webview_hover_cb: %s %s\n", title, uri);
4980 if (t == NULL) {
4981 show_oops(NULL, "webview_hover_cb");
4982 return;
4985 if (uri)
4986 set_status(t, uri, XT_STATUS_LINK);
4987 else {
4988 if (t->status)
4989 set_status(t, t->status, XT_STATUS_NOTHING);
4994 mark(struct tab *t, struct karg *arg)
4996 char mark;
4997 int index;
4998 double pos;
5000 mark = arg->s[1];
5001 if ((index = marktoindex(mark)) == -1)
5002 return (-1);
5004 if (arg->i == XT_MARK_SET)
5005 t->mark[index] = gtk_adjustment_get_value(t->adjust_v);
5006 else if (arg->i == XT_MARK_GOTO) {
5007 if (t->mark[index] == XT_INVALID_MARK) {
5008 show_oops(t, "mark '%c' does not exist", mark);
5009 return (-1);
5011 /* XXX t->mark[index] can be bigger than the maximum if ajax or
5012 something changes the document size */
5013 pos = gtk_adjustment_get_value(t->adjust_v);
5014 gtk_adjustment_set_value(t->adjust_v, t->mark[index]);
5015 t->mark[marktoindex('\'')] = pos;
5018 return (0);
5021 void
5022 marks_clear(struct tab *t)
5024 int i;
5026 for (i = 0; i < LENGTH(t->mark); i++)
5027 t->mark[i] = XT_INVALID_MARK;
5031 qmarks_load(void)
5033 char file[PATH_MAX];
5034 char *line = NULL, *p;
5035 int index, i;
5036 FILE *f;
5037 size_t linelen;
5039 snprintf(file, sizeof file, "%s" PS "%s", work_dir, XT_QMARKS_FILE);
5040 if ((f = fopen(file, "r+")) == NULL) {
5041 show_oops(NULL, "Can't open quickmarks file: %s", strerror(errno));
5042 return (1);
5045 for (i = 1; ; i++) {
5046 if ((line = fparseln(f, &linelen, NULL, NULL, 0)) == NULL)
5047 break;
5048 if (strlen(line) == 0 || line[0] == '#') {
5049 free(line);
5050 line = NULL;
5051 continue;
5054 p = strtok(line, " \t");
5056 if (p == NULL || strlen(p) != 1 ||
5057 (index = qmarktoindex(*p)) == -1) {
5058 warnx("corrupt quickmarks file, line %d", i);
5059 break;
5062 p = strtok(NULL, " \t");
5063 if (qmarks[index] != NULL)
5064 g_free(qmarks[index]);
5065 qmarks[index] = g_strdup(p);
5068 fclose(f);
5070 return (0);
5074 qmarks_save(void)
5076 char file[PATH_MAX];
5077 int i;
5078 FILE *f;
5080 snprintf(file, sizeof file, "%s" PS "%s", work_dir, XT_QMARKS_FILE);
5081 if ((f = fopen(file, "r+")) == NULL) {
5082 show_oops(NULL, "Can't open quickmarks file: %s", strerror(errno));
5083 return (1);
5086 for (i = 0; i < XT_NOQMARKS; i++)
5087 if (qmarks[i] != NULL)
5088 fprintf(f, "%c %s\n", indextoqmark(i), qmarks[i]);
5090 fclose(f);
5092 return (0);
5096 qmark(struct tab *t, struct karg *arg)
5098 char mark;
5099 int index;
5101 mark = arg->s[strlen(arg->s)-1];
5102 index = qmarktoindex(mark);
5103 if (index == -1)
5104 return (-1);
5106 switch (arg->i) {
5107 case XT_QMARK_SET:
5108 if (qmarks[index] != NULL) {
5109 g_free(qmarks[index]);
5110 qmarks[index] = NULL;
5113 qmarks_load(); /* sync if multiple instances */
5114 qmarks[index] = g_strdup(get_uri(t));
5115 qmarks_save();
5116 break;
5117 case XT_QMARK_OPEN:
5118 if (qmarks[index] != NULL)
5119 load_uri(t, qmarks[index]);
5120 else {
5121 show_oops(t, "quickmark \"%c\" does not exist",
5122 mark);
5123 return (-1);
5125 break;
5126 case XT_QMARK_TAB:
5127 if (qmarks[index] != NULL)
5128 create_new_tab(qmarks[index], NULL, 1, -1);
5129 else {
5130 show_oops(t, "quickmark \"%c\" does not exist",
5131 mark);
5132 return (-1);
5134 break;
5137 return (0);
5141 go_up(struct tab *t, struct karg *args)
5143 int levels;
5144 int lastidx;
5145 char *uri;
5146 char *tmp;
5147 char *p;
5149 if (args->i == XT_GO_UP_ROOT)
5150 levels = XT_GO_UP_ROOT;
5151 else if ((levels = atoi(args->s)) == 0)
5152 levels = 1;
5154 uri = g_strdup(get_uri(t));
5155 if (uri == NULL)
5156 return (1);
5158 if ((tmp = strstr(uri, XT_PROTO_DELIM)) == NULL)
5159 return (1);
5161 tmp += strlen(XT_PROTO_DELIM);
5163 /* it makes no sense to strip the last slash from ".../dir/", skip it */
5164 lastidx = strlen(tmp) - 1;
5165 if (lastidx > 0) {
5166 if (tmp[lastidx] == '/')
5167 tmp[lastidx] = '\0';
5170 while (levels--) {
5171 p = strrchr(tmp, '/');
5172 if (p == tmp) { /* Are we at the root of a file://-path? */
5173 p[1] = '\0';
5174 break;
5175 } else if (p != NULL)
5176 *p = '\0';
5177 else
5178 break;
5181 load_uri(t, uri);
5182 g_free(uri);
5184 return (0);
5188 gototab(struct tab *t, struct karg *args)
5190 int tab;
5191 struct karg arg = {0, NULL, -1};
5193 tab = atoi(args->s);
5195 if (args->i == 0)
5196 arg.i = XT_TAB_NEXT;
5197 else
5198 arg.i = args->i;
5200 arg.precount = tab;
5202 movetab(t, &arg);
5204 return (0);
5208 zoom_amount(struct tab *t, struct karg *arg)
5210 struct karg narg = {0, NULL, -1};
5212 narg.i = atoi(arg->s);
5213 resizetab(t, &narg);
5215 return (0);
5219 flip_colon(struct tab *t, struct karg *arg)
5221 struct karg narg = {0, NULL, -1};
5222 char *p;
5224 if (t == NULL || arg == NULL)
5225 return (1);
5227 p = strstr(arg->s, ":");
5228 if (p == NULL)
5229 return (1);
5230 *p = '\0';
5232 narg.i = ':';
5233 narg.s = arg->s;
5234 command(t, &narg);
5236 return (0);
5239 /* buffer commands receive the regex that triggered them in arg.s */
5240 char bcmd[XT_BUFCMD_SZ];
5241 struct buffercmd {
5242 char *regex;
5243 int precount;
5244 #define XT_PRE_NO (0)
5245 #define XT_PRE_YES (1)
5246 #define XT_PRE_MAYBE (2)
5247 char *cmd;
5248 int (*func)(struct tab *, struct karg *);
5249 int arg;
5250 regex_t cregex;
5251 } buffercmds[] = {
5252 { "^[0-9]*gu$", XT_PRE_MAYBE, "gu", go_up, 0 },
5253 { "^gU$", XT_PRE_NO, "gU", go_up, XT_GO_UP_ROOT },
5254 { "^gg$", XT_PRE_NO, "gg", move, XT_MOVE_TOP },
5255 { "^gG$", XT_PRE_NO, "gG", move, XT_MOVE_BOTTOM },
5256 { "^[0-9]+%$", XT_PRE_YES, "%", move, XT_MOVE_PERCENT },
5257 { "^zz$", XT_PRE_NO, "zz", move, XT_MOVE_CENTER },
5258 { "^gh$", XT_PRE_NO, "gh", go_home, 0 },
5259 { "^m[a-zA-Z0-9]$", XT_PRE_NO, "m", mark, XT_MARK_SET },
5260 { "^['][a-zA-Z0-9']$", XT_PRE_NO, "'", mark, XT_MARK_GOTO },
5261 { "^[0-9]+t$", XT_PRE_YES, "t", gototab, 0 },
5262 { "^g0$", XT_PRE_YES, "g0", movetab, XT_TAB_FIRST },
5263 { "^g[$]$", XT_PRE_YES, "g$", movetab, XT_TAB_LAST },
5264 { "^[0-9]*gt$", XT_PRE_YES, "t", movetab, XT_TAB_NEXT },
5265 { "^[0-9]*gT$", XT_PRE_YES, "T", movetab, XT_TAB_PREV },
5266 { "^M[a-zA-Z0-9]$", XT_PRE_NO, "M", qmark, XT_QMARK_SET },
5267 { "^go[a-zA-Z0-9]$", XT_PRE_NO, "go", qmark, XT_QMARK_OPEN },
5268 { "^gn[a-zA-Z0-9]$", XT_PRE_NO, "gn", qmark, XT_QMARK_TAB },
5269 { "^ZR$", XT_PRE_NO, "ZR", restart, 0 },
5270 { "^ZZ$", XT_PRE_NO, "ZZ", quit, 0 },
5271 { "^zi$", XT_PRE_NO, "zi", resizetab, XT_ZOOM_IN },
5272 { "^zo$", XT_PRE_NO, "zo", resizetab, XT_ZOOM_OUT },
5273 { "^z0$", XT_PRE_NO, "z0", resizetab, XT_ZOOM_NORMAL },
5274 { "^[0-9]+Z$", XT_PRE_YES, "Z", zoom_amount, 0 },
5275 { "^[0-9]+:$", XT_PRE_YES, ":", flip_colon, 0 },
5278 void
5279 buffercmd_init(void)
5281 int i;
5283 for (i = 0; i < LENGTH(buffercmds); i++)
5284 if (regcomp(&buffercmds[i].cregex, buffercmds[i].regex,
5285 REG_EXTENDED | REG_NOSUB))
5286 startpage_add("invalid buffercmd regex %s",
5287 buffercmds[i].regex);
5290 void
5291 buffercmd_abort(struct tab *t)
5293 int i;
5295 if (t == NULL)
5296 return;
5298 DNPRINTF(XT_D_BUFFERCMD, "%s: clearing buffer\n", __func__);
5300 for (i = 0; i < LENGTH(bcmd); i++)
5301 bcmd[i] = '\0';
5303 cmd_prefix = 0; /* clear prefix for non-buffer commands */
5304 gtk_entry_set_text(GTK_ENTRY(t->sbe.buffercmd), bcmd);
5307 void
5308 buffercmd_execute(struct tab *t, struct buffercmd *cmd)
5310 struct karg arg = {0, NULL, -1};
5312 arg.i = cmd->arg;
5313 arg.s = g_strdup(bcmd);
5315 DNPRINTF(XT_D_BUFFERCMD, "buffercmd_execute: buffer \"%s\" "
5316 "matches regex \"%s\", executing\n", bcmd, cmd->regex);
5317 cmd->func(t, &arg);
5319 if (arg.s)
5320 g_free(arg.s);
5322 buffercmd_abort(t);
5325 gboolean
5326 buffercmd_addkey(struct tab *t, guint keyval)
5328 int i, c, match ;
5329 char s[XT_BUFCMD_SZ];
5331 if (gtk_widget_get_visible(GTK_WIDGET(t->buffers))) {
5332 buffercmd_abort(t);
5333 return (XT_CB_PASSTHROUGH);
5336 if (keyval == GDK_Escape) {
5337 buffercmd_abort(t);
5338 return (XT_CB_HANDLED);
5341 /* key with modifier or non-ascii character */
5342 if (!isascii(keyval)) {
5344 * XXX this looks wrong but fixes some sites like
5345 * http://www.seslisozluk.com/
5346 * that eat a shift or ctrl and end putting default focus in js
5347 * instead of ignoring the keystroke
5348 * so instead of return (XT_CB_PASSTHROUGH); eat the key
5350 return (XT_CB_HANDLED);
5353 DNPRINTF(XT_D_BUFFERCMD, "buffercmd_addkey: adding key \"%c\" "
5354 "to buffer \"%s\"\n", keyval, bcmd);
5356 for (i = 0; i < LENGTH(bcmd); i++)
5357 if (bcmd[i] == '\0') {
5358 bcmd[i] = keyval;
5359 break;
5362 /* buffer full, ignore input */
5363 if (i >= LENGTH(bcmd) -1) {
5364 DNPRINTF(XT_D_BUFFERCMD, "buffercmd_addkey: buffer full\n");
5365 buffercmd_abort(t);
5366 return (XT_CB_HANDLED);
5369 gtk_entry_set_text(GTK_ENTRY(t->sbe.buffercmd), bcmd);
5371 /* find exact match */
5372 for (i = 0; i < LENGTH(buffercmds); i++)
5373 if (regexec(&buffercmds[i].cregex, bcmd,
5374 (size_t) 0, NULL, 0) == 0) {
5375 buffercmd_execute(t, &buffercmds[i]);
5376 goto done;
5379 /* find non exact matches to see if we need to abort ot not */
5380 for (i = 0, match = 0; i < LENGTH(buffercmds); i++) {
5381 DNPRINTF(XT_D_BUFFERCMD, "trying: %s\n", bcmd);
5382 c = -1;
5383 s[0] = '\0';
5384 if (buffercmds[i].precount == XT_PRE_MAYBE) {
5385 if (isdigit(bcmd[0])) {
5386 if (sscanf(bcmd, "%d%s", &c, s) == 0)
5387 continue;
5388 } else {
5389 c = 0;
5390 if (sscanf(bcmd, "%s", s) == 0)
5391 continue;
5393 } else if (buffercmds[i].precount == XT_PRE_YES) {
5394 if (sscanf(bcmd, "%d%s", &c, s) == 0)
5395 continue;
5396 } else {
5397 if (sscanf(bcmd, "%s", s) == 0)
5398 continue;
5400 if (c == -1 && buffercmds[i].precount)
5401 continue;
5402 if (!strncmp(s, buffercmds[i].cmd, strlen(s)))
5403 match++;
5405 DNPRINTF(XT_D_BUFFERCMD, "got[%d] %d <%s>: %d %s\n",
5406 i, match, buffercmds[i].cmd, c, s);
5408 if (match == 0) {
5409 DNPRINTF(XT_D_BUFFERCMD, "aborting: %s\n", bcmd);
5410 buffercmd_abort(t);
5413 done:
5414 return (XT_CB_HANDLED);
5417 gboolean
5418 handle_keypress(struct tab *t, GdkEventKey *e, int entry)
5420 struct key_binding *k;
5422 /* handle keybindings if buffercmd is empty.
5423 if not empty, allow commands like C-n */
5424 if (bcmd[0] == '\0' || ((e->state & (CTRL | MOD1)) != 0))
5425 TAILQ_FOREACH(k, &kbl, entry)
5426 if (e->keyval == k->key
5427 && (entry ? k->use_in_entry : 1)) {
5428 /* when we are edditing eat ctrl/mod keys */
5429 if (edit_mode == XT_EM_VI &&
5430 t->mode == XT_MODE_INSERT &&
5431 (e->state & CTRL || e->state & MOD1))
5432 return (XT_CB_PASSTHROUGH);
5434 if (k->mask == 0) {
5435 if ((e->state & (CTRL | MOD1)) == 0)
5436 return (cmd_execute(t, k->cmd));
5437 } else if ((e->state & k->mask) == k->mask) {
5438 return (cmd_execute(t, k->cmd));
5442 if (!entry && ((e->state & (CTRL | MOD1)) == 0))
5443 return buffercmd_addkey(t, e->keyval);
5445 return (XT_CB_PASSTHROUGH);
5449 wv_keypress_cb(GtkEntry *w, GdkEventKey *e, struct tab *t)
5451 char s[2];
5453 /* don't use w directly; use t->whatever instead */
5455 if (t == NULL) {
5456 show_oops(NULL, "wv_keypress_cb");
5457 return (XT_CB_PASSTHROUGH);
5460 hide_oops(t);
5462 if (t->mode_cb)
5463 return t->mode_cb(t, e, t->mode_cb_data);
5465 DNPRINTF(XT_D_KEY, "wv_keypress_cb: mode %d keyval 0x%x mask "
5466 "0x%x tab %d\n", t->mode, e->keyval, e->state, t->tab_id);
5468 /* Hide buffers, if they are visible, with escape. */
5469 if (gtk_widget_get_visible(GTK_WIDGET(t->buffers)) &&
5470 CLEAN(e->state) == 0 && e->keyval == GDK_Escape) {
5471 gtk_widget_grab_focus(GTK_WIDGET(t->wv));
5472 hide_buffers(t);
5473 return (XT_CB_HANDLED);
5476 if (t->mode == XT_MODE_HINT)
5477 return (XT_CB_HANDLED);
5479 if ((CLEAN(e->state) == 0 && e->keyval == GDK_Tab) ||
5480 (CLEAN(e->state) == SHFT && e->keyval == GDK_Tab))
5481 /* something focussy is about to happen */
5482 return (XT_CB_PASSTHROUGH);
5484 /* check if we are some sort of text input thing in the dom */
5485 input_check_mode(t);
5487 if (t->mode == XT_MODE_HINT) {
5488 /* XXX make sure cmd entry is enabled */
5489 return (XT_CB_HANDLED);
5490 } else if (t->mode == XT_MODE_PASSTHROUGH) {
5491 if (CLEAN(e->state) == 0 && e->keyval == GDK_Escape)
5492 t->mode = XT_MODE_COMMAND;
5493 return (XT_CB_PASSTHROUGH);
5494 } else if (t->mode == XT_MODE_COMMAND) {
5495 /* prefix input */
5496 snprintf(s, sizeof s, "%c", e->keyval);
5497 if (CLEAN(e->state) == 0 && isdigit(s[0]))
5498 cmd_prefix = 10 * cmd_prefix + atoi(s);
5499 return (handle_keypress(t, e, 0));
5500 } else {
5501 /* insert mode */
5502 return (handle_keypress(t, e, 1));
5505 /* NOTREACHED */
5506 return (XT_CB_PASSTHROUGH);
5509 gboolean
5510 hint_continue(struct tab *t)
5512 const gchar *c = gtk_entry_get_text(GTK_ENTRY(t->cmd));
5513 char *s;
5514 const gchar *errstr = NULL;
5515 gboolean rv = TRUE;
5516 int i;
5518 if (!(c[0] == '.' || c[0] == ','))
5519 goto done;
5520 if (strlen(c) == 1) {
5521 /* XXX should not happen */
5522 rv = TRUE;
5523 goto done;
5526 if (isdigit(c[1])) {
5527 /* numeric input */
5528 i = strtonum(&c[1], 1, 4096, &errstr);
5529 if (errstr) {
5530 show_oops(t, "invalid numerical hint %s", &c[1]);
5531 goto done;
5533 s = g_strdup_printf("hints.updateHints(%d);", i);
5534 run_script(t, s);
5535 g_free(s);
5536 } else {
5537 /* alphanumeric input */
5538 s = g_strdup_printf("hints.createHints('%s', '%c');",
5539 &c[1], c[0] == '.' ? 'f' : 'F');
5540 run_script(t, s);
5541 g_free(s);
5544 rv = FALSE;
5545 done:
5546 return (rv);
5549 gboolean
5550 search_continue(struct tab *t)
5552 const gchar *c = gtk_entry_get_text(GTK_ENTRY(t->cmd));
5553 gboolean rv = FALSE;
5555 if (c[0] == ':' || c[0] == '.' || c[0] == ',')
5556 goto done;
5557 if (strlen(c) == 1) {
5558 webkit_web_view_unmark_text_matches(t->wv);
5559 goto done;
5562 if (c[0] == '/')
5563 t->search_forward = TRUE;
5564 else if (c[0] == '?')
5565 t->search_forward = FALSE;
5566 else
5567 goto done;
5569 rv = TRUE;
5570 done:
5571 return (rv);
5574 gboolean
5575 search_cb(struct tab *t)
5577 const gchar *c = gtk_entry_get_text(GTK_ENTRY(t->cmd));
5578 GdkColor color;
5580 if (search_continue(t) == FALSE)
5581 goto done;
5583 /* search */
5584 if (webkit_web_view_search_text(t->wv, &c[1], FALSE, t->search_forward,
5585 TRUE) == FALSE) {
5586 /* not found, mark red */
5587 gdk_color_parse(XT_COLOR_RED, &color);
5588 gtk_widget_modify_base(t->cmd, GTK_STATE_NORMAL, &color);
5589 /* unmark and remove selection */
5590 webkit_web_view_unmark_text_matches(t->wv);
5591 /* my kingdom for a way to unselect text in webview */
5592 } else {
5593 /* found, highlight all */
5594 webkit_web_view_unmark_text_matches(t->wv);
5595 webkit_web_view_mark_text_matches(t->wv, &c[1], FALSE, 0);
5596 webkit_web_view_set_highlight_text_matches(t->wv, TRUE);
5597 gtk_widget_modify_base(t->cmd, GTK_STATE_NORMAL,
5598 &t->default_style->base[GTK_STATE_NORMAL]);
5600 done:
5601 t->search_id = 0;
5602 return (FALSE);
5606 cmd_keyrelease_cb(GtkEntry *w, GdkEventKey *e, struct tab *t)
5608 const gchar *c = gtk_entry_get_text(w);
5610 if (t == NULL) {
5611 show_oops(NULL, "cmd_keyrelease_cb invalid parameters");
5612 return (XT_CB_PASSTHROUGH);
5615 DNPRINTF(XT_D_CMD, "cmd_keyrelease_cb: keyval 0x%x mask 0x%x tab %d\n",
5616 e->keyval, e->state, t->tab_id);
5618 /* hinting */
5619 if (!(e->keyval == GDK_Tab || e->keyval == GDK_ISO_Left_Tab)) {
5620 if (hint_continue(t) == FALSE)
5621 goto done;
5624 /* search */
5625 if (search_continue(t) == FALSE)
5626 goto done;
5628 /* if search length is > 4 then no longer play timeout games */
5629 if (strlen(c) > 4) {
5630 if (t->search_id) {
5631 g_source_remove(t->search_id);
5632 t->search_id = 0;
5634 search_cb(t);
5635 goto done;
5638 /* reestablish a new timer if the user types fast */
5639 if (t->search_id)
5640 g_source_remove(t->search_id);
5641 t->search_id = g_timeout_add(250, (GSourceFunc)search_cb, (gpointer)t);
5643 done:
5644 return (XT_CB_PASSTHROUGH);
5647 gboolean
5648 match_uri(const gchar *uri, const gchar *key) {
5649 gchar *voffset;
5650 size_t len;
5651 gboolean match = FALSE;
5653 len = strlen(key);
5655 if (!strncmp(key, uri, len))
5656 match = TRUE;
5657 else {
5658 voffset = strstr(uri, "/") + 2;
5659 if (!strncmp(key, voffset, len))
5660 match = TRUE;
5661 else if (g_str_has_prefix(voffset, "www.")) {
5662 voffset = voffset + strlen("www.");
5663 if (!strncmp(key, voffset, len))
5664 match = TRUE;
5668 return (match);
5671 gboolean
5672 match_session(const gchar *name, const gchar *key) {
5673 char *sub;
5675 sub = strcasestr(name, key);
5677 return sub == name;
5680 void
5681 cmd_getlist(int id, char *key)
5683 int i, dep, c = 0;
5684 struct history *h;
5685 struct session *s;
5687 if (id >= 0) {
5688 if (cmds[id].type & XT_URLARG) {
5689 RB_FOREACH_REVERSE(h, history_list, &hl)
5690 if (match_uri(h->uri, key)) {
5691 cmd_status.list[c] = (char *)h->uri;
5692 if (++c > 255)
5693 break;
5695 cmd_status.len = c;
5696 return;
5697 } else if (cmds[id].type & XT_SESSARG) {
5698 TAILQ_FOREACH(s, &sessions, entry)
5699 if (match_session(s->name, key)) {
5700 cmd_status.list[c] = (char *)s->name;
5701 if (++c > 255)
5702 break;
5704 cmd_status.len = c;
5705 return;
5706 } else if (cmds[id].type & XT_SETARG) {
5707 for (i = 0; i < get_settings_size(); i++)
5708 if (!strncmp(key, get_setting_name(i),
5709 strlen(key)))
5710 cmd_status.list[c++] =
5711 get_setting_name(i);
5712 cmd_status.len = c;
5713 return;
5717 dep = (id == -1) ? 0 : cmds[id].level + 1;
5719 for (i = id + 1; i < LENGTH(cmds); i++) {
5720 if (cmds[i].level < dep)
5721 break;
5722 if (cmds[i].level == dep && !strncmp(key, cmds[i].cmd,
5723 strlen(key)) && !isdigit(cmds[i].cmd[0]))
5724 cmd_status.list[c++] = cmds[i].cmd;
5728 cmd_status.len = c;
5731 char *
5732 cmd_getnext(int dir)
5734 cmd_status.index += dir;
5736 if (cmd_status.index < 0)
5737 cmd_status.index = cmd_status.len - 1;
5738 else if (cmd_status.index >= cmd_status.len)
5739 cmd_status.index = 0;
5741 return cmd_status.list[cmd_status.index];
5745 cmd_tokenize(char *s, char *tokens[])
5747 int i = 0;
5748 char *tok, *last = NULL;
5749 size_t len = strlen(s);
5750 bool blank;
5752 blank = len == 0 || (len > 0 && s[len - 1] == ' ');
5753 for (tok = strtok_r(s, " ", &last); tok && i < 3;
5754 tok = strtok_r(NULL, " ", &last), i++)
5755 tokens[i] = tok;
5757 if (blank && i < 3)
5758 tokens[i++] = "";
5760 return (i);
5763 void
5764 cmd_complete(struct tab *t, char *str, int dir)
5766 GtkEntry *w = GTK_ENTRY(t->cmd);
5767 int i, j, levels, c = 0, dep = 0, parent = -1;
5768 int matchcount = 0;
5769 char *tok, *match, *s = g_strdup(str);
5770 char *tokens[3];
5771 char res[XT_MAX_URL_LENGTH + 32] = ":";
5772 char *sc = s;
5774 DNPRINTF(XT_D_CMD, "%s: complete %s\n", __func__, str);
5776 /* copy prefix*/
5777 for (i = 0; isdigit(s[i]); i++)
5778 res[i + 1] = s[i];
5780 for (; isspace(s[i]); i++)
5781 res[i + 1] = s[i];
5783 s += i;
5785 levels = cmd_tokenize(s, tokens);
5787 for (i = 0; i < levels - 1; i++) {
5788 tok = tokens[i];
5789 matchcount = 0;
5790 for (j = c; j < LENGTH(cmds); j++) {
5791 if (cmds[j].level < dep)
5792 break;
5793 if (cmds[j].level == dep && !strncmp(tok, cmds[j].cmd,
5794 strlen(tok))) {
5795 matchcount++;
5796 c = j + 1;
5797 if (strlen(tok) == strlen(cmds[j].cmd)) {
5798 matchcount = 1;
5799 break;
5804 if (matchcount == 1) {
5805 strlcat(res, tok, sizeof res);
5806 strlcat(res, " ", sizeof res);
5807 dep++;
5808 } else {
5809 g_free(sc);
5810 return;
5813 parent = c - 1;
5816 if (cmd_status.index == -1)
5817 cmd_getlist(parent, tokens[i]);
5819 if (cmd_status.len > 0) {
5820 match = cmd_getnext(dir);
5821 strlcat(res, match, sizeof res);
5822 gtk_entry_set_text(w, res);
5823 gtk_editable_set_position(GTK_EDITABLE(w), -1);
5826 g_free(sc);
5829 gboolean
5830 cmd_execute(struct tab *t, char *str)
5832 struct cmd *cmd = NULL;
5833 char *tok, *last = NULL, *s = g_strdup(str), *sc;
5834 char prefixstr[4];
5835 int j, len, c = 0, dep = 0, matchcount = 0;
5836 int prefix = -1, rv = XT_CB_PASSTHROUGH;
5837 struct karg arg = {0, NULL, -1};
5839 sc = s;
5841 /* copy prefix*/
5842 for (j = 0; j<3 && isdigit(s[j]); j++)
5843 prefixstr[j]=s[j];
5845 prefixstr[j]='\0';
5847 s += j;
5848 while (isspace(s[0]))
5849 s++;
5851 if (strlen(s) > 0 && strlen(prefixstr) > 0)
5852 prefix = atoi(prefixstr);
5853 else
5854 s = sc;
5856 for (tok = strtok_r(s, " ", &last); tok;
5857 tok = strtok_r(NULL, " ", &last)) {
5858 matchcount = 0;
5859 for (j = c; j < LENGTH(cmds); j++) {
5860 if (cmds[j].level < dep)
5861 break;
5862 len = (tok[strlen(tok) - 1] == '!') ? strlen(tok) - 1 :
5863 strlen(tok);
5864 if (cmds[j].level == dep &&
5865 !strncmp(tok, cmds[j].cmd, len)) {
5866 matchcount++;
5867 c = j + 1;
5868 cmd = &cmds[j];
5869 if (len == strlen(cmds[j].cmd)) {
5870 matchcount = 1;
5871 break;
5875 if (matchcount == 1) {
5876 if (cmd->type > 0)
5877 goto execute_cmd;
5878 dep++;
5879 } else {
5880 show_oops(t, "Invalid command: %s", str);
5881 goto done;
5884 execute_cmd:
5885 if (cmd == NULL) {
5886 show_oops(t, "Empty command");
5887 goto done;
5889 arg.i = cmd->arg;
5891 if (prefix != -1)
5892 arg.precount = prefix;
5893 else if (cmd_prefix > 0)
5894 arg.precount = cmd_prefix;
5896 if (j > 0 && !(cmd->type & XT_PREFIX) && arg.precount > -1) {
5897 show_oops(t, "No prefix allowed: %s", str);
5898 goto done;
5900 if (cmd->type > 1)
5901 arg.s = last ? g_strdup(last) : g_strdup("");
5902 if (cmd->type & XT_INTARG && last && strlen(last) > 0) {
5903 if (arg.s == NULL) {
5904 show_oops(t, "Invalid command");
5905 goto done;
5907 arg.precount = atoi(arg.s);
5908 if (arg.precount <= 0) {
5909 if (arg.s[0] == '0')
5910 show_oops(t, "Zero count");
5911 else
5912 show_oops(t, "Trailing characters");
5913 goto done;
5917 DNPRINTF(XT_D_CMD, "%s: prefix %d arg %s\n",
5918 __func__, arg.precount, arg.s);
5920 cmd->func(t, &arg);
5922 rv = XT_CB_HANDLED;
5923 done:
5924 if (j > 0)
5925 cmd_prefix = 0;
5926 g_free(sc);
5927 if (arg.s)
5928 g_free(arg.s);
5930 return (rv);
5934 entry_key_cb(GtkEntry *w, GdkEventKey *e, struct tab *t)
5936 if (t == NULL) {
5937 show_oops(NULL, "entry_key_cb invalid parameters");
5938 return (XT_CB_PASSTHROUGH);
5941 DNPRINTF(XT_D_CMD, "entry_key_cb: keyval 0x%x mask 0x%x tab %d\n",
5942 e->keyval, e->state, t->tab_id);
5944 hide_oops(t);
5946 if (e->keyval == GDK_Escape) {
5947 /* don't use focus_webview(t) because we want to type :cmds */
5948 gtk_widget_grab_focus(GTK_WIDGET(t->wv));
5951 return (handle_keypress(t, e, 1));
5954 struct command_entry *
5955 history_prev(struct command_list *l, struct command_entry *at)
5957 if (at == NULL)
5958 at = TAILQ_LAST(l, command_list);
5959 else {
5960 at = TAILQ_PREV(at, command_list, entry);
5961 if (at == NULL)
5962 at = TAILQ_LAST(l, command_list);
5965 return (at);
5968 struct command_entry *
5969 history_next(struct command_list *l, struct command_entry *at)
5971 if (at == NULL)
5972 at = TAILQ_FIRST(l);
5973 else {
5974 at = TAILQ_NEXT(at, entry);
5975 if (at == NULL)
5976 at = TAILQ_FIRST(l);
5979 return (at);
5983 cmd_keypress_cb(GtkEntry *w, GdkEventKey *e, struct tab *t)
5985 int rv = XT_CB_HANDLED;
5986 const gchar *c = gtk_entry_get_text(w);
5987 char *s;
5989 if (t == NULL) {
5990 show_oops(NULL, "cmd_keypress_cb parameters");
5991 return (XT_CB_PASSTHROUGH);
5994 DNPRINTF(XT_D_CMD, "cmd_keypress_cb: keyval 0x%x mask 0x%x tab %d\n",
5995 e->keyval, e->state, t->tab_id);
5997 /* sanity */
5998 if (c == NULL)
5999 e->keyval = GDK_Escape;
6000 else if (!(c[0] == ':' || c[0] == '/' || c[0] == '?' ||
6001 c[0] == '.' || c[0] == ','))
6002 e->keyval = GDK_Escape;
6004 if (e->keyval != GDK_Tab && e->keyval != GDK_Shift_L &&
6005 e->keyval != GDK_ISO_Left_Tab)
6006 cmd_status.index = -1;
6008 switch (e->keyval) {
6009 case GDK_Tab:
6010 if (c[0] == ':')
6011 cmd_complete(t, (char *)&c[1], 1);
6012 else if (c[0] == '.' || c[0] == ',')
6013 run_script(t, "hints.focusNextHint();");
6014 goto done;
6015 case GDK_ISO_Left_Tab:
6016 if (c[0] == ':')
6017 cmd_complete(t, (char *)&c[1], -1);
6018 else if (c[0] == '.' || c[0] == ',')
6019 run_script(t, "hints.focusPreviousHint();");
6020 goto done;
6021 case GDK_Down:
6022 if (c[0] == '?') {
6023 if ((search_at = history_next(&shl, search_at))) {
6024 search_at->line[0] = c[0];
6025 gtk_entry_set_text(w, search_at->line);
6026 gtk_editable_set_position(GTK_EDITABLE(w), -1);
6028 } else if (c[0] == '/') {
6029 if ((search_at = history_prev(&shl, search_at))) {
6030 search_at->line[0] = c[0];
6031 gtk_entry_set_text(w, search_at->line);
6032 gtk_editable_set_position(GTK_EDITABLE(w), -1);
6034 } if (c[0] == ':') {
6035 if ((history_at = history_prev(&chl, history_at))) {
6036 history_at->line[0] = c[0];
6037 gtk_entry_set_text(w, history_at->line);
6038 gtk_editable_set_position(GTK_EDITABLE(w), -1);
6041 goto done;
6042 case GDK_Up:
6043 if (c[0] == '/') {
6044 if ((search_at = history_next(&shl, search_at))) {
6045 search_at->line[0] = c[0];
6046 gtk_entry_set_text(w, search_at->line);
6047 gtk_editable_set_position(GTK_EDITABLE(w), -1);
6049 } else if (c[0] == '?') {
6050 if ((search_at = history_prev(&shl, search_at))) {
6051 search_at->line[0] = c[0];
6052 gtk_entry_set_text(w, search_at->line);
6053 gtk_editable_set_position(GTK_EDITABLE(w), -1);
6055 } if (c[0] == ':') {
6056 if ((history_at = history_next(&chl, history_at))) {
6057 history_at->line[0] = c[0];
6058 gtk_entry_set_text(w, history_at->line);
6059 gtk_editable_set_position(GTK_EDITABLE(w), -1);
6062 goto done;
6063 case GDK_BackSpace:
6064 if (!(!strcmp(c, ":") || !strcmp(c, "/") || !strcmp(c, "?") ||
6065 !strcmp(c, ".") || !strcmp(c, ","))) {
6066 /* see if we are doing hinting and reset it */
6067 if (c[0] == '.' || c[0] == ',') {
6068 /* recreate hints */
6069 s = g_strdup_printf("hints.createHints('', "
6070 "'%c');", c[0] == '.' ? 'f' : 'F');
6071 run_script(t, s);
6072 g_free(s);
6074 break;
6077 /* FALLTHROUGH */
6078 case GDK_Escape:
6079 hide_cmd(t);
6080 focus_webview(t);
6082 /* cancel search */
6083 if (c != NULL && (c[0] == '/' || c[0] == '?'))
6084 webkit_web_view_unmark_text_matches(t->wv);
6086 /* no need to cancel hints */
6087 goto done;
6090 rv = XT_CB_PASSTHROUGH;
6091 done:
6092 return (rv);
6095 void
6096 wv_popup_cb(GtkEntry *entry, GtkMenu *menu, struct tab *t)
6098 DNPRINTF(XT_D_CMD, "wv_popup_cb: tab %d\n", t->tab_id);
6101 void
6102 cmd_popup_cb(GtkEntry *entry, GtkMenu *menu, struct tab *t)
6104 /* popup menu enabled */
6105 t->popup = 1;
6109 cmd_focusout_cb(GtkWidget *w, GdkEventFocus *e, struct tab *t)
6111 if (t == NULL) {
6112 show_oops(NULL, "cmd_focusout_cb invalid parameters");
6113 return (XT_CB_PASSTHROUGH);
6116 DNPRINTF(XT_D_CMD, "cmd_focusout_cb: tab %d popup %d\n",
6117 t->tab_id, t->popup);
6119 /* if popup is enabled don't lose focus */
6120 if (t->popup) {
6121 t->popup = 0;
6122 return (XT_CB_PASSTHROUGH);
6125 hide_cmd(t);
6126 hide_oops(t);
6127 disable_hints(t);
6129 if (show_url == 0 || t->focus_wv)
6130 focus_webview(t);
6131 else
6132 gtk_widget_grab_focus(GTK_WIDGET(t->uri_entry));
6134 return (XT_CB_PASSTHROUGH);
6137 void
6138 cmd_activate_cb(GtkEntry *entry, struct tab *t)
6140 char *s;
6141 const gchar *c = gtk_entry_get_text(entry);
6143 if (t == NULL) {
6144 show_oops(NULL, "cmd_activate_cb invalid parameters");
6145 return;
6148 DNPRINTF(XT_D_CMD, "cmd_activate_cb: tab %d %s\n", t->tab_id, c);
6150 /* sanity */
6151 if (c == NULL)
6152 goto done;
6153 else if (!(c[0] == ':' || c[0] == '/' || c[0] == '?' ||
6154 c[0] == '.' || c[0] == ','))
6155 goto done;
6156 if (strlen(c) < 1)
6157 goto done;
6158 s = (char *)&c[1];
6160 if (c[0] == '/' || c[0] == '?') {
6161 /* see if there is a timer pending */
6162 if (t->search_id) {
6163 g_source_remove(t->search_id);
6164 t->search_id = 0;
6165 search_cb(t);
6168 if (t->search_text) {
6169 g_free(t->search_text);
6170 t->search_text = NULL;
6173 t->search_text = g_strdup(s);
6174 if (global_search)
6175 g_free(global_search);
6176 global_search = g_strdup(s);
6177 t->search_forward = c[0] == '/';
6179 history_add(&shl, search_file, s, &search_history_count);
6180 } else if (c[0] == '.' || c[0] == ',') {
6181 run_script(t, "hints.fire();");
6182 /* XXX history for link following? */
6183 } else if (c[0] == ':') {
6184 history_add(&chl, command_file, s, &cmd_history_count);
6185 /* can't call hide_cmd after cmd_execute */
6186 hide_cmd(t);
6187 cmd_execute(t, s);
6188 return;
6191 done:
6192 hide_cmd(t);
6195 void
6196 backward_cb(GtkWidget *w, struct tab *t)
6198 struct karg a;
6200 if (t == NULL) {
6201 show_oops(NULL, "backward_cb invalid parameters");
6202 return;
6205 DNPRINTF(XT_D_NAV, "backward_cb: tab %d\n", t->tab_id);
6207 a.i = XT_NAV_BACK;
6208 navaction(t, &a);
6211 void
6212 forward_cb(GtkWidget *w, struct tab *t)
6214 struct karg a;
6216 if (t == NULL) {
6217 show_oops(NULL, "forward_cb invalid parameters");
6218 return;
6221 DNPRINTF(XT_D_NAV, "forward_cb: tab %d\n", t->tab_id);
6223 a.i = XT_NAV_FORWARD;
6224 navaction(t, &a);
6227 void
6228 home_cb(GtkWidget *w, struct tab *t)
6230 if (t == NULL) {
6231 show_oops(NULL, "home_cb invalid parameters");
6232 return;
6235 DNPRINTF(XT_D_NAV, "home_cb: tab %d\n", t->tab_id);
6237 load_uri(t, home);
6240 void
6241 stop_cb(GtkWidget *w, struct tab *t)
6243 WebKitWebFrame *frame;
6245 if (t == NULL) {
6246 show_oops(NULL, "stop_cb invalid parameters");
6247 return;
6250 DNPRINTF(XT_D_NAV, "stop_cb: tab %d\n", t->tab_id);
6252 frame = webkit_web_view_get_main_frame(t->wv);
6253 if (frame == NULL) {
6254 show_oops(t, "stop_cb: no frame");
6255 return;
6258 webkit_web_frame_stop_loading(frame);
6259 abort_favicon_download(t);
6262 void
6263 setup_webkit(struct tab *t)
6265 if (is_g_object_setting(G_OBJECT(t->settings), "enable-dns-prefetching"))
6266 g_object_set(G_OBJECT(t->settings), "enable-dns-prefetching",
6267 FALSE, (char *)NULL);
6268 else
6269 warnx("webkit does not have \"enable-dns-prefetching\" property");
6270 g_object_set(G_OBJECT(t->settings),
6271 "user-agent", t->user_agent, (char *)NULL);
6272 g_object_set(G_OBJECT(t->settings),
6273 "enable-scripts", enable_scripts, (char *)NULL);
6274 g_object_set(G_OBJECT(t->settings),
6275 "enable-plugins", enable_plugins, (char *)NULL);
6276 g_object_set(G_OBJECT(t->settings),
6277 "javascript-can-open-windows-automatically", enable_scripts,
6278 (char *)NULL);
6279 g_object_set(G_OBJECT(t->settings),
6280 "enable-html5-database", FALSE, (char *)NULL);
6281 g_object_set(G_OBJECT(t->settings),
6282 "enable-html5-local-storage", enable_localstorage, (char *)NULL);
6283 g_object_set(G_OBJECT(t->settings),
6284 "enable_spell_checking", enable_spell_checking, (char *)NULL);
6285 g_object_set(G_OBJECT(t->settings),
6286 "spell_checking_languages", spell_check_languages, (char *)NULL);
6287 g_object_set(G_OBJECT(t->settings),
6288 "enable-developer-extras", TRUE, (char *)NULL);
6289 g_object_set(G_OBJECT(t->wv),
6290 "full-content-zoom", TRUE, (char *)NULL);
6291 g_object_set(G_OBJECT(t->settings),
6292 "auto-load-images", auto_load_images, (char *)NULL);
6294 webkit_web_view_set_settings(t->wv, t->settings);
6297 gboolean
6298 update_statusbar_position(GtkAdjustment* adjustment, gpointer data)
6300 struct tab *ti, *t = NULL;
6301 gdouble view_size, value, max;
6302 gchar *position;
6304 TAILQ_FOREACH(ti, &tabs, entry)
6305 if (ti->tab_id == gtk_notebook_get_current_page(notebook)) {
6306 t = ti;
6307 break;
6310 if (t == NULL)
6311 return FALSE;
6313 if (adjustment == NULL)
6314 adjustment = gtk_scrolled_window_get_vadjustment(
6315 GTK_SCROLLED_WINDOW(t->browser_win));
6317 view_size = gtk_adjustment_get_page_size(adjustment);
6318 value = gtk_adjustment_get_value(adjustment);
6319 max = gtk_adjustment_get_upper(adjustment) - view_size;
6321 if (max == 0)
6322 position = g_strdup("All");
6323 else if (value == max)
6324 position = g_strdup("Bot");
6325 else if (value == 0)
6326 position = g_strdup("Top");
6327 else
6328 position = g_strdup_printf("%d%%", (int) ((value / max) * 100));
6330 gtk_entry_set_text(GTK_ENTRY(t->sbe.position), position);
6331 g_free(position);
6333 return (TRUE);
6336 GtkWidget *
6337 create_window(const gchar *name)
6339 GtkWidget *w;
6341 w = gtk_window_new(GTK_WINDOW_TOPLEVEL);
6342 if (window_maximize)
6343 gtk_window_maximize(GTK_WINDOW(w));
6344 else
6345 gtk_window_set_default_size(GTK_WINDOW(w), window_width, window_height);
6346 gtk_widget_set_name(w, name);
6347 gtk_window_set_wmclass(GTK_WINDOW(w), name, "Xombrero");
6349 return (w);
6352 GtkWidget *
6353 create_browser(struct tab *t)
6355 GtkWidget *w;
6356 gchar *strval;
6357 GtkAdjustment *adjustment;
6359 if (t == NULL) {
6360 show_oops(NULL, "create_browser invalid parameters");
6361 return (NULL);
6364 t->sb_h = GTK_SCROLLBAR(gtk_hscrollbar_new(NULL));
6365 t->sb_v = GTK_SCROLLBAR(gtk_vscrollbar_new(NULL));
6366 t->adjust_h = gtk_range_get_adjustment(GTK_RANGE(t->sb_h));
6367 t->adjust_v = gtk_range_get_adjustment(GTK_RANGE(t->sb_v));
6369 w = gtk_scrolled_window_new(t->adjust_h, t->adjust_v);
6370 gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(w),
6371 GTK_POLICY_AUTOMATIC, GTK_POLICY_AUTOMATIC);
6373 t->wv = WEBKIT_WEB_VIEW(webkit_web_view_new());
6374 gtk_container_add(GTK_CONTAINER(w), GTK_WIDGET(t->wv));
6376 /* set defaults */
6377 t->settings = webkit_web_settings_new();
6379 g_object_set(t->settings, "default-encoding", encoding, (char *)NULL);
6381 if (user_agent == NULL) {
6382 g_object_get(G_OBJECT(t->settings), "user-agent", &strval,
6383 (char *)NULL);
6384 t->user_agent = g_strdup_printf("%s %s+", strval, version);
6385 g_free(strval);
6386 } else
6387 t->user_agent = g_strdup(user_agent->value);
6389 t->stylesheet = g_strdup_printf("file://%s/style.css", resource_dir);
6390 t->load_images = auto_load_images;
6392 adjustment =
6393 gtk_scrolled_window_get_vadjustment(GTK_SCROLLED_WINDOW(w));
6394 g_signal_connect(G_OBJECT(adjustment), "value-changed",
6395 G_CALLBACK(update_statusbar_position), NULL);
6397 setup_webkit(t);
6398 setup_inspector(t);
6400 return (w);
6403 GtkWidget *
6404 create_kiosk_toolbar(struct tab *t)
6406 GtkWidget *toolbar = NULL, *b;
6408 b = gtk_hbox_new(FALSE, 0);
6409 toolbar = b;
6410 gtk_container_set_border_width(GTK_CONTAINER(toolbar), 0);
6412 /* backward button */
6413 t->backward = create_button("Back", GTK_STOCK_GO_BACK, 0);
6414 gtk_widget_set_sensitive(t->backward, FALSE);
6415 g_signal_connect(G_OBJECT(t->backward), "clicked",
6416 G_CALLBACK(backward_cb), t);
6417 gtk_box_pack_start(GTK_BOX(b), t->backward, TRUE, TRUE, 0);
6419 /* forward button */
6420 t->forward = create_button("Forward", GTK_STOCK_GO_FORWARD, 0);
6421 gtk_widget_set_sensitive(t->forward, FALSE);
6422 g_signal_connect(G_OBJECT(t->forward), "clicked",
6423 G_CALLBACK(forward_cb), t);
6424 gtk_box_pack_start(GTK_BOX(b), t->forward, TRUE, TRUE, 0);
6426 /* home button */
6427 t->gohome = create_button("Home", GTK_STOCK_HOME, 0);
6428 gtk_widget_set_sensitive(t->gohome, true);
6429 g_signal_connect(G_OBJECT(t->gohome), "clicked",
6430 G_CALLBACK(home_cb), t);
6431 gtk_box_pack_start(GTK_BOX(b), t->gohome, TRUE, TRUE, 0);
6433 /* create widgets but don't use them */
6434 t->uri_entry = gtk_entry_new();
6435 t->default_style = gtk_rc_get_style(t->uri_entry);
6436 t->stop = create_button("Stop", GTK_STOCK_STOP, 0);
6437 t->js_toggle = create_button("JS-Toggle", enable_scripts ?
6438 GTK_STOCK_MEDIA_PLAY : GTK_STOCK_MEDIA_PAUSE, 0);
6440 return (toolbar);
6443 GtkWidget *
6444 create_toolbar(struct tab *t)
6446 GtkWidget *toolbar = NULL, *b, *eb1;
6448 b = gtk_hbox_new(FALSE, 0);
6449 toolbar = b;
6450 gtk_container_set_border_width(GTK_CONTAINER(toolbar), 0);
6452 /* backward button */
6453 t->backward = create_button("Back", GTK_STOCK_GO_BACK, 0);
6454 gtk_widget_set_sensitive(t->backward, FALSE);
6455 g_signal_connect(G_OBJECT(t->backward), "clicked",
6456 G_CALLBACK(backward_cb), t);
6457 gtk_box_pack_start(GTK_BOX(b), t->backward, FALSE, FALSE, 0);
6459 /* forward button */
6460 t->forward = create_button("Forward",GTK_STOCK_GO_FORWARD, 0);
6461 gtk_widget_set_sensitive(t->forward, FALSE);
6462 g_signal_connect(G_OBJECT(t->forward), "clicked",
6463 G_CALLBACK(forward_cb), t);
6464 gtk_box_pack_start(GTK_BOX(b), t->forward, FALSE,
6465 FALSE, 0);
6467 /* stop button */
6468 t->stop = create_button("Stop", GTK_STOCK_STOP, 0);
6469 gtk_widget_set_sensitive(t->stop, FALSE);
6470 g_signal_connect(G_OBJECT(t->stop), "clicked",
6471 G_CALLBACK(stop_cb), t);
6472 gtk_box_pack_start(GTK_BOX(b), t->stop, FALSE,
6473 FALSE, 0);
6475 /* JS button */
6476 t->js_toggle = create_button("JS-Toggle", enable_scripts ?
6477 GTK_STOCK_MEDIA_PLAY : GTK_STOCK_MEDIA_PAUSE, 0);
6478 gtk_widget_set_sensitive(t->js_toggle, TRUE);
6479 g_signal_connect(G_OBJECT(t->js_toggle), "clicked",
6480 G_CALLBACK(js_toggle_cb), t);
6481 gtk_box_pack_start(GTK_BOX(b), t->js_toggle, FALSE, FALSE, 0);
6483 t->uri_entry = gtk_entry_new();
6484 g_signal_connect(G_OBJECT(t->uri_entry), "activate",
6485 G_CALLBACK(activate_uri_entry_cb), t);
6486 g_signal_connect(G_OBJECT(t->uri_entry), "key-press-event",
6487 G_CALLBACK(entry_key_cb), t);
6488 completion_add(t);
6489 eb1 = gtk_hbox_new(FALSE, 0);
6490 gtk_container_set_border_width(GTK_CONTAINER(eb1), 1);
6491 gtk_box_pack_start(GTK_BOX(eb1), t->uri_entry, TRUE, TRUE, 0);
6492 gtk_box_pack_start(GTK_BOX(b), eb1, TRUE, TRUE, 0);
6494 /* search entry */
6495 if (search_string != NULL && strlen(search_string) != 0) {
6496 GtkWidget *eb2;
6497 t->search_entry = gtk_entry_new();
6498 gtk_entry_set_width_chars(GTK_ENTRY(t->search_entry), 30);
6499 g_signal_connect(G_OBJECT(t->search_entry), "activate",
6500 G_CALLBACK(activate_search_entry_cb), t);
6501 g_signal_connect(G_OBJECT(t->search_entry), "key-press-event",
6502 G_CALLBACK(entry_key_cb), t);
6503 gtk_widget_set_size_request(t->search_entry, -1, -1);
6504 eb2 = gtk_hbox_new(FALSE, 0);
6505 gtk_container_set_border_width(GTK_CONTAINER(eb2), 1);
6506 gtk_box_pack_start(GTK_BOX(eb2), t->search_entry, TRUE, TRUE,
6508 gtk_box_pack_start(GTK_BOX(b), eb2, FALSE, FALSE, 0);
6510 t->default_style = gtk_rc_get_style(t->uri_entry);
6512 return (toolbar);
6515 GtkWidget *
6516 create_buffers(struct tab *t)
6518 GtkCellRenderer *renderer;
6519 GtkWidget *view;
6521 view = gtk_tree_view_new();
6523 gtk_tree_view_set_headers_visible(GTK_TREE_VIEW(view), FALSE);
6525 renderer = gtk_cell_renderer_text_new();
6526 gtk_tree_view_insert_column_with_attributes
6527 (GTK_TREE_VIEW(view), -1, "Id", renderer, "text", COL_ID, (char *)NULL);
6529 renderer = gtk_cell_renderer_pixbuf_new();
6530 gtk_tree_view_insert_column_with_attributes
6531 (GTK_TREE_VIEW(view), -1, "Favicon", renderer, "pixbuf", COL_FAVICON,
6532 (char *)NULL);
6534 renderer = gtk_cell_renderer_text_new();
6535 gtk_tree_view_insert_column_with_attributes
6536 (GTK_TREE_VIEW(view), -1, "Title", renderer, "text", COL_TITLE,
6537 (char *)NULL);
6539 gtk_tree_view_set_model
6540 (GTK_TREE_VIEW(view), GTK_TREE_MODEL(buffers_store));
6542 return (view);
6545 void
6546 row_activated_cb(GtkTreeView *view, GtkTreePath *path,
6547 GtkTreeViewColumn *col, struct tab *t)
6549 GtkTreeIter iter;
6550 guint id;
6552 gtk_widget_grab_focus(GTK_WIDGET(t->wv));
6554 if (gtk_tree_model_get_iter(GTK_TREE_MODEL(buffers_store), &iter,
6555 path)) {
6556 gtk_tree_model_get
6557 (GTK_TREE_MODEL(buffers_store), &iter, COL_ID, &id, -1);
6558 set_current_tab(id - 1);
6561 hide_buffers(t);
6564 /* after tab reordering/creation/removal */
6565 void
6566 recalc_tabs(void)
6568 struct tab *t;
6569 int maxid = 0;
6571 TAILQ_FOREACH(t, &tabs, entry) {
6572 t->tab_id = gtk_notebook_page_num(notebook, t->vbox);
6573 if (t->tab_id > maxid)
6574 maxid = t->tab_id;
6576 gtk_widget_show(t->tab_elems.sep);
6579 TAILQ_FOREACH(t, &tabs, entry) {
6580 if (t->tab_id == maxid) {
6581 gtk_widget_hide(t->tab_elems.sep);
6582 break;
6587 /* after active tab change */
6588 void
6589 recolor_compact_tabs(void)
6591 struct tab *t;
6592 int curid = 0;
6593 GdkColor color;
6595 gdk_color_parse(XT_COLOR_CT_INACTIVE, &color);
6596 TAILQ_FOREACH(t, &tabs, entry)
6597 gtk_widget_modify_fg(t->tab_elems.label, GTK_STATE_NORMAL,
6598 &color);
6600 curid = gtk_notebook_get_current_page(notebook);
6601 TAILQ_FOREACH(t, &tabs, entry)
6602 if (t->tab_id == curid) {
6603 gdk_color_parse(XT_COLOR_CT_ACTIVE, &color);
6604 gtk_widget_modify_fg(t->tab_elems.label,
6605 GTK_STATE_NORMAL, &color);
6606 break;
6610 void
6611 set_current_tab(int page_num)
6613 buffercmd_abort(get_current_tab());
6614 gtk_notebook_set_current_page(notebook, page_num);
6615 recolor_compact_tabs();
6619 undo_close_tab_save(struct tab *t)
6621 int m, n;
6622 const gchar *uri;
6623 struct undo *u1, *u2;
6624 GList *items;
6625 WebKitWebHistoryItem *item;
6627 if ((uri = get_uri(t)) == NULL)
6628 return (1);
6630 u1 = g_malloc0(sizeof(struct undo));
6631 u1->uri = g_strdup(uri);
6633 t->bfl = webkit_web_view_get_back_forward_list(t->wv);
6635 m = webkit_web_back_forward_list_get_forward_length(t->bfl);
6636 n = webkit_web_back_forward_list_get_back_length(t->bfl);
6637 u1->back = n;
6639 /* forward history */
6640 items = webkit_web_back_forward_list_get_forward_list_with_limit(t->bfl, m);
6642 while (items) {
6643 item = items->data;
6644 u1->history = g_list_prepend(u1->history,
6645 webkit_web_history_item_copy(item));
6646 items = g_list_next(items);
6649 /* current item */
6650 if (m) {
6651 item = webkit_web_back_forward_list_get_current_item(t->bfl);
6652 u1->history = g_list_prepend(u1->history,
6653 webkit_web_history_item_copy(item));
6656 /* back history */
6657 items = webkit_web_back_forward_list_get_back_list_with_limit(t->bfl, n);
6659 while (items) {
6660 item = items->data;
6661 u1->history = g_list_prepend(u1->history,
6662 webkit_web_history_item_copy(item));
6663 items = g_list_next(items);
6666 TAILQ_INSERT_HEAD(&undos, u1, entry);
6668 if (undo_count > XT_MAX_UNDO_CLOSE_TAB) {
6669 u2 = TAILQ_LAST(&undos, undo_tailq);
6670 TAILQ_REMOVE(&undos, u2, entry);
6671 g_free(u2->uri);
6672 g_list_free(u2->history);
6673 g_free(u2);
6674 } else
6675 undo_count++;
6677 return (0);
6680 void
6681 delete_tab(struct tab *t)
6683 struct karg a;
6685 DNPRINTF(XT_D_TAB, "delete_tab: %p\n", t);
6687 if (t == NULL)
6688 return;
6691 * no need to join thread here because it won't access t on completion
6694 TAILQ_REMOVE(&tabs, t, entry);
6695 buffercmd_abort(t);
6697 /* Halt all webkit activity. */
6698 abort_favicon_download(t);
6699 webkit_web_view_stop_loading(t->wv);
6701 /* Save the tab, so we can undo the close. */
6702 undo_close_tab_save(t);
6704 /* just in case */
6705 if (t->search_id)
6706 g_source_remove(t->search_id);
6708 /* inspector */
6709 bzero(&a, sizeof a);
6710 a.i = XT_INS_CLOSE;
6711 inspector_cmd(t, &a);
6713 if (browser_mode == XT_BM_KIOSK) {
6714 gtk_widget_destroy(t->uri_entry);
6715 gtk_widget_destroy(t->stop);
6716 gtk_widget_destroy(t->js_toggle);
6719 gtk_widget_destroy(t->tab_elems.eventbox);
6720 gtk_widget_destroy(t->vbox);
6722 g_free(t->user_agent);
6723 g_free(t->stylesheet);
6724 g_free(t->tmp_uri);
6725 g_free(t);
6726 t = NULL;
6728 if (TAILQ_EMPTY(&tabs)) {
6729 if (browser_mode == XT_BM_KIOSK)
6730 create_new_tab(home, NULL, 1, -1);
6731 else
6732 create_new_tab(NULL, NULL, 1, -1);
6735 /* recreate session */
6736 if (session_autosave) {
6737 bzero(&a, sizeof a);
6738 a.s = NULL;
6739 save_tabs(NULL, &a);
6742 recalc_tabs();
6743 recolor_compact_tabs();
6746 void
6747 update_statusbar_zoom(struct tab *t)
6749 gfloat zoom;
6750 char s[16] = { '\0' };
6752 g_object_get(G_OBJECT(t->wv), "zoom-level", &zoom, (char *)NULL);
6753 if ((zoom <= 0.99 || zoom >= 1.01))
6754 snprintf(s, sizeof s, "%d%%", (int)(zoom * 100));
6755 gtk_entry_set_text(GTK_ENTRY(t->sbe.zoom), s);
6758 void
6759 setzoom_webkit(struct tab *t, int adjust)
6761 #define XT_ZOOMPERCENT 0.04
6763 gfloat zoom;
6765 if (t == NULL) {
6766 show_oops(NULL, "setzoom_webkit invalid parameters");
6767 return;
6770 g_object_get(G_OBJECT(t->wv), "zoom-level", &zoom, (char *)NULL);
6771 if (adjust == XT_ZOOM_IN)
6772 zoom += XT_ZOOMPERCENT;
6773 else if (adjust == XT_ZOOM_OUT)
6774 zoom -= XT_ZOOMPERCENT;
6775 else if (adjust > 0)
6776 zoom = default_zoom_level + adjust / 100.0 - 1.0;
6777 else {
6778 show_oops(t, "setzoom_webkit invalid zoom value");
6779 return;
6782 if (zoom < XT_ZOOMPERCENT)
6783 zoom = XT_ZOOMPERCENT;
6784 g_object_set(G_OBJECT(t->wv), "zoom-level", zoom, (char *)NULL);
6785 update_statusbar_zoom(t);
6788 gboolean
6789 tab_clicked_cb(GtkWidget *widget, GdkEventButton *event, gpointer data)
6791 struct tab *t = (struct tab *) data;
6793 DNPRINTF(XT_D_TAB, "tab_clicked_cb: tab: %d\n", t->tab_id);
6795 switch (event->button) {
6796 case 1:
6797 set_current_tab(t->tab_id);
6798 break;
6799 case 2:
6800 delete_tab(t);
6801 break;
6804 return TRUE;
6807 void
6808 append_tab(struct tab *t)
6810 if (t == NULL)
6811 return;
6813 TAILQ_INSERT_TAIL(&tabs, t, entry);
6814 t->tab_id = gtk_notebook_append_page(notebook, t->vbox, t->tab_content);
6817 GtkWidget *
6818 create_sbe(int width)
6820 GtkWidget *sbe;
6822 sbe = gtk_entry_new();
6823 gtk_entry_set_inner_border(GTK_ENTRY(sbe), NULL);
6824 gtk_entry_set_has_frame(GTK_ENTRY(sbe), FALSE);
6825 gtk_widget_set_can_focus(GTK_WIDGET(sbe), FALSE);
6826 gtk_widget_modify_font(GTK_WIDGET(sbe), statusbar_font);
6827 gtk_entry_set_alignment(GTK_ENTRY(sbe), 1.0);
6828 gtk_widget_set_size_request(sbe, width, -1);
6830 return sbe;
6833 struct tab *
6834 create_new_tab(char *title, struct undo *u, int focus, int position)
6836 struct tab *t;
6837 int load = 1, id;
6838 GtkWidget *b, *bb;
6839 WebKitWebHistoryItem *item;
6840 GList *items;
6841 GdkColor color;
6842 char *p;
6843 int sbe_p = 0, sbe_b = 0,
6844 sbe_z = 0;
6846 DNPRINTF(XT_D_TAB, "create_new_tab: title %s focus %d\n", title, focus);
6848 if (tabless && !TAILQ_EMPTY(&tabs)) {
6849 DNPRINTF(XT_D_TAB, "create_new_tab: new tab rejected\n");
6850 return (NULL);
6853 t = g_malloc0(sizeof *t);
6855 if (title == NULL) {
6856 title = "(untitled)";
6857 load = 0;
6860 t->vbox = gtk_vbox_new(FALSE, 0);
6862 /* label + button for tab */
6863 b = gtk_hbox_new(FALSE, 0);
6864 t->tab_content = b;
6866 #if GTK_CHECK_VERSION(2, 20, 0)
6867 t->spinner = gtk_spinner_new();
6868 #endif
6869 t->label = gtk_label_new(title);
6870 bb = create_button("Close", GTK_STOCK_CLOSE, 1);
6871 gtk_widget_set_size_request(t->label, 100, 0);
6872 gtk_label_set_max_width_chars(GTK_LABEL(t->label), 20);
6873 gtk_label_set_ellipsize(GTK_LABEL(t->label), PANGO_ELLIPSIZE_END);
6874 gtk_widget_set_size_request(b, 130, 0);
6876 gtk_box_pack_start(GTK_BOX(b), bb, FALSE, FALSE, 0);
6877 gtk_box_pack_start(GTK_BOX(b), t->label, FALSE, FALSE, 0);
6878 #if GTK_CHECK_VERSION(2, 20, 0)
6879 gtk_box_pack_start(GTK_BOX(b), t->spinner, FALSE, FALSE, 0);
6880 #endif
6882 /* toolbar */
6883 if (browser_mode == XT_BM_KIOSK) {
6884 t->toolbar = create_kiosk_toolbar(t);
6885 gtk_box_pack_start(GTK_BOX(t->vbox), t->toolbar, FALSE, FALSE,
6887 } else {
6888 t->toolbar = create_toolbar(t);
6889 if (fancy_bar)
6890 gtk_box_pack_start(GTK_BOX(t->vbox), t->toolbar, FALSE,
6891 FALSE, 0);
6894 /* marks */
6895 marks_clear(t);
6897 /* browser */
6898 t->browser_win = create_browser(t);
6899 gtk_box_pack_start(GTK_BOX(t->vbox), t->browser_win, TRUE, TRUE, 0);
6901 /* oops message for user feedback */
6902 t->oops = gtk_entry_new();
6903 gtk_entry_set_inner_border(GTK_ENTRY(t->oops), NULL);
6904 gtk_entry_set_has_frame(GTK_ENTRY(t->oops), FALSE);
6905 gtk_widget_set_can_focus(GTK_WIDGET(t->oops), FALSE);
6906 gdk_color_parse(XT_COLOR_RED, &color);
6907 gtk_widget_modify_base(t->oops, GTK_STATE_NORMAL, &color);
6908 gtk_box_pack_end(GTK_BOX(t->vbox), t->oops, FALSE, FALSE, 0);
6909 gtk_widget_modify_font(GTK_WIDGET(t->oops), oops_font);
6911 /* command entry */
6912 t->cmd = gtk_entry_new();
6913 gtk_entry_set_inner_border(GTK_ENTRY(t->cmd), NULL);
6914 gtk_entry_set_has_frame(GTK_ENTRY(t->cmd), FALSE);
6915 gtk_box_pack_end(GTK_BOX(t->vbox), t->cmd, FALSE, FALSE, 0);
6916 gtk_widget_modify_font(GTK_WIDGET(t->cmd), cmd_font);
6918 /* status bar */
6919 t->statusbar_box = gtk_hbox_new(FALSE, 0);
6921 t->sbe.statusbar = gtk_entry_new();
6922 gtk_entry_set_inner_border(GTK_ENTRY(t->sbe.statusbar), NULL);
6923 gtk_entry_set_has_frame(GTK_ENTRY(t->sbe.statusbar), FALSE);
6924 gtk_widget_set_can_focus(GTK_WIDGET(t->sbe.statusbar), FALSE);
6925 gtk_widget_modify_font(GTK_WIDGET(t->sbe.statusbar), statusbar_font);
6927 /* create these widgets only if specified in statusbar_elems */
6929 t->sbe.position = create_sbe(40);
6930 t->sbe.zoom = create_sbe(40);
6931 t->sbe.buffercmd = create_sbe(60);
6933 statusbar_modify_attr(t, XT_COLOR_WHITE, XT_COLOR_BLACK);
6935 gtk_box_pack_start(GTK_BOX(t->statusbar_box), t->sbe.statusbar, TRUE,
6936 TRUE, FALSE);
6938 /* gtk widgets cannot be added to a box twice. sbe_* variables
6939 make sure of this */
6940 for (p = statusbar_elems; *p != '\0'; p++) {
6941 switch (*p) {
6942 case '|':
6944 GtkWidget *sep = gtk_vseparator_new();
6946 gdk_color_parse(XT_COLOR_SB_SEPARATOR, &color);
6947 gtk_widget_modify_bg(sep, GTK_STATE_NORMAL, &color);
6948 gtk_box_pack_start(GTK_BOX(t->statusbar_box), sep,
6949 FALSE, FALSE, FALSE);
6950 break;
6952 case 'P':
6953 if (sbe_p) {
6954 warnx("flag \"%c\" specified more than "
6955 "once in statusbar_elems\n", *p);
6956 break;
6958 sbe_p = 1;
6959 gtk_box_pack_start(GTK_BOX(t->statusbar_box),
6960 t->sbe.position, FALSE, FALSE, FALSE);
6961 break;
6962 case 'B':
6963 if (sbe_b) {
6964 warnx("flag \"%c\" specified more than "
6965 "once in statusbar_elems\n", *p);
6966 break;
6968 sbe_b = 1;
6969 gtk_box_pack_start(GTK_BOX(t->statusbar_box),
6970 t->sbe.buffercmd, FALSE, FALSE, FALSE);
6971 break;
6972 case 'Z':
6973 if (sbe_z) {
6974 warnx("flag \"%c\" specified more than "
6975 "once in statusbar_elems\n", *p);
6976 break;
6978 sbe_z = 1;
6979 gtk_box_pack_start(GTK_BOX(t->statusbar_box),
6980 t->sbe.zoom, FALSE, FALSE, FALSE);
6981 break;
6982 default:
6983 warnx("illegal flag \"%c\" in statusbar_elems\n", *p);
6984 break;
6988 gtk_box_pack_end(GTK_BOX(t->vbox), t->statusbar_box, FALSE, FALSE, 0);
6990 /* buffer list */
6991 t->buffers = create_buffers(t);
6992 gtk_box_pack_end(GTK_BOX(t->vbox), t->buffers, FALSE, FALSE, 0);
6994 /* xtp meaning is normal by default */
6995 t->xtp_meaning = XT_XTP_TAB_MEANING_NORMAL;
6997 /* set empty favicon */
6998 xt_icon_from_name(t, "text-html");
7000 /* and show it all */
7001 gtk_widget_show_all(b);
7002 gtk_widget_show_all(t->vbox);
7004 /* compact tab bar */
7005 t->tab_elems.label = gtk_label_new(title);
7006 t->tab_elems.favicon = gtk_image_new();
7007 gtk_label_set_width_chars(GTK_LABEL(t->tab_elems.label), 1.0);
7008 gtk_misc_set_alignment(GTK_MISC(t->tab_elems.label), 0.0, 0.0);
7009 gtk_misc_set_padding(GTK_MISC(t->tab_elems.label), 4.0, 4.0);
7010 gtk_widget_modify_font(GTK_WIDGET(t->tab_elems.label), tabbar_font);
7012 t->tab_elems.eventbox = gtk_event_box_new();
7013 t->tab_elems.box = gtk_hbox_new(FALSE, 0);
7014 t->tab_elems.sep = gtk_vseparator_new();
7016 gdk_color_parse(XT_COLOR_CT_BACKGROUND, &color);
7017 gtk_widget_modify_bg(t->tab_elems.eventbox, GTK_STATE_NORMAL, &color);
7018 gdk_color_parse(XT_COLOR_CT_INACTIVE, &color);
7019 gtk_widget_modify_fg(t->tab_elems.label, GTK_STATE_NORMAL, &color);
7020 gdk_color_parse(XT_COLOR_CT_SEPARATOR, &color);
7021 gtk_widget_modify_bg(t->tab_elems.sep, GTK_STATE_NORMAL, &color);
7023 gtk_box_pack_start(GTK_BOX(t->tab_elems.box), t->tab_elems.favicon, FALSE,
7024 FALSE, 0);
7025 gtk_box_pack_start(GTK_BOX(t->tab_elems.box), t->tab_elems.label, TRUE,
7026 TRUE, 0);
7027 gtk_box_pack_start(GTK_BOX(t->tab_elems.box), t->tab_elems.sep, FALSE,
7028 FALSE, 0);
7029 gtk_container_add(GTK_CONTAINER(t->tab_elems.eventbox),
7030 t->tab_elems.box);
7032 gtk_box_pack_start(GTK_BOX(tab_bar), t->tab_elems.eventbox, TRUE,
7033 TRUE, 0);
7034 gtk_widget_show_all(t->tab_elems.eventbox);
7036 if (append_next == 0 || gtk_notebook_get_n_pages(notebook) == 0)
7037 append_tab(t);
7038 else {
7039 id = position >= 0 ? position :
7040 gtk_notebook_get_current_page(notebook) + 1;
7041 if (id > gtk_notebook_get_n_pages(notebook))
7042 append_tab(t);
7043 else {
7044 TAILQ_INSERT_TAIL(&tabs, t, entry);
7045 gtk_notebook_insert_page(notebook, t->vbox, b, id);
7046 gtk_box_reorder_child(GTK_BOX(tab_bar),
7047 t->tab_elems.eventbox, id);
7048 recalc_tabs();
7052 #if GTK_CHECK_VERSION(2, 20, 0)
7053 /* turn spinner off if we are a new tab without uri */
7054 if (!load) {
7055 gtk_spinner_stop(GTK_SPINNER(t->spinner));
7056 gtk_widget_hide(t->spinner);
7058 #endif
7059 /* make notebook tabs reorderable */
7060 gtk_notebook_set_tab_reorderable(notebook, t->vbox, TRUE);
7062 /* compact tabs clickable */
7063 g_signal_connect(G_OBJECT(t->tab_elems.eventbox),
7064 "button_press_event", G_CALLBACK(tab_clicked_cb), t);
7066 g_object_connect(G_OBJECT(t->cmd),
7067 "signal::key-press-event", G_CALLBACK(cmd_keypress_cb), t,
7068 "signal::key-release-event", G_CALLBACK(cmd_keyrelease_cb), t,
7069 "signal::focus-out-event", G_CALLBACK(cmd_focusout_cb), t,
7070 "signal::activate", G_CALLBACK(cmd_activate_cb), t,
7071 "signal::populate-popup", G_CALLBACK(cmd_popup_cb), t,
7072 (char *)NULL);
7074 /* reuse wv_button_cb to hide oops */
7075 g_object_connect(G_OBJECT(t->oops),
7076 "signal::button_press_event", G_CALLBACK(wv_button_cb), t,
7077 (char *)NULL);
7079 g_signal_connect(t->buffers,
7080 "row-activated", G_CALLBACK(row_activated_cb), t);
7081 g_object_connect(G_OBJECT(t->buffers),
7082 "signal::key-press-event", G_CALLBACK(wv_keypress_cb), t, (char *)NULL);
7084 g_object_connect(G_OBJECT(t->wv),
7085 "signal::key-press-event", G_CALLBACK(wv_keypress_cb), t,
7086 "signal::hovering-over-link", G_CALLBACK(webview_hover_cb), t,
7087 "signal::download-requested", G_CALLBACK(webview_download_cb), t,
7088 "signal::mime-type-policy-decision-requested", G_CALLBACK(webview_mimetype_cb), t,
7089 "signal::navigation-policy-decision-requested", G_CALLBACK(webview_npd_cb), t,
7090 "signal::new-window-policy-decision-requested", G_CALLBACK(webview_npd_cb), t,
7091 "signal::resource-request-starting", G_CALLBACK(webview_rrs_cb), t,
7092 "signal::create-web-view", G_CALLBACK(webview_cwv_cb), t,
7093 "signal::close-web-view", G_CALLBACK(webview_closewv_cb), t,
7094 "signal::event", G_CALLBACK(webview_event_cb), t,
7095 "signal::load-finished", G_CALLBACK(webview_load_finished_cb), t,
7096 "signal::load-progress-changed", G_CALLBACK(webview_progress_changed_cb), t,
7097 "signal::icon-loaded", G_CALLBACK(notify_icon_loaded_cb), t,
7098 "signal::button_press_event", G_CALLBACK(wv_button_cb), t,
7099 "signal::button_release_event", G_CALLBACK(wv_release_button_cb), t,
7100 "signal::populate-popup", G_CALLBACK(wv_popup_cb), t,
7101 (char *)NULL);
7102 g_signal_connect(t->wv,
7103 "notify::load-status", G_CALLBACK(notify_load_status_cb), t);
7104 g_signal_connect(t->wv,
7105 "notify::title", G_CALLBACK(notify_title_cb), t);
7107 /* hijack the unused keys as if we were the browser */
7108 //g_object_connect(G_OBJECT(t->toolbar),
7109 // "signal-after::key-press-event", G_CALLBACK(wv_keypress_after_cb), t,
7110 // (char *)NULL);
7112 g_signal_connect(G_OBJECT(bb), "button_press_event",
7113 G_CALLBACK(tab_close_cb), t);
7115 /* setup history */
7116 t->bfl = webkit_web_view_get_back_forward_list(t->wv);
7117 /* restore the tab's history */
7118 if (u && u->history) {
7119 items = u->history;
7120 while (items) {
7121 item = items->data;
7122 webkit_web_back_forward_list_add_item(t->bfl, item);
7123 items = g_list_next(items);
7126 item = g_list_nth_data(u->history, u->back);
7127 if (item)
7128 webkit_web_view_go_to_back_forward_item(t->wv, item);
7130 g_list_free(items);
7131 g_list_free(u->history);
7132 } else
7133 webkit_web_back_forward_list_clear(t->bfl);
7135 /* hide stuff */
7136 hide_cmd(t);
7137 hide_oops(t);
7138 hide_buffers(t);
7139 url_set_visibility();
7140 statusbar_set_visibility();
7142 if (focus) {
7143 set_current_tab(t->tab_id);
7144 DNPRINTF(XT_D_TAB, "create_new_tab: going to tab: %d\n",
7145 t->tab_id);
7147 if (load) {
7148 gtk_entry_set_text(GTK_ENTRY(t->uri_entry), title);
7149 load_uri(t, title);
7150 } else {
7151 if (show_url == 1)
7152 gtk_widget_grab_focus(GTK_WIDGET(t->uri_entry));
7153 else
7154 focus_webview(t);
7156 } else if (load)
7157 load_uri(t, title);
7159 if (userstyle_global)
7160 apply_style(t);
7162 recolor_compact_tabs();
7163 setzoom_webkit(t, XT_ZOOM_NORMAL);
7164 return (t);
7167 void
7168 notebook_switchpage_cb(GtkNotebook *nb, GtkWidget *nbp, guint pn,
7169 gpointer *udata)
7171 struct tab *t;
7172 const gchar *uri;
7174 DNPRINTF(XT_D_TAB, "notebook_switchpage_cb: tab: %d\n", pn);
7176 if (gtk_notebook_get_current_page(notebook) == -1)
7177 recalc_tabs();
7179 TAILQ_FOREACH(t, &tabs, entry) {
7180 if (t->tab_id == pn) {
7181 DNPRINTF(XT_D_TAB, "notebook_switchpage_cb: going to "
7182 "%d\n", pn);
7184 uri = get_title(t, TRUE);
7185 gtk_window_set_title(GTK_WINDOW(main_window), uri);
7187 hide_cmd(t);
7188 hide_oops(t);
7190 if (t->focus_wv) {
7191 /* can't use focus_webview here */
7192 gtk_widget_grab_focus(GTK_WIDGET(t->wv));
7198 void
7199 notebook_pagereordered_cb(GtkNotebook *nb, GtkWidget *nbp, guint pn,
7200 gpointer *udata)
7202 struct tab *t = NULL, *tt;
7204 recalc_tabs();
7206 TAILQ_FOREACH(tt, &tabs, entry)
7207 if (tt->tab_id == pn) {
7208 t = tt;
7209 break;
7211 if (t == NULL)
7212 return;
7213 DNPRINTF(XT_D_TAB, "page_reordered_cb: tab: %d\n", t->tab_id);
7215 gtk_box_reorder_child(GTK_BOX(tab_bar), t->tab_elems.eventbox,
7216 t->tab_id);
7219 void
7220 menuitem_response(struct tab *t)
7222 gtk_notebook_set_current_page(notebook, t->tab_id);
7225 gboolean
7226 arrow_cb(GtkWidget *w, GdkEventButton *event, gpointer user_data)
7228 GtkWidget *menu, *menu_items;
7229 GdkEventButton *bevent;
7230 const gchar *uri;
7231 struct tab *ti;
7233 if (event->type == GDK_BUTTON_PRESS) {
7234 bevent = (GdkEventButton *) event;
7235 menu = gtk_menu_new();
7237 TAILQ_FOREACH(ti, &tabs, entry) {
7238 if ((uri = get_uri(ti)) == NULL)
7239 /* XXX make sure there is something to print */
7240 /* XXX add gui pages in here to look purdy */
7241 uri = "(untitled)";
7242 menu_items = gtk_menu_item_new_with_label(uri);
7243 gtk_menu_shell_append(GTK_MENU_SHELL(menu), menu_items);
7244 gtk_widget_show(menu_items);
7246 g_signal_connect_swapped((menu_items),
7247 "activate", G_CALLBACK(menuitem_response),
7248 (gpointer)ti);
7251 gtk_menu_popup(GTK_MENU(menu), NULL, NULL, NULL, NULL,
7252 bevent->button, bevent->time);
7254 /* unref object so it'll free itself when popped down */
7255 #if !GTK_CHECK_VERSION(3, 0, 0)
7256 /* XXX does not need unref with gtk+3? */
7257 g_object_ref_sink(menu);
7258 g_object_unref(menu);
7259 #endif
7261 return (TRUE /* eat event */);
7264 return (FALSE /* propagate */);
7268 icon_size_map(int iconsz)
7270 if (iconsz <= GTK_ICON_SIZE_INVALID ||
7271 iconsz > GTK_ICON_SIZE_DIALOG)
7272 return (GTK_ICON_SIZE_SMALL_TOOLBAR);
7274 return (iconsz);
7277 GtkWidget *
7278 create_button(char *name, char *stockid, int size)
7280 GtkWidget *button, *image;
7281 gchar *rcstring;
7282 int gtk_icon_size;
7284 rcstring = g_strdup_printf(
7285 "style \"%s-style\"\n"
7286 "{\n"
7287 " GtkWidget::focus-padding = 0\n"
7288 " GtkWidget::focus-line-width = 0\n"
7289 " xthickness = 0\n"
7290 " ythickness = 0\n"
7291 "}\n"
7292 "widget \"*.%s\" style \"%s-style\"", name, name, name);
7293 gtk_rc_parse_string(rcstring);
7294 g_free(rcstring);
7295 button = gtk_button_new();
7296 gtk_button_set_focus_on_click(GTK_BUTTON(button), FALSE);
7297 gtk_icon_size = icon_size_map(size ? size : icon_size);
7299 image = gtk_image_new_from_stock(stockid, gtk_icon_size);
7300 gtk_widget_set_size_request(GTK_WIDGET(image), -1, -1);
7301 gtk_container_set_border_width(GTK_CONTAINER(button), 1);
7302 gtk_container_add(GTK_CONTAINER(button), GTK_WIDGET(image));
7303 gtk_widget_set_name(button, name);
7304 gtk_button_set_relief(GTK_BUTTON(button), GTK_RELIEF_NONE);
7306 return (button);
7309 void
7310 button_set_stockid(GtkWidget *button, char *stockid)
7312 GtkWidget *image;
7314 image = gtk_image_new_from_stock(stockid, icon_size_map(icon_size));
7315 gtk_widget_set_size_request(GTK_WIDGET(image), -1, -1);
7316 gtk_button_set_image(GTK_BUTTON(button), image);
7319 void
7320 clipb_primary_cb(GtkClipboard *primary, GdkEvent *event, gpointer notused)
7322 gchar *p = NULL;
7323 GdkAtom atom = gdk_atom_intern("CUT_BUFFER0", FALSE);
7324 gint len;
7326 if (xterm_workaround == 0)
7327 return;
7330 * xterm doesn't play nice with clipboards because it clears the
7331 * primary when clicked. We rely on primary being set to properly
7332 * handle middle mouse button clicks (paste). So when someone clears
7333 * primary copy whatever is in CUT_BUFFER0 into primary to simualte
7334 * other application behavior (as in DON'T clear primary).
7337 p = gtk_clipboard_wait_for_text(primary);
7338 if (p == NULL) {
7339 if (gdk_property_get(gdk_get_default_root_window(),
7340 atom,
7341 gdk_atom_intern("STRING", FALSE),
7343 1024 * 1024 /* picked out of my butt */,
7344 FALSE,
7345 NULL,
7346 NULL,
7347 &len,
7348 (guchar **)&p)) {
7349 if (p == NULL)
7350 return;
7351 /* yes sir, we need to NUL the string */
7352 p[len] = '\0';
7353 gtk_clipboard_set_text(primary, p, -1);
7357 if (p)
7358 g_free(p);
7361 void
7362 create_canvas(void)
7364 GtkWidget *vbox;
7365 GList *l = NULL;
7366 GdkPixbuf *pb;
7367 char file[PATH_MAX];
7368 int i;
7370 vbox = gtk_vbox_new(FALSE, 0);
7371 gtk_box_set_spacing(GTK_BOX(vbox), 0);
7372 notebook = GTK_NOTEBOOK(gtk_notebook_new());
7373 #if !GTK_CHECK_VERSION(3, 0, 0)
7374 /* XXX seems to be needed with gtk+2 */
7375 gtk_notebook_set_tab_hborder(notebook, 0);
7376 gtk_notebook_set_tab_vborder(notebook, 0);
7377 #endif
7378 gtk_notebook_set_scrollable(notebook, TRUE);
7379 gtk_notebook_set_show_border(notebook, FALSE);
7380 gtk_widget_set_can_focus(GTK_WIDGET(notebook), FALSE);
7382 abtn = gtk_button_new();
7383 arrow = gtk_arrow_new(GTK_ARROW_DOWN, GTK_SHADOW_NONE);
7384 gtk_widget_set_size_request(arrow, -1, -1);
7385 gtk_container_add(GTK_CONTAINER(abtn), arrow);
7386 gtk_widget_set_size_request(abtn, -1, 20);
7388 #if GTK_CHECK_VERSION(2, 20, 0)
7389 gtk_notebook_set_action_widget(notebook, abtn, GTK_PACK_END);
7390 #endif
7391 gtk_widget_set_size_request(GTK_WIDGET(notebook), -1, -1);
7393 /* compact tab bar */
7394 tab_bar = gtk_hbox_new(TRUE, 0);
7396 gtk_box_pack_start(GTK_BOX(vbox), tab_bar, FALSE, FALSE, 0);
7397 gtk_box_pack_start(GTK_BOX(vbox), GTK_WIDGET(notebook), TRUE, TRUE, 0);
7398 gtk_widget_set_size_request(vbox, -1, -1);
7400 g_object_connect(G_OBJECT(notebook),
7401 "signal::switch-page", G_CALLBACK(notebook_switchpage_cb), NULL,
7402 (char *)NULL);
7403 g_object_connect(G_OBJECT(notebook),
7404 "signal::page-reordered", G_CALLBACK(notebook_pagereordered_cb),
7405 NULL, (char *)NULL);
7406 g_signal_connect(G_OBJECT(abtn), "button_press_event",
7407 G_CALLBACK(arrow_cb), NULL);
7409 main_window = create_window("xombrero");
7410 gtk_container_add(GTK_CONTAINER(main_window), vbox);
7411 g_signal_connect(G_OBJECT(main_window), "delete_event",
7412 G_CALLBACK(gtk_main_quit), NULL);
7414 /* icons */
7415 for (i = 0; i < LENGTH(icons); i++) {
7416 snprintf(file, sizeof file, "%s" PS "%s", resource_dir, icons[i]);
7417 pb = gdk_pixbuf_new_from_file(file, NULL);
7418 l = g_list_append(l, pb);
7420 gtk_window_set_default_icon_list(l);
7422 /* clipboard work around */
7423 if (xterm_workaround)
7424 g_signal_connect(
7425 G_OBJECT(gtk_clipboard_get(GDK_SELECTION_PRIMARY)),
7426 "owner-change", G_CALLBACK(clipb_primary_cb), NULL);
7428 gtk_widget_show_all(abtn);
7429 gtk_widget_show_all(main_window);
7430 notebook_tab_set_visibility();
7433 #ifndef XT_SOCKET_DISABLE
7435 send_cmd_to_socket(char *cmd)
7437 int s, len, rv = 1;
7438 struct sockaddr_un sa;
7440 if ((s = socket(AF_UNIX, SOCK_STREAM, 0)) == -1) {
7441 warnx("%s: socket", __func__);
7442 return (rv);
7445 sa.sun_family = AF_UNIX;
7446 snprintf(sa.sun_path, sizeof(sa.sun_path), "%s" PS "%s",
7447 work_dir, XT_SOCKET_FILE);
7448 len = SUN_LEN(&sa);
7450 if (connect(s, (struct sockaddr *)&sa, len) == -1) {
7451 warnx("%s: connect", __func__);
7452 goto done;
7455 if (send(s, cmd, strlen(cmd) + 1, 0) == -1) {
7456 warnx("%s: send", __func__);
7457 goto done;
7460 rv = 0;
7461 done:
7462 close(s);
7463 return (rv);
7466 gboolean
7467 socket_watcher(GIOChannel *source, GIOCondition condition, gpointer data)
7469 int s, n;
7470 char str[XT_MAX_URL_LENGTH];
7471 socklen_t t = sizeof(struct sockaddr_un);
7472 struct sockaddr_un sa;
7473 struct passwd *p;
7474 uid_t uid;
7475 gid_t gid;
7476 struct tab *tt;
7477 gint fd = g_io_channel_unix_get_fd(source);
7479 if ((s = accept(fd, (struct sockaddr *)&sa, &t)) == -1) {
7480 warn("accept");
7481 return (FALSE);
7484 if (getpeereid(s, &uid, &gid) == -1) {
7485 warn("getpeereid");
7486 return (FALSE);
7488 if (uid != getuid() || gid != getgid()) {
7489 warnx("unauthorized user");
7490 return (FALSE);
7493 p = getpwuid(uid);
7494 if (p == NULL) {
7495 warnx("not a valid user");
7496 return (FALSE);
7499 n = recv(s, str, sizeof(str), 0);
7500 if (n <= 0)
7501 return (TRUE);
7503 tt = TAILQ_LAST(&tabs, tab_list);
7504 cmd_execute(tt, str);
7505 return (TRUE);
7509 is_running(void)
7511 int s, len, rv = 1;
7512 struct sockaddr_un sa;
7514 if ((s = socket(AF_UNIX, SOCK_STREAM, 0)) == -1) {
7515 warn("is_running: socket");
7516 return (-1);
7519 sa.sun_family = AF_UNIX;
7520 snprintf(sa.sun_path, sizeof(sa.sun_path), "%s" PS "%s",
7521 work_dir, XT_SOCKET_FILE);
7522 len = SUN_LEN(&sa);
7524 /* connect to see if there is a listener */
7525 if (connect(s, (struct sockaddr *)&sa, len) == -1)
7526 rv = 0; /* not running */
7527 else
7528 rv = 1; /* already running */
7530 close(s);
7532 return (rv);
7536 build_socket(void)
7538 int s, len;
7539 struct sockaddr_un sa;
7541 if ((s = socket(AF_UNIX, SOCK_STREAM, 0)) == -1) {
7542 warn("build_socket: socket");
7543 return (-1);
7546 sa.sun_family = AF_UNIX;
7547 snprintf(sa.sun_path, sizeof(sa.sun_path), "%s" PS "%s",
7548 work_dir, XT_SOCKET_FILE);
7549 len = SUN_LEN(&sa);
7551 /* connect to see if there is a listener */
7552 if (connect(s, (struct sockaddr *)&sa, len) == -1) {
7553 /* no listener so we will */
7554 unlink(sa.sun_path);
7556 if (bind(s, (struct sockaddr *)&sa, len) == -1) {
7557 warn("build_socket: bind");
7558 goto done;
7561 if (listen(s, 1) == -1) {
7562 warn("build_socket: listen");
7563 goto done;
7566 return (s);
7569 done:
7570 close(s);
7571 return (-1);
7573 #endif
7575 void
7576 xxx_dir(char *dir)
7578 struct stat sb;
7580 if (stat(dir, &sb)) {
7581 #if defined __MINGW32__
7582 printf("making: %s\n", dir);
7583 if (mkdir(dir) == -1)
7584 #else
7585 if (mkdir(dir, S_IRWXU) == -1)
7586 #endif
7587 err(1, "mkdir %s", dir);
7588 if (stat(dir, &sb))
7589 err(1, "stat %s", dir);
7591 if (S_ISDIR(sb.st_mode) == 0)
7592 errx(1, "%s not a dir", dir);
7593 #if !defined __MINGW32__
7594 if (((sb.st_mode & (S_IRWXU | S_IRWXG | S_IRWXO))) != S_IRWXU) {
7595 warnx("fixing invalid permissions on %s", dir);
7596 if (chmod(dir, S_IRWXU) == -1)
7597 err(1, "chmod %s", dir);
7599 #endif
7602 void
7603 usage(void)
7605 fprintf(stderr,
7606 "%s [-nSTVt][-f file][-s session] url ...\n", __progname);
7607 exit(0);
7610 GStaticRecMutex my_gdk_mtx = G_STATIC_REC_MUTEX_INIT;
7611 volatile int mtx_depth;
7612 int mtx_complain;
7615 * The linux flash plugin violates the gdk locking mechanism.
7616 * Work around the issue by using a recursive mutex with some match applied
7617 * to see if we hit a buggy condition.
7619 * The following code is painful so just don't read it. It really doesn't
7620 * make much sense but seems to work.
7622 void
7623 mtx_lock(void)
7625 char *s = NULL;
7626 g_static_rec_mutex_lock(&my_gdk_mtx);
7627 if (my_gdk_mtx.depth <= 0) {
7628 s = "lock <= 0";
7629 g_static_rec_mutex_lock(&my_gdk_mtx);
7630 goto complain;
7631 } else if (my_gdk_mtx.depth != 1) {
7632 s = "lock != 1";
7633 do {
7634 g_static_rec_mutex_unlock(&my_gdk_mtx);
7635 } while (my_gdk_mtx.depth > 1);
7636 goto complain;
7638 return;
7640 complain:
7641 if (mtx_complain == 0) {
7642 show_oops(NULL, "buggy mutex implementation detected(%s), "
7643 "work around implemented", s);
7644 mtx_complain = 1;
7648 void
7649 mtx_unlock(void)
7651 char *s = NULL;
7653 if (my_gdk_mtx.depth <= 0) {
7654 s = "unlock <= 0";
7655 goto complain;
7656 } else if (my_gdk_mtx.depth != 1) {
7657 s = "unlock != 1";
7658 g_static_rec_mutex_unlock_full(&my_gdk_mtx);
7659 goto complain;
7661 g_static_rec_mutex_unlock(&my_gdk_mtx);
7662 return;
7664 complain:
7665 if (mtx_complain == 0) {
7666 show_oops(NULL, "buggy mutex implementation detected(%s), "
7667 "work around implemented", s);
7668 mtx_complain = 1;
7672 void
7673 welcome(void)
7675 startpage_add("<b>Welcome to xombrero %s!</b><p>", version);
7676 startpage_add("Details at "
7677 "<a href=https://opensource.conformal.com/wiki/xombrero>xombrero "
7678 "wiki page</a><p>");
7682 main(int argc, char **argv)
7684 struct stat sb;
7685 int c, optn = 0, opte = 0, focus = 1;
7686 char conf[PATH_MAX] = { '\0' };
7687 char file[PATH_MAX];
7688 char sodversion[32];
7689 char *env_proxy = NULL;
7690 FILE *f = NULL;
7691 struct karg a;
7693 start_argv = (char * const *)argv;
7695 /* prepare gtk */
7696 #ifdef USE_THREADS
7697 #if !defined __MINGW32__
7698 /* http://web.archiveorange.com/archive/v/UsPjxkX5PsaXBIoOjqxf */
7699 XInitThreads();
7700 #endif
7701 /* http://developer.gnome.org/gdk/stable/gdk-Threads.html */
7702 g_thread_init(NULL);
7703 gdk_threads_set_lock_functions(mtx_lock, mtx_unlock);
7704 gdk_threads_init();
7705 gdk_threads_enter();
7707 /* http://www.gnupg.org/documentation/manuals/gcrypt/Multi_002dThreading.html */
7708 gcry_control (GCRYCTL_SET_THREAD_CBS, &gcry_threads_pthread);
7709 #endif
7710 gtk_init(&argc, &argv);
7712 gnutls_global_init();
7714 strlcpy(named_session, XT_SAVED_TABS_FILE, sizeof named_session);
7716 RB_INIT(&hl);
7717 RB_INIT(&js_wl);
7718 RB_INIT(&pl_wl);
7719 RB_INIT(&downloads);
7720 RB_INIT(&st_tree);
7722 TAILQ_INIT(&sessions);
7723 TAILQ_INIT(&tabs);
7724 TAILQ_INIT(&mtl);
7725 TAILQ_INIT(&aliases);
7726 TAILQ_INIT(&undos);
7727 TAILQ_INIT(&kbl);
7728 TAILQ_INIT(&spl);
7729 TAILQ_INIT(&chl);
7730 TAILQ_INIT(&shl);
7731 TAILQ_INIT(&ua_list);
7733 #ifndef XT_RESOURCE_LIMITS_DISABLE
7734 struct rlimit rlp;
7735 char *cmd = NULL;
7736 int s;
7737 GIOChannel *channel;
7739 /* fiddle with ulimits */
7740 if (getrlimit(RLIMIT_NOFILE, &rlp) == -1)
7741 warn("getrlimit");
7742 else {
7743 /* just use them all */
7744 rlp.rlim_cur = rlp.rlim_max;
7745 if (setrlimit(RLIMIT_NOFILE, &rlp) == -1)
7746 warn("setrlimit");
7747 if (getrlimit(RLIMIT_NOFILE, &rlp) == -1)
7748 warn("getrlimit");
7749 else if (rlp.rlim_cur < 1024)
7750 startpage_add("%s requires at least 1024 "
7751 "(2048 recommended) file " "descriptors, "
7752 "currently it has up to %d available",
7753 __progname, rlp.rlim_cur);
7755 #endif
7757 while ((c = getopt(argc, argv, "STVf:s:tne")) != -1) {
7758 switch (c) {
7759 case 'S':
7760 show_url = 0;
7761 break;
7762 case 'T':
7763 show_tabs = 0;
7764 break;
7765 case 'V':
7766 #ifdef XOMBRERO_BUILDSTR
7767 errx(0 , "Version: %s Build: %s",
7768 version, XOMBRERO_BUILDSTR);
7769 #else
7770 errx(0 , "Version: %s", version);
7771 #endif
7772 break;
7773 case 'f':
7774 strlcpy(conf, optarg, sizeof(conf));
7775 break;
7776 case 's':
7777 strlcpy(named_session, optarg, sizeof(named_session));
7778 break;
7779 case 't':
7780 tabless = 1;
7781 break;
7782 case 'n':
7783 optn = 1;
7784 break;
7785 case 'e':
7786 opte = 1;
7787 break;
7788 default:
7789 usage();
7790 /* NOTREACHED */
7793 argc -= optind;
7794 argv += optind;
7796 init_keybindings();
7798 xtp_generate_keys();
7800 /* XXX this hammer is way too big but treat all signaling the same */
7801 #ifndef XT_SIGNALS_DISABLE
7802 /* signals */
7803 struct sigaction sact;
7805 bzero(&sact, sizeof(sact));
7806 sigemptyset(&sact.sa_mask);
7807 sact.sa_handler = sigchild;
7808 sact.sa_flags = SA_NOCLDSTOP;
7809 sigaction(SIGCHLD, &sact, NULL);
7810 #endif
7812 /* set download dir */
7813 pwd = getpwuid(getuid());
7814 if (pwd == NULL)
7815 errx(1, "invalid user %d", getuid());
7816 strlcpy(download_dir, pwd->pw_dir, sizeof download_dir);
7818 /* compile buffer command regexes */
7819 buffercmd_init();
7821 /* set default string settings */
7822 home = g_strdup("https://www.cyphertite.com");
7823 search_string = g_strdup("about:search");
7824 resource_dir = g_strdup("/usr/local/share/xombrero/");
7825 strlcpy(runtime_settings, "runtime", sizeof runtime_settings);
7826 cmd_font_name = g_strdup("monospace normal 9");
7827 oops_font_name = g_strdup("monospace normal 9");
7828 statusbar_font_name = g_strdup("monospace normal 9");
7829 tabbar_font_name = g_strdup("monospace normal 9");
7830 statusbar_elems = g_strdup("BP");
7831 spell_check_languages = g_strdup("en_US");
7832 encoding = g_strdup("UTF-8");
7834 /* override os specific settings */
7835 if (os_init)
7836 os_init();
7838 /* read config file */
7839 if (strlen(conf) == 0)
7840 snprintf(conf, sizeof conf, "%s" PS ".%s",
7841 pwd->pw_dir, XT_CONF_FILE);
7842 config_parse(conf, 0);
7844 /* init fonts */
7845 cmd_font = pango_font_description_from_string(cmd_font_name);
7846 oops_font = pango_font_description_from_string(oops_font_name);
7847 statusbar_font = pango_font_description_from_string(statusbar_font_name);
7848 tabbar_font = pango_font_description_from_string(tabbar_font_name);
7850 /* working directory */
7851 if (strlen(work_dir) == 0)
7852 snprintf(work_dir, sizeof work_dir, "%s" PS "%s",
7853 pwd->pw_dir, XT_DIR);
7854 xxx_dir(work_dir);
7856 /* icon cache dir */
7857 snprintf(cache_dir, sizeof cache_dir, "%s" PS "%s", work_dir, XT_CACHE_DIR);
7858 xxx_dir(cache_dir);
7860 /* certs dir */
7861 snprintf(certs_dir, sizeof certs_dir, "%s" PS "%s", work_dir, XT_CERT_DIR);
7862 xxx_dir(certs_dir);
7864 /* sessions dir */
7865 snprintf(sessions_dir, sizeof sessions_dir, "%s" PS "%s",
7866 work_dir, XT_SESSIONS_DIR);
7867 xxx_dir(sessions_dir);
7869 /* js dir */
7870 snprintf(js_dir, sizeof js_dir, "%s" PS "%s", work_dir, XT_JS_DIR);
7871 xxx_dir(js_dir);
7873 /* temp dir */
7874 snprintf(temp_dir, sizeof temp_dir, "%s" PS "%s", work_dir, XT_TEMP_DIR);
7875 xxx_dir(temp_dir);
7877 /* runtime settings that can override config file */
7878 if (runtime_settings[0] != '\0')
7879 config_parse(runtime_settings, 1);
7881 /* download dir */
7882 if (!strcmp(download_dir, pwd->pw_dir))
7883 strlcat(download_dir, PS "downloads", sizeof download_dir);
7884 xxx_dir(download_dir);
7886 /* first start file */
7887 snprintf(file, sizeof file, "%s" PS "%s", work_dir, XT_SOD_FILE);
7888 if (stat(file, &sb)) {
7889 warnx("start of day file doesn't exist, creating it");
7890 if ((f = fopen(file, "w")) == NULL)
7891 err(1, "startofday");
7892 if (fputs(version, f) == EOF)
7893 err(1, "fputs");
7894 fclose(f);
7896 /* welcome user */
7897 welcome();
7898 } else {
7899 if ((f = fopen(file, "r+")) == NULL)
7900 err(1, "startofday");
7901 if (fgets(sodversion, sizeof sodversion, f) == NULL)
7902 err(1, "fgets");
7903 sodversion[strcspn(sodversion, "\n")] = '\0';
7904 if (strcmp(version, sodversion)) {
7905 if ((f = freopen(file, "w", f)) == NULL)
7906 err(1, "startofday");
7907 if (fputs(version, f) == EOF)
7908 err(1, "fputs");
7910 /* upgrade, say something smart */
7911 welcome();
7913 fclose(f);
7916 /* favorites file */
7917 snprintf(file, sizeof file, "%s" PS "%s", work_dir, XT_FAVS_FILE);
7918 if (stat(file, &sb)) {
7919 warnx("favorites file doesn't exist, creating it");
7920 if ((f = fopen(file, "w")) == NULL)
7921 err(1, "favorites");
7922 fclose(f);
7925 /* quickmarks file */
7926 snprintf(file, sizeof file, "%s" PS "%s", work_dir, XT_QMARKS_FILE);
7927 if (stat(file, &sb)) {
7928 warnx("quickmarks file doesn't exist, creating it");
7929 if ((f = fopen(file, "w")) == NULL)
7930 err(1, "quickmarks");
7931 fclose(f);
7934 /* search history */
7935 if (history_autosave) {
7936 snprintf(search_file, sizeof search_file, "%s" PS "%s",
7937 work_dir, XT_SEARCH_FILE);
7938 if (stat(search_file, &sb)) {
7939 warnx("search history file doesn't exist, creating it");
7940 if ((f = fopen(search_file, "w")) == NULL)
7941 err(1, "search_history");
7942 fclose(f);
7944 history_read(&shl, search_file, &search_history_count);
7947 /* command history */
7948 if (history_autosave) {
7949 snprintf(command_file, sizeof command_file, "%s" PS "%s",
7950 work_dir, XT_COMMAND_FILE);
7951 if (stat(command_file, &sb)) {
7952 warnx("command history file doesn't exist, creating it");
7953 if ((f = fopen(command_file, "w")) == NULL)
7954 err(1, "command_history");
7955 fclose(f);
7957 history_read(&chl, command_file, &cmd_history_count);
7960 /* cookies */
7961 session = webkit_get_default_session();
7962 setup_cookies();
7964 /* certs */
7965 set_ssl_ca_file(ssl_ca_file);
7967 /* guess_search regex */
7968 if (url_regex == NULL)
7969 url_regex = g_strdup(XT_URL_REGEX);
7970 if (url_regex)
7971 if (regcomp(&url_re, url_regex, REG_EXTENDED | REG_NOSUB))
7972 startpage_add("invalid url regex %s", url_regex);
7974 /* proxy */
7975 env_proxy = getenv("http_proxy");
7976 if (env_proxy)
7977 setup_proxy(env_proxy);
7978 else {
7979 env_proxy = getenv("HTTP_PROXY");
7980 if (env_proxy)
7981 setup_proxy(env_proxy);
7982 else
7983 setup_proxy(http_proxy);
7985 #ifndef XT_SOCKET_DISABLE
7986 if (opte) {
7987 send_cmd_to_socket(argv[0]);
7988 exit(0);
7990 #else
7991 opte = opte; /* shut mingw up */
7992 #endif
7993 /* set some connection parameters */
7994 g_object_set(session, "max-conns", max_connections, (char *)NULL);
7995 g_object_set(session, "max-conns-per-host", max_host_connections,
7996 (char *)NULL);
7998 g_signal_connect(session, "request-queued", G_CALLBACK(session_rq_cb),
7999 NULL);
8001 #ifndef XT_SOCKET_DISABLE
8002 /* see if there is already a xombrero running */
8003 if (single_instance && is_running()) {
8004 optn = 1;
8005 warnx("already running");
8008 if (optn) {
8009 while (argc) {
8010 cmd = g_strdup_printf("%s %s", "tabnew", argv[0]);
8011 send_cmd_to_socket(cmd);
8012 if (cmd)
8013 g_free(cmd);
8015 argc--;
8016 argv++;
8018 exit(0);
8020 #else
8021 optn = optn; /* shut mingw up */
8022 #endif
8023 /* tld list */
8024 tld_tree_init();
8026 if (enable_strict_transport)
8027 strict_transport_init();
8029 /* uri completion */
8030 completion_model = gtk_list_store_new(1, G_TYPE_STRING);
8032 /* buffers */
8033 buffers_store = gtk_list_store_new
8034 (NUM_COLS, G_TYPE_UINT, GDK_TYPE_PIXBUF, G_TYPE_STRING);
8036 qmarks_load();
8038 /* go graphical */
8039 create_canvas();
8040 notebook_tab_set_visibility();
8042 if (save_global_history)
8043 restore_global_history();
8045 /* restore session list */
8046 restore_sessions_list();
8048 if (!strcmp(named_session, XT_SAVED_TABS_FILE))
8049 restore_saved_tabs();
8050 else {
8051 a.s = named_session;
8052 a.i = XT_SES_DONOTHING;
8053 open_tabs(NULL, &a);
8056 /* see if we have an exception */
8057 if (!TAILQ_EMPTY(&spl)) {
8058 create_new_tab("about:startpage", NULL, focus, -1);
8059 focus = 0;
8062 while (argc) {
8063 create_new_tab(argv[0], NULL, focus, -1);
8064 focus = 0;
8066 argc--;
8067 argv++;
8070 if (TAILQ_EMPTY(&tabs))
8071 create_new_tab(home, NULL, 1, -1);
8072 #ifndef XT_SOCKET_DISABLE
8073 if (enable_socket)
8074 if ((s = build_socket()) != -1) {
8075 channel = g_io_channel_unix_new(s);
8076 g_io_add_watch(channel, G_IO_IN, socket_watcher, NULL);
8078 #endif
8080 gtk_main();
8082 #ifdef USE_THREADS
8083 GDK_FLUSH();
8084 gdk_threads_leave();
8085 g_static_rec_mutex_unlock_full(&my_gdk_mtx); /* just in case */
8086 #endif
8088 gnutls_global_deinit();
8090 if (url_regex)
8091 regfree(&url_re);
8093 return (0);