Add autorun JavaScript after page loads
[xombrero.git] / xxxterm.c
blob03aa39bdfc967e998908e44ca749869d77253a93
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 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>
9 * Permission to use, copy, modify, and distribute this software for any
10 * purpose with or without fee is hereby granted, provided that the above
11 * copyright notice and this permission notice appear in all copies.
13 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
14 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
15 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
16 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
17 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
18 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
19 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
22 #include "xxxterm.h"
24 char *version = XXXTERM_VERSION;
26 #ifdef XT_DEBUG
27 u_int32_t swm_debug = 0
28 | XT_D_MOVE
29 | XT_D_KEY
30 | XT_D_TAB
31 | XT_D_URL
32 | XT_D_CMD
33 | XT_D_NAV
34 | XT_D_DOWNLOAD
35 | XT_D_CONFIG
36 | XT_D_JS
37 | XT_D_FAVORITE
38 | XT_D_PRINTING
39 | XT_D_COOKIE
40 | XT_D_KEYBINDING
41 | XT_D_CLIP
42 | XT_D_BUFFERCMD
43 | XT_D_INSPECTOR
45 #endif
47 #ifdef USE_THREADS
48 GCRY_THREAD_OPTION_PTHREAD_IMPL;
49 #endif
51 char *icons[] = {
52 "xxxtermicon16.png",
53 "xxxtermicon32.png",
54 "xxxtermicon48.png",
55 "xxxtermicon64.png",
56 "xxxtermicon128.png"
59 struct session {
60 TAILQ_ENTRY(session) entry;
61 const gchar *name;
63 TAILQ_HEAD(session_list, session);
65 struct undo {
66 TAILQ_ENTRY(undo) entry;
67 gchar *uri;
68 GList *history;
69 int back; /* Keeps track of how many back
70 * history items there are. */
72 TAILQ_HEAD(undo_tailq, undo);
74 struct command_entry {
75 char *line;
76 TAILQ_ENTRY(command_entry) entry;
78 TAILQ_HEAD(command_list, command_entry);
80 /* defines */
81 #define XT_DIR (".xxxterm")
82 #define XT_CACHE_DIR ("cache")
83 #define XT_CERT_DIR ("certs/")
84 #define XT_JS_DIR ("js/")
85 #define XT_SESSIONS_DIR ("sessions/")
86 #define XT_CONF_FILE ("xxxterm.conf")
87 #define XT_QMARKS_FILE ("quickmarks")
88 #define XT_SAVED_TABS_FILE ("main_session")
89 #define XT_RESTART_TABS_FILE ("restart_tabs")
90 #define XT_SOCKET_FILE ("socket")
91 #define XT_HISTORY_FILE ("history")
92 #define XT_SAVE_SESSION_ID ("SESSION_NAME=")
93 #define XT_SEARCH_FILE ("search_history")
94 #define XT_COMMAND_FILE ("command_history")
95 #define XT_DLMAN_REFRESH "10"
96 #define XT_MAX_URL_LENGTH (4096) /* 1 page is atomic, don't make bigger */
97 #define XT_MAX_UNDO_CLOSE_TAB (32)
98 #define XT_RESERVED_CHARS "$&+,/:;=?@ \"<>#%%{}|^~[]`"
99 #define XT_PRINT_EXTRA_MARGIN 10
100 #define XT_URL_REGEX ("^[[:blank:]]*[^[:blank:]]*([[:alnum:]-]+\\.)+[[:alnum:]-][^[:blank:]]*[[:blank:]]*$")
101 #define XT_INVALID_MARK (-1) /* XXX this is a double, maybe use something else, like a nan */
103 /* colors */
104 #define XT_COLOR_RED "#cc0000"
105 #define XT_COLOR_YELLOW "#ffff66"
106 #define XT_COLOR_BLUE "lightblue"
107 #define XT_COLOR_GREEN "#99ff66"
108 #define XT_COLOR_WHITE "white"
109 #define XT_COLOR_BLACK "black"
111 #define XT_COLOR_CT_BACKGROUND "#000000"
112 #define XT_COLOR_CT_INACTIVE "#dddddd"
113 #define XT_COLOR_CT_ACTIVE "#bbbb00"
114 #define XT_COLOR_CT_SEPARATOR "#555555"
116 #define XT_COLOR_SB_SEPARATOR "#555555"
118 #define XT_PROTO_DELIM "://"
120 /* actions */
121 #define XT_MOVE_INVALID (0)
122 #define XT_MOVE_DOWN (1)
123 #define XT_MOVE_UP (2)
124 #define XT_MOVE_BOTTOM (3)
125 #define XT_MOVE_TOP (4)
126 #define XT_MOVE_PAGEDOWN (5)
127 #define XT_MOVE_PAGEUP (6)
128 #define XT_MOVE_HALFDOWN (7)
129 #define XT_MOVE_HALFUP (8)
130 #define XT_MOVE_LEFT (9)
131 #define XT_MOVE_FARLEFT (10)
132 #define XT_MOVE_RIGHT (11)
133 #define XT_MOVE_FARRIGHT (12)
134 #define XT_MOVE_PERCENT (13)
135 #define XT_MOVE_CENTER (14)
137 #define XT_QMARK_SET (0)
138 #define XT_QMARK_OPEN (1)
139 #define XT_QMARK_TAB (2)
141 #define XT_MARK_SET (0)
142 #define XT_MARK_GOTO (1)
144 #define XT_TAB_LAST (-4)
145 #define XT_TAB_FIRST (-3)
146 #define XT_TAB_PREV (-2)
147 #define XT_TAB_NEXT (-1)
148 #define XT_TAB_INVALID (0)
149 #define XT_TAB_NEW (1)
150 #define XT_TAB_DELETE (2)
151 #define XT_TAB_DELQUIT (3)
152 #define XT_TAB_OPEN (4)
153 #define XT_TAB_UNDO_CLOSE (5)
154 #define XT_TAB_SHOW (6)
155 #define XT_TAB_HIDE (7)
156 #define XT_TAB_NEXTSTYLE (8)
158 #define XT_NAV_INVALID (0)
159 #define XT_NAV_BACK (1)
160 #define XT_NAV_FORWARD (2)
161 #define XT_NAV_RELOAD (3)
162 #define XT_NAV_STOP (4)
164 #define XT_FOCUS_INVALID (0)
165 #define XT_FOCUS_URI (1)
166 #define XT_FOCUS_SEARCH (2)
168 #define XT_SEARCH_INVALID (0)
169 #define XT_SEARCH_NEXT (1)
170 #define XT_SEARCH_PREV (2)
172 #define XT_PASTE_CURRENT_TAB (0)
173 #define XT_PASTE_NEW_TAB (1)
175 #define XT_ZOOM_IN (-1)
176 #define XT_ZOOM_OUT (-2)
177 #define XT_ZOOM_NORMAL (100)
179 #define XT_URL_SHOW (1)
180 #define XT_URL_HIDE (2)
182 #define XT_CMD_OPEN (0)
183 #define XT_CMD_OPEN_CURRENT (1)
184 #define XT_CMD_TABNEW (2)
185 #define XT_CMD_TABNEW_CURRENT (3)
187 #define XT_STATUS_NOTHING (0)
188 #define XT_STATUS_LINK (1)
189 #define XT_STATUS_URI (2)
190 #define XT_STATUS_LOADING (3)
192 #define XT_SES_DONOTHING (0)
193 #define XT_SES_CLOSETABS (1)
195 #define XT_PREFIX (1<<0)
196 #define XT_USERARG (1<<1)
197 #define XT_URLARG (1<<2)
198 #define XT_INTARG (1<<3)
199 #define XT_SESSARG (1<<4)
200 #define XT_SETARG (1<<5)
202 #define XT_HINT_NEWTAB (1<<0)
204 #define XT_MODE_INSERT (0)
205 #define XT_MODE_COMMAND (1)
207 #define XT_BUFCMD_SZ (8)
209 #define XT_EJS_SHOW (1<<0)
211 GtkWidget * create_button(char *, char *, int);
213 void recalc_tabs(void);
214 void recolor_compact_tabs(void);
215 void set_current_tab(int page_num);
216 gboolean update_statusbar_position(GtkAdjustment*, gpointer);
217 void marks_clear(struct tab *t);
219 /* globals */
220 extern char *__progname;
221 char **start_argv;
222 struct passwd *pwd;
223 GtkWidget *main_window;
224 GtkNotebook *notebook;
225 GtkWidget *tab_bar;
226 GtkWidget *arrow, *abtn;
227 struct tab_list tabs;
228 struct history_list hl;
229 struct session_list sessions;
230 struct domain_list c_wl;
231 struct domain_list js_wl;
232 struct domain_list pl_wl;
233 struct undo_tailq undos;
234 struct keybinding_list kbl;
235 struct sp_list spl;
236 struct command_list chl;
237 struct command_list shl;
238 struct command_entry *history_at;
239 struct command_entry *search_at;
240 int undo_count;
241 int cmd_history_count = 0;
242 int search_history_count = 0;
243 char *global_search;
244 long long unsigned int blocked_cookies = 0;
245 char named_session[PATH_MAX];
246 GtkListStore *completion_model;
247 GtkListStore *buffers_store;
249 char *qmarks[XT_NOMARKS];
250 int btn_down; /* M1 down in any wv */
251 regex_t url_re; /* guess_search regex */
253 /* starts from 1 to catch atoi() failures when calling xtp_handle_dl() */
254 int next_download_id = 1;
256 void xxx_dir(char *);
257 int icon_size_map(int);
258 void completion_add(struct tab *);
259 void completion_add_uri(const gchar *);
261 void
262 history_delete(struct command_list *l, int *counter)
264 struct command_entry *c;
266 if (l == NULL || counter == NULL)
267 return;
269 c = TAILQ_LAST(l, command_list);
270 if (c == NULL)
271 return;
273 TAILQ_REMOVE(l, c, entry);
274 *counter -= 1;
275 g_free(c->line);
276 g_free(c);
279 void
280 history_add(struct command_list *list, char *file, char *l, int *counter)
282 struct command_entry *c;
283 FILE *f;
285 if (list == NULL || l == NULL || counter == NULL)
286 return;
288 /* don't add the same line */
289 c = TAILQ_FIRST(list);
290 if (c)
291 if (!strcmp(c->line + 1 /* skip space */, l))
292 return;
294 c = g_malloc0(sizeof *c);
295 c->line = g_strdup_printf(" %s", l);
297 *counter += 1;
298 TAILQ_INSERT_HEAD(list, c, entry);
300 if (*counter > 1000)
301 history_delete(list, counter);
303 if (history_autosave && file) {
304 f = fopen(file, "w");
305 if (f == NULL) {
306 show_oops(NULL, "couldn't write history %s", file);
307 return;
310 TAILQ_FOREACH_REVERSE(c, list, command_list, entry) {
311 c->line[0] = ' ';
312 fprintf(f, "%s\n", c->line);
315 fclose(f);
320 history_read(struct command_list *list, char *file, int *counter)
322 FILE *f;
323 char *s, line[65536];
325 if (list == NULL || file == NULL)
326 return (1);
328 f = fopen(file, "r");
329 if (f == NULL) {
330 startpage_add("couldn't open history file %s", file);
331 return (1);
334 for (;;) {
335 s = fgets(line, sizeof line, f);
336 if (s == NULL || feof(f) || ferror(f))
337 break;
338 if ((s = strchr(line, '\n')) == NULL) {
339 startpage_add("invalid history file %s", file);
340 fclose(f);
341 return (1);
343 *s = '\0';
345 history_add(list, NULL, line + 1, counter);
348 fclose(f);
350 return (0);
353 /* marks and quickmarks array storage.
354 * first a-z, then A-Z, then 0-9 */
355 char
356 indextomark(int i)
358 if (i < 0)
359 return (0);
361 if (i >= 0 && i <= 'z' - 'a')
362 return 'a' + i;
364 i -= 'z' - 'a' + 1;
365 if (i >= 0 && i <= 'Z' - 'A')
366 return 'A' + i;
368 i -= 'Z' - 'A' + 1;
369 if (i >= 10)
370 return (0);
372 return i + '0';
376 marktoindex(char m)
378 int ret = 0;
380 if (m >= 'a' && m <= 'z')
381 return ret + m - 'a';
383 ret += 'z' - 'a' + 1;
384 if (m >= 'A' && m <= 'Z')
385 return ret + m - 'A';
387 ret += 'Z' - 'A' + 1;
388 if (m >= '0' && m <= '9')
389 return ret + m - '0';
391 return (-1);
395 void
396 sigchild(int sig)
398 int saved_errno, status;
399 pid_t pid;
401 saved_errno = errno;
403 while ((pid = waitpid(WAIT_ANY, &status, WNOHANG)) != 0) {
404 if (pid == -1) {
405 if (errno == EINTR)
406 continue;
407 if (errno != ECHILD) {
409 clog_warn("sigchild: waitpid:");
412 break;
415 if (WIFEXITED(status)) {
416 if (WEXITSTATUS(status) != 0) {
418 clog_warnx("sigchild: child exit status: %d",
419 WEXITSTATUS(status));
422 } else {
424 clog_warnx("sigchild: child is terminated abnormally");
429 errno = saved_errno;
433 is_g_object_setting(GObject *o, char *str)
435 guint n_props = 0, i;
436 GParamSpec **proplist;
438 if (! G_IS_OBJECT(o))
439 return (0);
441 proplist = g_object_class_list_properties(G_OBJECT_GET_CLASS(o),
442 &n_props);
444 for (i=0; i < n_props; i++) {
445 if (! strcmp(proplist[i]->name, str))
446 return (1);
448 return (0);
451 struct tab *
452 get_current_tab(void)
454 struct tab *t;
456 TAILQ_FOREACH(t, &tabs, entry) {
457 if (t->tab_id == gtk_notebook_get_current_page(notebook))
458 return (t);
461 warnx("%s: no current tab", __func__);
463 return (NULL);
466 void
467 set_status(struct tab *t, gchar *s, int status)
469 gchar *type = NULL;
471 if (s == NULL)
472 return;
474 switch (status) {
475 case XT_STATUS_LOADING:
476 type = g_strdup_printf("Loading: %s", s);
477 s = type;
478 break;
479 case XT_STATUS_LINK:
480 type = g_strdup_printf("Link: %s", s);
481 if (!t->status)
482 t->status = g_strdup(gtk_entry_get_text(
483 GTK_ENTRY(t->sbe.statusbar)));
484 s = type;
485 break;
486 case XT_STATUS_URI:
487 type = g_strdup_printf("%s", s);
488 if (!t->status) {
489 t->status = g_strdup(type);
491 s = type;
492 if (!t->status)
493 t->status = g_strdup(s);
494 break;
495 case XT_STATUS_NOTHING:
496 /* FALL THROUGH */
497 default:
498 break;
500 gtk_entry_set_text(GTK_ENTRY(t->sbe.statusbar), s);
501 if (type)
502 g_free(type);
505 void
506 hide_cmd(struct tab *t)
508 DNPRINTF(XT_D_CMD, "%s: tab %d\n", __func__, t->tab_id);
510 history_at = NULL; /* just in case */
511 search_at = NULL; /* just in case */
512 gtk_widget_hide(t->cmd);
515 void
516 show_cmd(struct tab *t)
518 DNPRINTF(XT_D_CMD, "%s: tab %d\n", __func__, t->tab_id);
520 history_at = NULL;
521 search_at = NULL;
522 gtk_widget_hide(t->oops);
523 gtk_widget_show(t->cmd);
526 void
527 hide_buffers(struct tab *t)
529 gtk_widget_hide(t->buffers);
530 gtk_list_store_clear(buffers_store);
533 enum {
534 COL_ID = 0,
535 COL_TITLE,
536 NUM_COLS
540 sort_tabs_by_page_num(struct tab ***stabs)
542 int num_tabs = 0;
543 struct tab *t;
545 num_tabs = gtk_notebook_get_n_pages(notebook);
547 *stabs = g_malloc0(num_tabs * sizeof(struct tab *));
549 TAILQ_FOREACH(t, &tabs, entry)
550 (*stabs)[gtk_notebook_page_num(notebook, t->vbox)] = t;
552 return (num_tabs);
555 void
556 buffers_make_list(void)
558 int i, num_tabs;
559 const gchar *title = NULL;
560 GtkTreeIter iter;
561 struct tab **stabs = NULL;
563 num_tabs = sort_tabs_by_page_num(&stabs);
565 for (i = 0; i < num_tabs; i++)
566 if (stabs[i]) {
567 gtk_list_store_append(buffers_store, &iter);
568 title = get_title(stabs[i], FALSE);
569 gtk_list_store_set(buffers_store, &iter,
570 COL_ID, i + 1, /* Enumerate the tabs starting from 1
571 * rather than 0. */
572 COL_TITLE, title,
573 -1);
576 g_free(stabs);
579 void
580 show_buffers(struct tab *t)
582 buffers_make_list();
583 gtk_widget_show(t->buffers);
584 gtk_widget_grab_focus(GTK_WIDGET(t->buffers));
587 void
588 toggle_buffers(struct tab *t)
590 if (gtk_widget_get_visible(t->buffers))
591 hide_buffers(t);
592 else
593 show_buffers(t);
597 buffers(struct tab *t, struct karg *args)
599 show_buffers(t);
601 return (0);
604 void
605 hide_oops(struct tab *t)
607 gtk_widget_hide(t->oops);
610 void
611 show_oops(struct tab *at, const char *fmt, ...)
613 va_list ap;
614 char *msg = NULL;
615 struct tab *t = NULL;
617 if (fmt == NULL)
618 return;
620 if (at == NULL) {
621 if ((t = get_current_tab()) == NULL)
622 return;
623 } else
624 t = at;
626 va_start(ap, fmt);
627 if (vasprintf(&msg, fmt, ap) == -1)
628 errx(1, "show_oops failed");
629 va_end(ap);
631 gtk_entry_set_text(GTK_ENTRY(t->oops), msg);
632 gtk_widget_hide(t->cmd);
633 gtk_widget_show(t->oops);
635 if (msg)
636 free(msg);
639 char work_dir[PATH_MAX];
640 char certs_dir[PATH_MAX];
641 char js_dir[PATH_MAX];
642 char cache_dir[PATH_MAX];
643 char sessions_dir[PATH_MAX];
644 char cookie_file[PATH_MAX];
645 SoupSession *session;
646 SoupCookieJar *s_cookiejar;
647 SoupCookieJar *p_cookiejar;
648 char rc_fname[PATH_MAX];
650 struct mime_type_list mtl;
651 struct alias_list aliases;
653 /* protos */
654 struct tab *create_new_tab(char *, struct undo *, int, int);
655 void delete_tab(struct tab *);
656 void setzoom_webkit(struct tab *, int);
657 int run_script(struct tab *, char *);
658 int download_rb_cmp(struct download *, struct download *);
659 gboolean cmd_execute(struct tab *t, char *str);
662 history_rb_cmp(struct history *h1, struct history *h2)
664 return (strcmp(h1->uri, h2->uri));
666 RB_GENERATE(history_list, history, entry, history_rb_cmp);
669 domain_rb_cmp(struct domain *d1, struct domain *d2)
671 return (strcmp(d1->d, d2->d));
673 RB_GENERATE(domain_list, domain, entry, domain_rb_cmp);
676 download_rb_cmp(struct download *e1, struct download *e2)
678 return (e1->id < e2->id ? -1 : e1->id > e2->id);
680 RB_GENERATE(download_list, download, entry, download_rb_cmp);
682 struct valid_url_types {
683 char *type;
684 } vut[] = {
685 { "http://" },
686 { "https://" },
687 { "ftp://" },
688 { "file://" },
689 { XT_XTP_STR },
693 valid_url_type(char *url)
695 int i;
697 for (i = 0; i < LENGTH(vut); i++)
698 if (!strncasecmp(vut[i].type, url, strlen(vut[i].type)))
699 return (0);
701 return (1);
704 char *
705 match_alias(char *url_in)
707 struct alias *a;
708 char *arg;
709 char *url_out = NULL, *search, *enc_arg;
711 search = g_strdup(url_in);
712 arg = search;
713 if (strsep(&arg, " \t") == NULL) {
714 show_oops(NULL, "match_alias: NULL URL");
715 goto done;
718 TAILQ_FOREACH(a, &aliases, entry) {
719 if (!strcmp(search, a->a_name))
720 break;
723 if (a != NULL) {
724 DNPRINTF(XT_D_URL, "match_alias: matched alias %s\n",
725 a->a_name);
726 if (arg != NULL) {
727 enc_arg = soup_uri_encode(arg, XT_RESERVED_CHARS);
728 url_out = g_strdup_printf(a->a_uri, enc_arg);
729 g_free(enc_arg);
730 } else
731 url_out = g_strdup_printf(a->a_uri, "");
733 done:
734 g_free(search);
735 return (url_out);
738 char *
739 guess_url_type(char *url_in)
741 struct stat sb;
742 char *url_out = NULL, *enc_search = NULL;
743 int i;
745 /* substitute aliases */
746 url_out = match_alias(url_in);
747 if (url_out != NULL)
748 return (url_out);
750 /* see if we are an about page */
751 if (!strncmp(url_in, XT_URI_ABOUT, XT_URI_ABOUT_LEN))
752 for (i = 0; i < about_list_size(); i++)
753 if (!strcmp(&url_in[XT_URI_ABOUT_LEN],
754 about_list[i].name)) {
755 url_out = g_strdup(url_in);
756 goto done;
759 if (guess_search && url_regex &&
760 !(g_str_has_prefix(url_in, "http://") ||
761 g_str_has_prefix(url_in, "https://"))) {
762 if (regexec(&url_re, url_in, 0, NULL, 0)) {
763 /* invalid URI so search instead */
764 enc_search = soup_uri_encode(url_in, XT_RESERVED_CHARS);
765 url_out = g_strdup_printf(search_string, enc_search);
766 g_free(enc_search);
767 goto done;
771 /* XXX not sure about this heuristic */
772 if (stat(url_in, &sb) == 0)
773 url_out = g_strdup_printf("file://%s", url_in);
774 else
775 url_out = g_strdup_printf("http://%s", url_in); /* guess http */
776 done:
777 DNPRINTF(XT_D_URL, "guess_url_type: guessed %s\n", url_out);
779 return (url_out);
782 void
783 load_uri(struct tab *t, gchar *uri)
785 struct karg args;
786 gchar *newuri = NULL;
787 int i;
789 if (uri == NULL)
790 return;
792 /* Strip leading spaces. */
793 while (*uri && isspace(*uri))
794 uri++;
796 if (strlen(uri) == 0) {
797 blank(t, NULL);
798 return;
801 t->xtp_meaning = XT_XTP_TAB_MEANING_NORMAL;
803 if (valid_url_type(uri)) {
804 newuri = guess_url_type(uri);
805 uri = newuri;
808 if (!strncmp(uri, XT_URI_ABOUT, XT_URI_ABOUT_LEN)) {
809 for (i = 0; i < about_list_size(); i++)
810 if (!strcmp(&uri[XT_URI_ABOUT_LEN], about_list[i].name)) {
811 bzero(&args, sizeof args);
812 about_list[i].func(t, &args);
813 gtk_widget_set_sensitive(GTK_WIDGET(t->stop),
814 FALSE);
815 goto done;
817 show_oops(t, "invalid about page");
818 goto done;
821 set_status(t, (char *)uri, XT_STATUS_LOADING);
822 marks_clear(t);
823 webkit_web_view_load_uri(t->wv, uri);
824 done:
825 if (newuri)
826 g_free(newuri);
829 const gchar *
830 get_uri(struct tab *t)
832 const gchar *uri = NULL;
834 if (webkit_web_view_get_load_status(t->wv) == WEBKIT_LOAD_FAILED)
835 return NULL;
836 if (t->xtp_meaning == XT_XTP_TAB_MEANING_NORMAL) {
837 uri = webkit_web_view_get_uri(t->wv);
838 } else {
839 /* use tmp_uri to make sure it is g_freed */
840 if (t->tmp_uri)
841 g_free(t->tmp_uri);
842 t->tmp_uri =g_strdup_printf("%s%s", XT_URI_ABOUT,
843 about_list[t->xtp_meaning].name);
844 uri = t->tmp_uri;
846 return uri;
849 const gchar *
850 get_title(struct tab *t, bool window)
852 const gchar *set = NULL, *title = NULL;
853 WebKitLoadStatus status = webkit_web_view_get_load_status(t->wv);
855 if (status == WEBKIT_LOAD_PROVISIONAL || status == WEBKIT_LOAD_FAILED ||
856 t->xtp_meaning == XT_XTP_TAB_MEANING_BL)
857 goto notitle;
859 title = webkit_web_view_get_title(t->wv);
860 if ((set = title ? title : get_uri(t)))
861 return set;
863 notitle:
864 set = window ? XT_NAME : "(untitled)";
866 return set;
869 struct mime_type *
870 find_mime_type(char *mime_type)
872 struct mime_type *m, *def = NULL, *rv = NULL;
874 TAILQ_FOREACH(m, &mtl, entry) {
875 if (m->mt_default &&
876 !strncmp(mime_type, m->mt_type, strlen(m->mt_type)))
877 def = m;
879 if (m->mt_default == 0 && !strcmp(mime_type, m->mt_type)) {
880 rv = m;
881 break;
885 if (rv == NULL)
886 rv = def;
888 return (rv);
891 struct domain *
892 wl_find_uri(const gchar *s, struct domain_list *wl)
894 int i;
895 char *ss;
896 struct domain *r;
898 if (s == NULL || wl == NULL)
899 return (NULL);
901 if (!strncmp(s, "http://", strlen("http://")))
902 s = &s[strlen("http://")];
903 else if (!strncmp(s, "https://", strlen("https://")))
904 s = &s[strlen("https://")];
906 if (strlen(s) < 2)
907 return (NULL);
909 for (i = 0; i < strlen(s) + 1 /* yes er need this */; i++)
910 /* chop string at first slash */
911 if (s[i] == '/' || s[i] == ':' || s[i] == '\0') {
912 ss = g_strdup(s);
913 ss[i] = '\0';
914 r = wl_find(ss, wl);
915 g_free(ss);
916 return (r);
919 return (NULL);
922 char *
923 js_ref_to_string(JSContextRef context, JSValueRef ref)
925 char *s = NULL;
926 size_t l;
927 JSStringRef jsref;
929 jsref = JSValueToStringCopy(context, ref, NULL);
930 if (jsref == NULL)
931 return (NULL);
933 l = JSStringGetMaximumUTF8CStringSize(jsref);
934 s = g_malloc(l);
935 if (s)
936 JSStringGetUTF8CString(jsref, s, l);
937 JSStringRelease(jsref);
939 return (s);
942 void
943 disable_hints(struct tab *t)
945 DNPRINTF(XT_D_JS, "%s: tab %d\n", __func__, t->tab_id);
947 run_script(t, "hints.clearHints();");
948 t->hints_on = 0;
949 t->new_tab = 0;
952 void
953 enable_hints(struct tab *t)
955 DNPRINTF(XT_D_JS, "%s: tab %d\n", __func__, t->tab_id);
957 run_script(t, JS_HINTING);
958 if (t->new_tab)
959 run_script(t, "hints.createHints('', 'F');");
960 else
961 run_script(t, "hints.createHints('', 'f');");
962 t->hints_on = 1;
965 #define XT_JS_DONE ("done;")
966 #define XT_JS_DONE_LEN (strlen(XT_JS_DONE))
967 #define XT_JS_INSERT ("insert;")
968 #define XT_JS_INSERT_LEN (strlen(XT_JS_INSERT))
971 run_script(struct tab *t, char *s)
973 JSGlobalContextRef ctx;
974 WebKitWebFrame *frame;
975 JSStringRef str;
976 JSValueRef val, exception;
977 char *es;
979 DNPRINTF(XT_D_JS, "run_script: tab %d %s\n",
980 t->tab_id, s == (char *)JS_HINTING ? "JS_HINTING" : s);
982 /* a bit silly but it prevents some heartburn */
983 if (t->script_init == 0) {
984 t->script_init = 1;
985 run_script(t, JS_HINTING);
988 frame = webkit_web_view_get_main_frame(t->wv);
989 ctx = webkit_web_frame_get_global_context(frame);
991 str = JSStringCreateWithUTF8CString(s);
992 val = JSEvaluateScript(ctx, str, JSContextGetGlobalObject(ctx),
993 NULL, 0, &exception);
994 JSStringRelease(str);
996 DNPRINTF(XT_D_JS, "run_script: val %p\n", val);
997 if (val == NULL) {
998 es = js_ref_to_string(ctx, exception);
999 if (es) {
1000 /* show_oops(t, "script exception: %s", es); */
1001 DNPRINTF(XT_D_JS, "run_script: exception %s\n", es);
1002 g_free(es);
1004 return (1);
1005 } else {
1006 es = js_ref_to_string(ctx, val);
1007 #if 0
1008 /* return values */
1009 if (!strncmp(es, XT_JS_DONE, XT_JS_DONE_LEN))
1010 ; /* do nothing */
1011 if (!strncmp(es, XT_JS_INSERT, XT_JS_INSERT_LEN))
1012 ; /* do nothing */
1013 #endif
1014 if (es) {
1015 DNPRINTF(XT_D_JS, "run_script: val %s\n", es);
1016 g_free(es);
1020 return (0);
1024 hint(struct tab *t, struct karg *args)
1027 DNPRINTF(XT_D_JS, "hint: tab %d args %d\n", t->tab_id, args->i);
1029 if (t->hints_on == 0) {
1030 if (args->i == XT_HINT_NEWTAB)
1031 t->new_tab = 1;
1032 enable_hints(t);
1033 } else
1034 disable_hints(t);
1036 return (0);
1039 void
1040 apply_style(struct tab *t)
1042 g_object_set(G_OBJECT(t->settings),
1043 "user-stylesheet-uri", t->stylesheet, (char *)NULL);
1047 userstyle(struct tab *t, struct karg *args)
1049 DNPRINTF(XT_D_JS, "userstyle: tab %d\n", t->tab_id);
1051 if (t->styled) {
1052 t->styled = 0;
1053 g_object_set(G_OBJECT(t->settings),
1054 "user-stylesheet-uri", NULL, (char *)NULL);
1055 } else {
1056 t->styled = 1;
1057 apply_style(t);
1059 return (0);
1063 * Doesn't work fully, due to the following bug:
1064 * https://bugs.webkit.org/show_bug.cgi?id=51747
1067 restore_global_history(void)
1069 char file[PATH_MAX];
1070 FILE *f;
1071 struct history *h;
1072 gchar *uri;
1073 gchar *title;
1074 const char delim[3] = {'\\', '\\', '\0'};
1076 snprintf(file, sizeof file, "%s/%s", work_dir, XT_HISTORY_FILE);
1078 if ((f = fopen(file, "r")) == NULL) {
1079 warnx("%s: fopen", __func__);
1080 return (1);
1083 for (;;) {
1084 if ((uri = fparseln(f, NULL, NULL, delim, 0)) == NULL)
1085 if (feof(f) || ferror(f))
1086 break;
1088 if ((title = fparseln(f, NULL, NULL, delim, 0)) == NULL)
1089 if (feof(f) || ferror(f)) {
1090 free(uri);
1091 warnx("%s: broken history file\n", __func__);
1092 return (1);
1095 if (uri && strlen(uri) && title && strlen(title)) {
1096 webkit_web_history_item_new_with_data(uri, title);
1097 h = g_malloc(sizeof(struct history));
1098 h->uri = g_strdup(uri);
1099 h->title = g_strdup(title);
1100 RB_INSERT(history_list, &hl, h);
1101 completion_add_uri(h->uri);
1102 } else {
1103 warnx("%s: failed to restore history\n", __func__);
1104 free(uri);
1105 free(title);
1106 return (1);
1109 free(uri);
1110 free(title);
1111 uri = NULL;
1112 title = NULL;
1115 return (0);
1119 save_global_history_to_disk(struct tab *t)
1121 char file[PATH_MAX];
1122 FILE *f;
1123 struct history *h;
1125 snprintf(file, sizeof file, "%s/%s", work_dir, XT_HISTORY_FILE);
1127 if ((f = fopen(file, "w")) == NULL) {
1128 show_oops(t, "%s: global history file: %s",
1129 __func__, strerror(errno));
1130 return (1);
1133 RB_FOREACH_REVERSE(h, history_list, &hl) {
1134 if (h->uri && h->title)
1135 fprintf(f, "%s\n%s\n", h->uri, h->title);
1138 fclose(f);
1140 return (0);
1144 quit(struct tab *t, struct karg *args)
1146 if (save_global_history)
1147 save_global_history_to_disk(t);
1149 gtk_main_quit();
1151 return (1);
1154 void
1155 restore_sessions_list(void)
1157 DIR *sdir = NULL;
1158 struct dirent *dp = NULL;
1159 struct session *s;
1161 sdir = opendir(sessions_dir);
1162 if (sdir) {
1163 while ((dp = readdir(sdir)) != NULL)
1164 if (dp->d_type == DT_REG) {
1165 s = g_malloc(sizeof(struct session));
1166 s->name = g_strdup(dp->d_name);
1167 TAILQ_INSERT_TAIL(&sessions, s, entry);
1169 closedir(sdir);
1174 open_tabs(struct tab *t, struct karg *a)
1176 char file[PATH_MAX];
1177 FILE *f = NULL;
1178 char *uri = NULL;
1179 int rv = 1;
1180 struct tab *ti, *tt;
1182 if (a == NULL)
1183 goto done;
1185 ti = TAILQ_LAST(&tabs, tab_list);
1187 snprintf(file, sizeof file, "%s/%s", sessions_dir, a->s);
1188 if ((f = fopen(file, "r")) == NULL)
1189 goto done;
1191 for (;;) {
1192 if ((uri = fparseln(f, NULL, NULL, "\0\0\0", 0)) == NULL)
1193 if (feof(f) || ferror(f))
1194 break;
1196 /* retrieve session name */
1197 if (uri && g_str_has_prefix(uri, XT_SAVE_SESSION_ID)) {
1198 strlcpy(named_session,
1199 &uri[strlen(XT_SAVE_SESSION_ID)],
1200 sizeof named_session);
1201 continue;
1204 if (uri && strlen(uri))
1205 create_new_tab(uri, NULL, 1, -1);
1207 free(uri);
1208 uri = NULL;
1211 /* close open tabs */
1212 if (a->i == XT_SES_CLOSETABS && ti != NULL) {
1213 for (;;) {
1214 tt = TAILQ_FIRST(&tabs);
1215 if (tt == NULL)
1216 break;
1217 if (tt != ti) {
1218 delete_tab(tt);
1219 continue;
1221 delete_tab(tt);
1222 break;
1226 rv = 0;
1227 done:
1228 if (f)
1229 fclose(f);
1231 return (rv);
1235 restore_saved_tabs(void)
1237 char file[PATH_MAX];
1238 int unlink_file = 0;
1239 struct stat sb;
1240 struct karg a;
1241 int rv = 0;
1243 snprintf(file, sizeof file, "%s/%s",
1244 sessions_dir, XT_RESTART_TABS_FILE);
1245 if (stat(file, &sb) == -1)
1246 a.s = XT_SAVED_TABS_FILE;
1247 else {
1248 unlink_file = 1;
1249 a.s = XT_RESTART_TABS_FILE;
1252 a.i = XT_SES_DONOTHING;
1253 rv = open_tabs(NULL, &a);
1255 if (unlink_file)
1256 unlink(file);
1258 return (rv);
1262 save_tabs(struct tab *t, struct karg *a)
1264 char file[PATH_MAX];
1265 FILE *f;
1266 int num_tabs = 0, i;
1267 struct tab **stabs = NULL;
1269 /* tab may be null here */
1271 if (a == NULL)
1272 return (1);
1273 if (a->s == NULL)
1274 snprintf(file, sizeof file, "%s/%s",
1275 sessions_dir, named_session);
1276 else
1277 snprintf(file, sizeof file, "%s/%s", sessions_dir, a->s);
1279 if ((f = fopen(file, "w")) == NULL) {
1280 show_oops(t, "Can't open save_tabs file: %s", strerror(errno));
1281 return (1);
1284 /* save session name */
1285 fprintf(f, "%s%s\n", XT_SAVE_SESSION_ID, named_session);
1287 /* Save tabs, in the order they are arranged in the notebook. */
1288 num_tabs = sort_tabs_by_page_num(&stabs);
1290 for (i = 0; i < num_tabs; i++)
1291 if (stabs[i]) {
1292 if (get_uri(stabs[i]) != NULL)
1293 fprintf(f, "%s\n", get_uri(stabs[i]));
1294 else if (gtk_entry_get_text(GTK_ENTRY(
1295 stabs[i]->uri_entry)))
1296 fprintf(f, "%s\n", gtk_entry_get_text(GTK_ENTRY(
1297 stabs[i]->uri_entry)));
1300 g_free(stabs);
1302 /* try and make sure this gets to disk NOW. XXX Backup first? */
1303 if (fflush(f) != 0 || fsync(fileno(f)) != 0) {
1304 show_oops(t, "May not have managed to save session: %s",
1305 strerror(errno));
1308 fclose(f);
1310 return (0);
1314 save_tabs_and_quit(struct tab *t, struct karg *args)
1316 struct karg a;
1318 a.s = NULL;
1319 save_tabs(t, &a);
1320 quit(t, NULL);
1322 return (1);
1326 run_page_script(struct tab *t, struct karg *args)
1328 const gchar *uri;
1329 char *tmp, script[PATH_MAX];
1331 tmp = args->s != NULL && strlen(args->s) > 0 ? args->s : default_script;
1332 if (tmp[0] == '\0') {
1333 show_oops(t, "no script specified");
1334 return (1);
1337 if ((uri = get_uri(t)) == NULL) {
1338 show_oops(t, "tab is empty, not running script");
1339 return (1);
1342 if (tmp[0] == '~')
1343 snprintf(script, sizeof script, "%s/%s",
1344 pwd->pw_dir, &tmp[1]);
1345 else
1346 strlcpy(script, tmp, sizeof script);
1348 switch (fork()) {
1349 case -1:
1350 show_oops(t, "can't fork to run script");
1351 return (1);
1352 /* NOTREACHED */
1353 case 0:
1354 break;
1355 default:
1356 return (0);
1359 /* child */
1360 execlp(script, script, uri, (void *)NULL);
1362 _exit(0);
1364 /* NOTREACHED */
1366 return (0);
1370 yank_uri(struct tab *t, struct karg *args)
1372 const gchar *uri;
1373 GtkClipboard *clipboard;
1375 if ((uri = get_uri(t)) == NULL)
1376 return (1);
1378 clipboard = gtk_clipboard_get(GDK_SELECTION_PRIMARY);
1379 gtk_clipboard_set_text(clipboard, uri, -1);
1381 return (0);
1385 paste_uri(struct tab *t, struct karg *args)
1387 GtkClipboard *clipboard;
1388 GdkAtom atom = gdk_atom_intern("CUT_BUFFER0", FALSE);
1389 gint len;
1390 gchar *p = NULL, *uri;
1392 /* try primary clipboard first */
1393 clipboard = gtk_clipboard_get(GDK_SELECTION_PRIMARY);
1394 p = gtk_clipboard_wait_for_text(clipboard);
1396 /* if it failed get whatever text is in cut_buffer0 */
1397 if (p == NULL && xterm_workaround)
1398 if (gdk_property_get(gdk_get_default_root_window(),
1399 atom,
1400 gdk_atom_intern("STRING", FALSE),
1402 1024 * 1024 /* picked out of my butt */,
1403 FALSE,
1404 NULL,
1405 NULL,
1406 &len,
1407 (guchar **)&p)) {
1408 /* yes sir, we need to NUL the string */
1409 p[len] = '\0';
1412 if (p) {
1413 uri = p;
1414 while (*uri && isspace(*uri))
1415 uri++;
1416 if (strlen(uri) == 0) {
1417 show_oops(t, "empty paste buffer");
1418 goto done;
1420 if (guess_search == 0 && valid_url_type(uri)) {
1421 /* we can be clever and paste this in search box */
1422 show_oops(t, "not a valid URL");
1423 goto done;
1426 if (args->i == XT_PASTE_CURRENT_TAB)
1427 load_uri(t, uri);
1428 else if (args->i == XT_PASTE_NEW_TAB)
1429 create_new_tab(uri, NULL, 1, -1);
1432 done:
1433 if (p)
1434 g_free(p);
1436 return (0);
1439 void
1440 js_toggle_cb(GtkWidget *w, struct tab *t)
1442 struct karg a;
1443 int es, set;
1445 g_object_get(G_OBJECT(t->settings),
1446 "enable-scripts", &es, (char *)NULL);
1447 es = !es;
1448 if (es)
1449 set = XT_WL_ENABLE;
1450 else
1451 set = XT_WL_DISABLE;
1453 a.i = set | XT_WL_TOPLEVEL;
1454 toggle_pl(t, &a);
1456 a.i = set | XT_WL_TOPLEVEL;
1457 toggle_cwl(t, &a);
1459 a.i = XT_WL_TOGGLE | XT_WL_TOPLEVEL | XT_WL_RELOAD;
1460 toggle_js(t, &a);
1464 toggle_src(struct tab *t, struct karg *args)
1466 gboolean mode;
1468 if (t == NULL)
1469 return (0);
1471 mode = webkit_web_view_get_view_source_mode(t->wv);
1472 webkit_web_view_set_view_source_mode(t->wv, !mode);
1473 webkit_web_view_reload(t->wv);
1475 return (0);
1478 void
1479 focus_webview(struct tab *t)
1481 if (t == NULL)
1482 return;
1484 /* only grab focus if we are visible */
1485 if (gtk_notebook_get_current_page(notebook) == t->tab_id)
1486 gtk_widget_grab_focus(GTK_WIDGET(t->wv));
1490 focus(struct tab *t, struct karg *args)
1492 if (t == NULL || args == NULL)
1493 return (1);
1495 if (show_url == 0)
1496 return (0);
1498 if (args->i == XT_FOCUS_URI)
1499 gtk_widget_grab_focus(GTK_WIDGET(t->uri_entry));
1500 else if (args->i == XT_FOCUS_SEARCH)
1501 gtk_widget_grab_focus(GTK_WIDGET(t->search_entry));
1503 return (0);
1507 connect_socket_from_uri(const gchar *uri, const gchar **error_str, char *domain,
1508 size_t domain_sz)
1510 SoupURI *su = NULL;
1511 struct addrinfo hints, *res = NULL, *ai;
1512 int rv = -1, s = -1, on, error;
1513 char port[8];
1514 static gchar myerror[256]; /* this is not thread safe */
1516 myerror[0] = '\0';
1517 *error_str = myerror;
1518 if (uri && !g_str_has_prefix(uri, "https://")) {
1519 *error_str = "invalid URI";
1520 goto done;
1523 su = soup_uri_new(uri);
1524 if (su == NULL) {
1525 *error_str = "invalid soup URI";
1526 goto done;
1528 if (!SOUP_URI_VALID_FOR_HTTP(su)) {
1529 *error_str = "invalid HTTPS URI";
1530 goto done;
1533 snprintf(port, sizeof port, "%d", su->port);
1534 bzero(&hints, sizeof(struct addrinfo));
1535 hints.ai_flags = AI_CANONNAME;
1536 hints.ai_family = AF_UNSPEC;
1537 hints.ai_socktype = SOCK_STREAM;
1539 if ((error = getaddrinfo(su->host, port, &hints, &res))) {
1540 snprintf(myerror, sizeof myerror, "getaddrinfo failed: %s",
1541 gai_strerror(errno));
1542 goto done;
1545 for (ai = res; ai; ai = ai->ai_next) {
1546 if (s != -1) {
1547 close(s);
1548 s = -1;
1551 if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6)
1552 continue;
1553 s = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
1554 if (s == -1)
1555 continue;
1556 if (setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &on,
1557 sizeof(on)) == -1)
1558 continue;
1559 if (connect(s, ai->ai_addr, ai->ai_addrlen) == 0)
1560 break;
1562 if (s == -1) {
1563 snprintf(myerror, sizeof myerror,
1564 "could not obtain certificates from: %s",
1565 su->host);
1566 goto done;
1569 if (domain)
1570 strlcpy(domain, su->host, domain_sz);
1571 rv = s;
1572 done:
1573 if (su)
1574 soup_uri_free(su);
1575 if (res)
1576 freeaddrinfo(res);
1577 if (rv == -1 && s != -1)
1578 close(s);
1580 return (rv);
1584 stop_tls(gnutls_session_t gsession, gnutls_certificate_credentials_t xcred)
1586 if (gsession)
1587 gnutls_deinit(gsession);
1588 if (xcred)
1589 gnutls_certificate_free_credentials(xcred);
1591 return (0);
1595 start_tls(const gchar **error_str, int s, gnutls_session_t *gs,
1596 gnutls_certificate_credentials_t *xc)
1598 gnutls_certificate_credentials_t xcred;
1599 gnutls_session_t gsession;
1600 int rv = 1;
1601 static gchar myerror[1024]; /* this is not thread safe */
1603 if (gs == NULL || xc == NULL)
1604 goto done;
1606 myerror[0] = '\0';
1607 *gs = NULL;
1608 *xc = NULL;
1610 gnutls_certificate_allocate_credentials(&xcred);
1611 gnutls_certificate_set_x509_trust_file(xcred, ssl_ca_file,
1612 GNUTLS_X509_FMT_PEM);
1614 gnutls_init(&gsession, GNUTLS_CLIENT);
1615 gnutls_priority_set_direct(gsession, "PERFORMANCE", NULL);
1616 gnutls_credentials_set(gsession, GNUTLS_CRD_CERTIFICATE, xcred);
1617 gnutls_transport_set_ptr(gsession, (gnutls_transport_ptr_t)(long)s);
1618 if ((rv = gnutls_handshake(gsession)) < 0) {
1619 snprintf(myerror, sizeof myerror,
1620 "gnutls_handshake failed %d fatal %d %s",
1622 gnutls_error_is_fatal(rv),
1623 gnutls_strerror_name(rv));
1624 stop_tls(gsession, xcred);
1625 goto done;
1628 gnutls_credentials_type_t cred;
1629 cred = gnutls_auth_get_type(gsession);
1630 if (cred != GNUTLS_CRD_CERTIFICATE) {
1631 snprintf(myerror, sizeof myerror,
1632 "gnutls_auth_get_type failed %d",
1633 (int)cred);
1634 stop_tls(gsession, xcred);
1635 goto done;
1638 *gs = gsession;
1639 *xc = xcred;
1640 rv = 0;
1641 done:
1642 *error_str = myerror;
1643 return (rv);
1647 get_connection_certs(gnutls_session_t gsession, gnutls_x509_crt_t **certs,
1648 size_t *cert_count)
1650 unsigned int len;
1651 const gnutls_datum_t *cl;
1652 gnutls_x509_crt_t *all_certs;
1653 int i, rv = 1;
1655 if (certs == NULL || cert_count == NULL)
1656 goto done;
1657 if (gnutls_certificate_type_get(gsession) != GNUTLS_CRT_X509)
1658 goto done;
1659 cl = gnutls_certificate_get_peers(gsession, &len);
1660 if (len == 0)
1661 goto done;
1663 all_certs = g_malloc(sizeof(gnutls_x509_crt_t) * len);
1664 for (i = 0; i < len; i++) {
1665 gnutls_x509_crt_init(&all_certs[i]);
1666 if (gnutls_x509_crt_import(all_certs[i], &cl[i],
1667 GNUTLS_X509_FMT_PEM < 0)) {
1668 g_free(all_certs);
1669 goto done;
1673 *certs = all_certs;
1674 *cert_count = len;
1675 rv = 0;
1676 done:
1677 return (rv);
1680 void
1681 free_connection_certs(gnutls_x509_crt_t *certs, size_t cert_count)
1683 int i;
1685 for (i = 0; i < cert_count; i++)
1686 gnutls_x509_crt_deinit(certs[i]);
1687 g_free(certs);
1690 void
1691 statusbar_modify_attr(struct tab *t, const char *text, const char *base)
1693 GdkColor c_text, c_base;
1695 gdk_color_parse(text, &c_text);
1696 gdk_color_parse(base, &c_base);
1698 gtk_widget_modify_text(t->sbe.statusbar, GTK_STATE_NORMAL, &c_text);
1699 gtk_widget_modify_text(t->sbe.buffercmd, GTK_STATE_NORMAL, &c_text);
1700 gtk_widget_modify_text(t->sbe.zoom, GTK_STATE_NORMAL, &c_text);
1701 gtk_widget_modify_text(t->sbe.position, GTK_STATE_NORMAL, &c_text);
1703 gtk_widget_modify_base(t->sbe.statusbar, GTK_STATE_NORMAL, &c_base);
1704 gtk_widget_modify_base(t->sbe.buffercmd, GTK_STATE_NORMAL, &c_base);
1705 gtk_widget_modify_base(t->sbe.zoom, GTK_STATE_NORMAL, &c_base);
1706 gtk_widget_modify_base(t->sbe.position, GTK_STATE_NORMAL, &c_base);
1709 void
1710 save_certs(struct tab *t, gnutls_x509_crt_t *certs,
1711 size_t cert_count, char *domain)
1713 size_t cert_buf_sz;
1714 char cert_buf[64 * 1024], file[PATH_MAX];
1715 int i;
1716 FILE *f;
1717 GdkColor color;
1719 if (t == NULL || certs == NULL || cert_count <= 0 || domain == NULL)
1720 return;
1722 snprintf(file, sizeof file, "%s/%s", certs_dir, domain);
1723 if ((f = fopen(file, "w")) == NULL) {
1724 show_oops(t, "Can't create cert file %s %s",
1725 file, strerror(errno));
1726 return;
1729 for (i = 0; i < cert_count; i++) {
1730 cert_buf_sz = sizeof cert_buf;
1731 if (gnutls_x509_crt_export(certs[i], GNUTLS_X509_FMT_PEM,
1732 cert_buf, &cert_buf_sz)) {
1733 show_oops(t, "gnutls_x509_crt_export failed");
1734 goto done;
1736 if (fwrite(cert_buf, cert_buf_sz, 1, f) != 1) {
1737 show_oops(t, "Can't write certs: %s", strerror(errno));
1738 goto done;
1742 /* not the best spot but oh well */
1743 gdk_color_parse("lightblue", &color);
1744 gtk_widget_modify_base(t->uri_entry, GTK_STATE_NORMAL, &color);
1745 statusbar_modify_attr(t, XT_COLOR_BLACK, "lightblue");
1746 done:
1747 fclose(f);
1750 enum cert_trust {
1751 CERT_LOCAL,
1752 CERT_TRUSTED,
1753 CERT_UNTRUSTED,
1754 CERT_BAD
1757 enum cert_trust
1758 load_compare_cert(const gchar *uri, const gchar **error_str)
1760 char domain[8182], file[PATH_MAX];
1761 char cert_buf[64 * 1024], r_cert_buf[64 * 1024];
1762 int s = -1, i;
1763 unsigned int error = 0;
1764 FILE *f = NULL;
1765 size_t cert_buf_sz, cert_count;
1766 enum cert_trust rv = CERT_UNTRUSTED;
1767 static gchar serr[80]; /* this isn't thread safe */
1768 gnutls_session_t gsession;
1769 gnutls_x509_crt_t *certs;
1770 gnutls_certificate_credentials_t xcred;
1772 DNPRINTF(XT_D_URL, "%s: %s\n", __func__, uri);
1774 serr[0] = '\0';
1775 *error_str = serr;
1776 if ((s = connect_socket_from_uri(uri, error_str, domain,
1777 sizeof domain)) == -1)
1778 return (rv);
1780 DNPRINTF(XT_D_URL, "%s: fd %d\n", __func__, s);
1782 /* go ssl/tls */
1783 if (start_tls(error_str, s, &gsession, &xcred))
1784 goto done;
1785 DNPRINTF(XT_D_URL, "%s: got tls\n", __func__);
1787 /* verify certs in case cert file doesn't exist */
1788 if (gnutls_certificate_verify_peers2(gsession, &error) !=
1789 GNUTLS_E_SUCCESS) {
1790 *error_str = "Invalid certificates";
1791 goto done;
1794 /* get certs */
1795 if (get_connection_certs(gsession, &certs, &cert_count)) {
1796 *error_str = "Can't get connection certificates";
1797 goto done;
1800 snprintf(file, sizeof file, "%s/%s", certs_dir, domain);
1801 if ((f = fopen(file, "r")) == NULL) {
1802 if (!error)
1803 rv = CERT_TRUSTED;
1804 goto freeit;
1807 for (i = 0; i < cert_count; i++) {
1808 cert_buf_sz = sizeof cert_buf;
1809 if (gnutls_x509_crt_export(certs[i], GNUTLS_X509_FMT_PEM,
1810 cert_buf, &cert_buf_sz)) {
1811 goto freeit;
1813 if (fread(r_cert_buf, cert_buf_sz, 1, f) != 1) {
1814 rv = CERT_BAD; /* critical */
1815 goto freeit;
1817 if (bcmp(r_cert_buf, cert_buf, sizeof cert_buf_sz)) {
1818 rv = CERT_BAD; /* critical */
1819 goto freeit;
1821 rv = CERT_LOCAL;
1824 freeit:
1825 if (f)
1826 fclose(f);
1827 free_connection_certs(certs, cert_count);
1828 done:
1829 /* we close the socket first for speed */
1830 if (s != -1)
1831 close(s);
1833 /* only complain if we didn't save it locally */
1834 if (error && rv != CERT_LOCAL) {
1835 strlcpy(serr, "Certificate exception(s): ", sizeof serr);
1836 if (error & GNUTLS_CERT_INVALID)
1837 strlcat(serr, "invalid, ", sizeof serr);
1838 if (error & GNUTLS_CERT_REVOKED)
1839 strlcat(serr, "revoked, ", sizeof serr);
1840 if (error & GNUTLS_CERT_SIGNER_NOT_FOUND)
1841 strlcat(serr, "signer not found, ", sizeof serr);
1842 if (error & GNUTLS_CERT_SIGNER_NOT_CA)
1843 strlcat(serr, "not signed by CA, ", sizeof serr);
1844 if (error & GNUTLS_CERT_INSECURE_ALGORITHM)
1845 strlcat(serr, "insecure algorithm, ", sizeof serr);
1846 if (error & GNUTLS_CERT_NOT_ACTIVATED)
1847 strlcat(serr, "not activated, ", sizeof serr);
1848 if (error & GNUTLS_CERT_EXPIRED)
1849 strlcat(serr, "expired, ", sizeof serr);
1850 for (i = strlen(serr) - 1; i > 0; i--)
1851 if (serr[i] == ',') {
1852 serr[i] = '\0';
1853 break;
1855 *error_str = serr;
1858 stop_tls(gsession, xcred);
1860 return (rv);
1864 cert_cmd(struct tab *t, struct karg *args)
1866 const gchar *uri, *error_str = NULL;
1867 char domain[8182];
1868 int s = -1;
1869 size_t cert_count;
1870 gnutls_session_t gsession;
1871 gnutls_x509_crt_t *certs;
1872 gnutls_certificate_credentials_t xcred;
1874 if (t == NULL)
1875 return (1);
1877 if (ssl_ca_file == NULL) {
1878 show_oops(t, "Can't open CA file: %s", ssl_ca_file);
1879 return (1);
1882 if ((uri = get_uri(t)) == NULL) {
1883 show_oops(t, "Invalid URI");
1884 return (1);
1887 if ((s = connect_socket_from_uri(uri, &error_str, domain,
1888 sizeof domain)) == -1) {
1889 show_oops(t, "%s", error_str);
1890 return (1);
1893 /* go ssl/tls */
1894 if (start_tls(&error_str, s, &gsession, &xcred))
1895 goto done;
1897 /* get certs */
1898 if (get_connection_certs(gsession, &certs, &cert_count)) {
1899 show_oops(t, "get_connection_certs failed");
1900 goto done;
1903 if (args->i & XT_SHOW)
1904 show_certs(t, certs, cert_count, "Certificate Chain");
1905 else if (args->i & XT_SAVE)
1906 save_certs(t, certs, cert_count, domain);
1908 free_connection_certs(certs, cert_count);
1909 done:
1910 /* we close the socket first for speed */
1911 if (s != -1)
1912 close(s);
1913 stop_tls(gsession, xcred);
1914 if (error_str && strlen(error_str))
1915 show_oops(t, "%s", error_str);
1916 return (0);
1920 remove_cookie(int index)
1922 int i, rv = 1;
1923 GSList *cf;
1924 SoupCookie *c;
1926 DNPRINTF(XT_D_COOKIE, "remove_cookie: %d\n", index);
1928 cf = soup_cookie_jar_all_cookies(s_cookiejar);
1930 for (i = 1; cf; cf = cf->next, i++) {
1931 if (i != index)
1932 continue;
1933 c = cf->data;
1934 print_cookie("remove cookie", c);
1935 soup_cookie_jar_delete_cookie(s_cookiejar, c);
1936 rv = 0;
1937 break;
1940 soup_cookies_free(cf);
1942 return (rv);
1946 toplevel_cmd(struct tab *t, struct karg *args)
1948 js_toggle_cb(t->js_toggle, t);
1950 return (0);
1954 can_go_back_for_real(struct tab *t)
1956 int i;
1957 WebKitWebHistoryItem *item;
1958 const gchar *uri;
1960 if (t == NULL)
1961 return (FALSE);
1963 /* rely on webkit to make sure we can go backward when on an about page */
1964 uri = get_uri(t);
1965 if (uri == NULL || g_str_has_prefix(uri, "about:"))
1966 return (webkit_web_view_can_go_back(t->wv));
1968 /* the back/forwars list is stupid so help determine if we can go back */
1969 for (i = 0, item = webkit_web_back_forward_list_get_current_item(t->bfl);
1970 item != NULL;
1971 i--, item = webkit_web_back_forward_list_get_nth_item(t->bfl, i)) {
1972 if (strcmp(webkit_web_history_item_get_uri(item), uri))
1973 return (TRUE);
1976 return (FALSE);
1980 can_go_forward_for_real(struct tab *t)
1982 int i;
1983 WebKitWebHistoryItem *item;
1984 const gchar *uri;
1986 if (t == NULL)
1987 return (FALSE);
1989 /* rely on webkit to make sure we can go forward when on an about page */
1990 uri = get_uri(t);
1991 if (uri == NULL || g_str_has_prefix(uri, "about:"))
1992 return (webkit_web_view_can_go_forward(t->wv));
1994 /* the back/forwars list is stupid so help selecting a different item */
1995 for (i = 0, item = webkit_web_back_forward_list_get_current_item(t->bfl);
1996 item != NULL;
1997 i++, item = webkit_web_back_forward_list_get_nth_item(t->bfl, i)) {
1998 if (strcmp(webkit_web_history_item_get_uri(item), uri))
1999 return (TRUE);
2002 return (FALSE);
2005 void
2006 go_back_for_real(struct tab *t)
2008 int i;
2009 WebKitWebHistoryItem *item;
2010 const gchar *uri;
2012 if (t == NULL)
2013 return;
2015 uri = get_uri(t);
2016 if (uri == NULL) {
2017 webkit_web_view_go_back(t->wv);
2018 return;
2020 /* the back/forwars list is stupid so help selecting a different item */
2021 for (i = 0, item = webkit_web_back_forward_list_get_current_item(t->bfl);
2022 item != NULL;
2023 i--, item = webkit_web_back_forward_list_get_nth_item(t->bfl, i)) {
2024 if (strcmp(webkit_web_history_item_get_uri(item), uri)) {
2025 webkit_web_view_go_to_back_forward_item(t->wv, item);
2026 break;
2031 void
2032 go_forward_for_real(struct tab *t)
2034 int i;
2035 WebKitWebHistoryItem *item;
2036 const gchar *uri;
2038 if (t == NULL)
2039 return;
2041 uri = get_uri(t);
2042 if (uri == NULL) {
2043 webkit_web_view_go_forward(t->wv);
2044 return;
2046 /* the back/forwars list is stupid so help selecting a different item */
2047 for (i = 0, item = webkit_web_back_forward_list_get_current_item(t->bfl);
2048 item != NULL;
2049 i++, item = webkit_web_back_forward_list_get_nth_item(t->bfl, i)) {
2050 if (strcmp(webkit_web_history_item_get_uri(item), uri)) {
2051 webkit_web_view_go_to_back_forward_item(t->wv, item);
2052 break;
2058 navaction(struct tab *t, struct karg *args)
2060 WebKitWebHistoryItem *item;
2061 WebKitWebFrame *frame;
2063 DNPRINTF(XT_D_NAV, "navaction: tab %d opcode %d\n",
2064 t->tab_id, args->i);
2066 t->xtp_meaning = XT_XTP_TAB_MEANING_NORMAL;
2067 if (t->item) {
2068 if (args->i == XT_NAV_BACK)
2069 item = webkit_web_back_forward_list_get_current_item(t->bfl);
2070 else
2071 item = webkit_web_back_forward_list_get_forward_item(t->bfl);
2072 if (item == NULL)
2073 return (XT_CB_PASSTHROUGH);
2074 webkit_web_view_go_to_back_forward_item(t->wv, item);
2075 t->item = NULL;
2076 return (XT_CB_PASSTHROUGH);
2079 switch (args->i) {
2080 case XT_NAV_BACK:
2081 marks_clear(t);
2082 go_back_for_real(t);
2083 break;
2084 case XT_NAV_FORWARD:
2085 marks_clear(t);
2086 go_forward_for_real(t);
2087 break;
2088 case XT_NAV_RELOAD:
2089 frame = webkit_web_view_get_main_frame(t->wv);
2090 webkit_web_frame_reload(frame);
2091 break;
2092 case XT_NAV_STOP:
2093 frame = webkit_web_view_get_main_frame(t->wv);
2094 webkit_web_frame_stop_loading(frame);
2095 break;
2097 return (XT_CB_PASSTHROUGH);
2101 move(struct tab *t, struct karg *args)
2103 GtkAdjustment *adjust;
2104 double pi, si, pos, ps, upper, lower, max;
2105 double percent;
2107 switch (args->i) {
2108 case XT_MOVE_DOWN:
2109 case XT_MOVE_UP:
2110 case XT_MOVE_BOTTOM:
2111 case XT_MOVE_TOP:
2112 case XT_MOVE_PAGEDOWN:
2113 case XT_MOVE_PAGEUP:
2114 case XT_MOVE_HALFDOWN:
2115 case XT_MOVE_HALFUP:
2116 case XT_MOVE_PERCENT:
2117 case XT_MOVE_CENTER:
2118 adjust = t->adjust_v;
2119 break;
2120 default:
2121 adjust = t->adjust_h;
2122 break;
2125 pos = gtk_adjustment_get_value(adjust);
2126 ps = gtk_adjustment_get_page_size(adjust);
2127 upper = gtk_adjustment_get_upper(adjust);
2128 lower = gtk_adjustment_get_lower(adjust);
2129 si = gtk_adjustment_get_step_increment(adjust);
2130 pi = gtk_adjustment_get_page_increment(adjust);
2131 max = upper - ps;
2133 DNPRINTF(XT_D_MOVE, "move: opcode %d %s pos %f ps %f upper %f lower %f "
2134 "max %f si %f pi %f\n",
2135 args->i, adjust == t->adjust_h ? "horizontal" : "vertical",
2136 pos, ps, upper, lower, max, si, pi);
2138 switch (args->i) {
2139 case XT_MOVE_DOWN:
2140 case XT_MOVE_RIGHT:
2141 pos += si;
2142 gtk_adjustment_set_value(adjust, MIN(pos, max));
2143 break;
2144 case XT_MOVE_UP:
2145 case XT_MOVE_LEFT:
2146 pos -= si;
2147 gtk_adjustment_set_value(adjust, MAX(pos, lower));
2148 break;
2149 case XT_MOVE_BOTTOM:
2150 case XT_MOVE_FARRIGHT:
2151 gtk_adjustment_set_value(adjust, max);
2152 break;
2153 case XT_MOVE_TOP:
2154 case XT_MOVE_FARLEFT:
2155 gtk_adjustment_set_value(adjust, lower);
2156 break;
2157 case XT_MOVE_PAGEDOWN:
2158 pos += pi;
2159 gtk_adjustment_set_value(adjust, MIN(pos, max));
2160 break;
2161 case XT_MOVE_PAGEUP:
2162 pos -= pi;
2163 gtk_adjustment_set_value(adjust, MAX(pos, lower));
2164 break;
2165 case XT_MOVE_HALFDOWN:
2166 pos += pi / 2;
2167 gtk_adjustment_set_value(adjust, MIN(pos, max));
2168 break;
2169 case XT_MOVE_HALFUP:
2170 pos -= pi / 2;
2171 gtk_adjustment_set_value(adjust, MAX(pos, lower));
2172 break;
2173 case XT_MOVE_CENTER:
2174 args->s = g_strdup("50.0");
2175 /* FALLTHROUGH */
2176 case XT_MOVE_PERCENT:
2177 percent = atoi(args->s) / 100.0;
2178 pos = max * percent;
2179 if (pos < 0.0 || pos > max)
2180 break;
2181 gtk_adjustment_set_value(adjust, pos);
2182 break;
2183 default:
2184 return (XT_CB_PASSTHROUGH);
2187 DNPRINTF(XT_D_MOVE, "move: new pos %f %f\n", pos, MIN(pos, max));
2189 return (XT_CB_HANDLED);
2192 void
2193 url_set_visibility(void)
2195 struct tab *t;
2197 TAILQ_FOREACH(t, &tabs, entry)
2198 if (show_url == 0) {
2199 gtk_widget_hide(t->toolbar);
2200 focus_webview(t);
2201 } else
2202 gtk_widget_show(t->toolbar);
2205 void
2206 notebook_tab_set_visibility(void)
2208 if (show_tabs == 0) {
2209 gtk_widget_hide(tab_bar);
2210 gtk_notebook_set_show_tabs(notebook, FALSE);
2211 } else {
2212 if (tab_style == XT_TABS_NORMAL) {
2213 gtk_widget_hide(tab_bar);
2214 gtk_notebook_set_show_tabs(notebook, TRUE);
2215 } else if (tab_style == XT_TABS_COMPACT) {
2216 gtk_widget_show(tab_bar);
2217 gtk_notebook_set_show_tabs(notebook, FALSE);
2222 void
2223 statusbar_set_visibility(void)
2225 struct tab *t;
2227 TAILQ_FOREACH(t, &tabs, entry){
2228 if (show_statusbar == 0)
2229 gtk_widget_hide(t->statusbar_box);
2230 else
2231 gtk_widget_show(t->statusbar_box);
2233 focus_webview(t);
2237 void
2238 url_set(struct tab *t, int enable_url_entry)
2240 GdkPixbuf *pixbuf;
2241 int progress;
2243 show_url = enable_url_entry;
2245 if (enable_url_entry) {
2246 gtk_entry_set_icon_from_icon_name(GTK_ENTRY(t->sbe.statusbar),
2247 GTK_ENTRY_ICON_PRIMARY, NULL);
2248 gtk_entry_set_progress_fraction(GTK_ENTRY(t->sbe.statusbar), 0);
2249 } else {
2250 pixbuf = gtk_entry_get_icon_pixbuf(GTK_ENTRY(t->uri_entry),
2251 GTK_ENTRY_ICON_PRIMARY);
2252 progress =
2253 gtk_entry_get_progress_fraction(GTK_ENTRY(t->uri_entry));
2254 gtk_entry_set_icon_from_pixbuf(GTK_ENTRY(t->sbe.statusbar),
2255 GTK_ENTRY_ICON_PRIMARY, pixbuf);
2256 gtk_entry_set_progress_fraction(GTK_ENTRY(t->sbe.statusbar),
2257 progress);
2262 fullscreen(struct tab *t, struct karg *args)
2264 DNPRINTF(XT_D_TAB, "%s: %p %d\n", __func__, t, args->i);
2266 if (t == NULL)
2267 return (XT_CB_PASSTHROUGH);
2269 if (show_url == 0) {
2270 url_set(t, 1);
2271 show_tabs = 1;
2272 } else {
2273 url_set(t, 0);
2274 show_tabs = 0;
2277 url_set_visibility();
2278 notebook_tab_set_visibility();
2280 return (XT_CB_HANDLED);
2284 statustoggle(struct tab *t, struct karg *args)
2286 DNPRINTF(XT_D_TAB, "%s: %p %d\n", __func__, t, args->i);
2288 if (show_statusbar == 1) {
2289 show_statusbar = 0;
2290 statusbar_set_visibility();
2291 } else if (show_statusbar == 0) {
2292 show_statusbar = 1;
2293 statusbar_set_visibility();
2295 return (XT_CB_HANDLED);
2299 urlaction(struct tab *t, struct karg *args)
2301 int rv = XT_CB_HANDLED;
2303 DNPRINTF(XT_D_TAB, "%s: %p %d\n", __func__, t, args->i);
2305 if (t == NULL)
2306 return (XT_CB_PASSTHROUGH);
2308 switch (args->i) {
2309 case XT_URL_SHOW:
2310 if (show_url == 0) {
2311 url_set(t, 1);
2312 url_set_visibility();
2314 break;
2315 case XT_URL_HIDE:
2316 if (show_url == 1) {
2317 url_set(t, 0);
2318 url_set_visibility();
2320 break;
2322 return (rv);
2326 tabaction(struct tab *t, struct karg *args)
2328 int rv = XT_CB_HANDLED;
2329 char *url = args->s;
2330 struct undo *u;
2331 struct tab *tt;
2333 DNPRINTF(XT_D_TAB, "tabaction: %p %d\n", t, args->i);
2335 if (t == NULL)
2336 return (XT_CB_PASSTHROUGH);
2338 switch (args->i) {
2339 case XT_TAB_NEW:
2340 if (strlen(url) > 0)
2341 create_new_tab(url, NULL, 1, args->precount);
2342 else
2343 create_new_tab(NULL, NULL, 1, args->precount);
2344 break;
2345 case XT_TAB_DELETE:
2346 if (args->precount < 0)
2347 delete_tab(t);
2348 else
2349 TAILQ_FOREACH(tt, &tabs, entry)
2350 if (tt->tab_id == args->precount - 1) {
2351 delete_tab(tt);
2352 break;
2354 break;
2355 case XT_TAB_DELQUIT:
2356 if (gtk_notebook_get_n_pages(notebook) > 1)
2357 delete_tab(t);
2358 else
2359 quit(t, args);
2360 break;
2361 case XT_TAB_OPEN:
2362 if (strlen(url) > 0)
2364 else {
2365 rv = XT_CB_PASSTHROUGH;
2366 goto done;
2368 load_uri(t, url);
2369 break;
2370 case XT_TAB_SHOW:
2371 if (show_tabs == 0) {
2372 show_tabs = 1;
2373 notebook_tab_set_visibility();
2375 break;
2376 case XT_TAB_HIDE:
2377 if (show_tabs == 1) {
2378 show_tabs = 0;
2379 notebook_tab_set_visibility();
2381 break;
2382 case XT_TAB_NEXTSTYLE:
2383 if (tab_style == XT_TABS_NORMAL) {
2384 tab_style = XT_TABS_COMPACT;
2385 recolor_compact_tabs();
2387 else
2388 tab_style = XT_TABS_NORMAL;
2389 notebook_tab_set_visibility();
2390 break;
2391 case XT_TAB_UNDO_CLOSE:
2392 if (undo_count == 0) {
2393 DNPRINTF(XT_D_TAB, "%s: no tabs to undo close",
2394 __func__);
2395 goto done;
2396 } else {
2397 undo_count--;
2398 u = TAILQ_FIRST(&undos);
2399 create_new_tab(u->uri, u, 1, -1);
2401 TAILQ_REMOVE(&undos, u, entry);
2402 g_free(u->uri);
2403 /* u->history is freed in create_new_tab() */
2404 g_free(u);
2406 break;
2407 default:
2408 rv = XT_CB_PASSTHROUGH;
2409 goto done;
2412 done:
2413 if (args->s) {
2414 g_free(args->s);
2415 args->s = NULL;
2418 return (rv);
2422 resizetab(struct tab *t, struct karg *args)
2424 if (t == NULL || args == NULL) {
2425 show_oops(NULL, "resizetab invalid parameters");
2426 return (XT_CB_PASSTHROUGH);
2429 DNPRINTF(XT_D_TAB, "resizetab: tab %d %d\n",
2430 t->tab_id, args->i);
2432 setzoom_webkit(t, args->i);
2434 return (XT_CB_HANDLED);
2438 movetab(struct tab *t, struct karg *args)
2440 int n, dest;
2442 if (t == NULL || args == NULL) {
2443 show_oops(NULL, "movetab invalid parameters");
2444 return (XT_CB_PASSTHROUGH);
2447 DNPRINTF(XT_D_TAB, "movetab: tab %d opcode %d\n",
2448 t->tab_id, args->i);
2450 if (args->i >= XT_TAB_INVALID)
2451 return (XT_CB_PASSTHROUGH);
2453 if (TAILQ_EMPTY(&tabs))
2454 return (XT_CB_PASSTHROUGH);
2456 n = gtk_notebook_get_n_pages(notebook);
2457 dest = gtk_notebook_get_current_page(notebook);
2459 switch (args->i) {
2460 case XT_TAB_NEXT:
2461 if (args->precount < 0)
2462 dest = dest == n - 1 ? 0 : dest + 1;
2463 else
2464 dest = args->precount - 1;
2466 break;
2467 case XT_TAB_PREV:
2468 if (args->precount < 0)
2469 dest -= 1;
2470 else
2471 dest -= args->precount % n;
2473 if (dest < 0)
2474 dest += n;
2476 break;
2477 case XT_TAB_FIRST:
2478 dest = 0;
2479 break;
2480 case XT_TAB_LAST:
2481 dest = n - 1;
2482 break;
2483 default:
2484 return (XT_CB_PASSTHROUGH);
2487 if (dest < 0 || dest >= n)
2488 return (XT_CB_PASSTHROUGH);
2489 if (t->tab_id == dest) {
2490 DNPRINTF(XT_D_TAB, "movetab: do nothing\n");
2491 return (XT_CB_HANDLED);
2494 set_current_tab(dest);
2496 return (XT_CB_HANDLED);
2499 int cmd_prefix = 0;
2502 command_mode(struct tab *t, struct karg *args)
2504 run_script(t, JS_HINTING);
2505 if (args->i == XT_MODE_COMMAND)
2506 run_script(t, "hints.clearFocus();");
2507 else
2508 run_script(t, "hints.focusInput();");
2510 return (XT_CB_HANDLED);
2514 command(struct tab *t, struct karg *args)
2516 char *s = NULL, *ss = NULL;
2517 GdkColor color;
2518 const gchar *uri;
2519 struct karg a;
2521 if (t == NULL || args == NULL) {
2522 show_oops(NULL, "command invalid parameters");
2523 return (XT_CB_PASSTHROUGH);
2526 switch (args->i) {
2527 case '/':
2528 s = "/";
2529 break;
2530 case '?':
2531 s = "?";
2532 break;
2533 case ':':
2534 if (cmd_prefix == 0)
2535 s = ":";
2536 else {
2537 ss = g_strdup_printf(":%d", cmd_prefix);
2538 s = ss;
2539 cmd_prefix = 0;
2541 break;
2542 case '.':
2543 bzero(&a, sizeof a);
2544 a.i = 0;
2545 hint(t, &a);
2546 s = ".";
2547 break;
2548 case ',':
2549 bzero(&a, sizeof a);
2550 a.i = XT_HINT_NEWTAB;
2551 hint(t, &a);
2552 s = ",";
2553 break;
2554 case XT_CMD_OPEN:
2555 s = ":open ";
2556 break;
2557 case XT_CMD_TABNEW:
2558 s = ":tabnew ";
2559 break;
2560 case XT_CMD_OPEN_CURRENT:
2561 s = ":open ";
2562 /* FALL THROUGH */
2563 case XT_CMD_TABNEW_CURRENT:
2564 if (!s) /* FALL THROUGH? */
2565 s = ":tabnew ";
2566 if ((uri = get_uri(t)) != NULL) {
2567 ss = g_strdup_printf("%s%s", s, uri);
2568 s = ss;
2570 break;
2571 default:
2572 show_oops(t, "command: invalid opcode %d", args->i);
2573 return (XT_CB_PASSTHROUGH);
2576 DNPRINTF(XT_D_CMD, "%s: tab %d type %s\n", __func__, t->tab_id, s);
2578 gtk_entry_set_text(GTK_ENTRY(t->cmd), s);
2579 gdk_color_parse(XT_COLOR_WHITE, &color);
2580 gtk_widget_modify_base(t->cmd, GTK_STATE_NORMAL, &color);
2581 show_cmd(t);
2582 gtk_widget_grab_focus(GTK_WIDGET(t->cmd));
2583 gtk_editable_set_position(GTK_EDITABLE(t->cmd), -1);
2585 if (ss)
2586 g_free(ss);
2588 return (XT_CB_HANDLED);
2592 search(struct tab *t, struct karg *args)
2594 gboolean d;
2596 if (t == NULL || args == NULL) {
2597 show_oops(NULL, "search invalid parameters");
2598 return (1);
2601 switch (args->i) {
2602 case XT_SEARCH_NEXT:
2603 d = t->search_forward;
2604 break;
2605 case XT_SEARCH_PREV:
2606 d = !t->search_forward;
2607 break;
2608 default:
2609 return (XT_CB_PASSTHROUGH);
2612 if (t->search_text == NULL) {
2613 if (global_search == NULL)
2614 return (XT_CB_PASSTHROUGH);
2615 else {
2616 d = t->search_forward = TRUE;
2617 t->search_text = g_strdup(global_search);
2618 webkit_web_view_mark_text_matches(t->wv, global_search, FALSE, 0);
2619 webkit_web_view_set_highlight_text_matches(t->wv, TRUE);
2623 DNPRINTF(XT_D_CMD, "search: tab %d opc %d forw %d text %s\n",
2624 t->tab_id, args->i, t->search_forward, t->search_text);
2626 webkit_web_view_search_text(t->wv, t->search_text, FALSE, d, TRUE);
2628 return (XT_CB_HANDLED);
2632 session_save(struct tab *t, char *filename)
2634 struct karg a;
2635 int rv = 1;
2636 struct session *s;
2638 if (strlen(filename) == 0)
2639 goto done;
2641 if (filename[0] == '.' || filename[0] == '/')
2642 goto done;
2644 a.s = filename;
2645 if (save_tabs(t, &a))
2646 goto done;
2647 strlcpy(named_session, filename, sizeof named_session);
2649 /* add the new session to the list of sessions */
2650 s = g_malloc(sizeof(struct session));
2651 s->name = g_strdup(filename);
2652 TAILQ_INSERT_TAIL(&sessions, s, entry);
2654 rv = 0;
2655 done:
2656 return (rv);
2660 session_open(struct tab *t, char *filename)
2662 struct karg a;
2663 int rv = 1;
2665 if (strlen(filename) == 0)
2666 goto done;
2668 if (filename[0] == '.' || filename[0] == '/')
2669 goto done;
2671 a.s = filename;
2672 a.i = XT_SES_CLOSETABS;
2673 if (open_tabs(t, &a))
2674 goto done;
2676 strlcpy(named_session, filename, sizeof named_session);
2678 rv = 0;
2679 done:
2680 return (rv);
2684 session_delete(struct tab *t, char *filename)
2686 char file[PATH_MAX];
2687 int rv = 1;
2688 struct session *s;
2690 if (strlen(filename) == 0)
2691 goto done;
2693 if (filename[0] == '.' || filename[0] == '/')
2694 goto done;
2696 snprintf(file, sizeof file, "%s/%s", sessions_dir, filename);
2697 if (unlink(file))
2698 goto done;
2700 if (!strcmp(filename, named_session))
2701 strlcpy(named_session, XT_SAVED_TABS_FILE,
2702 sizeof named_session);
2704 /* remove session from sessions list */
2705 TAILQ_FOREACH(s, &sessions, entry) {
2706 if (!strcmp(s->name, filename))
2707 break;
2709 if (s == NULL)
2710 goto done;
2711 TAILQ_REMOVE(&sessions, s, entry);
2712 g_free((gpointer) s->name);
2713 g_free(s);
2715 rv = 0;
2716 done:
2717 return (rv);
2721 session_cmd(struct tab *t, struct karg *args)
2723 char *filename = args->s;
2725 if (t == NULL)
2726 return (1);
2728 if (args->i & XT_SHOW)
2729 show_oops(t, "Current session: %s", named_session[0] == '\0' ?
2730 XT_SAVED_TABS_FILE : named_session);
2731 else if (args->i & XT_SAVE) {
2732 if (session_save(t, filename)) {
2733 show_oops(t, "Can't save session: %s",
2734 filename ? filename : "INVALID");
2735 goto done;
2737 } else if (args->i & XT_OPEN) {
2738 if (session_open(t, filename)) {
2739 show_oops(t, "Can't open session: %s",
2740 filename ? filename : "INVALID");
2741 goto done;
2743 } else if (args->i & XT_DELETE) {
2744 if (session_delete(t, filename)) {
2745 show_oops(t, "Can't delete session: %s",
2746 filename ? filename : "INVALID");
2747 goto done;
2750 done:
2751 return (XT_CB_PASSTHROUGH);
2755 script_cmd(struct tab *t, struct karg *args)
2757 JSGlobalContextRef ctx;
2758 WebKitWebFrame *frame;
2759 JSStringRef str;
2760 JSValueRef val, exception;
2761 char *es;
2762 struct stat sb;
2763 FILE *f = NULL;
2764 char *buf = NULL;
2766 if (t == NULL)
2767 goto done;
2769 if ((f = fopen(args->s, "r")) == NULL) {
2770 show_oops(t, "Can't open script file: %s", args->s);
2771 goto done;
2774 if (fstat(fileno(f), &sb) == -1) {
2775 show_oops(t, "Can't stat script file: %s", args->s);
2776 goto done;
2779 buf = g_malloc0(sb.st_size + 1);
2780 if (fread(buf, 1, sb.st_size, f) != sb.st_size) {
2781 show_oops(t, "Can't read script file: %s", args->s);
2782 goto done;
2785 /* this code needs to be redone */
2786 frame = webkit_web_view_get_main_frame(t->wv);
2787 ctx = webkit_web_frame_get_global_context(frame);
2789 str = JSStringCreateWithUTF8CString(buf);
2790 val = JSEvaluateScript(ctx, str, JSContextGetGlobalObject(ctx),
2791 NULL, 0, &exception);
2792 JSStringRelease(str);
2794 DNPRINTF(XT_D_JS, "run_script: val %p\n", val);
2795 if (val == NULL) {
2796 es = js_ref_to_string(ctx, exception);
2797 if (es) {
2798 show_oops(t, "script exception: %s", es);
2799 g_free(es);
2801 goto done;
2802 } else {
2803 es = js_ref_to_string(ctx, val);
2804 #if 0
2805 /* return values */
2806 if (!strncmp(es, XT_JS_DONE, XT_JS_DONE_LEN))
2807 ; /* do nothing */
2808 if (!strncmp(es, XT_JS_INSERT, XT_JS_INSERT_LEN))
2809 ; /* do nothing */
2810 #endif
2811 if (es) {
2812 show_oops(t, "script complete return value: '%s'", es);
2813 g_free(es);
2814 } else
2815 show_oops(t, "script complete: without a return value");
2818 done:
2819 if (f)
2820 fclose(f);
2821 if (buf)
2822 g_free(buf);
2824 return (XT_CB_PASSTHROUGH);
2828 * Make a hardcopy of the page
2831 print_page(struct tab *t, struct karg *args)
2833 WebKitWebFrame *frame;
2834 GtkPageSetup *ps;
2835 GtkPrintOperation *op;
2836 GtkPrintOperationAction action;
2837 GtkPrintOperationResult print_res;
2838 GError *g_err = NULL;
2839 int marg_l, marg_r, marg_t, marg_b;
2841 DNPRINTF(XT_D_PRINTING, "%s:", __func__);
2843 ps = gtk_page_setup_new();
2844 op = gtk_print_operation_new();
2845 action = GTK_PRINT_OPERATION_ACTION_PRINT_DIALOG;
2846 frame = webkit_web_view_get_main_frame(t->wv);
2848 /* the default margins are too small, so we will bump them */
2849 marg_l = gtk_page_setup_get_left_margin(ps, GTK_UNIT_MM) +
2850 XT_PRINT_EXTRA_MARGIN;
2851 marg_r = gtk_page_setup_get_right_margin(ps, GTK_UNIT_MM) +
2852 XT_PRINT_EXTRA_MARGIN;
2853 marg_t = gtk_page_setup_get_top_margin(ps, GTK_UNIT_MM) +
2854 XT_PRINT_EXTRA_MARGIN;
2855 marg_b = gtk_page_setup_get_bottom_margin(ps, GTK_UNIT_MM) +
2856 XT_PRINT_EXTRA_MARGIN;
2858 /* set margins */
2859 gtk_page_setup_set_left_margin(ps, marg_l, GTK_UNIT_MM);
2860 gtk_page_setup_set_right_margin(ps, marg_r, GTK_UNIT_MM);
2861 gtk_page_setup_set_top_margin(ps, marg_t, GTK_UNIT_MM);
2862 gtk_page_setup_set_bottom_margin(ps, marg_b, GTK_UNIT_MM);
2864 gtk_print_operation_set_default_page_setup(op, ps);
2866 /* this appears to free 'op' and 'ps' */
2867 print_res = webkit_web_frame_print_full(frame, op, action, &g_err);
2869 /* check it worked */
2870 if (print_res == GTK_PRINT_OPERATION_RESULT_ERROR) {
2871 show_oops(NULL, "can't print: %s", g_err->message);
2872 g_error_free (g_err);
2873 return (1);
2876 return (0);
2880 go_home(struct tab *t, struct karg *args)
2882 load_uri(t, home);
2883 return (0);
2887 set_encoding(struct tab *t, struct karg *args)
2889 const gchar *e;
2891 if (args->s && strlen(g_strstrip(args->s)) == 0) {
2892 e = webkit_web_view_get_custom_encoding(t->wv);
2893 if (e == NULL)
2894 e = webkit_web_view_get_encoding(t->wv);
2895 show_oops(t, "encoding: %s", e ? e : "N/A");
2896 } else
2897 webkit_web_view_set_custom_encoding(t->wv, args->s);
2899 return (0);
2903 restart(struct tab *t, struct karg *args)
2905 struct karg a;
2907 a.s = XT_RESTART_TABS_FILE;
2908 save_tabs(t, &a);
2909 execvp(start_argv[0], start_argv);
2910 /* NOTREACHED */
2912 return (0);
2915 struct cmd {
2916 char *cmd;
2917 int level;
2918 int (*func)(struct tab *, struct karg *);
2919 int arg;
2920 int type;
2921 } cmds[] = {
2922 { "command_mode", 0, command_mode, XT_MODE_COMMAND, 0 },
2923 { "insert_mode", 0, command_mode, XT_MODE_INSERT, 0 },
2924 { "command", 0, command, ':', 0 },
2925 { "search", 0, command, '/', 0 },
2926 { "searchb", 0, command, '?', 0 },
2927 { "hinting", 0, command, '.', 0 },
2928 { "hinting_newtab", 0, command, ',', 0 },
2929 { "togglesrc", 0, toggle_src, 0, 0 },
2931 /* yanking and pasting */
2932 { "yankuri", 0, yank_uri, 0, 0 },
2933 /* XXX: pasteuri{cur,new} do not work from the cmd_entry? */
2934 { "pasteuricur", 0, paste_uri, XT_PASTE_CURRENT_TAB, 0 },
2935 { "pasteurinew", 0, paste_uri, XT_PASTE_NEW_TAB, 0 },
2937 /* search */
2938 { "searchnext", 0, search, XT_SEARCH_NEXT, 0 },
2939 { "searchprevious", 0, search, XT_SEARCH_PREV, 0 },
2941 /* focus */
2942 { "focusaddress", 0, focus, XT_FOCUS_URI, 0 },
2943 { "focussearch", 0, focus, XT_FOCUS_SEARCH, 0 },
2945 /* hinting */
2946 { "hinting", 0, hint, 0, 0 },
2947 { "hinting_newtab", 0, hint, XT_HINT_NEWTAB, 0 },
2949 /* custom stylesheet */
2950 { "userstyle", 0, userstyle, 0, 0 },
2952 /* navigation */
2953 { "goback", 0, navaction, XT_NAV_BACK, 0 },
2954 { "goforward", 0, navaction, XT_NAV_FORWARD, 0 },
2955 { "reload", 0, navaction, XT_NAV_RELOAD, 0 },
2956 { "stop", 0, navaction, XT_NAV_STOP, 0 },
2958 /* vertical movement */
2959 { "scrolldown", 0, move, XT_MOVE_DOWN, 0 },
2960 { "scrollup", 0, move, XT_MOVE_UP, 0 },
2961 { "scrollbottom", 0, move, XT_MOVE_BOTTOM, 0 },
2962 { "scrolltop", 0, move, XT_MOVE_TOP, 0 },
2963 { "1", 0, move, XT_MOVE_TOP, 0 },
2964 { "scrollhalfdown", 0, move, XT_MOVE_HALFDOWN, 0 },
2965 { "scrollhalfup", 0, move, XT_MOVE_HALFUP, 0 },
2966 { "scrollpagedown", 0, move, XT_MOVE_PAGEDOWN, 0 },
2967 { "scrollpageup", 0, move, XT_MOVE_PAGEUP, 0 },
2968 /* horizontal movement */
2969 { "scrollright", 0, move, XT_MOVE_RIGHT, 0 },
2970 { "scrollleft", 0, move, XT_MOVE_LEFT, 0 },
2971 { "scrollfarright", 0, move, XT_MOVE_FARRIGHT, 0 },
2972 { "scrollfarleft", 0, move, XT_MOVE_FARLEFT, 0 },
2974 { "favorites", 0, xtp_page_fl, 0, 0 },
2975 { "fav", 0, xtp_page_fl, 0, 0 },
2976 { "favadd", 0, add_favorite, 0, 0 },
2978 { "qall", 0, quit, 0, 0 },
2979 { "quitall", 0, quit, 0, 0 },
2980 { "w", 0, save_tabs, 0, 0 },
2981 { "wq", 0, save_tabs_and_quit, 0, 0 },
2982 { "help", 0, help, 0, 0 },
2983 { "about", 0, about, 0, 0 },
2984 { "stats", 0, stats, 0, 0 },
2985 { "version", 0, about, 0, 0 },
2987 /* js command */
2988 { "js", 0, js_cmd, XT_SHOW | XT_WL_PERSISTENT | XT_WL_SESSION, 0 },
2989 { "save", 1, js_cmd, XT_SAVE | XT_WL_FQDN, 0 },
2990 { "domain", 2, js_cmd, XT_SAVE | XT_WL_TOPLEVEL, 0 },
2991 { "fqdn", 2, js_cmd, XT_SAVE | XT_WL_FQDN, 0 },
2992 { "show", 1, js_cmd, XT_SHOW | XT_WL_PERSISTENT | XT_WL_SESSION, 0 },
2993 { "all", 2, js_cmd, XT_SHOW | XT_WL_PERSISTENT | XT_WL_SESSION, 0 },
2994 { "persistent", 2, js_cmd, XT_SHOW | XT_WL_PERSISTENT, 0 },
2995 { "session", 2, js_cmd, XT_SHOW | XT_WL_SESSION, 0 },
2996 { "toggle", 1, js_cmd, XT_WL_TOGGLE | XT_WL_FQDN, 0 },
2997 { "domain", 2, js_cmd, XT_WL_TOGGLE | XT_WL_TOPLEVEL, 0 },
2998 { "fqdn", 2, js_cmd, XT_WL_TOGGLE | XT_WL_FQDN, 0 },
3000 /* cookie command */
3001 { "cookie", 0, cookie_cmd, XT_SHOW | XT_WL_PERSISTENT | XT_WL_SESSION, 0 },
3002 { "save", 1, cookie_cmd, XT_SAVE | XT_WL_FQDN, 0 },
3003 { "domain", 2, cookie_cmd, XT_SAVE | XT_WL_TOPLEVEL, 0 },
3004 { "fqdn", 2, cookie_cmd, XT_SAVE | XT_WL_FQDN, 0 },
3005 { "show", 1, cookie_cmd, XT_SHOW | XT_WL_PERSISTENT | XT_WL_SESSION, 0 },
3006 { "all", 2, cookie_cmd, XT_SHOW | XT_WL_PERSISTENT | XT_WL_SESSION, 0 },
3007 { "persistent", 2, cookie_cmd, XT_SHOW | XT_WL_PERSISTENT, 0 },
3008 { "session", 2, cookie_cmd, XT_SHOW | XT_WL_SESSION, 0 },
3009 { "toggle", 1, cookie_cmd, XT_WL_TOGGLE | XT_WL_FQDN, 0 },
3010 { "domain", 2, cookie_cmd, XT_WL_TOGGLE | XT_WL_TOPLEVEL, 0 },
3011 { "fqdn", 2, cookie_cmd, XT_WL_TOGGLE | XT_WL_FQDN, 0 },
3013 /* plugin command */
3014 { "plugin", 0, pl_cmd, XT_SHOW | XT_WL_PERSISTENT | XT_WL_SESSION, 0 },
3015 { "save", 1, pl_cmd, XT_SAVE | XT_WL_FQDN, 0 },
3016 { "domain", 2, pl_cmd, XT_SAVE | XT_WL_TOPLEVEL, 0 },
3017 { "fqdn", 2, pl_cmd, XT_SAVE | XT_WL_FQDN, 0 },
3018 { "show", 1, pl_cmd, XT_SHOW | XT_WL_PERSISTENT | XT_WL_SESSION, 0 },
3019 { "all", 2, pl_cmd, XT_SHOW | XT_WL_PERSISTENT | XT_WL_SESSION, 0 },
3020 { "persistent", 2, pl_cmd, XT_SHOW | XT_WL_PERSISTENT, 0 },
3021 { "session", 2, pl_cmd, XT_SHOW | XT_WL_SESSION, 0 },
3022 { "toggle", 1, pl_cmd, XT_WL_TOGGLE | XT_WL_FQDN, 0 },
3023 { "domain", 2, pl_cmd, XT_WL_TOGGLE | XT_WL_TOPLEVEL, 0 },
3024 { "fqdn", 2, pl_cmd, XT_WL_TOGGLE | XT_WL_FQDN, 0 },
3026 /* toplevel (domain) command */
3027 { "toplevel", 0, toplevel_cmd, XT_WL_TOGGLE | XT_WL_TOPLEVEL | XT_WL_RELOAD, 0 },
3028 { "toggle", 1, toplevel_cmd, XT_WL_TOGGLE | XT_WL_TOPLEVEL | XT_WL_RELOAD, 0 },
3030 /* cookie jar */
3031 { "cookiejar", 0, xtp_page_cl, 0, 0 },
3033 /* cert command */
3034 { "cert", 0, cert_cmd, XT_SHOW, 0 },
3035 { "save", 1, cert_cmd, XT_SAVE, 0 },
3036 { "show", 1, cert_cmd, XT_SHOW, 0 },
3038 { "ca", 0, ca_cmd, 0, 0 },
3039 { "downloadmgr", 0, xtp_page_dl, 0, 0 },
3040 { "dl", 0, xtp_page_dl, 0, 0 },
3041 { "h", 0, xtp_page_hl, 0, 0 },
3042 { "history", 0, xtp_page_hl, 0, 0 },
3043 { "home", 0, go_home, 0, 0 },
3044 { "restart", 0, restart, 0, 0 },
3045 { "urlhide", 0, urlaction, XT_URL_HIDE, 0 },
3046 { "urlshow", 0, urlaction, XT_URL_SHOW, 0 },
3047 { "statustoggle", 0, statustoggle, 0, 0 },
3048 { "run_script", 0, run_page_script, 0, XT_USERARG },
3050 { "print", 0, print_page, 0, 0 },
3052 /* tabs */
3053 { "focusin", 0, resizetab, XT_ZOOM_IN, 0 },
3054 { "focusout", 0, resizetab, XT_ZOOM_OUT, 0 },
3055 { "focusreset", 0, resizetab, XT_ZOOM_NORMAL, 0 },
3056 { "q", 0, tabaction, XT_TAB_DELQUIT, 0 },
3057 { "quit", 0, tabaction, XT_TAB_DELQUIT, 0 },
3058 { "open", 0, tabaction, XT_TAB_OPEN, XT_URLARG },
3059 { "tabclose", 0, tabaction, XT_TAB_DELETE, XT_PREFIX | XT_INTARG},
3060 { "tabedit", 0, tabaction, XT_TAB_NEW, XT_PREFIX | XT_URLARG },
3061 { "tabfirst", 0, movetab, XT_TAB_FIRST, 0 },
3062 { "tabhide", 0, tabaction, XT_TAB_HIDE, 0 },
3063 { "tablast", 0, movetab, XT_TAB_LAST, 0 },
3064 { "tabnew", 0, tabaction, XT_TAB_NEW, XT_PREFIX | XT_URLARG },
3065 { "tabnext", 0, movetab, XT_TAB_NEXT, XT_PREFIX | XT_INTARG},
3066 { "tabnextstyle", 0, tabaction, XT_TAB_NEXTSTYLE, 0 },
3067 { "tabprevious", 0, movetab, XT_TAB_PREV, XT_PREFIX | XT_INTARG},
3068 { "tabrewind", 0, movetab, XT_TAB_FIRST, 0 },
3069 { "tabshow", 0, tabaction, XT_TAB_SHOW, 0 },
3070 { "tabs", 0, buffers, 0, 0 },
3071 { "tabundoclose", 0, tabaction, XT_TAB_UNDO_CLOSE, 0 },
3072 { "buffers", 0, buffers, 0, 0 },
3073 { "ls", 0, buffers, 0, 0 },
3074 { "encoding", 0, set_encoding, 0, XT_USERARG },
3076 /* command aliases (handy when -S flag is used) */
3077 { "promptopen", 0, command, XT_CMD_OPEN, 0 },
3078 { "promptopencurrent", 0, command, XT_CMD_OPEN_CURRENT, 0 },
3079 { "prompttabnew", 0, command, XT_CMD_TABNEW, 0 },
3080 { "prompttabnewcurrent",0, command, XT_CMD_TABNEW_CURRENT, 0 },
3082 /* settings */
3083 { "set", 0, set, 0, XT_SETARG },
3085 { "fullscreen", 0, fullscreen, 0, 0 },
3086 { "f", 0, fullscreen, 0, 0 },
3088 /* sessions */
3089 { "session", 0, session_cmd, XT_SHOW, 0 },
3090 { "delete", 1, session_cmd, XT_DELETE, XT_SESSARG },
3091 { "open", 1, session_cmd, XT_OPEN, XT_SESSARG },
3092 { "save", 1, session_cmd, XT_SAVE, XT_USERARG },
3093 { "show", 1, session_cmd, XT_SHOW, 0 },
3095 /* external javascript */
3096 { "script", 0, script_cmd, XT_EJS_SHOW, XT_USERARG },
3098 /* inspector */
3099 { "inspector", 0, inspector_cmd, XT_INS_SHOW, 0 },
3100 { "show", 1, inspector_cmd, XT_INS_SHOW, 0 },
3101 { "hide", 1, inspector_cmd, XT_INS_HIDE, 0 },
3104 struct {
3105 int index;
3106 int len;
3107 gchar *list[256];
3108 } cmd_status = {-1, 0};
3110 gboolean
3111 wv_release_button_cb(GtkWidget *btn, GdkEventButton *e, struct tab *t)
3114 if (e->type == GDK_BUTTON_RELEASE && e->button == 1)
3115 btn_down = 0;
3117 return (FALSE);
3120 gboolean
3121 wv_button_cb(GtkWidget *btn, GdkEventButton *e, struct tab *t)
3123 struct karg a;
3125 hide_oops(t);
3126 hide_buffers(t);
3128 if (e->type == GDK_BUTTON_PRESS && e->button == 1)
3129 btn_down = 1;
3130 else if (e->type == GDK_BUTTON_PRESS && e->button == 8 /* btn 4 */) {
3131 /* go backward */
3132 a.i = XT_NAV_BACK;
3133 navaction(t, &a);
3135 return (TRUE);
3136 } else if (e->type == GDK_BUTTON_PRESS && e->button == 9 /* btn 5 */) {
3137 /* go forward */
3138 a.i = XT_NAV_FORWARD;
3139 navaction(t, &a);
3141 return (TRUE);
3144 return (FALSE);
3147 gboolean
3148 tab_close_cb(GtkWidget *btn, GdkEventButton *e, struct tab *t)
3150 DNPRINTF(XT_D_TAB, "tab_close_cb: tab %d\n", t->tab_id);
3152 if (e->type == GDK_BUTTON_PRESS && e->button == 1)
3153 delete_tab(t);
3155 return (FALSE);
3160 void
3161 activate_uri_entry_cb(GtkWidget* entry, struct tab *t)
3163 const gchar *uri = gtk_entry_get_text(GTK_ENTRY(entry));
3165 DNPRINTF(XT_D_URL, "activate_uri_entry_cb: %s\n", uri);
3167 if (t == NULL) {
3168 show_oops(NULL, "activate_uri_entry_cb invalid parameters");
3169 return;
3172 if (uri == NULL) {
3173 show_oops(t, "activate_uri_entry_cb no uri");
3174 return;
3177 uri += strspn(uri, "\t ");
3179 /* if xxxt:// treat specially */
3180 if (parse_xtp_url(t, uri))
3181 return;
3183 /* otherwise continue to load page normally */
3184 load_uri(t, (gchar *)uri);
3185 focus_webview(t);
3188 void
3189 activate_search_entry_cb(GtkWidget* entry, struct tab *t)
3191 const gchar *search = gtk_entry_get_text(GTK_ENTRY(entry));
3192 char *newuri = NULL;
3193 gchar *enc_search;
3195 DNPRINTF(XT_D_URL, "activate_search_entry_cb: %s\n", search);
3197 if (t == NULL) {
3198 show_oops(NULL, "activate_search_entry_cb invalid parameters");
3199 return;
3202 if (search_string == NULL) {
3203 show_oops(t, "no search_string");
3204 return;
3207 t->xtp_meaning = XT_XTP_TAB_MEANING_NORMAL;
3209 enc_search = soup_uri_encode(search, XT_RESERVED_CHARS);
3210 newuri = g_strdup_printf(search_string, enc_search);
3211 g_free(enc_search);
3213 marks_clear(t);
3214 webkit_web_view_load_uri(t->wv, newuri);
3215 focus_webview(t);
3217 if (newuri)
3218 g_free(newuri);
3221 void
3222 check_and_set_cookie(const gchar *uri, struct tab *t)
3224 struct domain *d = NULL;
3225 int es = 0;
3227 if (uri == NULL || t == NULL)
3228 return;
3230 if ((d = wl_find_uri(uri, &c_wl)) == NULL)
3231 es = 0;
3232 else
3233 es = 1;
3235 DNPRINTF(XT_D_COOKIE, "check_and_set_cookie: %s %s\n",
3236 es ? "enable" : "disable", uri);
3238 g_object_set(G_OBJECT(t->settings),
3239 "enable-html5-local-storage", es, (char *)NULL);
3240 webkit_web_view_set_settings(t->wv, t->settings);
3243 void
3244 check_and_set_js(const gchar *uri, struct tab *t)
3246 struct domain *d = NULL;
3247 int es = 0;
3249 if (uri == NULL || t == NULL)
3250 return;
3252 if ((d = wl_find_uri(uri, &js_wl)) == NULL)
3253 es = 0;
3254 else
3255 es = 1;
3257 DNPRINTF(XT_D_JS, "check_and_set_js: %s %s\n",
3258 es ? "enable" : "disable", uri);
3260 g_object_set(G_OBJECT(t->settings),
3261 "enable-scripts", es, (char *)NULL);
3262 g_object_set(G_OBJECT(t->settings),
3263 "javascript-can-open-windows-automatically", es, (char *)NULL);
3264 webkit_web_view_set_settings(t->wv, t->settings);
3266 button_set_stockid(t->js_toggle,
3267 es ? GTK_STOCK_MEDIA_PLAY : GTK_STOCK_MEDIA_PAUSE);
3270 void
3271 check_and_set_pl(const gchar *uri, struct tab *t)
3273 struct domain *d = NULL;
3274 int es = 0;
3276 if (uri == NULL || t == NULL)
3277 return;
3279 if ((d = wl_find_uri(uri, &pl_wl)) == NULL)
3280 es = 0;
3281 else
3282 es = 1;
3284 DNPRINTF(XT_D_JS, "check_and_set_pl: %s %s\n",
3285 es ? "enable" : "disable", uri);
3287 g_object_set(G_OBJECT(t->settings),
3288 "enable-plugins", es, (char *)NULL);
3289 webkit_web_view_set_settings(t->wv, t->settings);
3292 void
3293 color_address_bar(gpointer p)
3295 GdkColor color;
3296 struct tab *tt, *t = p;
3297 gchar *col_str = XT_COLOR_WHITE;
3298 const gchar *uri, *u = NULL, *error_str = NULL;
3300 #ifdef USE_THREADS
3301 gdk_threads_enter();
3302 #endif
3303 DNPRINTF(XT_D_URL, "%s:\n", __func__);
3305 /* make sure t still exists */
3306 if (t == NULL)
3307 return;
3308 TAILQ_FOREACH(tt, &tabs, entry)
3309 if (t == tt)
3310 break;
3311 if (t != tt)
3312 goto done;
3314 if ((uri = get_uri(t)) == NULL)
3315 goto white;
3316 u = g_strdup(uri);
3318 #ifdef USE_THREADS
3319 gdk_threads_leave();
3320 #endif
3322 col_str = XT_COLOR_YELLOW;
3323 switch (load_compare_cert(u, &error_str)) {
3324 case CERT_LOCAL:
3325 col_str = XT_COLOR_BLUE;
3326 break;
3327 case CERT_TRUSTED:
3328 col_str = XT_COLOR_GREEN;
3329 break;
3330 case CERT_UNTRUSTED:
3331 col_str = XT_COLOR_YELLOW;
3332 break;
3333 case CERT_BAD:
3334 col_str = XT_COLOR_RED;
3335 break;
3338 #ifdef USE_THREADS
3339 gdk_threads_enter();
3340 #endif
3341 /* make sure t isn't deleted */
3342 TAILQ_FOREACH(tt, &tabs, entry)
3343 if (t == tt)
3344 break;
3345 if (t != tt)
3346 goto done;
3348 #ifdef USE_THREADS
3349 /* test to see if the user navigated away and canceled the thread */
3350 if (t->thread != g_thread_self())
3351 goto done;
3352 if ((uri = get_uri(t)) == NULL) {
3353 t->thread = NULL;
3354 goto done;
3356 if (strcmp(uri, u)) {
3357 /* make sure we are still the same url */
3358 t->thread = NULL;
3359 goto done;
3361 #endif
3362 white:
3363 gdk_color_parse(col_str, &color);
3364 gtk_widget_modify_base(t->uri_entry, GTK_STATE_NORMAL, &color);
3366 if (!strcmp(col_str, XT_COLOR_WHITE))
3367 statusbar_modify_attr(t, col_str, XT_COLOR_BLACK);
3368 else
3369 statusbar_modify_attr(t, XT_COLOR_BLACK, col_str);
3371 if (error_str && error_str[0] != '\0')
3372 show_oops(t, "%s", error_str);
3373 #ifdef USE_THREADS
3374 t->thread = NULL;
3375 #endif
3376 done:
3377 /* t is invalid at this point */
3378 if (u)
3379 g_free((gpointer)u);
3380 #ifdef USE_THREADS
3381 gdk_threads_leave();
3382 #endif
3385 void
3386 show_ca_status(struct tab *t, const char *uri)
3388 GdkColor color;
3389 gchar *col_str = XT_COLOR_WHITE;
3391 DNPRINTF(XT_D_URL, "show_ca_status: %d %s %s\n",
3392 ssl_strict_certs, ssl_ca_file, uri);
3394 if (t == NULL)
3395 return;
3397 if (uri == NULL)
3398 goto done;
3399 if (ssl_ca_file == NULL) {
3400 if (g_str_has_prefix(uri, "http://"))
3401 goto done;
3402 if (g_str_has_prefix(uri, "https://")) {
3403 col_str = XT_COLOR_RED;
3404 goto done;
3406 return;
3408 if (g_str_has_prefix(uri, "http://") ||
3409 !g_str_has_prefix(uri, "https://"))
3410 goto done;
3411 #ifdef USE_THREADS
3413 * It is not necessary to see if the thread is already running.
3414 * If the thread is in progress setting it to something else aborts it
3415 * on the way out.
3418 /* thread the coloring of the address bar */
3419 t->thread = g_thread_create((GThreadFunc)color_address_bar, t, TRUE, NULL);
3420 #else
3421 color_address_bar(t);
3422 #endif
3423 return;
3425 done:
3426 if (col_str) {
3427 gdk_color_parse(col_str, &color);
3428 gtk_widget_modify_base(t->uri_entry, GTK_STATE_NORMAL, &color);
3430 if (!strcmp(col_str, XT_COLOR_WHITE))
3431 statusbar_modify_attr(t, col_str, XT_COLOR_BLACK);
3432 else
3433 statusbar_modify_attr(t, XT_COLOR_BLACK, col_str);
3437 void
3438 free_favicon(struct tab *t)
3440 DNPRINTF(XT_D_DOWNLOAD, "%s: down %p req %p\n",
3441 __func__, t->icon_download, t->icon_request);
3443 if (t->icon_request)
3444 g_object_unref(t->icon_request);
3445 if (t->icon_dest_uri)
3446 g_free(t->icon_dest_uri);
3448 t->icon_request = NULL;
3449 t->icon_dest_uri = NULL;
3452 void
3453 xt_icon_from_name(struct tab *t, gchar *name)
3455 gtk_entry_set_icon_from_icon_name(GTK_ENTRY(t->uri_entry),
3456 GTK_ENTRY_ICON_PRIMARY, "text-html");
3457 if (show_url == 0)
3458 gtk_entry_set_icon_from_icon_name(GTK_ENTRY(t->sbe.statusbar),
3459 GTK_ENTRY_ICON_PRIMARY, "text-html");
3460 else
3461 gtk_entry_set_icon_from_icon_name(GTK_ENTRY(t->sbe.statusbar),
3462 GTK_ENTRY_ICON_PRIMARY, NULL);
3465 void
3466 xt_icon_from_pixbuf(struct tab *t, GdkPixbuf *pb)
3468 GdkPixbuf *pb_scaled;
3470 if (gdk_pixbuf_get_width(pb) > 16 || gdk_pixbuf_get_height(pb) > 16)
3471 pb_scaled = gdk_pixbuf_scale_simple(pb, 16, 16,
3472 GDK_INTERP_BILINEAR);
3473 else
3474 pb_scaled = pb;
3476 gtk_entry_set_icon_from_pixbuf(GTK_ENTRY(t->uri_entry),
3477 GTK_ENTRY_ICON_PRIMARY, pb_scaled);
3478 if (show_url == 0)
3479 gtk_entry_set_icon_from_pixbuf(GTK_ENTRY(t->sbe.statusbar),
3480 GTK_ENTRY_ICON_PRIMARY, pb_scaled);
3481 else
3482 gtk_entry_set_icon_from_icon_name(GTK_ENTRY(t->sbe.statusbar),
3483 GTK_ENTRY_ICON_PRIMARY, NULL);
3485 if (pb_scaled != pb)
3486 g_object_unref(pb_scaled);
3489 void
3490 xt_icon_from_file(struct tab *t, char *file)
3492 GdkPixbuf *pb;
3494 if (g_str_has_prefix(file, "file://"))
3495 file += strlen("file://");
3497 pb = gdk_pixbuf_new_from_file(file, NULL);
3498 if (pb) {
3499 xt_icon_from_pixbuf(t, pb);
3500 g_object_unref(pb);
3501 } else
3502 xt_icon_from_name(t, "text-html");
3505 gboolean
3506 is_valid_icon(char *file)
3508 gboolean valid = 0;
3509 const char *mime_type;
3510 GFileInfo *fi;
3511 GFile *gf;
3513 gf = g_file_new_for_path(file);
3514 fi = g_file_query_info(gf, G_FILE_ATTRIBUTE_STANDARD_CONTENT_TYPE, 0,
3515 NULL, NULL);
3516 mime_type = g_file_info_get_content_type(fi);
3517 valid = g_strcmp0(mime_type, "image/x-ico") == 0 ||
3518 g_strcmp0(mime_type, "image/vnd.microsoft.icon") == 0 ||
3519 g_strcmp0(mime_type, "image/png") == 0 ||
3520 g_strcmp0(mime_type, "image/gif") == 0 ||
3521 g_strcmp0(mime_type, "application/octet-stream") == 0;
3522 g_object_unref(fi);
3523 g_object_unref(gf);
3525 return (valid);
3528 void
3529 set_favicon_from_file(struct tab *t, char *file)
3531 struct stat sb;
3533 if (t == NULL || file == NULL)
3534 return;
3536 if (g_str_has_prefix(file, "file://"))
3537 file += strlen("file://");
3538 DNPRINTF(XT_D_DOWNLOAD, "%s: loading %s\n", __func__, file);
3540 if (!stat(file, &sb)) {
3541 if (sb.st_size == 0 || !is_valid_icon(file)) {
3542 /* corrupt icon so trash it */
3543 DNPRINTF(XT_D_DOWNLOAD, "%s: corrupt icon %s\n",
3544 __func__, file);
3545 unlink(file);
3546 /* no need to set icon to default here */
3547 return;
3550 xt_icon_from_file(t, file);
3553 void
3554 favicon_download_status_changed_cb(WebKitDownload *download, GParamSpec *spec,
3555 WebKitWebView *wv)
3557 WebKitDownloadStatus status = webkit_download_get_status(download);
3558 struct tab *tt = NULL, *t = NULL;
3561 * find the webview instead of passing in the tab as it could have been
3562 * deleted from underneath us.
3564 TAILQ_FOREACH(tt, &tabs, entry) {
3565 if (tt->wv == wv) {
3566 t = tt;
3567 break;
3570 if (t == NULL)
3571 return;
3573 DNPRINTF(XT_D_DOWNLOAD, "%s: tab %d status %d\n",
3574 __func__, t->tab_id, status);
3576 switch (status) {
3577 case WEBKIT_DOWNLOAD_STATUS_ERROR:
3578 /* -1 */
3579 t->icon_download = NULL;
3580 free_favicon(t);
3581 break;
3582 case WEBKIT_DOWNLOAD_STATUS_CREATED:
3583 /* 0 */
3584 break;
3585 case WEBKIT_DOWNLOAD_STATUS_STARTED:
3586 /* 1 */
3587 break;
3588 case WEBKIT_DOWNLOAD_STATUS_CANCELLED:
3589 /* 2 */
3590 DNPRINTF(XT_D_DOWNLOAD, "%s: freeing favicon %d\n",
3591 __func__, t->tab_id);
3592 t->icon_download = NULL;
3593 free_favicon(t);
3594 break;
3595 case WEBKIT_DOWNLOAD_STATUS_FINISHED:
3596 /* 3 */
3598 DNPRINTF(XT_D_DOWNLOAD, "%s: setting icon to %s\n",
3599 __func__, t->icon_dest_uri);
3600 set_favicon_from_file(t, t->icon_dest_uri);
3601 /* these will be freed post callback */
3602 t->icon_request = NULL;
3603 t->icon_download = NULL;
3604 break;
3605 default:
3606 break;
3610 void
3611 abort_favicon_download(struct tab *t)
3613 DNPRINTF(XT_D_DOWNLOAD, "%s: down %p\n", __func__, t->icon_download);
3615 #if !WEBKIT_CHECK_VERSION(1, 4, 0)
3616 if (t->icon_download) {
3617 g_signal_handlers_disconnect_by_func(G_OBJECT(t->icon_download),
3618 G_CALLBACK(favicon_download_status_changed_cb), t->wv);
3619 webkit_download_cancel(t->icon_download);
3620 t->icon_download = NULL;
3621 } else
3622 free_favicon(t);
3623 #endif
3625 xt_icon_from_name(t, "text-html");
3628 void
3629 notify_icon_loaded_cb(WebKitWebView *wv, gchar *uri, struct tab *t)
3631 DNPRINTF(XT_D_DOWNLOAD, "%s %s\n", __func__, uri);
3633 if (uri == NULL || t == NULL)
3634 return;
3636 #if WEBKIT_CHECK_VERSION(1, 4, 0)
3637 /* take icon from WebKitIconDatabase */
3638 GdkPixbuf *pb;
3640 pb = webkit_web_view_get_icon_pixbuf(wv);
3641 if (pb) {
3642 xt_icon_from_pixbuf(t, pb);
3643 g_object_unref(pb);
3644 } else
3645 xt_icon_from_name(t, "text-html");
3646 #elif WEBKIT_CHECK_VERSION(1, 1, 18)
3647 /* download icon to cache dir */
3648 gchar *name_hash, file[PATH_MAX];
3649 struct stat sb;
3651 if (t->icon_request) {
3652 DNPRINTF(XT_D_DOWNLOAD, "%s: download in progress\n", __func__);
3653 return;
3656 /* check to see if we got the icon in cache */
3657 name_hash = g_compute_checksum_for_string(G_CHECKSUM_SHA256, uri, -1);
3658 snprintf(file, sizeof file, "%s/%s.ico", cache_dir, name_hash);
3659 g_free(name_hash);
3661 if (!stat(file, &sb)) {
3662 if (sb.st_size > 0) {
3663 DNPRINTF(XT_D_DOWNLOAD, "%s: loading from cache %s\n",
3664 __func__, file);
3665 set_favicon_from_file(t, file);
3666 return;
3669 /* corrupt icon so trash it */
3670 DNPRINTF(XT_D_DOWNLOAD, "%s: corrupt icon %s\n",
3671 __func__, file);
3672 unlink(file);
3675 /* create download for icon */
3676 t->icon_request = webkit_network_request_new(uri);
3677 if (t->icon_request == NULL) {
3678 DNPRINTF(XT_D_DOWNLOAD, "%s: invalid uri %s\n",
3679 __func__, uri);
3680 return;
3683 t->icon_download = webkit_download_new(t->icon_request);
3684 if (t->icon_download == NULL)
3685 return;
3687 /* we have to free icon_dest_uri later */
3688 t->icon_dest_uri = g_strdup_printf("file://%s", file);
3689 webkit_download_set_destination_uri(t->icon_download,
3690 t->icon_dest_uri);
3692 if (webkit_download_get_status(t->icon_download) ==
3693 WEBKIT_DOWNLOAD_STATUS_ERROR) {
3694 g_object_unref(t->icon_request);
3695 g_free(t->icon_dest_uri);
3696 t->icon_request = NULL;
3697 t->icon_dest_uri = NULL;
3698 return;
3701 g_signal_connect(G_OBJECT(t->icon_download), "notify::status",
3702 G_CALLBACK(favicon_download_status_changed_cb), t->wv);
3704 webkit_download_start(t->icon_download);
3705 #endif
3708 void
3709 notify_load_status_cb(WebKitWebView* wview, GParamSpec* pspec, struct tab *t)
3711 const gchar *uri = NULL, *title = NULL;
3712 struct history *h, find;
3713 struct karg a;
3714 GdkColor color;
3716 DNPRINTF(XT_D_URL, "notify_load_status_cb: %d %s\n",
3717 webkit_web_view_get_load_status(wview),
3718 get_uri(t) ? get_uri(t) : "NOTHING");
3720 if (t == NULL) {
3721 show_oops(NULL, "notify_load_status_cb invalid parameters");
3722 return;
3725 switch (webkit_web_view_get_load_status(wview)) {
3726 case WEBKIT_LOAD_PROVISIONAL:
3727 /* 0 */
3728 abort_favicon_download(t);
3729 #if GTK_CHECK_VERSION(2, 20, 0)
3730 gtk_widget_show(t->spinner);
3731 gtk_spinner_start(GTK_SPINNER(t->spinner));
3732 #endif
3733 gtk_label_set_text(GTK_LABEL(t->label), "Loading");
3735 gtk_widget_set_sensitive(GTK_WIDGET(t->stop), TRUE);
3737 /* assume we are a new address */
3738 gdk_color_parse("white", &color);
3739 gtk_widget_modify_base(t->uri_entry, GTK_STATE_NORMAL, &color);
3740 statusbar_modify_attr(t, "white", XT_COLOR_BLACK);
3742 /* take focus if we are visible */
3743 focus_webview(t);
3744 t->focus_wv = 1;
3746 marks_clear(t);
3747 #ifdef USE_THREAD
3748 /* kill color thread */
3749 t->thread = NULL;
3750 #endif
3751 break;
3753 case WEBKIT_LOAD_COMMITTED:
3754 /* 1 */
3755 uri = get_uri(t);
3756 if (uri == NULL)
3757 return;
3758 gtk_entry_set_text(GTK_ENTRY(t->uri_entry), uri);
3760 if (t->status) {
3761 g_free(t->status);
3762 t->status = NULL;
3764 set_status(t, (char *)uri, XT_STATUS_LOADING);
3766 /* check if js white listing is enabled */
3767 if (enable_plugin_whitelist)
3768 check_and_set_pl(uri, t);
3769 if (enable_cookie_whitelist)
3770 check_and_set_cookie(uri, t);
3771 if (enable_js_whitelist)
3772 check_and_set_js(uri, t);
3774 if (t->styled)
3775 apply_style(t);
3778 /* we know enough to autosave the session */
3779 if (session_autosave) {
3780 a.s = NULL;
3781 save_tabs(t, &a);
3784 show_ca_status(t, uri);
3785 break;
3787 case WEBKIT_LOAD_FIRST_VISUALLY_NON_EMPTY_LAYOUT:
3788 /* 3 */
3789 break;
3791 case WEBKIT_LOAD_FINISHED:
3792 /* 2 */
3793 uri = get_uri(t);
3794 if (uri == NULL)
3795 return;
3797 if (!strncmp(uri, "http://", strlen("http://")) ||
3798 !strncmp(uri, "https://", strlen("https://")) ||
3799 !strncmp(uri, "file://", strlen("file://"))) {
3800 find.uri = uri;
3801 h = RB_FIND(history_list, &hl, &find);
3802 if (!h) {
3803 title = get_title(t, FALSE);
3804 h = g_malloc(sizeof *h);
3805 h->uri = g_strdup(uri);
3806 h->title = g_strdup(title);
3807 RB_INSERT(history_list, &hl, h);
3808 completion_add_uri(h->uri);
3809 update_history_tabs(NULL);
3813 set_status(t, (char *)uri, XT_STATUS_URI);
3814 #if WEBKIT_CHECK_VERSION(1, 1, 18)
3815 case WEBKIT_LOAD_FAILED:
3816 /* 4 */
3817 #endif
3818 #if GTK_CHECK_VERSION(2, 20, 0)
3819 gtk_spinner_stop(GTK_SPINNER(t->spinner));
3820 gtk_widget_hide(t->spinner);
3821 #endif
3822 default:
3823 gtk_widget_set_sensitive(GTK_WIDGET(t->stop), FALSE);
3824 break;
3827 if (t->item)
3828 gtk_widget_set_sensitive(GTK_WIDGET(t->backward), TRUE);
3829 else
3830 gtk_widget_set_sensitive(GTK_WIDGET(t->backward),
3831 can_go_back_for_real(t));
3833 gtk_widget_set_sensitive(GTK_WIDGET(t->forward),
3834 can_go_forward_for_real(t));
3837 void
3838 notify_title_cb(WebKitWebView* wview, GParamSpec* pspec, struct tab *t)
3840 const gchar *title = NULL, *win_title = NULL;
3842 title = get_title(t, FALSE);
3843 win_title = get_title(t, TRUE);
3844 gtk_label_set_text(GTK_LABEL(t->label), title);
3845 gtk_label_set_text(GTK_LABEL(t->tab_elems.label), title);
3846 if (t->tab_id == gtk_notebook_get_current_page(notebook))
3847 gtk_window_set_title(GTK_WINDOW(main_window), win_title);
3850 char *
3851 get_domain(const gchar *host)
3853 size_t x;
3854 int silly_domain = 0;
3855 char *p;
3857 /* handle silly domains like .co.uk */
3859 if ((x = strlen(host)) <= 6)
3860 return (g_strdup(host));
3862 if (host[x - 3] == '.' && host[x - 6] == '.') {
3863 silly_domain = 1;
3864 x = x - 7;
3865 while (x > 0)
3866 if (host[x] != '.')
3867 x--;
3868 else
3869 return (g_strdup(&host[x + 1]));
3872 /* find first . */
3873 p = g_strrstr(host, ".");
3874 if (p == NULL)
3875 return (g_strdup(""));
3876 p--;
3877 while (p > host)
3878 if (*p != '.')
3879 p--;
3880 else
3881 return (g_strdup(p + 1));
3883 return (g_strdup(host));
3886 void
3887 js_autorun(struct tab *t)
3889 SoupURI *su = NULL;
3890 const gchar *uri;
3891 size_t got_default = 0, got_host = 0;
3892 struct stat sb;
3893 char deff[PATH_MAX], hostf[PATH_MAX];
3894 char *js = NULL, *jsat, *domain = NULL;
3895 FILE *deffile = NULL, *hostfile = NULL;
3896 JSGlobalContextRef ctx;
3897 WebKitWebFrame *frame;
3898 JSStringRef str;
3899 JSValueRef val, exception;
3900 char *es;
3902 if (js_autorun_enabled == 0)
3903 return;
3905 uri = get_uri(t);
3906 if (uri &&
3907 !(g_str_has_prefix(uri, "http://") ||
3908 g_str_has_prefix(uri, "https://"))) {
3909 show_oops(t, "invalid uri");
3910 goto done;
3913 su = soup_uri_new(uri);
3914 if (su == NULL) {
3915 show_oops(t, "invalid soup URI");
3916 goto done;
3918 if (!SOUP_URI_VALID_FOR_HTTP(su)) {
3919 show_oops(t, "invalid HTTPS URI");
3920 goto done;
3923 DNPRINTF(XT_D_JS, "%s: host: %s domain: %s\n", __func__,
3924 su->host, domain);
3925 domain = get_domain(su->host);
3927 snprintf(deff, sizeof deff, "%s/default.js", js_dir);
3928 if ((deffile = fopen(deff, "r")) != NULL) {
3929 if (fstat(fileno(deffile), &sb) == -1) {
3930 show_oops(t, "can't stat default JS file");
3931 goto done;
3933 got_default = sb.st_size;
3936 /* try host first followed by domain */
3937 snprintf(hostf, sizeof hostf, "%s/%s.js", js_dir, su->host);
3938 DNPRINTF(XT_D_JS, "trying file: %s\n", hostf);
3939 if ((hostfile = fopen(hostf, "r")) == NULL) {
3940 snprintf(hostf, sizeof hostf, "%s/%s.js", js_dir, domain);
3941 DNPRINTF(XT_D_JS, "trying file: %s\n", hostf);
3942 if ((hostfile = fopen(hostf, "r")) == NULL)
3943 goto nofile;
3945 DNPRINTF(XT_D_JS, "file: %s\n", hostf);
3946 if (fstat(fileno(hostfile), &sb) == -1) {
3947 show_oops(t, "can't stat %s JS file", hostf);
3948 goto done;
3950 got_host = sb.st_size;
3952 nofile:
3953 if (got_default + got_host == 0)
3954 goto done;
3956 js = g_malloc0(got_default + got_host + 1);
3957 jsat = js;
3959 if (got_default) {
3960 if (fread(js, got_default, 1, deffile) != 1) {
3961 show_oops(t, "default file read error");
3962 goto done;
3964 jsat = js + got_default;
3967 if (got_host) {
3968 if (fread(jsat, got_host, 1, hostfile) != 1) {
3969 show_oops(t, "host file read error");
3970 goto done;
3974 /* this code needs to be redone */
3975 frame = webkit_web_view_get_main_frame(t->wv);
3976 ctx = webkit_web_frame_get_global_context(frame);
3978 str = JSStringCreateWithUTF8CString(js);
3979 val = JSEvaluateScript(ctx, str, JSContextGetGlobalObject(ctx),
3980 NULL, 0, &exception);
3981 JSStringRelease(str);
3983 DNPRINTF(XT_D_JS, "run_script: val %p\n", val);
3984 if (val == NULL) {
3985 es = js_ref_to_string(ctx, exception);
3986 if (es) {
3987 show_oops(t, "script exception: %s", es);
3988 g_free(es);
3990 goto done;
3991 } else {
3992 es = js_ref_to_string(ctx, val);
3993 #if 0
3994 /* return values */
3995 if (!strncmp(es, XT_JS_DONE, XT_JS_DONE_LEN))
3996 ; /* do nothing */
3997 if (!strncmp(es, XT_JS_INSERT, XT_JS_INSERT_LEN))
3998 ; /* do nothing */
3999 #endif
4000 if (es) {
4001 show_oops(t, "script complete return value: '%s'", es);
4002 g_free(es);
4003 } else
4004 show_oops(t, "script complete: without a return value");
4006 done:
4007 if (su)
4008 soup_uri_free(su);
4009 if (js)
4010 g_free(js);
4011 if (deffile)
4012 fclose(deffile);
4013 if (hostfile)
4014 fclose(hostfile);
4015 if (domain)
4016 g_free(domain);
4019 void
4020 webview_load_finished_cb(WebKitWebView *wv, WebKitWebFrame *wf, struct tab *t)
4022 /* autorun some js if enabled */
4023 js_autorun(t);
4025 run_script(t, JS_HINTING);
4026 if (autofocus_onload &&
4027 t->tab_id == gtk_notebook_get_current_page(notebook))
4028 run_script(t, "hints.focusInput();");
4029 else
4030 run_script(t, "hints.clearFocus();");
4033 void
4034 webview_progress_changed_cb(WebKitWebView *wv, int progress, struct tab *t)
4036 gtk_entry_set_progress_fraction(GTK_ENTRY(t->uri_entry),
4037 progress == 100 ? 0 : (double)progress / 100);
4038 if (show_url == 0) {
4039 gtk_entry_set_progress_fraction(GTK_ENTRY(t->sbe.statusbar),
4040 progress == 100 ? 0 : (double)progress / 100);
4043 update_statusbar_position(NULL, NULL);
4047 webview_npd_cb(WebKitWebView *wv, WebKitWebFrame *wf,
4048 WebKitNetworkRequest *request, WebKitWebNavigationAction *na,
4049 WebKitWebPolicyDecision *pd, struct tab *t)
4051 char *uri;
4052 WebKitWebNavigationReason reason;
4053 struct domain *d = NULL;
4055 if (t == NULL) {
4056 show_oops(NULL, "webview_npd_cb invalid parameters");
4057 return (FALSE);
4060 DNPRINTF(XT_D_NAV, "webview_npd_cb: ctrl_click %d %s\n",
4061 t->ctrl_click,
4062 webkit_network_request_get_uri(request));
4064 uri = (char *)webkit_network_request_get_uri(request);
4066 /* if this is an xtp url, we don't load anything else */
4067 if (parse_xtp_url(t, uri))
4068 return (TRUE);
4070 if ((t->hints_on && t->new_tab) || t->ctrl_click) {
4071 t->ctrl_click = 0;
4072 create_new_tab(uri, NULL, ctrl_click_focus, -1);
4073 webkit_web_policy_decision_ignore(pd);
4074 return (TRUE); /* we made the decission */
4078 * This is a little hairy but it comes down to this:
4079 * when we run in whitelist mode we have to assist the browser in
4080 * opening the URL that it would have opened in a new tab.
4082 reason = webkit_web_navigation_action_get_reason(na);
4083 if (reason == WEBKIT_WEB_NAVIGATION_REASON_LINK_CLICKED) {
4084 t->xtp_meaning = XT_XTP_TAB_MEANING_NORMAL;
4085 if (enable_scripts == 0 && enable_cookie_whitelist == 1)
4086 if (uri && (d = wl_find_uri(uri, &js_wl)) == NULL)
4087 load_uri(t, uri);
4088 webkit_web_policy_decision_use(pd);
4089 return (TRUE); /* we made the decision */
4092 return (FALSE);
4095 WebKitWebView *
4096 webview_cwv_cb(WebKitWebView *wv, WebKitWebFrame *wf, struct tab *t)
4098 struct tab *tt;
4099 struct domain *d = NULL;
4100 const gchar *uri;
4101 WebKitWebView *webview = NULL;
4103 DNPRINTF(XT_D_NAV, "webview_cwv_cb: %s\n",
4104 webkit_web_view_get_uri(wv));
4106 if (tabless) {
4107 /* open in current tab */
4108 webview = t->wv;
4109 } else if (enable_scripts == 0 && enable_cookie_whitelist == 1) {
4110 uri = webkit_web_view_get_uri(wv);
4111 if (uri && (d = wl_find_uri(uri, &js_wl)) == NULL)
4112 return (NULL);
4114 tt = create_new_tab(NULL, NULL, 1, -1);
4115 webview = tt->wv;
4116 } else if (enable_scripts == 1) {
4117 tt = create_new_tab(NULL, NULL, 1, -1);
4118 webview = tt->wv;
4121 return (webview);
4124 gboolean
4125 webview_closewv_cb(WebKitWebView *wv, struct tab *t)
4127 const gchar *uri;
4128 struct domain *d = NULL;
4130 DNPRINTF(XT_D_NAV, "webview_close_cb: %d\n", t->tab_id);
4132 if (enable_scripts == 0 && enable_cookie_whitelist == 1) {
4133 uri = webkit_web_view_get_uri(wv);
4134 if (uri && (d = wl_find_uri(uri, &js_wl)) == NULL)
4135 return (FALSE);
4137 delete_tab(t);
4138 } else if (enable_scripts == 1)
4139 delete_tab(t);
4141 return (TRUE);
4145 webview_event_cb(GtkWidget *w, GdkEventButton *e, struct tab *t)
4147 /* we can not eat the event without throwing gtk off so defer it */
4149 /* catch middle click */
4150 if (e->type == GDK_BUTTON_RELEASE && e->button == 2) {
4151 t->ctrl_click = 1;
4152 goto done;
4155 /* catch ctrl click */
4156 if (e->type == GDK_BUTTON_RELEASE &&
4157 CLEAN(e->state) == GDK_CONTROL_MASK)
4158 t->ctrl_click = 1;
4159 else
4160 t->ctrl_click = 0;
4161 done:
4162 return (XT_CB_PASSTHROUGH);
4166 run_mimehandler(struct tab *t, char *mime_type, WebKitNetworkRequest *request)
4168 struct mime_type *m;
4170 m = find_mime_type(mime_type);
4171 if (m == NULL)
4172 return (1);
4173 if (m->mt_download)
4174 return (1);
4176 switch (fork()) {
4177 case -1:
4178 show_oops(t, "can't fork mime handler");
4179 return (1);
4180 /* NOTREACHED */
4181 case 0:
4182 break;
4183 default:
4184 return (0);
4187 /* child */
4188 execlp(m->mt_action, m->mt_action,
4189 webkit_network_request_get_uri(request), (void *)NULL);
4191 _exit(0);
4193 /* NOTREACHED */
4194 return (0);
4197 char *
4198 get_mime_type(const char *file)
4200 const gchar *m;
4201 char *mime_type = NULL;
4202 GFileInfo *fi;
4203 GFile *gf;
4205 if (g_str_has_prefix(file, "file://"))
4206 file += strlen("file://");
4208 gf = g_file_new_for_path(file);
4209 fi = g_file_query_info(gf, G_FILE_ATTRIBUTE_STANDARD_CONTENT_TYPE, 0,
4210 NULL, NULL);
4211 if ((m = g_file_info_get_content_type(fi)) != NULL)
4212 mime_type = g_strdup(m);
4213 g_object_unref(fi);
4214 g_object_unref(gf);
4216 return (mime_type);
4220 run_download_mimehandler(char *mime_type, char *file)
4222 struct mime_type *m;
4224 m = find_mime_type(mime_type);
4225 if (m == NULL)
4226 return (1);
4228 switch (fork()) {
4229 case -1:
4230 show_oops(NULL, "can't fork download mime handler");
4231 return (1);
4232 /* NOTREACHED */
4233 case 0:
4234 break;
4235 default:
4236 return (0);
4239 /* child */
4240 if (g_str_has_prefix(file, "file://"))
4241 file += strlen("file://");
4242 execlp(m->mt_action, m->mt_action, file, (void *)NULL);
4244 _exit(0);
4246 /* NOTREACHED */
4247 return (0);
4250 void
4251 download_status_changed_cb(WebKitDownload *download, GParamSpec *spec,
4252 WebKitWebView *wv)
4254 WebKitDownloadStatus status;
4255 const char *file = NULL;
4256 char *mime = NULL;
4258 if (download == NULL)
4259 return;
4260 status = webkit_download_get_status(download);
4261 if (status != WEBKIT_DOWNLOAD_STATUS_FINISHED)
4262 return;
4264 file = webkit_download_get_destination_uri(download);
4265 if (file == NULL)
4266 return;
4267 mime = get_mime_type(file);
4268 if (mime == NULL)
4269 return;
4271 run_download_mimehandler((char *)mime, (char *)file);
4272 g_free(mime);
4276 webview_mimetype_cb(WebKitWebView *wv, WebKitWebFrame *frame,
4277 WebKitNetworkRequest *request, char *mime_type,
4278 WebKitWebPolicyDecision *decision, struct tab *t)
4280 if (t == NULL) {
4281 show_oops(NULL, "webview_mimetype_cb invalid parameters");
4282 return (FALSE);
4285 DNPRINTF(XT_D_DOWNLOAD, "webview_mimetype_cb: tab %d mime %s\n",
4286 t->tab_id, mime_type);
4288 if (run_mimehandler(t, mime_type, request) == 0) {
4289 webkit_web_policy_decision_ignore(decision);
4290 focus_webview(t);
4291 return (TRUE);
4294 if (webkit_web_view_can_show_mime_type(wv, mime_type) == FALSE) {
4295 webkit_web_policy_decision_download(decision);
4296 return (TRUE);
4299 return (FALSE);
4303 webview_download_cb(WebKitWebView *wv, WebKitDownload *wk_download,
4304 struct tab *t)
4306 struct stat sb;
4307 const gchar *suggested_name;
4308 gchar *filename = NULL;
4309 char *uri = NULL;
4310 struct download *download_entry;
4311 int i, ret = TRUE;
4313 if (wk_download == NULL || t == NULL) {
4314 show_oops(NULL, "%s invalid parameters", __func__);
4315 return (FALSE);
4318 suggested_name = webkit_download_get_suggested_filename(wk_download);
4319 if (suggested_name == NULL)
4320 return (FALSE); /* abort download */
4322 i = 0;
4323 do {
4324 if (filename) {
4325 g_free(filename);
4326 filename = NULL;
4328 if (i) {
4329 g_free(uri);
4330 uri = NULL;
4331 filename = g_strdup_printf("%d%s", i, suggested_name);
4333 uri = g_strdup_printf("file://%s/%s", download_dir, i ?
4334 filename : suggested_name);
4335 i++;
4336 } while (!stat(uri + strlen("file://"), &sb));
4338 DNPRINTF(XT_D_DOWNLOAD, "%s: tab %d filename %s "
4339 "local %s\n", __func__, t->tab_id, filename, uri);
4341 webkit_download_set_destination_uri(wk_download, uri);
4343 if (webkit_download_get_status(wk_download) ==
4344 WEBKIT_DOWNLOAD_STATUS_ERROR) {
4345 show_oops(t, "%s: download failed to start", __func__);
4346 ret = FALSE;
4347 gtk_label_set_text(GTK_LABEL(t->label), "Download Failed");
4348 } else {
4349 /* connect "download first" mime handler */
4350 g_signal_connect(G_OBJECT(wk_download), "notify::status",
4351 G_CALLBACK(download_status_changed_cb), NULL);
4353 download_entry = g_malloc(sizeof(struct download));
4354 download_entry->download = wk_download;
4355 download_entry->tab = t;
4356 download_entry->id = next_download_id++;
4357 RB_INSERT(download_list, &downloads, download_entry);
4358 /* get from history */
4359 g_object_ref(wk_download);
4360 gtk_label_set_text(GTK_LABEL(t->label), "Downloading");
4361 show_oops(t, "Download of '%s' started...",
4362 basename((char *)webkit_download_get_destination_uri(wk_download)));
4365 if (uri)
4366 g_free(uri);
4368 if (filename)
4369 g_free(filename);
4371 /* sync other download manager tabs */
4372 update_download_tabs(NULL);
4375 * NOTE: never redirect/render the current tab before this
4376 * function returns. This will cause the download to never start.
4378 return (ret); /* start download */
4381 void
4382 webview_hover_cb(WebKitWebView *wv, gchar *title, gchar *uri, struct tab *t)
4384 DNPRINTF(XT_D_KEY, "webview_hover_cb: %s %s\n", title, uri);
4386 if (t == NULL) {
4387 show_oops(NULL, "webview_hover_cb");
4388 return;
4391 if (uri)
4392 set_status(t, uri, XT_STATUS_LINK);
4393 else {
4394 if (t->status)
4395 set_status(t, t->status, XT_STATUS_NOTHING);
4400 mark(struct tab *t, struct karg *arg)
4402 char mark;
4403 int index;
4405 mark = arg->s[1];
4406 if ((index = marktoindex(mark)) == -1)
4407 return (-1);
4409 if (arg->i == XT_MARK_SET)
4410 t->mark[index] = gtk_adjustment_get_value(t->adjust_v);
4411 else if (arg->i == XT_MARK_GOTO) {
4412 if (t->mark[index] == XT_INVALID_MARK) {
4413 show_oops(t, "mark '%c' does not exist", mark);
4414 return (-1);
4416 /* XXX t->mark[index] can be bigger than the maximum if ajax or
4417 something changes the document size */
4418 gtk_adjustment_set_value(t->adjust_v, t->mark[index]);
4421 return (0);
4424 void
4425 marks_clear(struct tab *t)
4427 int i;
4429 for (i = 0; i < LENGTH(t->mark); i++)
4430 t->mark[i] = XT_INVALID_MARK;
4434 qmarks_load(void)
4436 char file[PATH_MAX];
4437 char *line = NULL, *p;
4438 int index, i;
4439 FILE *f;
4440 size_t linelen;
4442 snprintf(file, sizeof file, "%s/%s", work_dir, XT_QMARKS_FILE);
4443 if ((f = fopen(file, "r+")) == NULL) {
4444 show_oops(NULL, "Can't open quickmarks file: %s", strerror(errno));
4445 return (1);
4448 for (i = 1; ; i++) {
4449 if ((line = fparseln(f, &linelen, NULL, NULL, 0)) == NULL)
4450 break;
4451 if (strlen(line) == 0 || line[0] == '#') {
4452 free(line);
4453 line = NULL;
4454 continue;
4457 p = strtok(line, " \t");
4459 if (p == NULL || strlen(p) != 1 ||
4460 (index = marktoindex(*p)) == -1) {
4461 warnx("corrupt quickmarks file, line %d", i);
4462 break;
4465 p = strtok(NULL, " \t");
4466 if (qmarks[index] != NULL)
4467 g_free(qmarks[index]);
4468 qmarks[index] = g_strdup(p);
4471 fclose(f);
4473 return (0);
4477 qmarks_save(void)
4479 char file[PATH_MAX];
4480 int i;
4481 FILE *f;
4483 snprintf(file, sizeof file, "%s/%s", work_dir, XT_QMARKS_FILE);
4484 if ((f = fopen(file, "r+")) == NULL) {
4485 show_oops(NULL, "Can't open quickmarks file: %s", strerror(errno));
4486 return (1);
4489 for (i = 0; i < XT_NOMARKS; i++)
4490 if (qmarks[i] != NULL)
4491 fprintf(f, "%c %s\n", indextomark(i), qmarks[i]);
4493 fclose(f);
4495 return (0);
4499 qmark(struct tab *t, struct karg *arg)
4501 char mark;
4502 int index;
4504 mark = arg->s[strlen(arg->s)-1];
4505 index = marktoindex(mark);
4506 if (index == -1)
4507 return (-1);
4509 switch (arg->i) {
4510 case XT_QMARK_SET:
4511 if (qmarks[index] != NULL)
4512 g_free(qmarks[index]);
4514 qmarks_load(); /* sync if multiple instances */
4515 qmarks[index] = g_strdup(get_uri(t));
4516 qmarks_save();
4517 break;
4518 case XT_QMARK_OPEN:
4519 if (qmarks[index] != NULL)
4520 load_uri(t, qmarks[index]);
4521 else {
4522 show_oops(t, "quickmark \"%c\" does not exist",
4523 mark);
4524 return (-1);
4526 break;
4527 case XT_QMARK_TAB:
4528 if (qmarks[index] != NULL)
4529 create_new_tab(qmarks[index], NULL, 1, -1);
4530 else {
4531 show_oops(t, "quickmark \"%c\" does not exist",
4532 mark);
4533 return (-1);
4535 break;
4538 return (0);
4542 go_up(struct tab *t, struct karg *args)
4544 int levels;
4545 char *uri;
4546 char *tmp;
4548 levels = atoi(args->s);
4549 if (levels == 0)
4550 levels = 1;
4552 uri = g_strdup(webkit_web_view_get_uri(t->wv));
4553 if ((tmp = strstr(uri, XT_PROTO_DELIM)) == NULL)
4554 return (1);
4555 tmp += strlen(XT_PROTO_DELIM);
4557 /* if an uri starts with a slash, leave it alone (for file:///) */
4558 if (tmp[0] == '/')
4559 tmp++;
4561 while (levels--) {
4562 char *p;
4564 p = strrchr(tmp, '/');
4565 if (p != NULL)
4566 *p = '\0';
4567 else
4568 break;
4571 load_uri(t, uri);
4572 g_free(uri);
4574 return (0);
4578 gototab(struct tab *t, struct karg *args)
4580 int tab;
4581 struct karg arg = {0, NULL, -1};
4583 tab = atoi(args->s);
4585 arg.i = XT_TAB_NEXT;
4586 arg.precount = tab;
4588 movetab(t, &arg);
4590 return (0);
4594 zoom_amount(struct tab *t, struct karg *arg)
4596 struct karg narg = {0, NULL, -1};
4598 narg.i = atoi(arg->s);
4599 resizetab(t, &narg);
4601 return (0);
4605 flip_colon(struct tab *t, struct karg *arg)
4607 struct karg narg = {0, NULL, -1};
4608 char *p;
4610 if (t == NULL || arg == NULL)
4611 return (1);
4613 p = strstr(arg->s, ":");
4614 if (p == NULL)
4615 return (1);
4616 *p = '\0';
4618 narg.i = ':';
4619 narg.s = arg->s;
4620 command(t, &narg);
4622 return (0);
4625 /* buffer commands receive the regex that triggered them in arg.s */
4626 char bcmd[XT_BUFCMD_SZ];
4627 struct buffercmd {
4628 char *regex;
4629 int precount;
4630 #define XT_PRE_NO (0)
4631 #define XT_PRE_YES (1)
4632 #define XT_PRE_MAYBE (2)
4633 char *cmd;
4634 int (*func)(struct tab *, struct karg *);
4635 int arg;
4636 regex_t cregex;
4637 } buffercmds[] = {
4638 { "^[0-9]*gu$", XT_PRE_MAYBE, "gu", go_up, 0 },
4639 { "^gg$", XT_PRE_NO, "gg", move, XT_MOVE_TOP },
4640 { "^gG$", XT_PRE_NO, "gG", move, XT_MOVE_BOTTOM },
4641 { "^[0-9]+%$", XT_PRE_YES, "%", move, XT_MOVE_PERCENT },
4642 { "^zz$", XT_PRE_NO, "zz", move, XT_MOVE_CENTER },
4643 { "^gh$", XT_PRE_NO, "gh", go_home, 0 },
4644 { "^m[a-zA-Z0-9]$", XT_PRE_NO, "m", mark, XT_MARK_SET },
4645 { "^['][a-zA-Z0-9]$", XT_PRE_NO, "'", mark, XT_MARK_GOTO },
4646 { "^[0-9]+t$", XT_PRE_YES, "t", gototab, 0 },
4647 { "^M[a-zA-Z0-9]$", XT_PRE_NO, "M", qmark, XT_QMARK_SET },
4648 { "^go[a-zA-Z0-9]$", XT_PRE_NO, "go", qmark, XT_QMARK_OPEN },
4649 { "^gn[a-zA-Z0-9]$", XT_PRE_NO, "gn", qmark, XT_QMARK_TAB },
4650 { "^ZR$", XT_PRE_NO, "ZR", restart, 0 },
4651 { "^ZZ$", XT_PRE_NO, "ZZ", quit, 0 },
4652 { "^zi$", XT_PRE_NO, "zi", resizetab, XT_ZOOM_IN },
4653 { "^zo$", XT_PRE_NO, "zo", resizetab, XT_ZOOM_OUT },
4654 { "^z0$", XT_PRE_NO, "z0", resizetab, XT_ZOOM_NORMAL },
4655 { "^[0-9]+Z$", XT_PRE_YES, "Z", zoom_amount, 0 },
4656 { "^[0-9]+:$", XT_PRE_YES, ":", flip_colon, 0 },
4659 void
4660 buffercmd_init(void)
4662 int i;
4664 for (i = 0; i < LENGTH(buffercmds); i++)
4665 if (regcomp(&buffercmds[i].cregex, buffercmds[i].regex,
4666 REG_EXTENDED | REG_NOSUB))
4667 startpage_add("invalid buffercmd regex %s",
4668 buffercmds[i].regex);
4671 void
4672 buffercmd_abort(struct tab *t)
4674 int i;
4676 DNPRINTF(XT_D_BUFFERCMD, "buffercmd_abort: clearing buffer\n");
4677 for (i = 0; i < LENGTH(bcmd); i++)
4678 bcmd[i] = '\0';
4680 cmd_prefix = 0; /* clear prefix for non-buffer commands */
4681 gtk_entry_set_text(GTK_ENTRY(t->sbe.buffercmd), bcmd);
4684 void
4685 buffercmd_execute(struct tab *t, struct buffercmd *cmd)
4687 struct karg arg = {0, NULL, -1};
4689 arg.i = cmd->arg;
4690 arg.s = g_strdup(bcmd);
4692 DNPRINTF(XT_D_BUFFERCMD, "buffercmd_execute: buffer \"%s\" "
4693 "matches regex \"%s\", executing\n", bcmd, cmd->regex);
4694 cmd->func(t, &arg);
4696 if (arg.s)
4697 g_free(arg.s);
4699 buffercmd_abort(t);
4702 gboolean
4703 buffercmd_addkey(struct tab *t, guint keyval)
4705 int i, c, match ;
4706 char s[XT_BUFCMD_SZ];
4708 if (keyval == GDK_Escape) {
4709 buffercmd_abort(t);
4710 return (XT_CB_HANDLED);
4713 /* key with modifier or non-ascii character */
4714 if (!isascii(keyval))
4715 return (XT_CB_PASSTHROUGH);
4717 DNPRINTF(XT_D_BUFFERCMD, "buffercmd_addkey: adding key \"%c\" "
4718 "to buffer \"%s\"\n", keyval, bcmd);
4720 for (i = 0; i < LENGTH(bcmd); i++)
4721 if (bcmd[i] == '\0') {
4722 bcmd[i] = keyval;
4723 break;
4726 /* buffer full, ignore input */
4727 if (i >= LENGTH(bcmd) -1) {
4728 DNPRINTF(XT_D_BUFFERCMD, "buffercmd_addkey: buffer full\n");
4729 buffercmd_abort(t);
4730 return (XT_CB_HANDLED);
4733 gtk_entry_set_text(GTK_ENTRY(t->sbe.buffercmd), bcmd);
4735 /* find exact match */
4736 for (i = 0; i < LENGTH(buffercmds); i++)
4737 if (regexec(&buffercmds[i].cregex, bcmd,
4738 (size_t) 0, NULL, 0) == 0) {
4739 buffercmd_execute(t, &buffercmds[i]);
4740 goto done;
4743 /* find non exact matches to see if we need to abort ot not */
4744 for (i = 0, match = 0; i < LENGTH(buffercmds); i++) {
4745 DNPRINTF(XT_D_BUFFERCMD, "trying: %s\n", bcmd);
4746 c = -1;
4747 s[0] = '\0';
4748 if (buffercmds[i].precount == XT_PRE_MAYBE) {
4749 if (isdigit(bcmd[0])) {
4750 if (sscanf(bcmd, "%d%s", &c, s) == 0)
4751 continue;
4752 } else {
4753 c = 0;
4754 if (sscanf(bcmd, "%s", s) == 0)
4755 continue;
4757 } else if (buffercmds[i].precount == XT_PRE_YES) {
4758 if (sscanf(bcmd, "%d%s", &c, s) == 0)
4759 continue;
4760 } else {
4761 if (sscanf(bcmd, "%s", s) == 0)
4762 continue;
4764 if (c == -1 && buffercmds[i].precount)
4765 continue;
4766 if (!strncmp(s, buffercmds[i].cmd, strlen(s)))
4767 match++;
4769 DNPRINTF(XT_D_BUFFERCMD, "got[%d] %d <%s>: %d %s\n",
4770 i, match, buffercmds[i].cmd, c, s);
4772 if (match == 0) {
4773 DNPRINTF(XT_D_BUFFERCMD, "aborting: %s\n", bcmd);
4774 buffercmd_abort(t);
4777 done:
4778 return (XT_CB_HANDLED);
4781 gboolean
4782 handle_keypress(struct tab *t, GdkEventKey *e, int entry)
4784 struct key_binding *k;
4786 /* handle keybindings if buffercmd is empty.
4787 if not empty, allow commands like C-n */
4788 if (bcmd[0] == '\0' || ((e->state & (CTRL | MOD1)) != 0))
4789 TAILQ_FOREACH(k, &kbl, entry)
4790 if (e->keyval == k->key
4791 && (entry ? k->use_in_entry : 1)) {
4792 if (k->mask == 0) {
4793 if ((e->state & (CTRL | MOD1)) == 0)
4794 return (cmd_execute(t, k->cmd));
4795 } else if ((e->state & k->mask) == k->mask) {
4796 return (cmd_execute(t, k->cmd));
4800 if (!entry && ((e->state & (CTRL | MOD1)) == 0))
4801 return buffercmd_addkey(t, e->keyval);
4803 return (XT_CB_PASSTHROUGH);
4807 wv_keypress_after_cb(GtkWidget *w, GdkEventKey *e, struct tab *t)
4809 char s[2];
4811 /* don't use w directly; use t->whatever instead */
4813 if (t == NULL) {
4814 show_oops(NULL, "wv_keypress_after_cb");
4815 return (XT_CB_PASSTHROUGH);
4818 DNPRINTF(XT_D_KEY, "wv_keypress_after_cb: keyval 0x%x mask 0x%x tab %d\n",
4819 e->keyval, e->state, t->tab_id);
4821 if (t->hints_on) {
4822 /* XXX make sure cmd entry is enabled */
4823 return (XT_CB_HANDLED);
4824 } else {
4825 /* prefix input*/
4826 snprintf(s, sizeof s, "%c", e->keyval);
4827 if (CLEAN(e->state) == 0 && isdigit(s[0]))
4828 cmd_prefix = 10 * cmd_prefix + atoi(s);
4831 return (handle_keypress(t, e, 0));
4835 wv_keypress_cb(GtkEntry *w, GdkEventKey *e, struct tab *t)
4837 hide_oops(t);
4839 /* Hide buffers, if they are visible, with escape. */
4840 if (gtk_widget_get_visible(GTK_WIDGET(t->buffers)) &&
4841 CLEAN(e->state) == 0 && e->keyval == GDK_Escape) {
4842 gtk_widget_grab_focus(GTK_WIDGET(t->wv));
4843 hide_buffers(t);
4844 return (XT_CB_HANDLED);
4847 return (XT_CB_PASSTHROUGH);
4850 gboolean
4851 hint_continue(struct tab *t)
4853 const gchar *c = gtk_entry_get_text(GTK_ENTRY(t->cmd));
4854 char *s;
4855 const gchar *errstr = NULL;
4856 gboolean rv = TRUE;
4857 long long i;
4859 if (!(c[0] == '.' || c[0] == ','))
4860 goto done;
4861 if (strlen(c) == 1) {
4862 /* XXX should not happen */
4863 rv = TRUE;
4864 goto done;
4867 if (isdigit(c[1])) {
4868 /* numeric input */
4869 i = strtonum(&c[1], 1, 4096, &errstr);
4870 if (errstr) {
4871 show_oops(t, "invalid numerical hint %s", &c[1]);
4872 goto done;
4874 s = g_strdup_printf("hints.updateHints(%lld);", i);
4875 run_script(t, s);
4876 g_free(s);
4877 } else {
4878 /* alphanumeric input */
4879 s = g_strdup_printf("hints.createHints('%s', '%c');",
4880 &c[1], c[0] == '.' ? 'f' : 'F');
4881 run_script(t, s);
4882 g_free(s);
4885 rv = FALSE;
4886 done:
4887 return (rv);
4890 gboolean
4891 search_continue(struct tab *t)
4893 const gchar *c = gtk_entry_get_text(GTK_ENTRY(t->cmd));
4894 gboolean rv = FALSE;
4896 if (c[0] == ':' || c[0] == '.' || c[0] == ',')
4897 goto done;
4898 if (strlen(c) == 1) {
4899 webkit_web_view_unmark_text_matches(t->wv);
4900 goto done;
4903 if (c[0] == '/')
4904 t->search_forward = TRUE;
4905 else if (c[0] == '?')
4906 t->search_forward = FALSE;
4907 else
4908 goto done;
4910 rv = TRUE;
4911 done:
4912 return (rv);
4915 gboolean
4916 search_cb(struct tab *t)
4918 const gchar *c = gtk_entry_get_text(GTK_ENTRY(t->cmd));
4919 GdkColor color;
4921 if (search_continue(t) == FALSE)
4922 goto done;
4924 /* search */
4925 if (webkit_web_view_search_text(t->wv, &c[1], FALSE, t->search_forward,
4926 TRUE) == FALSE) {
4927 /* not found, mark red */
4928 gdk_color_parse(XT_COLOR_RED, &color);
4929 gtk_widget_modify_base(t->cmd, GTK_STATE_NORMAL, &color);
4930 /* unmark and remove selection */
4931 webkit_web_view_unmark_text_matches(t->wv);
4932 /* my kingdom for a way to unselect text in webview */
4933 } else {
4934 /* found, highlight all */
4935 webkit_web_view_unmark_text_matches(t->wv);
4936 webkit_web_view_mark_text_matches(t->wv, &c[1], FALSE, 0);
4937 webkit_web_view_set_highlight_text_matches(t->wv, TRUE);
4938 gdk_color_parse(XT_COLOR_WHITE, &color);
4939 gtk_widget_modify_base(t->cmd, GTK_STATE_NORMAL, &color);
4941 done:
4942 t->search_id = 0;
4943 return (FALSE);
4947 cmd_keyrelease_cb(GtkEntry *w, GdkEventKey *e, struct tab *t)
4949 const gchar *c = gtk_entry_get_text(w);
4951 if (t == NULL) {
4952 show_oops(NULL, "cmd_keyrelease_cb invalid parameters");
4953 return (XT_CB_PASSTHROUGH);
4956 DNPRINTF(XT_D_CMD, "cmd_keyrelease_cb: keyval 0x%x mask 0x%x tab %d\n",
4957 e->keyval, e->state, t->tab_id);
4959 /* hinting */
4960 if (!(e->keyval == GDK_Tab || e->keyval == GDK_ISO_Left_Tab)) {
4961 if (hint_continue(t) == FALSE)
4962 goto done;
4965 /* search */
4966 if (search_continue(t) == FALSE)
4967 goto done;
4969 /* if search length is > 4 then no longer play timeout games */
4970 if (strlen(c) > 4) {
4971 if (t->search_id) {
4972 g_source_remove(t->search_id);
4973 t->search_id = 0;
4975 search_cb(t);
4976 goto done;
4979 /* reestablish a new timer if the user types fast */
4980 if (t->search_id)
4981 g_source_remove(t->search_id);
4982 t->search_id = g_timeout_add(250, (GSourceFunc)search_cb, (gpointer)t);
4984 done:
4985 return (XT_CB_PASSTHROUGH);
4988 gboolean
4989 match_uri(const gchar *uri, const gchar *key) {
4990 gchar *voffset;
4991 size_t len;
4992 gboolean match = FALSE;
4994 len = strlen(key);
4996 if (!strncmp(key, uri, len))
4997 match = TRUE;
4998 else {
4999 voffset = strstr(uri, "/") + 2;
5000 if (!strncmp(key, voffset, len))
5001 match = TRUE;
5002 else if (g_str_has_prefix(voffset, "www.")) {
5003 voffset = voffset + strlen("www.");
5004 if (!strncmp(key, voffset, len))
5005 match = TRUE;
5009 return (match);
5012 gboolean
5013 match_session(const gchar *name, const gchar *key) {
5014 char *sub;
5016 sub = strcasestr(name, key);
5018 return sub == name;
5021 void
5022 cmd_getlist(int id, char *key)
5024 int i, dep, c = 0;
5025 struct history *h;
5026 struct session *s;
5028 if (id >= 0) {
5029 if (cmds[id].type & XT_URLARG) {
5030 RB_FOREACH_REVERSE(h, history_list, &hl)
5031 if (match_uri(h->uri, key)) {
5032 cmd_status.list[c] = (char *)h->uri;
5033 if (++c > 255)
5034 break;
5036 cmd_status.len = c;
5037 return;
5038 } else if (cmds[id].type & XT_SESSARG) {
5039 TAILQ_FOREACH(s, &sessions, entry)
5040 if (match_session(s->name, key)) {
5041 cmd_status.list[c] = (char *)s->name;
5042 if (++c > 255)
5043 break;
5045 cmd_status.len = c;
5046 return;
5047 } else if (cmds[id].type & XT_SETARG) {
5048 for (i = 0; i < get_settings_size(); i++)
5049 if(!strncmp(key, get_setting_name(i),
5050 strlen(key)))
5051 cmd_status.list[c++] = get_setting_name(i);
5052 cmd_status.len = c;
5053 return;
5057 dep = (id == -1) ? 0 : cmds[id].level + 1;
5059 for (i = id + 1; i < LENGTH(cmds); i++) {
5060 if (cmds[i].level < dep)
5061 break;
5062 if (cmds[i].level == dep && !strncmp(key, cmds[i].cmd,
5063 strlen(key)) && !isdigit(cmds[i].cmd[0]))
5064 cmd_status.list[c++] = cmds[i].cmd;
5068 cmd_status.len = c;
5071 char *
5072 cmd_getnext(int dir)
5074 cmd_status.index += dir;
5076 if (cmd_status.index < 0)
5077 cmd_status.index = cmd_status.len - 1;
5078 else if (cmd_status.index >= cmd_status.len)
5079 cmd_status.index = 0;
5081 return cmd_status.list[cmd_status.index];
5085 cmd_tokenize(char *s, char *tokens[])
5087 int i = 0;
5088 char *tok, *last = NULL;
5089 size_t len = strlen(s);
5090 bool blank;
5092 blank = len == 0 || (len > 0 && s[len - 1] == ' ');
5093 for (tok = strtok_r(s, " ", &last); tok && i < 3;
5094 tok = strtok_r(NULL, " ", &last), i++)
5095 tokens[i] = tok;
5097 if (blank && i < 3)
5098 tokens[i++] = "";
5100 return (i);
5103 void
5104 cmd_complete(struct tab *t, char *str, int dir)
5106 GtkEntry *w = GTK_ENTRY(t->cmd);
5107 int i, j, levels, c = 0, dep = 0, parent = -1;
5108 int matchcount = 0;
5109 char *tok, *match, *s = g_strdup(str);
5110 char *tokens[3];
5111 char res[XT_MAX_URL_LENGTH + 32] = ":";
5112 char *sc = s;
5114 DNPRINTF(XT_D_CMD, "%s: complete %s\n", __func__, str);
5116 /* copy prefix*/
5117 for (i = 0; isdigit(s[i]); i++)
5118 res[i + 1] = s[i];
5120 for (; isspace(s[i]); i++)
5121 res[i + 1] = s[i];
5123 s += i;
5125 levels = cmd_tokenize(s, tokens);
5127 for (i = 0; i < levels - 1; i++) {
5128 tok = tokens[i];
5129 matchcount = 0;
5130 for (j = c; j < LENGTH(cmds); j++) {
5131 if (cmds[j].level < dep)
5132 break;
5133 if (cmds[j].level == dep && !strncmp(tok, cmds[j].cmd,
5134 strlen(tok))) {
5135 matchcount++;
5136 c = j + 1;
5137 if (strlen(tok) == strlen(cmds[j].cmd)) {
5138 matchcount = 1;
5139 break;
5144 if (matchcount == 1) {
5145 strlcat(res, tok, sizeof res);
5146 strlcat(res, " ", sizeof res);
5147 dep++;
5148 } else {
5149 g_free(sc);
5150 return;
5153 parent = c - 1;
5156 if (cmd_status.index == -1)
5157 cmd_getlist(parent, tokens[i]);
5159 if (cmd_status.len > 0) {
5160 match = cmd_getnext(dir);
5161 strlcat(res, match, sizeof res);
5162 gtk_entry_set_text(w, res);
5163 gtk_editable_set_position(GTK_EDITABLE(w), -1);
5166 g_free(sc);
5169 gboolean
5170 cmd_execute(struct tab *t, char *str)
5172 struct cmd *cmd = NULL;
5173 char *tok, *last = NULL, *s = g_strdup(str), *sc;
5174 char prefixstr[4];
5175 int j, len, c = 0, dep = 0, matchcount = 0;
5176 int prefix = -1, rv = XT_CB_PASSTHROUGH;
5177 struct karg arg = {0, NULL, -1};
5179 sc = s;
5181 /* copy prefix*/
5182 for (j = 0; j<3 && isdigit(s[j]); j++)
5183 prefixstr[j]=s[j];
5185 prefixstr[j]='\0';
5187 s += j;
5188 while (isspace(s[0]))
5189 s++;
5191 if (strlen(s) > 0 && strlen(prefixstr) > 0)
5192 prefix = atoi(prefixstr);
5193 else
5194 s = sc;
5196 for (tok = strtok_r(s, " ", &last); tok;
5197 tok = strtok_r(NULL, " ", &last)) {
5198 matchcount = 0;
5199 for (j = c; j < LENGTH(cmds); j++) {
5200 if (cmds[j].level < dep)
5201 break;
5202 len = (tok[strlen(tok) - 1] == '!') ? strlen(tok) - 1 :
5203 strlen(tok);
5204 if (cmds[j].level == dep &&
5205 !strncmp(tok, cmds[j].cmd, len)) {
5206 matchcount++;
5207 c = j + 1;
5208 cmd = &cmds[j];
5209 if (len == strlen(cmds[j].cmd)) {
5210 matchcount = 1;
5211 break;
5215 if (matchcount == 1) {
5216 if (cmd->type > 0)
5217 goto execute_cmd;
5218 dep++;
5219 } else {
5220 show_oops(t, "Invalid command: %s", str);
5221 goto done;
5224 execute_cmd:
5225 if (cmd == NULL) {
5226 show_oops(t, "Empty command");
5227 goto done;
5229 arg.i = cmd->arg;
5231 if (prefix != -1)
5232 arg.precount = prefix;
5233 else if (cmd_prefix > 0)
5234 arg.precount = cmd_prefix;
5236 if (j > 0 && !(cmd->type & XT_PREFIX) && arg.precount > -1) {
5237 show_oops(t, "No prefix allowed: %s", str);
5238 goto done;
5240 if (cmd->type > 1)
5241 arg.s = last ? g_strdup(last) : g_strdup("");
5242 if (cmd->type & XT_INTARG && last && strlen(last) > 0) {
5243 if (arg.s == NULL) {
5244 show_oops(t, "Invalid command");
5245 goto done;
5247 arg.precount = atoi(arg.s);
5248 if (arg.precount <= 0) {
5249 if (arg.s[0] == '0')
5250 show_oops(t, "Zero count");
5251 else
5252 show_oops(t, "Trailing characters");
5253 goto done;
5257 DNPRINTF(XT_D_CMD, "%s: prefix %d arg %s\n",
5258 __func__, arg.precount, arg.s);
5260 cmd->func(t, &arg);
5262 rv = XT_CB_HANDLED;
5263 done:
5264 if (j > 0)
5265 cmd_prefix = 0;
5266 g_free(sc);
5267 if (arg.s)
5268 g_free(arg.s);
5270 return (rv);
5274 entry_key_cb(GtkEntry *w, GdkEventKey *e, struct tab *t)
5276 if (t == NULL) {
5277 show_oops(NULL, "entry_key_cb invalid parameters");
5278 return (XT_CB_PASSTHROUGH);
5281 DNPRINTF(XT_D_CMD, "entry_key_cb: keyval 0x%x mask 0x%x tab %d\n",
5282 e->keyval, e->state, t->tab_id);
5284 hide_oops(t);
5286 if (e->keyval == GDK_Escape) {
5287 /* don't use focus_webview(t) because we want to type :cmds */
5288 gtk_widget_grab_focus(GTK_WIDGET(t->wv));
5291 return (handle_keypress(t, e, 1));
5294 struct command_entry *
5295 history_prev(struct command_list *l, struct command_entry *at)
5297 if (at == NULL)
5298 at = TAILQ_LAST(l, command_list);
5299 else {
5300 at = TAILQ_PREV(at, command_list, entry);
5301 if (at == NULL)
5302 at = TAILQ_LAST(l, command_list);
5305 return (at);
5308 struct command_entry *
5309 history_next(struct command_list *l, struct command_entry *at)
5311 if (at == NULL)
5312 at = TAILQ_FIRST(l);
5313 else {
5314 at = TAILQ_NEXT(at, entry);
5315 if (at == NULL)
5316 at = TAILQ_FIRST(l);
5319 return (at);
5323 cmd_keypress_cb(GtkEntry *w, GdkEventKey *e, struct tab *t)
5325 int rv = XT_CB_HANDLED;
5326 const gchar *c = gtk_entry_get_text(w);
5327 char *s;
5329 if (t == NULL) {
5330 show_oops(NULL, "cmd_keypress_cb parameters");
5331 return (XT_CB_PASSTHROUGH);
5334 DNPRINTF(XT_D_CMD, "cmd_keypress_cb: keyval 0x%x mask 0x%x tab %d\n",
5335 e->keyval, e->state, t->tab_id);
5337 /* sanity */
5338 if (c == NULL)
5339 e->keyval = GDK_Escape;
5340 else if (!(c[0] == ':' || c[0] == '/' || c[0] == '?' ||
5341 c[0] == '.' || c[0] == ','))
5342 e->keyval = GDK_Escape;
5344 if (e->keyval != GDK_Tab && e->keyval != GDK_Shift_L &&
5345 e->keyval != GDK_ISO_Left_Tab)
5346 cmd_status.index = -1;
5348 switch (e->keyval) {
5349 case GDK_Tab:
5350 if (c[0] == ':')
5351 cmd_complete(t, (char *)&c[1], 1);
5352 else if (c[0] == '.' || c[0] == ',')
5353 run_script(t, "hints.focusNextHint();");
5354 goto done;
5355 case GDK_ISO_Left_Tab:
5356 if (c[0] == ':')
5357 cmd_complete(t, (char *)&c[1], -1);
5358 else if (c[0] == '.' || c[0] == ',')
5359 run_script(t, "hints.focusPreviousHint();");
5360 goto done;
5361 case GDK_Down:
5362 if (c[0] == '?') {
5363 if ((search_at = history_next(&shl, search_at))) {
5364 search_at->line[0] = c[0];
5365 gtk_entry_set_text(w, search_at->line);
5366 gtk_editable_set_position(GTK_EDITABLE(w), -1);
5368 } else if (c[0] == '/') {
5369 if ((search_at = history_prev(&chl, search_at))) {
5370 search_at->line[0] = c[0];
5371 gtk_entry_set_text(w, search_at->line);
5372 gtk_editable_set_position(GTK_EDITABLE(w), -1);
5374 } if (c[0] == ':') {
5375 if ((history_at = history_prev(&chl, history_at))) {
5376 history_at->line[0] = c[0];
5377 gtk_entry_set_text(w, history_at->line);
5378 gtk_editable_set_position(GTK_EDITABLE(w), -1);
5381 goto done;
5382 case GDK_Up:
5383 if (c[0] == '/') {
5384 if ((search_at = history_next(&shl, search_at))) {
5385 search_at->line[0] = c[0];
5386 gtk_entry_set_text(w, search_at->line);
5387 gtk_editable_set_position(GTK_EDITABLE(w), -1);
5389 } else if (c[0] == '?') {
5390 if ((search_at = history_prev(&chl, search_at))) {
5391 search_at->line[0] = c[0];
5392 gtk_entry_set_text(w, search_at->line);
5393 gtk_editable_set_position(GTK_EDITABLE(w), -1);
5395 } if (c[0] == ':') {
5396 if ((history_at = history_next(&chl, history_at))) {
5397 history_at->line[0] = c[0];
5398 gtk_entry_set_text(w, history_at->line);
5399 gtk_editable_set_position(GTK_EDITABLE(w), -1);
5402 goto done;
5403 case GDK_BackSpace:
5404 if (!(!strcmp(c, ":") || !strcmp(c, "/") || !strcmp(c, "?") ||
5405 !strcmp(c, ".") || !strcmp(c, ","))) {
5406 /* see if we are doing hinting and reset it */
5407 if (c[0] == '.' || c[0] == ',') {
5408 /* recreate hints */
5409 s = g_strdup_printf("hints.createHints('', "
5410 "'%c');", c[0] == '.' ? 'f' : 'F');
5411 run_script(t, s);
5412 g_free(s);
5414 break;
5417 /* FALLTHROUGH */
5418 case GDK_Escape:
5419 hide_cmd(t);
5420 focus_webview(t);
5422 /* cancel search */
5423 if (c != NULL && (c[0] == '/' || c[0] == '?'))
5424 webkit_web_view_unmark_text_matches(t->wv);
5426 /* no need to cancel hints */
5427 goto done;
5430 rv = XT_CB_PASSTHROUGH;
5431 done:
5432 return (rv);
5435 void
5436 wv_popup_cb(GtkEntry *entry, GtkMenu *menu, struct tab *t)
5438 DNPRINTF(XT_D_CMD, "wv_popup_cb: tab %d\n", t->tab_id);
5441 void
5442 cmd_popup_cb(GtkEntry *entry, GtkMenu *menu, struct tab *t)
5444 /* popup menu enabled */
5445 t->popup = 1;
5449 cmd_focusout_cb(GtkWidget *w, GdkEventFocus *e, struct tab *t)
5451 if (t == NULL) {
5452 show_oops(NULL, "cmd_focusout_cb invalid parameters");
5453 return (XT_CB_PASSTHROUGH);
5456 DNPRINTF(XT_D_CMD, "cmd_focusout_cb: tab %d popup %d\n",
5457 t->tab_id, t->popup);
5459 /* if popup is enabled don't lose focus */
5460 if (t->popup) {
5461 t->popup = 0;
5462 return (XT_CB_PASSTHROUGH);
5465 hide_cmd(t);
5466 hide_oops(t);
5467 disable_hints(t);
5469 if (show_url == 0 || t->focus_wv)
5470 focus_webview(t);
5471 else
5472 gtk_widget_grab_focus(GTK_WIDGET(t->uri_entry));
5474 return (XT_CB_PASSTHROUGH);
5477 void
5478 cmd_activate_cb(GtkEntry *entry, struct tab *t)
5480 char *s;
5481 const gchar *c = gtk_entry_get_text(entry);
5483 if (t == NULL) {
5484 show_oops(NULL, "cmd_activate_cb invalid parameters");
5485 return;
5488 DNPRINTF(XT_D_CMD, "cmd_activate_cb: tab %d %s\n", t->tab_id, c);
5490 /* sanity */
5491 if (c == NULL)
5492 goto done;
5493 else if (!(c[0] == ':' || c[0] == '/' || c[0] == '?' ||
5494 c[0] == '.' || c[0] == ','))
5495 goto done;
5496 if (strlen(c) < 1)
5497 goto done;
5498 s = (char *)&c[1];
5500 if (c[0] == '/' || c[0] == '?') {
5501 /* see if there is a timer pending */
5502 if (t->search_id) {
5503 g_source_remove(t->search_id);
5504 t->search_id = 0;
5505 search_cb(t);
5508 if (t->search_text) {
5509 g_free(t->search_text);
5510 t->search_text = NULL;
5513 t->search_text = g_strdup(s);
5514 if (global_search)
5515 g_free(global_search);
5516 global_search = g_strdup(s);
5517 t->search_forward = c[0] == '/';
5519 history_add(&shl, search_file, s, &search_history_count);
5520 } else if (c[0] == '.' || c[0] == ',') {
5521 run_script(t, "hints.fire();");
5522 /* XXX history for link following? */
5523 } else if (c[0] == ':') {
5524 history_add(&chl, command_file, s, &cmd_history_count);
5525 /* can't call hide_cmd after cmd_execute */
5526 hide_cmd(t);
5527 cmd_execute(t, s);
5528 return;
5531 done:
5532 hide_cmd(t);
5535 void
5536 backward_cb(GtkWidget *w, struct tab *t)
5538 struct karg a;
5540 if (t == NULL) {
5541 show_oops(NULL, "backward_cb invalid parameters");
5542 return;
5545 DNPRINTF(XT_D_NAV, "backward_cb: tab %d\n", t->tab_id);
5547 a.i = XT_NAV_BACK;
5548 navaction(t, &a);
5551 void
5552 forward_cb(GtkWidget *w, struct tab *t)
5554 struct karg a;
5556 if (t == NULL) {
5557 show_oops(NULL, "forward_cb invalid parameters");
5558 return;
5561 DNPRINTF(XT_D_NAV, "forward_cb: tab %d\n", t->tab_id);
5563 a.i = XT_NAV_FORWARD;
5564 navaction(t, &a);
5567 void
5568 home_cb(GtkWidget *w, struct tab *t)
5570 if (t == NULL) {
5571 show_oops(NULL, "home_cb invalid parameters");
5572 return;
5575 DNPRINTF(XT_D_NAV, "home_cb: tab %d\n", t->tab_id);
5577 load_uri(t, home);
5580 void
5581 stop_cb(GtkWidget *w, struct tab *t)
5583 WebKitWebFrame *frame;
5585 if (t == NULL) {
5586 show_oops(NULL, "stop_cb invalid parameters");
5587 return;
5590 DNPRINTF(XT_D_NAV, "stop_cb: tab %d\n", t->tab_id);
5592 frame = webkit_web_view_get_main_frame(t->wv);
5593 if (frame == NULL) {
5594 show_oops(t, "stop_cb: no frame");
5595 return;
5598 webkit_web_frame_stop_loading(frame);
5599 abort_favicon_download(t);
5602 void
5603 setup_webkit(struct tab *t)
5605 if (is_g_object_setting(G_OBJECT(t->settings), "enable-dns-prefetching"))
5606 g_object_set(G_OBJECT(t->settings), "enable-dns-prefetching",
5607 FALSE, (char *)NULL);
5608 else
5609 warnx("webkit does not have \"enable-dns-prefetching\" property");
5610 g_object_set(G_OBJECT(t->settings),
5611 "user-agent", t->user_agent, (char *)NULL);
5612 g_object_set(G_OBJECT(t->settings),
5613 "enable-scripts", enable_scripts, (char *)NULL);
5614 g_object_set(G_OBJECT(t->settings),
5615 "enable-plugins", enable_plugins, (char *)NULL);
5616 g_object_set(G_OBJECT(t->settings),
5617 "javascript-can-open-windows-automatically", enable_scripts,
5618 (char *)NULL);
5619 g_object_set(G_OBJECT(t->settings),
5620 "enable-html5-database", FALSE, (char *)NULL);
5621 g_object_set(G_OBJECT(t->settings),
5622 "enable-html5-local-storage", enable_localstorage, (char *)NULL);
5623 g_object_set(G_OBJECT(t->settings),
5624 "enable_spell_checking", enable_spell_checking, (char *)NULL);
5625 g_object_set(G_OBJECT(t->settings),
5626 "spell_checking_languages", spell_check_languages, (char *)NULL);
5627 g_object_set(G_OBJECT(t->settings),
5628 "enable-developer-extras", TRUE, (char *)NULL);
5629 g_object_set(G_OBJECT(t->wv),
5630 "full-content-zoom", TRUE, (char *)NULL);
5632 webkit_web_view_set_settings(t->wv, t->settings);
5635 gboolean
5636 update_statusbar_position(GtkAdjustment* adjustment, gpointer data)
5638 struct tab *ti, *t = NULL;
5639 gdouble view_size, value, max;
5640 gchar *position;
5642 TAILQ_FOREACH(ti, &tabs, entry)
5643 if (ti->tab_id == gtk_notebook_get_current_page(notebook)) {
5644 t = ti;
5645 break;
5648 if (t == NULL)
5649 return FALSE;
5651 if (adjustment == NULL)
5652 adjustment = gtk_scrolled_window_get_vadjustment(
5653 GTK_SCROLLED_WINDOW(t->browser_win));
5655 view_size = gtk_adjustment_get_page_size(adjustment);
5656 value = gtk_adjustment_get_value(adjustment);
5657 max = gtk_adjustment_get_upper(adjustment) - view_size;
5659 if (max == 0)
5660 position = g_strdup("All");
5661 else if (value == max)
5662 position = g_strdup("Bot");
5663 else if (value == 0)
5664 position = g_strdup("Top");
5665 else
5666 position = g_strdup_printf("%d%%", (int) ((value / max) * 100));
5668 gtk_entry_set_text(GTK_ENTRY(t->sbe.position), position);
5669 g_free(position);
5671 return (TRUE);
5674 GtkWidget *
5675 create_window(const gchar *name)
5677 GtkWidget *w;
5679 w = gtk_window_new(GTK_WINDOW_TOPLEVEL);
5680 gtk_window_set_default_size(GTK_WINDOW(w), window_width, window_height);
5681 gtk_widget_set_name(w, name);
5682 gtk_window_set_wmclass(GTK_WINDOW(w), name, "XXXTerm");
5684 return (w);
5687 GtkWidget *
5688 create_browser(struct tab *t)
5690 GtkWidget *w;
5691 gchar *strval;
5692 GtkAdjustment *adjustment;
5694 if (t == NULL) {
5695 show_oops(NULL, "create_browser invalid parameters");
5696 return (NULL);
5699 t->sb_h = GTK_SCROLLBAR(gtk_hscrollbar_new(NULL));
5700 t->sb_v = GTK_SCROLLBAR(gtk_vscrollbar_new(NULL));
5701 t->adjust_h = gtk_range_get_adjustment(GTK_RANGE(t->sb_h));
5702 t->adjust_v = gtk_range_get_adjustment(GTK_RANGE(t->sb_v));
5704 w = gtk_scrolled_window_new(t->adjust_h, t->adjust_v);
5705 gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(w),
5706 GTK_POLICY_AUTOMATIC, GTK_POLICY_AUTOMATIC);
5708 t->wv = WEBKIT_WEB_VIEW(webkit_web_view_new());
5709 gtk_container_add(GTK_CONTAINER(w), GTK_WIDGET(t->wv));
5711 /* set defaults */
5712 t->settings = webkit_web_settings_new();
5714 g_object_set(t->settings, "default-encoding", encoding, (char *)NULL);
5716 if (user_agent == NULL) {
5717 g_object_get(G_OBJECT(t->settings), "user-agent", &strval,
5718 (char *)NULL);
5719 t->user_agent = g_strdup_printf("%s %s+", strval, version);
5720 g_free(strval);
5721 } else
5722 t->user_agent = g_strdup(user_agent);
5724 t->stylesheet = g_strdup_printf("file://%s/style.css", resource_dir);
5726 adjustment =
5727 gtk_scrolled_window_get_vadjustment(GTK_SCROLLED_WINDOW(w));
5728 g_signal_connect(G_OBJECT(adjustment), "value-changed",
5729 G_CALLBACK(update_statusbar_position), NULL);
5731 setup_webkit(t);
5732 setup_inspector(t);
5734 return (w);
5737 GtkWidget *
5738 create_kiosk_toolbar(struct tab *t)
5740 GtkWidget *toolbar = NULL, *b;
5742 b = gtk_hbox_new(FALSE, 0);
5743 toolbar = b;
5744 gtk_container_set_border_width(GTK_CONTAINER(toolbar), 0);
5746 /* backward button */
5747 t->backward = create_button("Back", GTK_STOCK_GO_BACK, 0);
5748 gtk_widget_set_sensitive(t->backward, FALSE);
5749 g_signal_connect(G_OBJECT(t->backward), "clicked",
5750 G_CALLBACK(backward_cb), t);
5751 gtk_box_pack_start(GTK_BOX(b), t->backward, TRUE, TRUE, 0);
5753 /* forward button */
5754 t->forward = create_button("Forward", GTK_STOCK_GO_FORWARD, 0);
5755 gtk_widget_set_sensitive(t->forward, FALSE);
5756 g_signal_connect(G_OBJECT(t->forward), "clicked",
5757 G_CALLBACK(forward_cb), t);
5758 gtk_box_pack_start(GTK_BOX(b), t->forward, TRUE, TRUE, 0);
5760 /* home button */
5761 t->gohome = create_button("Home", GTK_STOCK_HOME, 0);
5762 gtk_widget_set_sensitive(t->gohome, true);
5763 g_signal_connect(G_OBJECT(t->gohome), "clicked",
5764 G_CALLBACK(home_cb), t);
5765 gtk_box_pack_start(GTK_BOX(b), t->gohome, TRUE, TRUE, 0);
5767 /* create widgets but don't use them */
5768 t->uri_entry = gtk_entry_new();
5769 t->stop = create_button("Stop", GTK_STOCK_STOP, 0);
5770 t->js_toggle = create_button("JS-Toggle", enable_scripts ?
5771 GTK_STOCK_MEDIA_PLAY : GTK_STOCK_MEDIA_PAUSE, 0);
5773 return (toolbar);
5776 GtkWidget *
5777 create_toolbar(struct tab *t)
5779 GtkWidget *toolbar = NULL, *b, *eb1;
5781 b = gtk_hbox_new(FALSE, 0);
5782 toolbar = b;
5783 gtk_container_set_border_width(GTK_CONTAINER(toolbar), 0);
5785 /* backward button */
5786 t->backward = create_button("Back", GTK_STOCK_GO_BACK, 0);
5787 gtk_widget_set_sensitive(t->backward, FALSE);
5788 g_signal_connect(G_OBJECT(t->backward), "clicked",
5789 G_CALLBACK(backward_cb), t);
5790 gtk_box_pack_start(GTK_BOX(b), t->backward, FALSE, FALSE, 0);
5792 /* forward button */
5793 t->forward = create_button("Forward",GTK_STOCK_GO_FORWARD, 0);
5794 gtk_widget_set_sensitive(t->forward, FALSE);
5795 g_signal_connect(G_OBJECT(t->forward), "clicked",
5796 G_CALLBACK(forward_cb), t);
5797 gtk_box_pack_start(GTK_BOX(b), t->forward, FALSE,
5798 FALSE, 0);
5800 /* stop button */
5801 t->stop = create_button("Stop", GTK_STOCK_STOP, 0);
5802 gtk_widget_set_sensitive(t->stop, FALSE);
5803 g_signal_connect(G_OBJECT(t->stop), "clicked",
5804 G_CALLBACK(stop_cb), t);
5805 gtk_box_pack_start(GTK_BOX(b), t->stop, FALSE,
5806 FALSE, 0);
5808 /* JS button */
5809 t->js_toggle = create_button("JS-Toggle", enable_scripts ?
5810 GTK_STOCK_MEDIA_PLAY : GTK_STOCK_MEDIA_PAUSE, 0);
5811 gtk_widget_set_sensitive(t->js_toggle, TRUE);
5812 g_signal_connect(G_OBJECT(t->js_toggle), "clicked",
5813 G_CALLBACK(js_toggle_cb), t);
5814 gtk_box_pack_start(GTK_BOX(b), t->js_toggle, FALSE, FALSE, 0);
5816 t->uri_entry = gtk_entry_new();
5817 g_signal_connect(G_OBJECT(t->uri_entry), "activate",
5818 G_CALLBACK(activate_uri_entry_cb), t);
5819 g_signal_connect(G_OBJECT(t->uri_entry), "key-press-event",
5820 G_CALLBACK(entry_key_cb), t);
5821 completion_add(t);
5822 eb1 = gtk_hbox_new(FALSE, 0);
5823 gtk_container_set_border_width(GTK_CONTAINER(eb1), 1);
5824 gtk_box_pack_start(GTK_BOX(eb1), t->uri_entry, TRUE, TRUE, 0);
5825 gtk_box_pack_start(GTK_BOX(b), eb1, TRUE, TRUE, 0);
5827 /* search entry */
5828 if (search_string) {
5829 GtkWidget *eb2;
5830 t->search_entry = gtk_entry_new();
5831 gtk_entry_set_width_chars(GTK_ENTRY(t->search_entry), 30);
5832 g_signal_connect(G_OBJECT(t->search_entry), "activate",
5833 G_CALLBACK(activate_search_entry_cb), t);
5834 g_signal_connect(G_OBJECT(t->search_entry), "key-press-event",
5835 G_CALLBACK(entry_key_cb), t);
5836 gtk_widget_set_size_request(t->search_entry, -1, -1);
5837 eb2 = gtk_hbox_new(FALSE, 0);
5838 gtk_container_set_border_width(GTK_CONTAINER(eb2), 1);
5839 gtk_box_pack_start(GTK_BOX(eb2), t->search_entry, TRUE, TRUE,
5841 gtk_box_pack_start(GTK_BOX(b), eb2, FALSE, FALSE, 0);
5844 return (toolbar);
5847 GtkWidget *
5848 create_buffers(struct tab *t)
5850 GtkCellRenderer *renderer;
5851 GtkWidget *view;
5853 view = gtk_tree_view_new();
5855 gtk_tree_view_set_headers_visible(GTK_TREE_VIEW(view), FALSE);
5857 renderer = gtk_cell_renderer_text_new();
5858 gtk_tree_view_insert_column_with_attributes
5859 (GTK_TREE_VIEW(view), -1, "Id", renderer, "text", COL_ID, (char *)NULL);
5861 renderer = gtk_cell_renderer_text_new();
5862 gtk_tree_view_insert_column_with_attributes
5863 (GTK_TREE_VIEW(view), -1, "Title", renderer, "text", COL_TITLE,
5864 (char *)NULL);
5866 gtk_tree_view_set_model
5867 (GTK_TREE_VIEW(view), GTK_TREE_MODEL(buffers_store));
5869 return view;
5872 void
5873 row_activated_cb(GtkTreeView *view, GtkTreePath *path,
5874 GtkTreeViewColumn *col, struct tab *t)
5876 GtkTreeIter iter;
5877 guint id;
5879 gtk_widget_grab_focus(GTK_WIDGET(t->wv));
5881 if (gtk_tree_model_get_iter(GTK_TREE_MODEL(buffers_store), &iter,
5882 path)) {
5883 gtk_tree_model_get
5884 (GTK_TREE_MODEL(buffers_store), &iter, COL_ID, &id, -1);
5885 set_current_tab(id - 1);
5888 hide_buffers(t);
5891 /* after tab reordering/creation/removal */
5892 void
5893 recalc_tabs(void)
5895 struct tab *t;
5896 int maxid = 0;
5898 TAILQ_FOREACH(t, &tabs, entry) {
5899 t->tab_id = gtk_notebook_page_num(notebook, t->vbox);
5900 if (t->tab_id > maxid)
5901 maxid = t->tab_id;
5903 gtk_widget_show(t->tab_elems.sep);
5906 TAILQ_FOREACH(t, &tabs, entry) {
5907 if (t->tab_id == maxid) {
5908 gtk_widget_hide(t->tab_elems.sep);
5909 break;
5914 /* after active tab change */
5915 void
5916 recolor_compact_tabs(void)
5918 struct tab *t;
5919 int curid = 0;
5920 GdkColor color;
5922 gdk_color_parse(XT_COLOR_CT_INACTIVE, &color);
5923 TAILQ_FOREACH(t, &tabs, entry)
5924 gtk_widget_modify_fg(t->tab_elems.label, GTK_STATE_NORMAL,
5925 &color);
5927 curid = gtk_notebook_get_current_page(notebook);
5928 TAILQ_FOREACH(t, &tabs, entry)
5929 if (t->tab_id == curid) {
5930 gdk_color_parse(XT_COLOR_CT_ACTIVE, &color);
5931 gtk_widget_modify_fg(t->tab_elems.label,
5932 GTK_STATE_NORMAL, &color);
5933 break;
5937 void
5938 set_current_tab(int page_num)
5940 buffercmd_abort(get_current_tab());
5941 gtk_notebook_set_current_page(notebook, page_num);
5942 recolor_compact_tabs();
5946 undo_close_tab_save(struct tab *t)
5948 int m, n;
5949 const gchar *uri;
5950 struct undo *u1, *u2;
5951 GList *items;
5952 WebKitWebHistoryItem *item;
5954 if ((uri = get_uri(t)) == NULL)
5955 return (1);
5957 u1 = g_malloc0(sizeof(struct undo));
5958 u1->uri = g_strdup(uri);
5960 t->bfl = webkit_web_view_get_back_forward_list(t->wv);
5962 m = webkit_web_back_forward_list_get_forward_length(t->bfl);
5963 n = webkit_web_back_forward_list_get_back_length(t->bfl);
5964 u1->back = n;
5966 /* forward history */
5967 items = webkit_web_back_forward_list_get_forward_list_with_limit(t->bfl, m);
5969 while (items) {
5970 item = items->data;
5971 u1->history = g_list_prepend(u1->history,
5972 webkit_web_history_item_copy(item));
5973 items = g_list_next(items);
5976 /* current item */
5977 if (m) {
5978 item = webkit_web_back_forward_list_get_current_item(t->bfl);
5979 u1->history = g_list_prepend(u1->history,
5980 webkit_web_history_item_copy(item));
5983 /* back history */
5984 items = webkit_web_back_forward_list_get_back_list_with_limit(t->bfl, n);
5986 while (items) {
5987 item = items->data;
5988 u1->history = g_list_prepend(u1->history,
5989 webkit_web_history_item_copy(item));
5990 items = g_list_next(items);
5993 TAILQ_INSERT_HEAD(&undos, u1, entry);
5995 if (undo_count > XT_MAX_UNDO_CLOSE_TAB) {
5996 u2 = TAILQ_LAST(&undos, undo_tailq);
5997 TAILQ_REMOVE(&undos, u2, entry);
5998 g_free(u2->uri);
5999 g_list_free(u2->history);
6000 g_free(u2);
6001 } else
6002 undo_count++;
6004 return (0);
6007 void
6008 delete_tab(struct tab *t)
6010 struct karg a;
6012 DNPRINTF(XT_D_TAB, "delete_tab: %p\n", t);
6014 if (t == NULL)
6015 return;
6018 * no need to join thread here because it won't access t on completion
6021 TAILQ_REMOVE(&tabs, t, entry);
6022 buffercmd_abort(t);
6024 /* Halt all webkit activity. */
6025 abort_favicon_download(t);
6026 webkit_web_view_stop_loading(t->wv);
6028 /* Save the tab, so we can undo the close. */
6029 undo_close_tab_save(t);
6031 /* just in case */
6032 if (t->search_id)
6033 g_source_remove(t->search_id);
6035 /* inspector */
6036 bzero(&a, sizeof a);
6037 a.i = XT_INS_CLOSE;
6038 inspector_cmd(t, &a);
6040 if (browser_mode == XT_BM_KIOSK) {
6041 gtk_widget_destroy(t->uri_entry);
6042 gtk_widget_destroy(t->stop);
6043 gtk_widget_destroy(t->js_toggle);
6046 gtk_widget_destroy(t->tab_elems.eventbox);
6047 gtk_widget_destroy(t->vbox);
6049 g_free(t->user_agent);
6050 g_free(t->stylesheet);
6051 g_free(t->tmp_uri);
6052 g_free(t);
6053 t = NULL;
6055 if (TAILQ_EMPTY(&tabs)) {
6056 if (browser_mode == XT_BM_KIOSK)
6057 create_new_tab(home, NULL, 1, -1);
6058 else
6059 create_new_tab(NULL, NULL, 1, -1);
6062 /* recreate session */
6063 if (session_autosave) {
6064 bzero(&a, sizeof a);
6065 a.s = NULL;
6066 save_tabs(NULL, &a);
6069 recalc_tabs();
6070 recolor_compact_tabs();
6073 void
6074 update_statusbar_zoom(struct tab *t)
6076 gfloat zoom;
6077 char s[16] = { '\0' };
6079 g_object_get(G_OBJECT(t->wv), "zoom-level", &zoom, (char *)NULL);
6080 if ((zoom <= 0.99 || zoom >= 1.01))
6081 snprintf(s, sizeof s, "%d%%", (int)(zoom * 100));
6082 gtk_entry_set_text(GTK_ENTRY(t->sbe.zoom), s);
6085 void
6086 setzoom_webkit(struct tab *t, int adjust)
6088 #define XT_ZOOMPERCENT 0.04
6090 gfloat zoom;
6092 if (t == NULL) {
6093 show_oops(NULL, "setzoom_webkit invalid parameters");
6094 return;
6097 g_object_get(G_OBJECT(t->wv), "zoom-level", &zoom, (char *)NULL);
6098 if (adjust == XT_ZOOM_IN)
6099 zoom += XT_ZOOMPERCENT;
6100 else if (adjust == XT_ZOOM_OUT)
6101 zoom -= XT_ZOOMPERCENT;
6102 else if (adjust > 0)
6103 zoom = default_zoom_level + adjust / 100.0 - 1.0;
6104 else {
6105 show_oops(t, "setzoom_webkit invalid zoom value");
6106 return;
6109 if (zoom < XT_ZOOMPERCENT)
6110 zoom = XT_ZOOMPERCENT;
6111 g_object_set(G_OBJECT(t->wv), "zoom-level", zoom, (char *)NULL);
6112 update_statusbar_zoom(t);
6115 gboolean
6116 tab_clicked_cb(GtkWidget *widget, GdkEventButton *event, gpointer data)
6118 struct tab *t = (struct tab *) data;
6120 DNPRINTF(XT_D_TAB, "tab_clicked_cb: tab: %d\n", t->tab_id);
6122 switch (event->button) {
6123 case 1:
6124 set_current_tab(t->tab_id);
6125 break;
6126 case 2:
6127 delete_tab(t);
6128 break;
6131 return TRUE;
6134 void
6135 append_tab(struct tab *t)
6137 if (t == NULL)
6138 return;
6140 TAILQ_INSERT_TAIL(&tabs, t, entry);
6141 t->tab_id = gtk_notebook_append_page(notebook, t->vbox, t->tab_content);
6144 GtkWidget *
6145 create_sbe(int width)
6147 GtkWidget *sbe;
6149 sbe = gtk_entry_new();
6150 gtk_entry_set_inner_border(GTK_ENTRY(sbe), NULL);
6151 gtk_entry_set_has_frame(GTK_ENTRY(sbe), FALSE);
6152 gtk_widget_set_can_focus(GTK_WIDGET(sbe), FALSE);
6153 gtk_widget_modify_font(GTK_WIDGET(sbe), statusbar_font);
6154 gtk_entry_set_alignment(GTK_ENTRY(sbe), 1.0);
6155 gtk_widget_set_size_request(sbe, width, -1);
6157 return sbe;
6160 struct tab *
6161 create_new_tab(char *title, struct undo *u, int focus, int position)
6163 struct tab *t;
6164 int load = 1, id;
6165 GtkWidget *b, *bb;
6166 WebKitWebHistoryItem *item;
6167 GList *items;
6168 GdkColor color;
6169 char *p;
6170 int sbe_p = 0, sbe_b = 0,
6171 sbe_z = 0;
6173 DNPRINTF(XT_D_TAB, "create_new_tab: title %s focus %d\n", title, focus);
6175 if (tabless && !TAILQ_EMPTY(&tabs)) {
6176 DNPRINTF(XT_D_TAB, "create_new_tab: new tab rejected\n");
6177 return (NULL);
6180 t = g_malloc0(sizeof *t);
6182 if (title == NULL) {
6183 title = "(untitled)";
6184 load = 0;
6187 t->vbox = gtk_vbox_new(FALSE, 0);
6189 /* label + button for tab */
6190 b = gtk_hbox_new(FALSE, 0);
6191 t->tab_content = b;
6193 #if GTK_CHECK_VERSION(2, 20, 0)
6194 t->spinner = gtk_spinner_new();
6195 #endif
6196 t->label = gtk_label_new(title);
6197 bb = create_button("Close", GTK_STOCK_CLOSE, 1);
6198 gtk_widget_set_size_request(t->label, 100, 0);
6199 gtk_label_set_max_width_chars(GTK_LABEL(t->label), 20);
6200 gtk_label_set_ellipsize(GTK_LABEL(t->label), PANGO_ELLIPSIZE_END);
6201 gtk_widget_set_size_request(b, 130, 0);
6203 gtk_box_pack_start(GTK_BOX(b), bb, FALSE, FALSE, 0);
6204 gtk_box_pack_start(GTK_BOX(b), t->label, FALSE, FALSE, 0);
6205 #if GTK_CHECK_VERSION(2, 20, 0)
6206 gtk_box_pack_start(GTK_BOX(b), t->spinner, FALSE, FALSE, 0);
6207 #endif
6209 /* toolbar */
6210 if (browser_mode == XT_BM_KIOSK) {
6211 t->toolbar = create_kiosk_toolbar(t);
6212 gtk_box_pack_start(GTK_BOX(t->vbox), t->toolbar, FALSE, FALSE,
6214 } else {
6215 t->toolbar = create_toolbar(t);
6216 if (fancy_bar)
6217 gtk_box_pack_start(GTK_BOX(t->vbox), t->toolbar, FALSE,
6218 FALSE, 0);
6221 /* marks */
6222 marks_clear(t);
6224 /* browser */
6225 t->browser_win = create_browser(t);
6226 gtk_box_pack_start(GTK_BOX(t->vbox), t->browser_win, TRUE, TRUE, 0);
6228 /* oops message for user feedback */
6229 t->oops = gtk_entry_new();
6230 gtk_entry_set_inner_border(GTK_ENTRY(t->oops), NULL);
6231 gtk_entry_set_has_frame(GTK_ENTRY(t->oops), FALSE);
6232 gtk_widget_set_can_focus(GTK_WIDGET(t->oops), FALSE);
6233 gdk_color_parse(XT_COLOR_RED, &color);
6234 gtk_widget_modify_base(t->oops, GTK_STATE_NORMAL, &color);
6235 gtk_box_pack_end(GTK_BOX(t->vbox), t->oops, FALSE, FALSE, 0);
6236 gtk_widget_modify_font(GTK_WIDGET(t->oops), oops_font);
6238 /* command entry */
6239 t->cmd = gtk_entry_new();
6240 gtk_entry_set_inner_border(GTK_ENTRY(t->cmd), NULL);
6241 gtk_entry_set_has_frame(GTK_ENTRY(t->cmd), FALSE);
6242 gtk_box_pack_end(GTK_BOX(t->vbox), t->cmd, FALSE, FALSE, 0);
6243 gtk_widget_modify_font(GTK_WIDGET(t->cmd), cmd_font);
6245 /* status bar */
6246 t->statusbar_box = gtk_hbox_new(FALSE, 0);
6248 t->sbe.statusbar = gtk_entry_new();
6249 gtk_entry_set_inner_border(GTK_ENTRY(t->sbe.statusbar), NULL);
6250 gtk_entry_set_has_frame(GTK_ENTRY(t->sbe.statusbar), FALSE);
6251 gtk_widget_set_can_focus(GTK_WIDGET(t->sbe.statusbar), FALSE);
6252 gtk_widget_modify_font(GTK_WIDGET(t->sbe.statusbar), statusbar_font);
6254 /* create these widgets only if specified in statusbar_elems */
6256 t->sbe.position = create_sbe(40);
6257 t->sbe.zoom = create_sbe(40);
6258 t->sbe.buffercmd = create_sbe(60);
6260 statusbar_modify_attr(t, XT_COLOR_WHITE, XT_COLOR_BLACK);
6262 gtk_box_pack_start(GTK_BOX(t->statusbar_box), t->sbe.statusbar, TRUE,
6263 TRUE, FALSE);
6265 /* gtk widgets cannot be added to a box twice. sbe_* variables
6266 make sure of this */
6267 for (p = statusbar_elems; *p != '\0'; p++) {
6268 switch (*p) {
6269 case '|':
6271 GtkWidget *sep = gtk_vseparator_new();
6273 gdk_color_parse(XT_COLOR_SB_SEPARATOR, &color);
6274 gtk_widget_modify_bg(sep, GTK_STATE_NORMAL, &color);
6275 gtk_box_pack_start(GTK_BOX(t->statusbar_box), sep,
6276 FALSE, FALSE, FALSE);
6277 break;
6279 case 'P':
6280 if (sbe_p) {
6281 warnx("flag \"%c\" specified more than "
6282 "once in statusbar_elems\n", *p);
6283 break;
6285 sbe_p = 1;
6286 gtk_box_pack_start(GTK_BOX(t->statusbar_box),
6287 t->sbe.position, FALSE, FALSE, FALSE);
6288 break;
6289 case 'B':
6290 if (sbe_b) {
6291 warnx("flag \"%c\" specified more than "
6292 "once in statusbar_elems\n", *p);
6293 break;
6295 sbe_b = 1;
6296 gtk_box_pack_start(GTK_BOX(t->statusbar_box),
6297 t->sbe.buffercmd, FALSE, FALSE, FALSE);
6298 break;
6299 case 'Z':
6300 if (sbe_z) {
6301 warnx("flag \"%c\" specified more than "
6302 "once in statusbar_elems\n", *p);
6303 break;
6305 sbe_z = 1;
6306 gtk_box_pack_start(GTK_BOX(t->statusbar_box),
6307 t->sbe.zoom, FALSE, FALSE, FALSE);
6308 break;
6309 default:
6310 warnx("illegal flag \"%c\" in statusbar_elems\n", *p);
6311 break;
6315 gtk_box_pack_end(GTK_BOX(t->vbox), t->statusbar_box, FALSE, FALSE, 0);
6317 /* buffer list */
6318 t->buffers = create_buffers(t);
6319 gtk_box_pack_end(GTK_BOX(t->vbox), t->buffers, FALSE, FALSE, 0);
6321 /* xtp meaning is normal by default */
6322 t->xtp_meaning = XT_XTP_TAB_MEANING_NORMAL;
6324 /* set empty favicon */
6325 xt_icon_from_name(t, "text-html");
6327 /* and show it all */
6328 gtk_widget_show_all(b);
6329 gtk_widget_show_all(t->vbox);
6331 /* compact tab bar */
6332 t->tab_elems.label = gtk_label_new(title);
6333 gtk_label_set_width_chars(GTK_LABEL(t->tab_elems.label), 1.0);
6334 gtk_misc_set_alignment(GTK_MISC(t->tab_elems.label), 0.0, 0.0);
6335 gtk_misc_set_padding(GTK_MISC(t->tab_elems.label), 4.0, 4.0);
6336 gtk_widget_modify_font(GTK_WIDGET(t->tab_elems.label), tabbar_font);
6338 t->tab_elems.eventbox = gtk_event_box_new();
6339 t->tab_elems.box = gtk_hbox_new(FALSE, 0);
6340 t->tab_elems.sep = gtk_vseparator_new();
6342 gdk_color_parse(XT_COLOR_CT_BACKGROUND, &color);
6343 gtk_widget_modify_bg(t->tab_elems.eventbox, GTK_STATE_NORMAL, &color);
6344 gdk_color_parse(XT_COLOR_CT_INACTIVE, &color);
6345 gtk_widget_modify_fg(t->tab_elems.label, GTK_STATE_NORMAL, &color);
6346 gdk_color_parse(XT_COLOR_CT_SEPARATOR, &color);
6347 gtk_widget_modify_bg(t->tab_elems.sep, GTK_STATE_NORMAL, &color);
6349 gtk_box_pack_start(GTK_BOX(t->tab_elems.box), t->tab_elems.label, TRUE,
6350 TRUE, 0);
6351 gtk_box_pack_start(GTK_BOX(t->tab_elems.box), t->tab_elems.sep, FALSE,
6352 FALSE, 0);
6353 gtk_container_add(GTK_CONTAINER(t->tab_elems.eventbox),
6354 t->tab_elems.box);
6356 gtk_box_pack_start(GTK_BOX(tab_bar), t->tab_elems.eventbox, TRUE,
6357 TRUE, 0);
6358 gtk_widget_show_all(t->tab_elems.eventbox);
6360 if (append_next == 0 || gtk_notebook_get_n_pages(notebook) == 0)
6361 append_tab(t);
6362 else {
6363 id = position >= 0 ? position :
6364 gtk_notebook_get_current_page(notebook) + 1;
6365 if (id > gtk_notebook_get_n_pages(notebook))
6366 append_tab(t);
6367 else {
6368 TAILQ_INSERT_TAIL(&tabs, t, entry);
6369 gtk_notebook_insert_page(notebook, t->vbox, b, id);
6370 gtk_box_reorder_child(GTK_BOX(tab_bar),
6371 t->tab_elems.eventbox, id);
6372 recalc_tabs();
6376 #if GTK_CHECK_VERSION(2, 20, 0)
6377 /* turn spinner off if we are a new tab without uri */
6378 if (!load) {
6379 gtk_spinner_stop(GTK_SPINNER(t->spinner));
6380 gtk_widget_hide(t->spinner);
6382 #endif
6383 /* make notebook tabs reorderable */
6384 gtk_notebook_set_tab_reorderable(notebook, t->vbox, TRUE);
6386 /* compact tabs clickable */
6387 g_signal_connect(G_OBJECT(t->tab_elems.eventbox),
6388 "button_press_event", G_CALLBACK(tab_clicked_cb), t);
6390 g_object_connect(G_OBJECT(t->cmd),
6391 "signal::key-press-event", G_CALLBACK(cmd_keypress_cb), t,
6392 "signal::key-release-event", G_CALLBACK(cmd_keyrelease_cb), t,
6393 "signal::focus-out-event", G_CALLBACK(cmd_focusout_cb), t,
6394 "signal::activate", G_CALLBACK(cmd_activate_cb), t,
6395 "signal::populate-popup", G_CALLBACK(cmd_popup_cb), t,
6396 (char *)NULL);
6398 /* reuse wv_button_cb to hide oops */
6399 g_object_connect(G_OBJECT(t->oops),
6400 "signal::button_press_event", G_CALLBACK(wv_button_cb), t,
6401 (char *)NULL);
6403 g_signal_connect(t->buffers,
6404 "row-activated", G_CALLBACK(row_activated_cb), t);
6405 g_object_connect(G_OBJECT(t->buffers),
6406 "signal::key-press-event", G_CALLBACK(wv_keypress_cb), t, (char *)NULL);
6408 g_object_connect(G_OBJECT(t->wv),
6409 "signal::key-press-event", G_CALLBACK(wv_keypress_cb), t,
6410 "signal-after::key-press-event", G_CALLBACK(wv_keypress_after_cb), t,
6411 "signal::hovering-over-link", G_CALLBACK(webview_hover_cb), t,
6412 "signal::download-requested", G_CALLBACK(webview_download_cb), t,
6413 "signal::mime-type-policy-decision-requested", G_CALLBACK(webview_mimetype_cb), t,
6414 "signal::navigation-policy-decision-requested", G_CALLBACK(webview_npd_cb), t,
6415 "signal::new-window-policy-decision-requested", G_CALLBACK(webview_npd_cb), t,
6416 "signal::create-web-view", G_CALLBACK(webview_cwv_cb), t,
6417 "signal::close-web-view", G_CALLBACK(webview_closewv_cb), t,
6418 "signal::event", G_CALLBACK(webview_event_cb), t,
6419 "signal::load-finished", G_CALLBACK(webview_load_finished_cb), t,
6420 "signal::load-progress-changed", G_CALLBACK(webview_progress_changed_cb), t,
6421 "signal::icon-loaded", G_CALLBACK(notify_icon_loaded_cb), t,
6422 "signal::button_press_event", G_CALLBACK(wv_button_cb), t,
6423 "signal::button_release_event", G_CALLBACK(wv_release_button_cb), t,
6424 "signal::populate-popup", G_CALLBACK(wv_popup_cb), t,
6425 (char *)NULL);
6426 g_signal_connect(t->wv,
6427 "notify::load-status", G_CALLBACK(notify_load_status_cb), t);
6428 g_signal_connect(t->wv,
6429 "notify::title", G_CALLBACK(notify_title_cb), t);
6431 /* hijack the unused keys as if we were the browser */
6432 g_object_connect(G_OBJECT(t->toolbar),
6433 "signal-after::key-press-event", G_CALLBACK(wv_keypress_after_cb), t,
6434 (char *)NULL);
6436 g_signal_connect(G_OBJECT(bb), "button_press_event",
6437 G_CALLBACK(tab_close_cb), t);
6439 /* setup history */
6440 t->bfl = webkit_web_view_get_back_forward_list(t->wv);
6441 /* restore the tab's history */
6442 if (u && u->history) {
6443 items = u->history;
6444 while (items) {
6445 item = items->data;
6446 webkit_web_back_forward_list_add_item(t->bfl, item);
6447 items = g_list_next(items);
6450 item = g_list_nth_data(u->history, u->back);
6451 if (item)
6452 webkit_web_view_go_to_back_forward_item(t->wv, item);
6454 g_list_free(items);
6455 g_list_free(u->history);
6456 } else
6457 webkit_web_back_forward_list_clear(t->bfl);
6459 /* hide stuff */
6460 hide_cmd(t);
6461 hide_oops(t);
6462 hide_buffers(t);
6463 url_set_visibility();
6464 statusbar_set_visibility();
6466 if (focus) {
6467 set_current_tab(t->tab_id);
6468 DNPRINTF(XT_D_TAB, "create_new_tab: going to tab: %d\n",
6469 t->tab_id);
6471 if (load) {
6472 gtk_entry_set_text(GTK_ENTRY(t->uri_entry), title);
6473 load_uri(t, title);
6474 } else {
6475 if (show_url == 1)
6476 gtk_widget_grab_focus(GTK_WIDGET(t->uri_entry));
6477 else
6478 focus_webview(t);
6480 } else if (load)
6481 load_uri(t, title);
6483 recolor_compact_tabs();
6484 setzoom_webkit(t, XT_ZOOM_NORMAL);
6485 return (t);
6488 void
6489 notebook_switchpage_cb(GtkNotebook *nb, GtkWidget *nbp, guint pn,
6490 gpointer *udata)
6492 struct tab *t;
6493 const gchar *uri;
6495 DNPRINTF(XT_D_TAB, "notebook_switchpage_cb: tab: %d\n", pn);
6497 if (gtk_notebook_get_current_page(notebook) == -1)
6498 recalc_tabs();
6500 TAILQ_FOREACH(t, &tabs, entry) {
6501 if (t->tab_id == pn) {
6502 DNPRINTF(XT_D_TAB, "notebook_switchpage_cb: going to "
6503 "%d\n", pn);
6505 uri = get_title(t, TRUE);
6506 gtk_window_set_title(GTK_WINDOW(main_window), uri);
6508 hide_cmd(t);
6509 hide_oops(t);
6511 if (t->focus_wv) {
6512 /* can't use focus_webview here */
6513 gtk_widget_grab_focus(GTK_WIDGET(t->wv));
6519 void
6520 notebook_pagereordered_cb(GtkNotebook *nb, GtkWidget *nbp, guint pn,
6521 gpointer *udata)
6523 struct tab *t = NULL, *tt;
6525 recalc_tabs();
6527 TAILQ_FOREACH(tt, &tabs, entry)
6528 if (tt->tab_id == pn) {
6529 t = tt;
6530 break;
6532 if (t == NULL)
6533 return;
6534 DNPRINTF(XT_D_TAB, "page_reordered_cb: tab: %d\n", t->tab_id);
6536 gtk_box_reorder_child(GTK_BOX(tab_bar), t->tab_elems.eventbox,
6537 t->tab_id);
6540 void
6541 menuitem_response(struct tab *t)
6543 gtk_notebook_set_current_page(notebook, t->tab_id);
6546 gboolean
6547 arrow_cb(GtkWidget *w, GdkEventButton *event, gpointer user_data)
6549 GtkWidget *menu, *menu_items;
6550 GdkEventButton *bevent;
6551 const gchar *uri;
6552 struct tab *ti;
6554 if (event->type == GDK_BUTTON_PRESS) {
6555 bevent = (GdkEventButton *) event;
6556 menu = gtk_menu_new();
6558 TAILQ_FOREACH(ti, &tabs, entry) {
6559 if ((uri = get_uri(ti)) == NULL)
6560 /* XXX make sure there is something to print */
6561 /* XXX add gui pages in here to look purdy */
6562 uri = "(untitled)";
6563 menu_items = gtk_menu_item_new_with_label(uri);
6564 gtk_menu_shell_append(GTK_MENU_SHELL(menu), menu_items);
6565 gtk_widget_show(menu_items);
6567 g_signal_connect_swapped((menu_items),
6568 "activate", G_CALLBACK(menuitem_response),
6569 (gpointer)ti);
6572 gtk_menu_popup(GTK_MENU(menu), NULL, NULL, NULL, NULL,
6573 bevent->button, bevent->time);
6575 /* unref object so it'll free itself when popped down */
6576 #if !GTK_CHECK_VERSION(3, 0, 0)
6577 /* XXX does not need unref with gtk+3? */
6578 g_object_ref_sink(menu);
6579 g_object_unref(menu);
6580 #endif
6582 return (TRUE /* eat event */);
6585 return (FALSE /* propagate */);
6589 icon_size_map(int iconsz)
6591 if (iconsz <= GTK_ICON_SIZE_INVALID ||
6592 iconsz > GTK_ICON_SIZE_DIALOG)
6593 return (GTK_ICON_SIZE_SMALL_TOOLBAR);
6595 return (iconsz);
6598 GtkWidget *
6599 create_button(char *name, char *stockid, int size)
6601 GtkWidget *button, *image;
6602 gchar *rcstring;
6603 int gtk_icon_size;
6605 rcstring = g_strdup_printf(
6606 "style \"%s-style\"\n"
6607 "{\n"
6608 " GtkWidget::focus-padding = 0\n"
6609 " GtkWidget::focus-line-width = 0\n"
6610 " xthickness = 0\n"
6611 " ythickness = 0\n"
6612 "}\n"
6613 "widget \"*.%s\" style \"%s-style\"", name, name, name);
6614 gtk_rc_parse_string(rcstring);
6615 g_free(rcstring);
6616 button = gtk_button_new();
6617 gtk_button_set_focus_on_click(GTK_BUTTON(button), FALSE);
6618 gtk_icon_size = icon_size_map(size ? size : icon_size);
6620 image = gtk_image_new_from_stock(stockid, gtk_icon_size);
6621 gtk_widget_set_size_request(GTK_WIDGET(image), -1, -1);
6622 gtk_container_set_border_width(GTK_CONTAINER(button), 1);
6623 gtk_container_add(GTK_CONTAINER(button), GTK_WIDGET(image));
6624 gtk_widget_set_name(button, name);
6625 gtk_button_set_relief(GTK_BUTTON(button), GTK_RELIEF_NONE);
6627 return (button);
6630 void
6631 button_set_stockid(GtkWidget *button, char *stockid)
6633 GtkWidget *image;
6635 image = gtk_image_new_from_stock(stockid, icon_size_map(icon_size));
6636 gtk_widget_set_size_request(GTK_WIDGET(image), -1, -1);
6637 gtk_button_set_image(GTK_BUTTON(button), image);
6640 void
6641 clipb_primary_cb(GtkClipboard *primary, GdkEvent *event, gpointer notused)
6643 gchar *p = NULL;
6644 GdkAtom atom = gdk_atom_intern("CUT_BUFFER0", FALSE);
6645 gint len;
6647 if (xterm_workaround == 0)
6648 return;
6651 * xterm doesn't play nice with clipboards because it clears the
6652 * primary when clicked. We rely on primary being set to properly
6653 * handle middle mouse button clicks (paste). So when someone clears
6654 * primary copy whatever is in CUT_BUFFER0 into primary to simualte
6655 * other application behavior (as in DON'T clear primary).
6658 p = gtk_clipboard_wait_for_text(primary);
6659 if (p == NULL) {
6660 if (gdk_property_get(gdk_get_default_root_window(),
6661 atom,
6662 gdk_atom_intern("STRING", FALSE),
6664 1024 * 1024 /* picked out of my butt */,
6665 FALSE,
6666 NULL,
6667 NULL,
6668 &len,
6669 (guchar **)&p)) {
6670 /* yes sir, we need to NUL the string */
6671 p[len] = '\0';
6672 gtk_clipboard_set_text(primary, p, -1);
6676 if (p)
6677 g_free(p);
6680 void
6681 create_canvas(void)
6683 GtkWidget *vbox;
6684 GList *l = NULL;
6685 GdkPixbuf *pb;
6686 char file[PATH_MAX];
6687 int i;
6689 vbox = gtk_vbox_new(FALSE, 0);
6690 gtk_box_set_spacing(GTK_BOX(vbox), 0);
6691 notebook = GTK_NOTEBOOK(gtk_notebook_new());
6692 #if !GTK_CHECK_VERSION(3, 0, 0)
6693 /* XXX seems to be needed with gtk+2 */
6694 gtk_notebook_set_tab_hborder(notebook, 0);
6695 gtk_notebook_set_tab_vborder(notebook, 0);
6696 #endif
6697 gtk_notebook_set_scrollable(notebook, TRUE);
6698 gtk_notebook_set_show_border(notebook, FALSE);
6699 gtk_widget_set_can_focus(GTK_WIDGET(notebook), FALSE);
6701 abtn = gtk_button_new();
6702 arrow = gtk_arrow_new(GTK_ARROW_DOWN, GTK_SHADOW_NONE);
6703 gtk_widget_set_size_request(arrow, -1, -1);
6704 gtk_container_add(GTK_CONTAINER(abtn), arrow);
6705 gtk_widget_set_size_request(abtn, -1, 20);
6707 #if GTK_CHECK_VERSION(2, 20, 0)
6708 gtk_notebook_set_action_widget(notebook, abtn, GTK_PACK_END);
6709 #endif
6710 gtk_widget_set_size_request(GTK_WIDGET(notebook), -1, -1);
6712 /* compact tab bar */
6713 tab_bar = gtk_hbox_new(TRUE, 0);
6715 gtk_box_pack_start(GTK_BOX(vbox), tab_bar, FALSE, FALSE, 0);
6716 gtk_box_pack_start(GTK_BOX(vbox), GTK_WIDGET(notebook), TRUE, TRUE, 0);
6717 gtk_widget_set_size_request(vbox, -1, -1);
6719 g_object_connect(G_OBJECT(notebook),
6720 "signal::switch-page", G_CALLBACK(notebook_switchpage_cb), NULL,
6721 (char *)NULL);
6722 g_object_connect(G_OBJECT(notebook),
6723 "signal::page-reordered", G_CALLBACK(notebook_pagereordered_cb),
6724 NULL, (char *)NULL);
6725 g_signal_connect(G_OBJECT(abtn), "button_press_event",
6726 G_CALLBACK(arrow_cb), NULL);
6728 main_window = create_window("xxxterm");
6729 gtk_container_add(GTK_CONTAINER(main_window), vbox);
6730 g_signal_connect(G_OBJECT(main_window), "delete_event",
6731 G_CALLBACK(gtk_main_quit), NULL);
6733 /* icons */
6734 for (i = 0; i < LENGTH(icons); i++) {
6735 snprintf(file, sizeof file, "%s/%s", resource_dir, icons[i]);
6736 pb = gdk_pixbuf_new_from_file(file, NULL);
6737 l = g_list_append(l, pb);
6739 gtk_window_set_default_icon_list(l);
6741 /* clipboard work around */
6742 if (xterm_workaround)
6743 g_signal_connect(
6744 G_OBJECT(gtk_clipboard_get(GDK_SELECTION_PRIMARY)),
6745 "owner-change", G_CALLBACK(clipb_primary_cb), NULL);
6747 gtk_widget_show_all(abtn);
6748 gtk_widget_show_all(main_window);
6749 notebook_tab_set_visibility();
6753 send_cmd_to_socket(char *cmd)
6755 int s, len, rv = 1;
6756 struct sockaddr_un sa;
6758 if ((s = socket(AF_UNIX, SOCK_STREAM, 0)) == -1) {
6759 warnx("%s: socket", __func__);
6760 return (rv);
6763 sa.sun_family = AF_UNIX;
6764 snprintf(sa.sun_path, sizeof(sa.sun_path), "%s/%s",
6765 work_dir, XT_SOCKET_FILE);
6766 len = SUN_LEN(&sa);
6768 if (connect(s, (struct sockaddr *)&sa, len) == -1) {
6769 warnx("%s: connect", __func__);
6770 goto done;
6773 if (send(s, cmd, strlen(cmd) + 1, 0) == -1) {
6774 warnx("%s: send", __func__);
6775 goto done;
6778 rv = 0;
6779 done:
6780 close(s);
6781 return (rv);
6784 gboolean
6785 socket_watcher(GIOChannel *source, GIOCondition condition, gpointer data)
6787 int s, n;
6788 char str[XT_MAX_URL_LENGTH];
6789 socklen_t t = sizeof(struct sockaddr_un);
6790 struct sockaddr_un sa;
6791 struct passwd *p;
6792 uid_t uid;
6793 gid_t gid;
6794 struct tab *tt;
6795 gint fd = g_io_channel_unix_get_fd(source);
6797 if ((s = accept(fd, (struct sockaddr *)&sa, &t)) == -1) {
6798 warn("accept");
6799 return (FALSE);
6802 if (getpeereid(s, &uid, &gid) == -1) {
6803 warn("getpeereid");
6804 return (FALSE);
6806 if (uid != getuid() || gid != getgid()) {
6807 warnx("unauthorized user");
6808 return (FALSE);
6811 p = getpwuid(uid);
6812 if (p == NULL) {
6813 warnx("not a valid user");
6814 return (FALSE);
6817 n = recv(s, str, sizeof(str), 0);
6818 if (n <= 0)
6819 return (TRUE);
6821 tt = TAILQ_LAST(&tabs, tab_list);
6822 cmd_execute(tt, str);
6823 return (TRUE);
6827 is_running(void)
6829 int s, len, rv = 1;
6830 struct sockaddr_un sa;
6832 if ((s = socket(AF_UNIX, SOCK_STREAM, 0)) == -1) {
6833 warn("is_running: socket");
6834 return (-1);
6837 sa.sun_family = AF_UNIX;
6838 snprintf(sa.sun_path, sizeof(sa.sun_path), "%s/%s",
6839 work_dir, XT_SOCKET_FILE);
6840 len = SUN_LEN(&sa);
6842 /* connect to see if there is a listener */
6843 if (connect(s, (struct sockaddr *)&sa, len) == -1)
6844 rv = 0; /* not running */
6845 else
6846 rv = 1; /* already running */
6848 close(s);
6850 return (rv);
6854 build_socket(void)
6856 int s, len;
6857 struct sockaddr_un sa;
6859 if ((s = socket(AF_UNIX, SOCK_STREAM, 0)) == -1) {
6860 warn("build_socket: socket");
6861 return (-1);
6864 sa.sun_family = AF_UNIX;
6865 snprintf(sa.sun_path, sizeof(sa.sun_path), "%s/%s",
6866 work_dir, XT_SOCKET_FILE);
6867 len = SUN_LEN(&sa);
6869 /* connect to see if there is a listener */
6870 if (connect(s, (struct sockaddr *)&sa, len) == -1) {
6871 /* no listener so we will */
6872 unlink(sa.sun_path);
6874 if (bind(s, (struct sockaddr *)&sa, len) == -1) {
6875 warn("build_socket: bind");
6876 goto done;
6879 if (listen(s, 1) == -1) {
6880 warn("build_socket: listen");
6881 goto done;
6884 return (s);
6887 done:
6888 close(s);
6889 return (-1);
6892 gboolean
6893 completion_select_cb(GtkEntryCompletion *widget, GtkTreeModel *model,
6894 GtkTreeIter *iter, struct tab *t)
6896 gchar *value;
6898 gtk_tree_model_get(model, iter, 0, &value, -1);
6899 load_uri(t, value);
6900 g_free(value);
6902 return (FALSE);
6905 gboolean
6906 completion_hover_cb(GtkEntryCompletion *widget, GtkTreeModel *model,
6907 GtkTreeIter *iter, struct tab *t)
6909 gchar *value;
6911 gtk_tree_model_get(model, iter, 0, &value, -1);
6912 gtk_entry_set_text(GTK_ENTRY(t->uri_entry), value);
6913 gtk_editable_set_position(GTK_EDITABLE(t->uri_entry), -1);
6914 g_free(value);
6916 return (TRUE);
6919 void
6920 completion_add_uri(const gchar *uri)
6922 GtkTreeIter iter;
6924 /* add uri to list_store */
6925 gtk_list_store_append(completion_model, &iter);
6926 gtk_list_store_set(completion_model, &iter, 0, uri, -1);
6929 gboolean
6930 completion_match(GtkEntryCompletion *completion, const gchar *key,
6931 GtkTreeIter *iter, gpointer user_data)
6933 gchar *value;
6934 gboolean match = FALSE;
6936 gtk_tree_model_get(GTK_TREE_MODEL(completion_model), iter, 0, &value,
6937 -1);
6939 if (value == NULL)
6940 return FALSE;
6942 match = match_uri(value, key);
6944 g_free(value);
6945 return (match);
6948 void
6949 completion_add(struct tab *t)
6951 /* enable completion for tab */
6952 t->completion = gtk_entry_completion_new();
6953 gtk_entry_completion_set_text_column(t->completion, 0);
6954 gtk_entry_set_completion(GTK_ENTRY(t->uri_entry), t->completion);
6955 gtk_entry_completion_set_model(t->completion,
6956 GTK_TREE_MODEL(completion_model));
6957 gtk_entry_completion_set_match_func(t->completion, completion_match,
6958 NULL, NULL);
6959 gtk_entry_completion_set_minimum_key_length(t->completion, 1);
6960 gtk_entry_completion_set_inline_selection(t->completion, TRUE);
6961 g_signal_connect(G_OBJECT (t->completion), "match-selected",
6962 G_CALLBACK(completion_select_cb), t);
6963 g_signal_connect(G_OBJECT (t->completion), "cursor-on-match",
6964 G_CALLBACK(completion_hover_cb), t);
6967 void
6968 xxx_dir(char *dir)
6970 struct stat sb;
6972 if (stat(dir, &sb)) {
6973 if (mkdir(dir, S_IRWXU) == -1)
6974 err(1, "mkdir %s", dir);
6975 if (stat(dir, &sb))
6976 err(1, "stat %s", dir);
6978 if (S_ISDIR(sb.st_mode) == 0)
6979 errx(1, "%s not a dir", dir);
6980 if (((sb.st_mode & (S_IRWXU | S_IRWXG | S_IRWXO))) != S_IRWXU) {
6981 warnx("fixing invalid permissions on %s", dir);
6982 if (chmod(dir, S_IRWXU) == -1)
6983 err(1, "chmod %s", dir);
6987 void
6988 usage(void)
6990 fprintf(stderr,
6991 "%s [-nSTVt][-f file][-s session] url ...\n", __progname);
6992 exit(0);
6995 GStaticRecMutex my_gdk_mtx = G_STATIC_REC_MUTEX_INIT;
6996 volatile int mtx_depth;
6997 int mtx_complain;
7000 * The linux flash plugin violates the gdk locking mechanism.
7001 * Work around the issue by using a recursive mutex with some match applied
7002 * to see if we hit a buggy condition.
7004 * The following code is painful so just don't read it. It really doesn't
7005 * make much sense but seems to work.
7007 void
7008 mtx_lock(void)
7010 g_static_rec_mutex_lock(&my_gdk_mtx);
7011 mtx_depth++;
7013 if (mtx_depth <= 0) {
7014 /* should not happen */
7015 show_oops(NULL, "negative mutex locking bug, trying to "
7016 "correct");
7017 fprintf(stderr, "negative mutex locking bug, trying to "
7018 "correct\n");
7019 g_static_rec_mutex_unlock_full(&my_gdk_mtx);
7020 g_static_rec_mutex_lock(&my_gdk_mtx);
7021 mtx_depth = 1;
7022 return;
7025 if (mtx_depth != 1) {
7026 /* decrease mutext depth to 1 */
7027 do {
7028 g_static_rec_mutex_unlock(&my_gdk_mtx);
7029 mtx_depth--;
7030 } while (mtx_depth > 1);
7034 void
7035 mtx_unlock(void)
7037 guint x;
7039 /* if mutex depth isn't 1 then something went bad */
7040 if (mtx_depth != 1) {
7041 x = g_static_rec_mutex_unlock_full(&my_gdk_mtx);
7042 if (x != 1) {
7043 /* should not happen */
7044 show_oops(NULL, "mutex unlocking bug, trying to "
7045 "correct");
7046 fprintf(stderr, "mutex unlocking bug, trying to "
7047 "correct\n");
7049 mtx_depth = 0;
7050 if (mtx_complain == 0) {
7051 show_oops(NULL, "buggy mutex implementation detected, "
7052 "work around implemented");
7053 fprintf(stderr, "buggy mutex implementation detected, "
7054 "work around implemented");
7055 mtx_complain = 1;
7057 return;
7060 mtx_depth--;
7061 g_static_rec_mutex_unlock(&my_gdk_mtx);
7065 main(int argc, char *argv[])
7067 struct stat sb;
7068 int c, s, optn = 0, opte = 0, focus = 1;
7069 char conf[PATH_MAX] = { '\0' };
7070 char file[PATH_MAX];
7071 char *env_proxy = NULL;
7072 char *cmd = NULL;
7073 FILE *f = NULL;
7074 struct karg a;
7075 struct sigaction sact;
7076 GIOChannel *channel;
7077 struct rlimit rlp;
7079 start_argv = argv;
7081 /* prepare gtk */
7082 #ifdef USE_THREADS
7083 g_thread_init(NULL);
7084 gdk_threads_set_lock_functions(mtx_lock, mtx_unlock);
7085 gdk_threads_init();
7086 gdk_threads_enter();
7088 gcry_control (GCRYCTL_SET_THREAD_CBS, &gcry_threads_pthread);
7089 #endif
7090 gtk_init(&argc, &argv);
7092 gnutls_global_init();
7094 strlcpy(named_session, XT_SAVED_TABS_FILE, sizeof named_session);
7096 RB_INIT(&hl);
7097 RB_INIT(&js_wl);
7098 RB_INIT(&pl_wl);
7099 RB_INIT(&downloads);
7101 TAILQ_INIT(&sessions);
7102 TAILQ_INIT(&tabs);
7103 TAILQ_INIT(&mtl);
7104 TAILQ_INIT(&aliases);
7105 TAILQ_INIT(&undos);
7106 TAILQ_INIT(&kbl);
7107 TAILQ_INIT(&spl);
7108 TAILQ_INIT(&chl);
7109 TAILQ_INIT(&shl);
7111 /* fiddle with ulimits */
7112 if (getrlimit(RLIMIT_NOFILE, &rlp) == -1)
7113 warn("getrlimit");
7114 else {
7115 /* just use them all */
7116 rlp.rlim_cur = rlp.rlim_max;
7117 if (setrlimit(RLIMIT_NOFILE, &rlp) == -1)
7118 warn("setrlimit");
7119 if (getrlimit(RLIMIT_NOFILE, &rlp) == -1)
7120 warn("getrlimit");
7121 else if (rlp.rlim_cur <= 256)
7122 startpage_add("%s requires at least 256 file "
7123 "descriptors, currently it has up to %d available",
7124 __progname, rlp.rlim_cur);
7127 while ((c = getopt(argc, argv, "STVf:s:tne")) != -1) {
7128 switch (c) {
7129 case 'S':
7130 show_url = 0;
7131 break;
7132 case 'T':
7133 show_tabs = 0;
7134 break;
7135 case 'V':
7136 errx(0 , "Version: %s", version);
7137 break;
7138 case 'f':
7139 strlcpy(conf, optarg, sizeof(conf));
7140 break;
7141 case 's':
7142 strlcpy(named_session, optarg, sizeof(named_session));
7143 break;
7144 case 't':
7145 tabless = 1;
7146 break;
7147 case 'n':
7148 optn = 1;
7149 break;
7150 case 'e':
7151 opte = 1;
7152 break;
7153 default:
7154 usage();
7155 /* NOTREACHED */
7158 argc -= optind;
7159 argv += optind;
7161 init_keybindings();
7163 xtp_generate_keys();
7165 /* signals */
7166 bzero(&sact, sizeof(sact));
7167 sigemptyset(&sact.sa_mask);
7168 sact.sa_handler = sigchild;
7169 sact.sa_flags = SA_NOCLDSTOP;
7170 sigaction(SIGCHLD, &sact, NULL);
7172 /* set download dir */
7173 pwd = getpwuid(getuid());
7174 if (pwd == NULL)
7175 errx(1, "invalid user %d", getuid());
7176 strlcpy(download_dir, pwd->pw_dir, sizeof download_dir);
7178 /* compile buffer command regexes */
7179 buffercmd_init();
7181 /* set default string settings */
7182 home = g_strdup("https://www.cyphertite.com");
7183 search_string = g_strdup("https://ssl.scroogle.org/cgi-bin/nbbwssl.cgi?Gw=%s");
7184 resource_dir = g_strdup("/usr/local/share/xxxterm/");
7185 strlcpy(runtime_settings, "runtime", sizeof runtime_settings);
7186 cmd_font_name = g_strdup("monospace normal 9");
7187 oops_font_name = g_strdup("monospace normal 9");
7188 statusbar_font_name = g_strdup("monospace normal 9");
7189 tabbar_font_name = g_strdup("monospace normal 9");
7190 statusbar_elems = g_strdup("BP");
7191 encoding = g_strdup("UTF-8");
7193 /* read config file */
7194 if (strlen(conf) == 0)
7195 snprintf(conf, sizeof conf, "%s/.%s",
7196 pwd->pw_dir, XT_CONF_FILE);
7197 config_parse(conf, 0);
7199 /* init fonts */
7200 cmd_font = pango_font_description_from_string(cmd_font_name);
7201 oops_font = pango_font_description_from_string(oops_font_name);
7202 statusbar_font = pango_font_description_from_string(statusbar_font_name);
7203 tabbar_font = pango_font_description_from_string(tabbar_font_name);
7205 /* working directory */
7206 if (strlen(work_dir) == 0)
7207 snprintf(work_dir, sizeof work_dir, "%s/%s",
7208 pwd->pw_dir, XT_DIR);
7209 xxx_dir(work_dir);
7211 /* icon cache dir */
7212 snprintf(cache_dir, sizeof cache_dir, "%s/%s", work_dir, XT_CACHE_DIR);
7213 xxx_dir(cache_dir);
7215 /* certs dir */
7216 snprintf(certs_dir, sizeof certs_dir, "%s/%s", work_dir, XT_CERT_DIR);
7217 xxx_dir(certs_dir);
7219 /* sessions dir */
7220 snprintf(sessions_dir, sizeof sessions_dir, "%s/%s",
7221 work_dir, XT_SESSIONS_DIR);
7222 xxx_dir(sessions_dir);
7224 /* js dir */
7225 snprintf(js_dir, sizeof js_dir, "%s/%s", work_dir, XT_JS_DIR);
7226 xxx_dir(js_dir);
7228 /* runtime settings that can override config file */
7229 if (runtime_settings[0] != '\0')
7230 config_parse(runtime_settings, 1);
7232 /* download dir */
7233 if (!strcmp(download_dir, pwd->pw_dir))
7234 strlcat(download_dir, "/downloads", sizeof download_dir);
7235 xxx_dir(download_dir);
7237 /* favorites file */
7238 snprintf(file, sizeof file, "%s/%s", work_dir, XT_FAVS_FILE);
7239 if (stat(file, &sb)) {
7240 warnx("favorites file doesn't exist, creating it");
7241 if ((f = fopen(file, "w")) == NULL)
7242 err(1, "favorites");
7243 fclose(f);
7246 /* quickmarks file */
7247 snprintf(file, sizeof file, "%s/%s", work_dir, XT_QMARKS_FILE);
7248 if (stat(file, &sb)) {
7249 warnx("quickmarks file doesn't exist, creating it");
7250 if ((f = fopen(file, "w")) == NULL)
7251 err(1, "quickmarks");
7252 fclose(f);
7255 /* search history */
7256 if (history_autosave) {
7257 snprintf(search_file, sizeof search_file, "%s/%s",
7258 work_dir, XT_SEARCH_FILE);
7259 if (stat(search_file, &sb)) {
7260 warnx("search history file doesn't exist, creating it");
7261 if ((f = fopen(search_file, "w")) == NULL)
7262 err(1, "search_history");
7263 fclose(f);
7265 history_read(&shl, search_file, &search_history_count);
7268 /* command history */
7269 if (history_autosave) {
7270 snprintf(command_file, sizeof command_file, "%s/%s",
7271 work_dir, XT_COMMAND_FILE);
7272 if (stat(command_file, &sb)) {
7273 warnx("command history file doesn't exist, creating it");
7274 if ((f = fopen(command_file, "w")) == NULL)
7275 err(1, "command_history");
7276 fclose(f);
7278 history_read(&chl, command_file, &cmd_history_count);
7281 /* cookies */
7282 session = webkit_get_default_session();
7283 setup_cookies();
7285 /* certs */
7286 if (ssl_ca_file) {
7287 if (stat(ssl_ca_file, &sb)) {
7288 warnx("no CA file: %s", ssl_ca_file);
7289 g_free(ssl_ca_file);
7290 ssl_ca_file = NULL;
7291 } else
7292 g_object_set(session,
7293 SOUP_SESSION_SSL_CA_FILE, ssl_ca_file,
7294 SOUP_SESSION_SSL_STRICT, ssl_strict_certs,
7295 (void *)NULL);
7298 /* guess_search regex */
7299 if (url_regex == NULL)
7300 url_regex = g_strdup(XT_URL_REGEX);
7301 if (url_regex)
7302 if (regcomp(&url_re, url_regex, REG_EXTENDED | REG_NOSUB))
7303 startpage_add("invalid url regex %s", url_regex);
7305 /* proxy */
7306 env_proxy = getenv("http_proxy");
7307 if (env_proxy)
7308 setup_proxy(env_proxy);
7309 else
7310 setup_proxy(http_proxy);
7312 if (opte) {
7313 send_cmd_to_socket(argv[0]);
7314 exit(0);
7317 /* set some connection parameters */
7318 g_object_set(session, "max-conns", max_connections, (char *)NULL);
7319 g_object_set(session, "max-conns-per-host", max_host_connections,
7320 (char *)NULL);
7322 /* see if there is already an xxxterm running */
7323 if (single_instance && is_running()) {
7324 optn = 1;
7325 warnx("already running");
7328 if (optn) {
7329 while (argc) {
7330 cmd = g_strdup_printf("%s %s", "tabnew", argv[0]);
7331 send_cmd_to_socket(cmd);
7332 if (cmd)
7333 g_free(cmd);
7335 argc--;
7336 argv++;
7338 exit(0);
7341 /* uri completion */
7342 completion_model = gtk_list_store_new(1, G_TYPE_STRING);
7344 /* buffers */
7345 buffers_store = gtk_list_store_new
7346 (NUM_COLS, G_TYPE_UINT, G_TYPE_STRING);
7348 qmarks_load();
7350 /* go graphical */
7351 create_canvas();
7352 notebook_tab_set_visibility();
7354 if (save_global_history)
7355 restore_global_history();
7357 /* restore session list */
7358 restore_sessions_list();
7360 if (!strcmp(named_session, XT_SAVED_TABS_FILE))
7361 restore_saved_tabs();
7362 else {
7363 a.s = named_session;
7364 a.i = XT_SES_DONOTHING;
7365 open_tabs(NULL, &a);
7368 /* see if we have an exception */
7369 if (!TAILQ_EMPTY(&spl)) {
7370 create_new_tab("about:startpage", NULL, focus, -1);
7371 focus = 0;
7374 while (argc) {
7375 create_new_tab(argv[0], NULL, focus, -1);
7376 focus = 0;
7378 argc--;
7379 argv++;
7382 if (TAILQ_EMPTY(&tabs))
7383 create_new_tab(home, NULL, 1, -1);
7385 if (enable_socket)
7386 if ((s = build_socket()) != -1) {
7387 channel = g_io_channel_unix_new(s);
7388 g_io_add_watch(channel, G_IO_IN, socket_watcher, NULL);
7391 gtk_main();
7393 #ifdef USE_THREADS
7394 gdk_threads_leave();
7395 g_static_rec_mutex_unlock_full(&my_gdk_mtx); /* just in case */
7396 #endif
7398 gnutls_global_deinit();
7400 if (url_regex)
7401 regfree(&url_re);
7403 return (0);