add a welcome screen for start of day and upgrades and use it to announce the name...
[xombrero.git] / xxxterm.c
blob2526ccbb642e9762736506bc429c64015f3286b6
1 /*
2 * Copyright (c) 2010, 2011 Marco Peereboom <marco@peereboom.us>
3 * Copyright (c) 2011 Stevan Andjelkovic <stevan@student.chalmers.se>
4 * Copyright (c) 2010, 2011, 2012 Edd Barrett <vext01@gmail.com>
5 * Copyright (c) 2011 Todd T. Fries <todd@fries.net>
6 * Copyright (c) 2011 Raphael Graf <r@undefined.ch>
7 * Copyright (c) 2011 Michal Mazurek <akfaew@jasminek.net>
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>
23 #include "version.h"
25 char *version = XXXTERM_VERSION;
27 #ifdef XT_DEBUG
28 uint32_t swm_debug = 0
29 | XT_D_MOVE
30 | XT_D_KEY
31 | XT_D_TAB
32 | XT_D_URL
33 | XT_D_CMD
34 | XT_D_NAV
35 | XT_D_DOWNLOAD
36 | XT_D_CONFIG
37 | XT_D_JS
38 | XT_D_FAVORITE
39 | XT_D_PRINTING
40 | XT_D_COOKIE
41 | XT_D_KEYBINDING
42 | XT_D_CLIP
43 | XT_D_BUFFERCMD
44 | XT_D_INSPECTOR
45 | XT_D_VISITED
46 | XT_D_HISTORY
48 #endif
50 #ifdef USE_THREADS
51 GCRY_THREAD_OPTION_PTHREAD_IMPL;
52 #endif
54 char *icons[] = {
55 "xxxtermicon16.png",
56 "xxxtermicon32.png",
57 "xxxtermicon48.png",
58 "xxxtermicon64.png",
59 "xxxtermicon128.png"
62 struct session {
63 TAILQ_ENTRY(session) entry;
64 const gchar *name;
66 TAILQ_HEAD(session_list, session);
68 struct undo {
69 TAILQ_ENTRY(undo) entry;
70 gchar *uri;
71 GList *history;
72 int back; /* Keeps track of how many back
73 * history items there are. */
75 TAILQ_HEAD(undo_tailq, undo);
77 struct command_entry {
78 char *line;
79 TAILQ_ENTRY(command_entry) entry;
81 TAILQ_HEAD(command_list, command_entry);
83 /* defines */
84 #define XT_DIR (".xxxterm")
85 #define XT_CACHE_DIR ("cache")
86 #define XT_CERT_DIR ("certs")
87 #define XT_JS_DIR ("js")
88 #define XT_SESSIONS_DIR ("sessions")
89 #define XT_TEMP_DIR ("tmp")
90 #define XT_CONF_FILE ("xxxterm.conf")
91 #define XT_QMARKS_FILE ("quickmarks")
92 #define XT_SAVED_TABS_FILE ("main_session")
93 #define XT_RESTART_TABS_FILE ("restart_tabs")
94 #define XT_SOCKET_FILE ("socket")
95 #define XT_SAVE_SESSION_ID ("SESSION_NAME=")
96 #define XT_SEARCH_FILE ("search_history")
97 #define XT_COMMAND_FILE ("command_history")
98 #define XT_DLMAN_REFRESH "10"
99 #define XT_MAX_URL_LENGTH (4096) /* 1 page is atomic, don't make bigger */
100 #define XT_MAX_UNDO_CLOSE_TAB (32)
101 #define XT_RESERVED_CHARS "$&+,/:;=?@ \"<>#%%{}|^~[]`"
102 #define XT_PRINT_EXTRA_MARGIN 10
103 #define XT_URL_REGEX ("^[[:blank:]]*[^[:blank:]]*([[:alnum:]-]+\\.)+[[:alnum:]-][^[:blank:]]*[[:blank:]]*$")
104 #define XT_INVALID_MARK (-1) /* XXX this is a double, maybe use something else, like a nan */
106 /* colors */
107 #define XT_COLOR_RED "#cc0000"
108 #define XT_COLOR_YELLOW "#ffff66"
109 #define XT_COLOR_BLUE "lightblue"
110 #define XT_COLOR_GREEN "#99ff66"
111 #define XT_COLOR_WHITE "white"
112 #define XT_COLOR_BLACK "black"
114 #define XT_COLOR_CT_BACKGROUND "#000000"
115 #define XT_COLOR_CT_INACTIVE "#dddddd"
116 #define XT_COLOR_CT_ACTIVE "#bbbb00"
117 #define XT_COLOR_CT_SEPARATOR "#555555"
119 #define XT_COLOR_SB_SEPARATOR "#555555"
121 #define XT_PROTO_DELIM "://"
123 /* actions */
124 #define XT_MOVE_INVALID (0)
125 #define XT_MOVE_DOWN (1)
126 #define XT_MOVE_UP (2)
127 #define XT_MOVE_BOTTOM (3)
128 #define XT_MOVE_TOP (4)
129 #define XT_MOVE_PAGEDOWN (5)
130 #define XT_MOVE_PAGEUP (6)
131 #define XT_MOVE_HALFDOWN (7)
132 #define XT_MOVE_HALFUP (8)
133 #define XT_MOVE_LEFT (9)
134 #define XT_MOVE_FARLEFT (10)
135 #define XT_MOVE_RIGHT (11)
136 #define XT_MOVE_FARRIGHT (12)
137 #define XT_MOVE_PERCENT (13)
138 #define XT_MOVE_CENTER (14)
140 #define XT_QMARK_SET (0)
141 #define XT_QMARK_OPEN (1)
142 #define XT_QMARK_TAB (2)
144 #define XT_MARK_SET (0)
145 #define XT_MARK_GOTO (1)
147 #define XT_GO_UP_ROOT (999)
149 #define XT_TAB_LAST (-4)
150 #define XT_TAB_FIRST (-3)
151 #define XT_TAB_PREV (-2)
152 #define XT_TAB_NEXT (-1)
153 #define XT_TAB_INVALID (0)
154 #define XT_TAB_NEW (1)
155 #define XT_TAB_DELETE (2)
156 #define XT_TAB_DELQUIT (3)
157 #define XT_TAB_OPEN (4)
158 #define XT_TAB_UNDO_CLOSE (5)
159 #define XT_TAB_SHOW (6)
160 #define XT_TAB_HIDE (7)
161 #define XT_TAB_NEXTSTYLE (8)
162 #define XT_TAB_LOAD_IMAGES (9)
164 #define XT_NAV_INVALID (0)
165 #define XT_NAV_BACK (1)
166 #define XT_NAV_FORWARD (2)
167 #define XT_NAV_RELOAD (3)
168 #define XT_NAV_STOP (4)
170 #define XT_FOCUS_INVALID (0)
171 #define XT_FOCUS_URI (1)
172 #define XT_FOCUS_SEARCH (2)
174 #define XT_SEARCH_INVALID (0)
175 #define XT_SEARCH_NEXT (1)
176 #define XT_SEARCH_PREV (2)
178 #define XT_STYLE_CURRENT_TAB (0)
179 #define XT_STYLE_GLOBAL (1)
181 #define XT_PASTE_CURRENT_TAB (0)
182 #define XT_PASTE_NEW_TAB (1)
184 #define XT_ZOOM_IN (-1)
185 #define XT_ZOOM_OUT (-2)
186 #define XT_ZOOM_NORMAL (100)
188 #define XT_URL_SHOW (1)
189 #define XT_URL_HIDE (2)
191 #define XT_CMD_OPEN (0)
192 #define XT_CMD_OPEN_CURRENT (1)
193 #define XT_CMD_TABNEW (2)
194 #define XT_CMD_TABNEW_CURRENT (3)
196 #define XT_STATUS_NOTHING (0)
197 #define XT_STATUS_LINK (1)
198 #define XT_STATUS_URI (2)
199 #define XT_STATUS_LOADING (3)
201 #define XT_SES_DONOTHING (0)
202 #define XT_SES_CLOSETABS (1)
204 #define XT_PREFIX (1<<0)
205 #define XT_USERARG (1<<1)
206 #define XT_URLARG (1<<2)
207 #define XT_INTARG (1<<3)
208 #define XT_SESSARG (1<<4)
209 #define XT_SETARG (1<<5)
211 #define XT_HINT_NEWTAB (1<<0)
213 #define XT_BUFCMD_SZ (8)
215 #define XT_EJS_SHOW (1<<0)
217 GtkWidget * create_button(char *, char *, int);
219 void recalc_tabs(void);
220 void recolor_compact_tabs(void);
221 void set_current_tab(int page_num);
222 gboolean update_statusbar_position(GtkAdjustment*, gpointer);
223 void marks_clear(struct tab *t);
225 /* globals */
226 extern char *__progname;
227 char * const *start_argv;
228 struct passwd *pwd;
229 GtkWidget *main_window;
230 GtkNotebook *notebook;
231 GtkWidget *tab_bar;
232 GtkWidget *arrow, *abtn;
233 struct tab_list tabs;
234 struct history_list hl;
235 int hl_purge_count = 0;
236 struct session_list sessions;
237 struct domain_list c_wl;
238 struct domain_list js_wl;
239 struct domain_list pl_wl;
240 struct strict_transport_tree st_tree;
241 struct undo_tailq undos;
242 struct keybinding_list kbl;
243 struct sp_list spl;
244 struct user_agent_list ua_list;
245 int user_agent_count = 0;
246 struct command_list chl;
247 struct command_list shl;
248 struct command_entry *history_at;
249 struct command_entry *search_at;
250 int undo_count;
251 int cmd_history_count = 0;
252 int search_history_count = 0;
253 char *global_search;
254 uint64_t blocked_cookies = 0;
255 char named_session[PATH_MAX];
256 GtkListStore *completion_model;
257 GtkListStore *buffers_store;
259 char *qmarks[XT_NOMARKS];
260 int btn_down; /* M1 down in any wv */
261 regex_t url_re; /* guess_search regex */
263 /* starts from 1 to catch atoi() failures when calling xtp_handle_dl() */
264 int next_download_id = 1;
266 void xxx_dir(char *);
267 int icon_size_map(int);
269 void
270 history_delete(struct command_list *l, int *counter)
272 struct command_entry *c;
274 if (l == NULL || counter == NULL)
275 return;
277 c = TAILQ_LAST(l, command_list);
278 if (c == NULL)
279 return;
281 TAILQ_REMOVE(l, c, entry);
282 *counter -= 1;
283 g_free(c->line);
284 g_free(c);
287 void
288 history_add(struct command_list *list, char *file, char *l, int *counter)
290 struct command_entry *c;
291 FILE *f;
293 if (list == NULL || l == NULL || counter == NULL)
294 return;
296 /* don't add the same line */
297 c = TAILQ_FIRST(list);
298 if (c)
299 if (!strcmp(c->line + 1 /* skip space */, l))
300 return;
302 c = g_malloc0(sizeof *c);
303 c->line = g_strdup_printf(" %s", l);
305 *counter += 1;
306 TAILQ_INSERT_HEAD(list, c, entry);
308 if (*counter > 1000)
309 history_delete(list, counter);
311 if (history_autosave && file) {
312 f = fopen(file, "w");
313 if (f == NULL) {
314 show_oops(NULL, "couldn't write history %s", file);
315 return;
318 TAILQ_FOREACH_REVERSE(c, list, command_list, entry) {
319 c->line[0] = ' ';
320 fprintf(f, "%s\n", c->line);
323 fclose(f);
328 history_read(struct command_list *list, char *file, int *counter)
330 FILE *f;
331 char *s, line[65536];
333 if (list == NULL || file == NULL)
334 return (1);
336 f = fopen(file, "r");
337 if (f == NULL) {
338 startpage_add("couldn't open history file %s", file);
339 return (1);
342 for (;;) {
343 s = fgets(line, sizeof line, f);
344 if (s == NULL || feof(f) || ferror(f))
345 break;
346 if ((s = strchr(line, '\n')) == NULL) {
347 startpage_add("invalid history file %s", file);
348 fclose(f);
349 return (1);
351 *s = '\0';
353 history_add(list, NULL, line + 1, counter);
356 fclose(f);
358 return (0);
361 /* marks and quickmarks array storage.
362 * first a-z, then A-Z, then 0-9 */
363 char
364 indextomark(int i)
366 if (i < 0)
367 return (0);
369 if (i >= 0 && i <= 'z' - 'a')
370 return 'a' + i;
372 i -= 'z' - 'a' + 1;
373 if (i >= 0 && i <= 'Z' - 'A')
374 return 'A' + i;
376 i -= 'Z' - 'A' + 1;
377 if (i >= 10)
378 return (0);
380 return i + '0';
384 marktoindex(char m)
386 int ret = 0;
388 if (m >= 'a' && m <= 'z')
389 return ret + m - 'a';
391 ret += 'z' - 'a' + 1;
392 if (m >= 'A' && m <= 'Z')
393 return ret + m - 'A';
395 ret += 'Z' - 'A' + 1;
396 if (m >= '0' && m <= '9')
397 return ret + m - '0';
399 return (-1);
402 #ifndef XT_SIGNALS_DISABLE
403 void
404 sigchild(int sig)
406 int saved_errno, status;
407 pid_t pid;
409 saved_errno = errno;
411 while ((pid = waitpid(WAIT_ANY, &status, WNOHANG)) != 0) {
412 if (pid == -1) {
413 if (errno == EINTR)
414 continue;
415 if (errno != ECHILD) {
417 clog_warn("sigchild: waitpid:");
420 break;
423 if (WIFEXITED(status)) {
424 if (WEXITSTATUS(status) != 0) {
426 clog_warnx("sigchild: child exit status: %d",
427 WEXITSTATUS(status));
430 } else {
432 clog_warnx("sigchild: child is terminated abnormally");
437 errno = saved_errno;
439 #endif
442 is_g_object_setting(GObject *o, char *str)
444 guint n_props = 0, i;
445 GParamSpec **proplist;
446 int rv = 0;
448 if (!G_IS_OBJECT(o))
449 return (0);
451 proplist = g_object_class_list_properties(G_OBJECT_GET_CLASS(o),
452 &n_props);
454 for (i = 0; i < n_props; i++) {
455 if (! strcmp(proplist[i]->name, str)) {
456 rv = 1;
457 break;
461 g_free(proplist);
462 return (rv);
465 struct tab *
466 get_current_tab(void)
468 struct tab *t;
470 TAILQ_FOREACH(t, &tabs, entry) {
471 if (t->tab_id == gtk_notebook_get_current_page(notebook))
472 return (t);
475 warnx("%s: no current tab", __func__);
477 return (NULL);
480 void
481 set_status(struct tab *t, gchar *s, int status)
483 gchar *type = NULL;
485 if (s == NULL)
486 return;
488 switch (status) {
489 case XT_STATUS_LOADING:
490 type = g_strdup_printf("Loading: %s", s);
491 s = type;
492 break;
493 case XT_STATUS_LINK:
494 type = g_strdup_printf("Link: %s", s);
495 if (!t->status)
496 t->status = g_strdup(gtk_entry_get_text(
497 GTK_ENTRY(t->sbe.statusbar)));
498 s = type;
499 break;
500 case XT_STATUS_URI:
501 type = g_strdup_printf("%s", s);
502 if (!t->status) {
503 t->status = g_strdup(type);
505 s = type;
506 if (!t->status)
507 t->status = g_strdup(s);
508 break;
509 case XT_STATUS_NOTHING:
510 /* FALL THROUGH */
511 default:
512 break;
514 gtk_entry_set_text(GTK_ENTRY(t->sbe.statusbar), s);
515 if (type)
516 g_free(type);
519 void
520 hide_cmd(struct tab *t)
522 DNPRINTF(XT_D_CMD, "%s: tab %d\n", __func__, t->tab_id);
524 history_at = NULL; /* just in case */
525 search_at = NULL; /* just in case */
526 gtk_widget_hide(t->cmd);
529 void
530 show_cmd(struct tab *t)
532 DNPRINTF(XT_D_CMD, "%s: tab %d\n", __func__, t->tab_id);
534 history_at = NULL;
535 search_at = NULL;
536 gtk_widget_hide(t->oops);
537 gtk_widget_show(t->cmd);
540 void
541 hide_buffers(struct tab *t)
543 gtk_widget_hide(t->buffers);
544 gtk_list_store_clear(buffers_store);
547 enum {
548 COL_ID = 0,
549 COL_FAVICON,
550 COL_TITLE,
551 NUM_COLS
555 sort_tabs_by_page_num(struct tab ***stabs)
557 int num_tabs = 0;
558 struct tab *t;
560 num_tabs = gtk_notebook_get_n_pages(notebook);
562 *stabs = g_malloc0(num_tabs * sizeof(struct tab *));
564 TAILQ_FOREACH(t, &tabs, entry)
565 (*stabs)[gtk_notebook_page_num(notebook, t->vbox)] = t;
567 return (num_tabs);
570 void
571 buffers_make_list(void)
573 int i, num_tabs;
574 const gchar *title = NULL;
575 GtkTreeIter iter;
576 struct tab **stabs = NULL;
578 num_tabs = sort_tabs_by_page_num(&stabs);
580 for (i = 0; i < num_tabs; i++)
581 if (stabs[i]) {
582 gtk_list_store_append(buffers_store, &iter);
583 title = get_title(stabs[i], FALSE);
584 gtk_list_store_set(buffers_store, &iter,
585 COL_ID, i + 1, /* Enumerate the tabs starting from 1
586 * rather than 0. */
587 COL_FAVICON, gtk_image_get_pixbuf
588 (GTK_IMAGE(stabs[i]->tab_elems.favicon)),
589 COL_TITLE, title,
590 -1);
593 g_free(stabs);
596 void
597 show_buffers(struct tab *t)
599 if (gtk_widget_get_visible(GTK_WIDGET(t->buffers)))
600 return;
602 buffers_make_list();
603 gtk_widget_show(t->buffers);
604 gtk_widget_grab_focus(GTK_WIDGET(t->buffers));
607 void
608 toggle_buffers(struct tab *t)
610 if (gtk_widget_get_visible(t->buffers))
611 hide_buffers(t);
612 else
613 show_buffers(t);
617 buffers(struct tab *t, struct karg *args)
619 show_buffers(t);
621 return (0);
624 void
625 hide_oops(struct tab *t)
627 gtk_widget_hide(t->oops);
630 void
631 show_oops(struct tab *at, const char *fmt, ...)
633 va_list ap;
634 char *msg = NULL;
635 struct tab *t = NULL;
637 if (fmt == NULL)
638 return;
640 if (at == NULL) {
641 if ((t = get_current_tab()) == NULL)
642 return;
643 } else
644 t = at;
646 va_start(ap, fmt);
647 if (vasprintf(&msg, fmt, ap) == -1)
648 errx(1, "show_oops failed");
649 va_end(ap);
651 gtk_entry_set_text(GTK_ENTRY(t->oops), msg);
652 gtk_widget_hide(t->cmd);
653 gtk_widget_show(t->oops);
655 if (msg)
656 free(msg);
659 char work_dir[PATH_MAX];
660 char certs_dir[PATH_MAX];
661 char js_dir[PATH_MAX];
662 char cache_dir[PATH_MAX];
663 char sessions_dir[PATH_MAX];
664 char temp_dir[PATH_MAX];
665 char cookie_file[PATH_MAX];
666 char *strict_transport_file = NULL;
667 SoupSession *session;
668 SoupCookieJar *s_cookiejar;
669 SoupCookieJar *p_cookiejar;
670 char rc_fname[PATH_MAX];
672 struct mime_type_list mtl;
673 struct alias_list aliases;
675 /* protos */
676 struct tab *create_new_tab(char *, struct undo *, int, int);
677 void delete_tab(struct tab *);
678 void setzoom_webkit(struct tab *, int);
679 int download_rb_cmp(struct download *, struct download *);
680 gboolean cmd_execute(struct tab *t, char *str);
683 history_rb_cmp(struct history *h1, struct history *h2)
685 return (strcmp(h1->uri, h2->uri));
687 RB_GENERATE(history_list, history, entry, history_rb_cmp);
690 domain_rb_cmp(struct domain *d1, struct domain *d2)
692 return (strcmp(d1->d, d2->d));
694 RB_GENERATE(domain_list, domain, entry, domain_rb_cmp);
697 download_rb_cmp(struct download *e1, struct download *e2)
699 return (e1->id < e2->id ? -1 : e1->id > e2->id);
701 RB_GENERATE(download_list, download, entry, download_rb_cmp);
703 struct valid_url_types {
704 char *type;
705 } vut[] = {
706 { "http://" },
707 { "https://" },
708 { "ftp://" },
709 { "file://" },
710 { XT_XTP_STR },
714 valid_url_type(char *url)
716 int i;
718 for (i = 0; i < LENGTH(vut); i++)
719 if (!strncasecmp(vut[i].type, url, strlen(vut[i].type)))
720 return (0);
722 return (1);
725 char *
726 match_alias(char *url_in)
728 struct alias *a;
729 char *arg;
730 char *url_out = NULL, *search, *enc_arg;
732 search = g_strdup(url_in);
733 arg = search;
734 if (strsep(&arg, " \t") == NULL) {
735 show_oops(NULL, "match_alias: NULL URL");
736 goto done;
739 TAILQ_FOREACH(a, &aliases, entry) {
740 if (!strcmp(search, a->a_name))
741 break;
744 if (a != NULL) {
745 DNPRINTF(XT_D_URL, "match_alias: matched alias %s\n",
746 a->a_name);
747 if (arg != NULL) {
748 enc_arg = soup_uri_encode(arg, XT_RESERVED_CHARS);
749 url_out = g_strdup_printf(a->a_uri, enc_arg);
750 g_free(enc_arg);
751 } else
752 url_out = g_strdup_printf(a->a_uri, "");
754 done:
755 g_free(search);
756 return (url_out);
759 char *
760 guess_url_type(char *url_in)
762 struct stat sb;
763 char *url_out = NULL, *enc_search = NULL;
764 int i;
765 char *cwd;
768 /* substitute aliases */
769 url_out = match_alias(url_in);
770 if (url_out != NULL)
771 return (url_out);
773 /* see if we are an about page */
774 if (!strncmp(url_in, XT_URI_ABOUT, XT_URI_ABOUT_LEN))
775 for (i = 0; i < about_list_size(); i++)
776 if (!strcmp(&url_in[XT_URI_ABOUT_LEN],
777 about_list[i].name)) {
778 url_out = g_strdup(url_in);
779 goto done;
782 if (guess_search && url_regex &&
783 !(g_str_has_prefix(url_in, "http://") ||
784 g_str_has_prefix(url_in, "https://"))) {
785 if (regexec(&url_re, url_in, 0, NULL, 0)) {
786 /* invalid URI so search instead */
787 enc_search = soup_uri_encode(url_in, XT_RESERVED_CHARS);
788 url_out = g_strdup_printf(search_string, enc_search);
789 g_free(enc_search);
790 goto done;
794 /* XXX not sure about this heuristic */
795 if (stat(url_in, &sb) == 0) {
796 if (url_in[0] == '/')
797 url_out = g_strdup_printf("file://%s", url_in);
798 else {
799 cwd = malloc(PATH_MAX);
800 if (getcwd(cwd, PATH_MAX) != NULL) {
801 url_out = g_strdup_printf("file://%s/%s",cwd, url_in);
803 free(cwd);
805 } else
806 url_out = g_strdup_printf("http://%s", url_in); /* guess http */
807 done:
808 DNPRINTF(XT_D_URL, "guess_url_type: guessed %s\n", url_out);
810 return (url_out);
813 void
814 load_uri(struct tab *t, gchar *uri)
816 struct karg args;
817 gchar *newuri = NULL;
818 int i;
820 if (uri == NULL)
821 return;
823 /* Strip leading spaces. */
824 while (*uri && isspace(*uri))
825 uri++;
827 if (strlen(uri) == 0) {
828 blank(t, NULL);
829 return;
832 t->xtp_meaning = XT_XTP_TAB_MEANING_NORMAL;
834 if (valid_url_type(uri)) {
835 newuri = guess_url_type(uri);
836 uri = newuri;
839 if (!strncmp(uri, XT_URI_ABOUT, XT_URI_ABOUT_LEN)) {
840 for (i = 0; i < about_list_size(); i++)
841 if (!strcmp(&uri[XT_URI_ABOUT_LEN], about_list[i].name)) {
842 bzero(&args, sizeof args);
843 about_list[i].func(t, &args);
844 gtk_widget_set_sensitive(GTK_WIDGET(t->stop),
845 FALSE);
846 goto done;
848 show_oops(t, "invalid about page");
849 goto done;
852 set_status(t, (char *)uri, XT_STATUS_LOADING);
853 marks_clear(t);
854 webkit_web_view_load_uri(t->wv, uri);
855 done:
856 if (newuri)
857 g_free(newuri);
860 const gchar *
861 get_uri(struct tab *t)
863 const gchar *uri = NULL;
865 if (webkit_web_view_get_load_status(t->wv) == WEBKIT_LOAD_FAILED)
866 return (NULL);
867 if (t->xtp_meaning == XT_XTP_TAB_MEANING_NORMAL) {
868 uri = webkit_web_view_get_uri(t->wv);
869 } else {
870 /* use tmp_uri to make sure it is g_freed */
871 if (t->tmp_uri)
872 g_free(t->tmp_uri);
873 t->tmp_uri =g_strdup_printf("%s%s", XT_URI_ABOUT,
874 about_list[t->xtp_meaning].name);
875 uri = t->tmp_uri;
877 return uri;
880 const gchar *
881 get_title(struct tab *t, bool window)
883 const gchar *set = NULL, *title = NULL;
884 WebKitLoadStatus status = webkit_web_view_get_load_status(t->wv);
886 if (status == WEBKIT_LOAD_PROVISIONAL || status == WEBKIT_LOAD_FAILED ||
887 t->xtp_meaning == XT_XTP_TAB_MEANING_BL)
888 goto notitle;
890 title = webkit_web_view_get_title(t->wv);
891 if ((set = title ? title : get_uri(t)))
892 return set;
894 notitle:
895 set = window ? XT_NAME : "(untitled)";
897 return set;
900 struct mime_type *
901 find_mime_type(char *mime_type)
903 struct mime_type *m, *def = NULL, *rv = NULL;
905 TAILQ_FOREACH(m, &mtl, entry) {
906 if (m->mt_default &&
907 !strncmp(mime_type, m->mt_type, strlen(m->mt_type)))
908 def = m;
910 if (m->mt_default == 0 && !strcmp(mime_type, m->mt_type)) {
911 rv = m;
912 break;
916 if (rv == NULL)
917 rv = def;
919 return (rv);
922 struct domain *
923 wl_find_uri(const gchar *s, struct domain_list *wl)
925 int i;
926 char *ss;
927 struct domain *r;
929 if (s == NULL || wl == NULL)
930 return (NULL);
932 if (!strncmp(s, "http://", strlen("http://")))
933 s = &s[strlen("http://")];
934 else if (!strncmp(s, "https://", strlen("https://")))
935 s = &s[strlen("https://")];
937 if (strlen(s) < 2)
938 return (NULL);
940 for (i = 0; i < strlen(s) + 1 /* yes er need this */; i++)
941 /* chop string at first slash */
942 if (s[i] == '/' || s[i] == ':' || s[i] == '\0') {
943 ss = g_strdup(s);
944 ss[i] = '\0';
945 r = wl_find(ss, wl);
946 g_free(ss);
947 return (r);
950 return (NULL);
953 char *
954 js_ref_to_string(JSContextRef context, JSValueRef ref)
956 char *s = NULL;
957 size_t l;
958 JSStringRef jsref;
960 jsref = JSValueToStringCopy(context, ref, NULL);
961 if (jsref == NULL)
962 return (NULL);
964 l = JSStringGetMaximumUTF8CStringSize(jsref);
965 s = g_malloc(l);
966 if (s)
967 JSStringGetUTF8CString(jsref, s, l);
968 JSStringRelease(jsref);
970 return (s);
973 #define XT_JS_DONE ("done;")
974 #define XT_JS_DONE_LEN (strlen(XT_JS_DONE))
975 #define XT_JS_INSERT ("insert;")
976 #define XT_JS_INSERT_LEN (strlen(XT_JS_INSERT))
979 run_script(struct tab *t, char *s)
981 JSGlobalContextRef ctx;
982 WebKitWebFrame *frame;
983 JSStringRef str;
984 JSValueRef val, exception;
985 char *es;
987 DNPRINTF(XT_D_JS, "%s: tab %d %s\n", __func__,
988 t->tab_id, s == (char *)JS_HINTING ? "JS_HINTING" : s);
990 frame = webkit_web_view_get_main_frame(t->wv);
991 ctx = webkit_web_frame_get_global_context(frame);
993 str = JSStringCreateWithUTF8CString(s);
994 val = JSEvaluateScript(ctx, str, JSContextGetGlobalObject(ctx),
995 NULL, 0, &exception);
996 JSStringRelease(str);
998 DNPRINTF(XT_D_JS, "%s: val %p\n", __func__, val);
999 if (val == NULL) {
1000 es = js_ref_to_string(ctx, exception);
1001 if (es) {
1002 DNPRINTF(XT_D_JS, "%s: exception %s\n", __func__, es);
1003 g_free(es);
1005 return (1);
1006 } else {
1007 es = js_ref_to_string(ctx, val);
1008 #if 0
1009 /* return values */
1010 if (!strncmp(es, XT_JS_DONE, XT_JS_DONE_LEN))
1011 ; /* do nothing */
1012 if (!strncmp(es, XT_JS_INSERT, XT_JS_INSERT_LEN))
1013 ; /* do nothing */
1014 #endif
1015 if (es) {
1016 DNPRINTF(XT_D_JS, "%s: val %s\n", __func__, es);
1017 g_free(es);
1021 return (0);
1024 void
1025 enable_hints(struct tab *t)
1027 DNPRINTF(XT_D_JS, "%s: tab %d\n", __func__, t->tab_id);
1029 if (t->new_tab)
1030 run_script(t, "hints.createHints('', 'F');");
1031 else
1032 run_script(t, "hints.createHints('', 'f');");
1033 t->mode = XT_MODE_HINT;
1036 void
1037 disable_hints(struct tab *t)
1039 DNPRINTF(XT_D_JS, "%s: tab %d\n", __func__, t->tab_id);
1041 run_script(t, "hints.clearHints();");
1042 t->mode = XT_MODE_COMMAND;
1043 t->new_tab = 0;
1047 passthrough(struct tab *t, struct karg *args)
1049 t->mode = XT_MODE_PASSTHROUGH;
1050 return (0);
1054 hint(struct tab *t, struct karg *args)
1057 DNPRINTF(XT_D_JS, "hint: tab %d args %d\n", t->tab_id, args->i);
1059 if (t->mode == XT_MODE_HINT) {
1060 if (args->i == XT_HINT_NEWTAB)
1061 t->new_tab = 1;
1062 enable_hints(t);
1063 } else
1064 disable_hints(t);
1066 return (0);
1069 void
1070 apply_style(struct tab *t)
1072 t->styled = 1;
1073 g_object_set(G_OBJECT(t->settings),
1074 "user-stylesheet-uri", t->stylesheet, (char *)NULL);
1077 void
1078 remove_style(struct tab *t)
1080 t->styled = 0;
1081 g_object_set(G_OBJECT(t->settings),
1082 "user-stylesheet-uri", NULL, (char *)NULL);
1086 userstyle(struct tab *t, struct karg *args)
1088 struct tab *tt;
1090 DNPRINTF(XT_D_JS, "userstyle: tab %d\n", t->tab_id);
1092 switch (args->i) {
1093 case XT_STYLE_CURRENT_TAB:
1094 if (t->styled)
1095 remove_style(t);
1096 else
1097 apply_style(t);
1098 break;
1099 case XT_STYLE_GLOBAL:
1100 if (userstyle_global) {
1101 userstyle_global = 0;
1102 TAILQ_FOREACH(tt, &tabs, entry)
1103 remove_style(tt);
1104 } else {
1105 userstyle_global = 1;
1106 TAILQ_FOREACH(tt, &tabs, entry)
1107 apply_style(tt);
1109 break;
1112 return (0);
1116 quit(struct tab *t, struct karg *args)
1118 if (save_global_history)
1119 save_global_history_to_disk(t);
1121 gtk_main_quit();
1123 return (1);
1126 void
1127 restore_sessions_list(void)
1129 DIR *sdir = NULL;
1130 struct dirent *dp = NULL;
1131 struct session *s;
1132 int reg;
1134 sdir = opendir(sessions_dir);
1135 if (sdir) {
1136 while ((dp = readdir(sdir)) != NULL) {
1137 #if defined __MINGW32__
1138 reg = 1; /* windows only has regular files */
1139 #else
1140 reg = dp->d_type == DT_REG;
1141 #endif
1142 if (dp && reg) {
1143 s = g_malloc(sizeof(struct session));
1144 s->name = g_strdup(dp->d_name);
1145 TAILQ_INSERT_TAIL(&sessions, s, entry);
1148 closedir(sdir);
1153 open_tabs(struct tab *t, struct karg *a)
1155 char file[PATH_MAX];
1156 FILE *f = NULL;
1157 char *uri = NULL;
1158 int rv = 1;
1159 struct tab *ti, *tt;
1161 if (a == NULL)
1162 goto done;
1164 ti = TAILQ_LAST(&tabs, tab_list);
1166 snprintf(file, sizeof file, "%s" PS "%s", sessions_dir, a->s);
1167 if ((f = fopen(file, "r")) == NULL)
1168 goto done;
1170 for (;;) {
1171 if ((uri = fparseln(f, NULL, NULL, "\0\0\0", 0)) == NULL)
1172 if (feof(f) || ferror(f))
1173 break;
1175 /* retrieve session name */
1176 if (uri && g_str_has_prefix(uri, XT_SAVE_SESSION_ID)) {
1177 strlcpy(named_session,
1178 &uri[strlen(XT_SAVE_SESSION_ID)],
1179 sizeof named_session);
1180 continue;
1183 if (uri && strlen(uri))
1184 create_new_tab(uri, NULL, 1, -1);
1186 free(uri);
1187 uri = NULL;
1190 /* close open tabs */
1191 if (a->i == XT_SES_CLOSETABS && ti != NULL) {
1192 for (;;) {
1193 tt = TAILQ_FIRST(&tabs);
1194 if (tt == NULL)
1195 break;
1196 if (tt != ti) {
1197 delete_tab(tt);
1198 continue;
1200 delete_tab(tt);
1201 break;
1205 rv = 0;
1206 done:
1207 if (f)
1208 fclose(f);
1210 return (rv);
1214 restore_saved_tabs(void)
1216 char file[PATH_MAX];
1217 int unlink_file = 0;
1218 struct stat sb;
1219 struct karg a;
1220 int rv = 0;
1222 snprintf(file, sizeof file, "%s" PS "%s",
1223 sessions_dir, XT_RESTART_TABS_FILE);
1224 if (stat(file, &sb) == -1)
1225 a.s = XT_SAVED_TABS_FILE;
1226 else {
1227 unlink_file = 1;
1228 a.s = XT_RESTART_TABS_FILE;
1231 a.i = XT_SES_DONOTHING;
1232 rv = open_tabs(NULL, &a);
1234 if (unlink_file)
1235 unlink(file);
1237 return (rv);
1241 save_tabs(struct tab *t, struct karg *a)
1243 char file[PATH_MAX];
1244 FILE *f;
1245 int num_tabs = 0, i;
1246 struct tab **stabs = NULL;
1248 /* tab may be null here */
1250 if (a == NULL)
1251 return (1);
1252 if (a->s == NULL)
1253 snprintf(file, sizeof file, "%s" PS "%s",
1254 sessions_dir, named_session);
1255 else
1256 snprintf(file, sizeof file, "%s" PS "%s", sessions_dir, a->s);
1258 if ((f = fopen(file, "w")) == NULL) {
1259 show_oops(t, "Can't open save_tabs file: %s", strerror(errno));
1260 return (1);
1263 /* save session name */
1264 fprintf(f, "%s%s\n", XT_SAVE_SESSION_ID, named_session);
1266 /* Save tabs, in the order they are arranged in the notebook. */
1267 num_tabs = sort_tabs_by_page_num(&stabs);
1269 for (i = 0; i < num_tabs; i++)
1270 if (stabs[i]) {
1271 if (get_uri(stabs[i]) != NULL)
1272 fprintf(f, "%s\n", get_uri(stabs[i]));
1273 else if (gtk_entry_get_text(GTK_ENTRY(
1274 stabs[i]->uri_entry)))
1275 fprintf(f, "%s\n", gtk_entry_get_text(GTK_ENTRY(
1276 stabs[i]->uri_entry)));
1279 g_free(stabs);
1281 /* try and make sure this gets to disk NOW. XXX Backup first? */
1282 if (fflush(f) != 0 || fsync(fileno(f)) != 0) {
1283 show_oops(t, "May not have managed to save session: %s",
1284 strerror(errno));
1287 fclose(f);
1289 return (0);
1293 save_tabs_and_quit(struct tab *t, struct karg *args)
1295 struct karg a;
1297 a.s = NULL;
1298 save_tabs(t, &a);
1299 quit(t, NULL);
1301 return (1);
1305 run_page_script(struct tab *t, struct karg *args)
1307 const gchar *uri;
1308 char *tmp, script[PATH_MAX];
1310 tmp = args->s != NULL && strlen(args->s) > 0 ? args->s : default_script;
1311 if (tmp[0] == '\0') {
1312 show_oops(t, "no script specified");
1313 return (1);
1316 if ((uri = get_uri(t)) == NULL) {
1317 show_oops(t, "tab is empty, not running script");
1318 return (1);
1321 if (tmp[0] == '~')
1322 snprintf(script, sizeof script, "%s" PS "%s",
1323 pwd->pw_dir, &tmp[1]);
1324 else
1325 strlcpy(script, tmp, sizeof script);
1327 return (fork_exec(t, script, uri, "can't launch external script", 1));
1331 yank_uri(struct tab *t, struct karg *args)
1333 const gchar *uri;
1334 GtkClipboard *clipboard;
1336 if ((uri = get_uri(t)) == NULL)
1337 return (1);
1339 clipboard = gtk_clipboard_get(GDK_SELECTION_PRIMARY);
1340 gtk_clipboard_set_text(clipboard, uri, -1);
1342 return (0);
1346 paste_uri(struct tab *t, struct karg *args)
1348 GtkClipboard *clipboard;
1349 GdkAtom atom = gdk_atom_intern("CUT_BUFFER0", FALSE);
1350 gint len;
1351 gchar *p = NULL, *uri;
1353 /* try primary clipboard first */
1354 clipboard = gtk_clipboard_get(GDK_SELECTION_PRIMARY);
1355 p = gtk_clipboard_wait_for_text(clipboard);
1357 /* if it failed get whatever text is in cut_buffer0 */
1358 if (p == NULL && xterm_workaround)
1359 if (gdk_property_get(gdk_get_default_root_window(),
1360 atom,
1361 gdk_atom_intern("STRING", FALSE),
1363 1024 * 1024 /* picked out of my butt */,
1364 FALSE,
1365 NULL,
1366 NULL,
1367 &len,
1368 (guchar **)&p)) {
1369 if (p == NULL)
1370 goto done;
1371 /* yes sir, we need to NUL the string */
1372 p[len] = '\0';
1375 if (p) {
1376 uri = p;
1377 while (*uri && isspace(*uri))
1378 uri++;
1379 if (strlen(uri) == 0) {
1380 show_oops(t, "empty paste buffer");
1381 goto done;
1383 if (guess_search == 0 && valid_url_type(uri)) {
1384 /* we can be clever and paste this in search box */
1385 show_oops(t, "not a valid URL");
1386 goto done;
1389 if (args->i == XT_PASTE_CURRENT_TAB)
1390 load_uri(t, uri);
1391 else if (args->i == XT_PASTE_NEW_TAB)
1392 create_new_tab(uri, NULL, 1, -1);
1395 done:
1396 if (p)
1397 g_free(p);
1399 return (0);
1402 void
1403 js_toggle_cb(GtkWidget *w, struct tab *t)
1405 struct karg a;
1406 int es, set;
1408 g_object_get(G_OBJECT(t->settings),
1409 "enable-scripts", &es, (char *)NULL);
1410 es = !es;
1411 if (es)
1412 set = XT_WL_ENABLE;
1413 else
1414 set = XT_WL_DISABLE;
1416 a.i = set | XT_WL_TOPLEVEL;
1417 toggle_pl(t, &a);
1419 a.i = set | XT_WL_TOPLEVEL;
1420 toggle_cwl(t, &a);
1422 a.i = XT_WL_TOGGLE | XT_WL_TOPLEVEL | XT_WL_RELOAD;
1423 toggle_js(t, &a);
1427 toggle_src(struct tab *t, struct karg *args)
1429 gboolean mode;
1431 if (t == NULL)
1432 return (0);
1434 mode = webkit_web_view_get_view_source_mode(t->wv);
1435 webkit_web_view_set_view_source_mode(t->wv, !mode);
1436 webkit_web_view_reload(t->wv);
1438 return (0);
1441 void
1442 focus_webview(struct tab *t)
1444 if (t == NULL)
1445 return;
1447 /* only grab focus if we are visible */
1448 if (gtk_notebook_get_current_page(notebook) == t->tab_id)
1449 gtk_widget_grab_focus(GTK_WIDGET(t->wv));
1453 focus(struct tab *t, struct karg *args)
1455 if (t == NULL || args == NULL)
1456 return (1);
1458 if (show_url == 0)
1459 return (0);
1461 if (args->i == XT_FOCUS_URI)
1462 gtk_widget_grab_focus(GTK_WIDGET(t->uri_entry));
1463 else if (args->i == XT_FOCUS_SEARCH)
1464 gtk_widget_grab_focus(GTK_WIDGET(t->search_entry));
1466 return (0);
1470 connect_socket_from_uri(const gchar *uri, const gchar **error_str, char *domain,
1471 size_t domain_sz)
1473 SoupURI *su = NULL;
1474 struct addrinfo hints, *res = NULL, *ai;
1475 int rv = -1, s = -1, on, error;
1476 char port[8];
1477 static gchar myerror[256]; /* this is not thread safe */
1479 myerror[0] = '\0';
1480 *error_str = myerror;
1481 if (uri && !g_str_has_prefix(uri, "https://")) {
1482 *error_str = "invalid URI";
1483 goto done;
1486 su = soup_uri_new(uri);
1487 if (su == NULL) {
1488 *error_str = "invalid soup URI";
1489 goto done;
1491 if (!SOUP_URI_VALID_FOR_HTTP(su)) {
1492 *error_str = "invalid HTTPS URI";
1493 goto done;
1496 snprintf(port, sizeof port, "%d", su->port);
1497 bzero(&hints, sizeof(struct addrinfo));
1498 hints.ai_flags = AI_CANONNAME;
1499 hints.ai_family = AF_UNSPEC;
1500 hints.ai_socktype = SOCK_STREAM;
1502 if ((error = getaddrinfo(su->host, port, &hints, &res))) {
1503 snprintf(myerror, sizeof myerror, "getaddrinfo failed: %s",
1504 gai_strerror(errno));
1505 goto done;
1508 for (ai = res; ai; ai = ai->ai_next) {
1509 if (s != -1) {
1510 close(s);
1511 s = -1;
1514 if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6)
1515 continue;
1516 s = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
1517 if (s == -1)
1518 continue;
1519 if (setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &on,
1520 sizeof(on)) == -1)
1521 continue;
1522 if (connect(s, ai->ai_addr, ai->ai_addrlen) == 0)
1523 break;
1525 if (s == -1) {
1526 snprintf(myerror, sizeof myerror,
1527 "could not obtain certificates from: %s",
1528 su->host);
1529 goto done;
1532 if (domain)
1533 strlcpy(domain, su->host, domain_sz);
1534 rv = s;
1535 done:
1536 if (su)
1537 soup_uri_free(su);
1538 if (res)
1539 freeaddrinfo(res);
1540 if (rv == -1 && s != -1)
1541 close(s);
1543 return (rv);
1546 #ifdef __MINGW32__
1547 static ssize_t
1548 custom_gnutls_push(void *s, const void *buf, size_t len)
1550 return send((size_t)s, buf, len, 0);
1553 static ssize_t
1554 custom_gnutls_pull(void *s, void *buf, size_t len)
1556 return recv((size_t)s, buf, len, 0);
1558 #endif
1561 stop_tls(gnutls_session_t gsession, gnutls_certificate_credentials_t xcred)
1563 if (gsession)
1564 gnutls_deinit(gsession);
1565 if (xcred)
1566 gnutls_certificate_free_credentials(xcred);
1568 return (0);
1572 start_tls(const gchar **error_str, int s, gnutls_session_t *gs,
1573 gnutls_certificate_credentials_t *xc)
1575 gnutls_certificate_credentials_t xcred;
1576 gnutls_session_t gsession;
1577 int rv = 1;
1578 static gchar myerror[1024]; /* this is not thread safe */
1580 if (gs == NULL || xc == NULL)
1581 goto done;
1583 myerror[0] = '\0';
1584 *gs = NULL;
1585 *xc = NULL;
1587 gnutls_certificate_allocate_credentials(&xcred);
1588 gnutls_certificate_set_x509_trust_file(xcred, ssl_ca_file,
1589 GNUTLS_X509_FMT_PEM);
1591 gnutls_init(&gsession, GNUTLS_CLIENT);
1592 gnutls_priority_set_direct(gsession, "PERFORMANCE", NULL);
1593 gnutls_credentials_set(gsession, GNUTLS_CRD_CERTIFICATE, xcred);
1594 gnutls_transport_set_ptr(gsession, (gnutls_transport_ptr_t)(long)s);
1595 #ifdef __MINGW32__
1596 /* sockets on windows don't use file descriptors */
1597 gnutls_transport_set_push_function(gsession, custom_gnutls_push);
1598 gnutls_transport_set_pull_function(gsession, custom_gnutls_pull);
1599 #endif
1600 if ((rv = gnutls_handshake(gsession)) < 0) {
1601 snprintf(myerror, sizeof myerror,
1602 "gnutls_handshake failed %d fatal %d %s",
1604 gnutls_error_is_fatal(rv),
1605 #if LIBGNUTLS_VERSION_MAJOR >= 2 && LIBGNUTLS_VERSION_MINOR >= 6
1606 gnutls_strerror_name(rv));
1607 #else
1608 "GNUTLS version is too old to provide human readable error");
1609 #endif
1610 stop_tls(gsession, xcred);
1611 goto done;
1614 gnutls_credentials_type_t cred;
1615 cred = gnutls_auth_get_type(gsession);
1616 if (cred != GNUTLS_CRD_CERTIFICATE) {
1617 snprintf(myerror, sizeof myerror,
1618 "gnutls_auth_get_type failed %d",
1619 (int)cred);
1620 stop_tls(gsession, xcred);
1621 goto done;
1624 *gs = gsession;
1625 *xc = xcred;
1626 rv = 0;
1627 done:
1628 *error_str = myerror;
1629 return (rv);
1633 get_connection_certs(gnutls_session_t gsession, gnutls_x509_crt_t **certs,
1634 size_t *cert_count)
1636 unsigned int len;
1637 const gnutls_datum_t *cl;
1638 gnutls_x509_crt_t *all_certs;
1639 int i, rv = 1;
1641 if (certs == NULL || cert_count == NULL)
1642 goto done;
1643 if (gnutls_certificate_type_get(gsession) != GNUTLS_CRT_X509)
1644 goto done;
1645 cl = gnutls_certificate_get_peers(gsession, &len);
1646 if (len == 0)
1647 goto done;
1649 all_certs = g_malloc(sizeof(gnutls_x509_crt_t) * len);
1650 for (i = 0; i < len; i++) {
1651 gnutls_x509_crt_init(&all_certs[i]);
1652 if (gnutls_x509_crt_import(all_certs[i], &cl[i],
1653 GNUTLS_X509_FMT_PEM < 0)) {
1654 g_free(all_certs);
1655 goto done;
1659 *certs = all_certs;
1660 *cert_count = len;
1661 rv = 0;
1662 done:
1663 return (rv);
1666 void
1667 free_connection_certs(gnutls_x509_crt_t *certs, size_t cert_count)
1669 int i;
1671 for (i = 0; i < cert_count; i++)
1672 gnutls_x509_crt_deinit(certs[i]);
1673 g_free(certs);
1676 void
1677 statusbar_modify_attr(struct tab *t, const char *text, const char *base)
1679 GdkColor c_text, c_base;
1681 gdk_color_parse(text, &c_text);
1682 gdk_color_parse(base, &c_base);
1684 gtk_widget_modify_text(t->sbe.statusbar, GTK_STATE_NORMAL, &c_text);
1685 gtk_widget_modify_text(t->sbe.buffercmd, GTK_STATE_NORMAL, &c_text);
1686 gtk_widget_modify_text(t->sbe.zoom, GTK_STATE_NORMAL, &c_text);
1687 gtk_widget_modify_text(t->sbe.position, GTK_STATE_NORMAL, &c_text);
1689 gtk_widget_modify_base(t->sbe.statusbar, GTK_STATE_NORMAL, &c_base);
1690 gtk_widget_modify_base(t->sbe.buffercmd, GTK_STATE_NORMAL, &c_base);
1691 gtk_widget_modify_base(t->sbe.zoom, GTK_STATE_NORMAL, &c_base);
1692 gtk_widget_modify_base(t->sbe.position, GTK_STATE_NORMAL, &c_base);
1695 void
1696 save_certs(struct tab *t, gnutls_x509_crt_t *certs,
1697 size_t cert_count, char *domain)
1699 size_t cert_buf_sz;
1700 char cert_buf[64 * 1024], file[PATH_MAX];
1701 int i;
1702 FILE *f;
1703 GdkColor color;
1705 if (t == NULL || certs == NULL || cert_count <= 0 || domain == NULL)
1706 return;
1708 snprintf(file, sizeof file, "%s" PS "%s", certs_dir, domain);
1709 if ((f = fopen(file, "w")) == NULL) {
1710 show_oops(t, "Can't create cert file %s %s",
1711 file, strerror(errno));
1712 return;
1715 for (i = 0; i < cert_count; i++) {
1716 cert_buf_sz = sizeof cert_buf;
1717 if (gnutls_x509_crt_export(certs[i], GNUTLS_X509_FMT_PEM,
1718 cert_buf, &cert_buf_sz)) {
1719 show_oops(t, "gnutls_x509_crt_export failed");
1720 goto done;
1722 if (fwrite(cert_buf, cert_buf_sz, 1, f) != 1) {
1723 show_oops(t, "Can't write certs: %s", strerror(errno));
1724 goto done;
1728 /* not the best spot but oh well */
1729 gdk_color_parse("lightblue", &color);
1730 gtk_widget_modify_base(t->uri_entry, GTK_STATE_NORMAL, &color);
1731 statusbar_modify_attr(t, XT_COLOR_BLACK, "lightblue");
1732 done:
1733 fclose(f);
1736 enum cert_trust {
1737 CERT_LOCAL,
1738 CERT_TRUSTED,
1739 CERT_UNTRUSTED,
1740 CERT_BAD
1743 enum cert_trust
1744 load_compare_cert(const gchar *uri, const gchar **error_str)
1746 char domain[8182], file[PATH_MAX];
1747 char cert_buf[64 * 1024], r_cert_buf[64 * 1024];
1748 int s = -1, i;
1749 unsigned int error = 0;
1750 FILE *f = NULL;
1751 size_t cert_buf_sz, cert_count;
1752 enum cert_trust rv = CERT_UNTRUSTED;
1753 static gchar serr[80]; /* this isn't thread safe */
1754 gnutls_session_t gsession;
1755 gnutls_x509_crt_t *certs;
1756 gnutls_certificate_credentials_t xcred;
1758 DNPRINTF(XT_D_URL, "%s: %s\n", __func__, uri);
1760 serr[0] = '\0';
1761 *error_str = serr;
1762 if ((s = connect_socket_from_uri(uri, error_str, domain,
1763 sizeof domain)) == -1)
1764 return (rv);
1766 DNPRINTF(XT_D_URL, "%s: fd %d\n", __func__, s);
1768 /* go ssl/tls */
1769 if (start_tls(error_str, s, &gsession, &xcred))
1770 goto done;
1771 DNPRINTF(XT_D_URL, "%s: got tls\n", __func__);
1773 /* verify certs in case cert file doesn't exist */
1774 if (gnutls_certificate_verify_peers2(gsession, &error) !=
1775 GNUTLS_E_SUCCESS) {
1776 *error_str = "Invalid certificates";
1777 goto done;
1780 /* get certs */
1781 if (get_connection_certs(gsession, &certs, &cert_count)) {
1782 *error_str = "Can't get connection certificates";
1783 goto done;
1786 snprintf(file, sizeof file, "%s" PS "%s", certs_dir, domain);
1787 if ((f = fopen(file, "r")) == NULL) {
1788 if (!error)
1789 rv = CERT_TRUSTED;
1790 goto freeit;
1793 for (i = 0; i < cert_count; i++) {
1794 cert_buf_sz = sizeof cert_buf;
1795 if (gnutls_x509_crt_export(certs[i], GNUTLS_X509_FMT_PEM,
1796 cert_buf, &cert_buf_sz)) {
1797 goto freeit;
1799 if (fread(r_cert_buf, cert_buf_sz, 1, f) != 1) {
1800 rv = CERT_BAD; /* critical */
1801 goto freeit;
1803 if (bcmp(r_cert_buf, cert_buf, sizeof cert_buf_sz)) {
1804 rv = CERT_BAD; /* critical */
1805 goto freeit;
1807 rv = CERT_LOCAL;
1810 freeit:
1811 if (f)
1812 fclose(f);
1813 free_connection_certs(certs, cert_count);
1814 done:
1815 /* we close the socket first for speed */
1816 if (s != -1)
1817 close(s);
1819 /* only complain if we didn't save it locally */
1820 if (error && rv != CERT_LOCAL) {
1821 strlcpy(serr, "Certificate exception(s): ", sizeof serr);
1822 if (error & GNUTLS_CERT_INVALID)
1823 strlcat(serr, "invalid, ", sizeof serr);
1824 if (error & GNUTLS_CERT_REVOKED)
1825 strlcat(serr, "revoked, ", sizeof serr);
1826 if (error & GNUTLS_CERT_SIGNER_NOT_FOUND)
1827 strlcat(serr, "signer not found, ", sizeof serr);
1828 if (error & GNUTLS_CERT_SIGNER_NOT_CA)
1829 strlcat(serr, "not signed by CA, ", sizeof serr);
1830 if (error & GNUTLS_CERT_INSECURE_ALGORITHM)
1831 strlcat(serr, "insecure algorithm, ", sizeof serr);
1832 #if LIBGNUTLS_VERSION_MAJOR >= 2 && LIBGNUTLS_VERSION_MINOR >= 6
1833 if (error & GNUTLS_CERT_NOT_ACTIVATED)
1834 strlcat(serr, "not activated, ", sizeof serr);
1835 if (error & GNUTLS_CERT_EXPIRED)
1836 strlcat(serr, "expired, ", sizeof serr);
1837 #endif
1838 for (i = strlen(serr) - 1; i > 0; i--)
1839 if (serr[i] == ',') {
1840 serr[i] = '\0';
1841 break;
1843 *error_str = serr;
1846 stop_tls(gsession, xcred);
1848 return (rv);
1852 cert_cmd(struct tab *t, struct karg *args)
1854 const gchar *uri, *error_str = NULL;
1855 char domain[8182];
1856 int s = -1;
1857 size_t cert_count;
1858 gnutls_session_t gsession;
1859 gnutls_x509_crt_t *certs;
1860 gnutls_certificate_credentials_t xcred;
1862 if (t == NULL)
1863 return (1);
1865 if (ssl_ca_file == NULL) {
1866 show_oops(t, "Can't open CA file: %s", ssl_ca_file);
1867 return (1);
1870 if ((uri = get_uri(t)) == NULL) {
1871 show_oops(t, "Invalid URI");
1872 return (1);
1875 if ((s = connect_socket_from_uri(uri, &error_str, domain,
1876 sizeof domain)) == -1) {
1877 show_oops(t, "%s", error_str);
1878 return (1);
1881 /* go ssl/tls */
1882 if (start_tls(&error_str, s, &gsession, &xcred))
1883 goto done;
1885 /* get certs */
1886 if (get_connection_certs(gsession, &certs, &cert_count)) {
1887 show_oops(t, "get_connection_certs failed");
1888 goto done;
1891 if (args->i & XT_SHOW)
1892 show_certs(t, certs, cert_count, "Certificate Chain");
1893 else if (args->i & XT_SAVE)
1894 save_certs(t, certs, cert_count, domain);
1896 free_connection_certs(certs, cert_count);
1897 done:
1898 /* we close the socket first for speed */
1899 if (s != -1)
1900 close(s);
1901 stop_tls(gsession, xcred);
1902 if (error_str && strlen(error_str))
1903 show_oops(t, "%s", error_str);
1904 return (0);
1908 remove_cookie(int index)
1910 int i, rv = 1;
1911 GSList *cf;
1912 SoupCookie *c;
1914 DNPRINTF(XT_D_COOKIE, "remove_cookie: %d\n", index);
1916 cf = soup_cookie_jar_all_cookies(s_cookiejar);
1918 for (i = 1; cf; cf = cf->next, i++) {
1919 if (i != index)
1920 continue;
1921 c = cf->data;
1922 print_cookie("remove cookie", c);
1923 soup_cookie_jar_delete_cookie(s_cookiejar, c);
1924 rv = 0;
1925 break;
1928 soup_cookies_free(cf);
1930 return (rv);
1934 remove_cookie_domain(int domain_id)
1936 int domain_count, rv = 1;
1937 GSList *cf;
1938 SoupCookie *c;
1939 char *last_domain;
1941 DNPRINTF(XT_D_COOKIE, "remove_cookie_domain: %d\n", domain_id);
1943 last_domain = "";
1944 cf = soup_cookie_jar_all_cookies(s_cookiejar);
1946 for (domain_count = 0; cf; cf = cf->next) {
1947 c = cf->data;
1949 if (strcmp(last_domain, c->domain) != 0) {
1950 domain_count++;
1951 last_domain = c->domain;
1954 if (domain_count < domain_id)
1955 continue;
1956 else if (domain_count > domain_id)
1957 break;
1959 print_cookie("remove cookie", c);
1960 soup_cookie_jar_delete_cookie(s_cookiejar, c);
1961 rv = 0;
1964 soup_cookies_free(cf);
1966 return (rv);
1970 remove_cookie_all()
1972 int rv = 1;
1973 GSList *cf;
1974 SoupCookie *c;
1976 DNPRINTF(XT_D_COOKIE, "remove_cookie_all\n");
1978 cf = soup_cookie_jar_all_cookies(s_cookiejar);
1980 for (; cf; cf = cf->next) {
1981 c = cf->data;
1983 print_cookie("remove cookie", c);
1984 soup_cookie_jar_delete_cookie(s_cookiejar, c);
1985 rv = 0;
1988 soup_cookies_free(cf);
1990 return (rv);
1994 toplevel_cmd(struct tab *t, struct karg *args)
1996 js_toggle_cb(t->js_toggle, t);
1998 return (0);
2002 can_go_back_for_real(struct tab *t)
2004 int i;
2005 WebKitWebHistoryItem *item;
2006 const gchar *uri;
2008 if (t == NULL)
2009 return (FALSE);
2011 /* rely on webkit to make sure we can go backward when on an about page */
2012 uri = get_uri(t);
2013 if (uri == NULL || g_str_has_prefix(uri, "about:"))
2014 return (webkit_web_view_can_go_back(t->wv));
2016 /* the back/forwars list is stupid so help determine if we can go back */
2017 for (i = 0, item = webkit_web_back_forward_list_get_current_item(t->bfl);
2018 item != NULL;
2019 i--, item = webkit_web_back_forward_list_get_nth_item(t->bfl, i)) {
2020 if (strcmp(webkit_web_history_item_get_uri(item), uri))
2021 return (TRUE);
2024 return (FALSE);
2028 can_go_forward_for_real(struct tab *t)
2030 int i;
2031 WebKitWebHistoryItem *item;
2032 const gchar *uri;
2034 if (t == NULL)
2035 return (FALSE);
2037 /* rely on webkit to make sure we can go forward when on an about page */
2038 uri = get_uri(t);
2039 if (uri == NULL || g_str_has_prefix(uri, "about:"))
2040 return (webkit_web_view_can_go_forward(t->wv));
2042 /* the back/forwars list is stupid so help selecting a different item */
2043 for (i = 0, item = webkit_web_back_forward_list_get_current_item(t->bfl);
2044 item != NULL;
2045 i++, item = webkit_web_back_forward_list_get_nth_item(t->bfl, i)) {
2046 if (strcmp(webkit_web_history_item_get_uri(item), uri))
2047 return (TRUE);
2050 return (FALSE);
2053 void
2054 go_back_for_real(struct tab *t)
2056 int i;
2057 WebKitWebHistoryItem *item;
2058 const gchar *uri;
2060 if (t == NULL)
2061 return;
2063 uri = get_uri(t);
2064 if (uri == NULL) {
2065 webkit_web_view_go_back(t->wv);
2066 return;
2068 /* the back/forwars list is stupid so help selecting a different item */
2069 for (i = 0, item = webkit_web_back_forward_list_get_current_item(t->bfl);
2070 item != NULL;
2071 i--, item = webkit_web_back_forward_list_get_nth_item(t->bfl, i)) {
2072 if (strcmp(webkit_web_history_item_get_uri(item), uri)) {
2073 webkit_web_view_go_to_back_forward_item(t->wv, item);
2074 break;
2079 void
2080 go_forward_for_real(struct tab *t)
2082 int i;
2083 WebKitWebHistoryItem *item;
2084 const gchar *uri;
2086 if (t == NULL)
2087 return;
2089 uri = get_uri(t);
2090 if (uri == NULL) {
2091 webkit_web_view_go_forward(t->wv);
2092 return;
2094 /* the back/forwars list is stupid so help selecting a different item */
2095 for (i = 0, item = webkit_web_back_forward_list_get_current_item(t->bfl);
2096 item != NULL;
2097 i++, item = webkit_web_back_forward_list_get_nth_item(t->bfl, i)) {
2098 if (strcmp(webkit_web_history_item_get_uri(item), uri)) {
2099 webkit_web_view_go_to_back_forward_item(t->wv, item);
2100 break;
2106 navaction(struct tab *t, struct karg *args)
2108 WebKitWebHistoryItem *item;
2109 WebKitWebFrame *frame;
2111 DNPRINTF(XT_D_NAV, "navaction: tab %d opcode %d\n",
2112 t->tab_id, args->i);
2114 t->xtp_meaning = XT_XTP_TAB_MEANING_NORMAL;
2115 if (t->item) {
2116 if (args->i == XT_NAV_BACK)
2117 item = webkit_web_back_forward_list_get_current_item(t->bfl);
2118 else
2119 item = webkit_web_back_forward_list_get_forward_item(t->bfl);
2120 if (item == NULL)
2121 return (XT_CB_PASSTHROUGH);
2122 webkit_web_view_go_to_back_forward_item(t->wv, item);
2123 t->item = NULL;
2124 return (XT_CB_PASSTHROUGH);
2127 switch (args->i) {
2128 case XT_NAV_BACK:
2129 marks_clear(t);
2130 go_back_for_real(t);
2131 break;
2132 case XT_NAV_FORWARD:
2133 marks_clear(t);
2134 go_forward_for_real(t);
2135 break;
2136 case XT_NAV_RELOAD:
2137 frame = webkit_web_view_get_main_frame(t->wv);
2138 webkit_web_frame_reload(frame);
2139 break;
2140 case XT_NAV_STOP:
2141 frame = webkit_web_view_get_main_frame(t->wv);
2142 webkit_web_frame_stop_loading(frame);
2143 break;
2145 return (XT_CB_PASSTHROUGH);
2149 move(struct tab *t, struct karg *args)
2151 GtkAdjustment *adjust;
2152 double pi, si, pos, ps, upper, lower, max;
2153 double percent;
2155 switch (args->i) {
2156 case XT_MOVE_DOWN:
2157 case XT_MOVE_UP:
2158 case XT_MOVE_BOTTOM:
2159 case XT_MOVE_TOP:
2160 case XT_MOVE_PAGEDOWN:
2161 case XT_MOVE_PAGEUP:
2162 case XT_MOVE_HALFDOWN:
2163 case XT_MOVE_HALFUP:
2164 case XT_MOVE_PERCENT:
2165 case XT_MOVE_CENTER:
2166 adjust = t->adjust_v;
2167 break;
2168 default:
2169 adjust = t->adjust_h;
2170 break;
2173 pos = gtk_adjustment_get_value(adjust);
2174 ps = gtk_adjustment_get_page_size(adjust);
2175 upper = gtk_adjustment_get_upper(adjust);
2176 lower = gtk_adjustment_get_lower(adjust);
2177 si = gtk_adjustment_get_step_increment(adjust);
2178 pi = gtk_adjustment_get_page_increment(adjust);
2179 max = upper - ps;
2181 DNPRINTF(XT_D_MOVE, "move: opcode %d %s pos %f ps %f upper %f lower %f "
2182 "max %f si %f pi %f\n",
2183 args->i, adjust == t->adjust_h ? "horizontal" : "vertical",
2184 pos, ps, upper, lower, max, si, pi);
2186 switch (args->i) {
2187 case XT_MOVE_DOWN:
2188 case XT_MOVE_RIGHT:
2189 pos += si;
2190 gtk_adjustment_set_value(adjust, MIN(pos, max));
2191 break;
2192 case XT_MOVE_UP:
2193 case XT_MOVE_LEFT:
2194 pos -= si;
2195 gtk_adjustment_set_value(adjust, MAX(pos, lower));
2196 break;
2197 case XT_MOVE_BOTTOM:
2198 case XT_MOVE_FARRIGHT:
2199 gtk_adjustment_set_value(adjust, max);
2200 break;
2201 case XT_MOVE_TOP:
2202 case XT_MOVE_FARLEFT:
2203 gtk_adjustment_set_value(adjust, lower);
2204 break;
2205 case XT_MOVE_PAGEDOWN:
2206 pos += pi;
2207 gtk_adjustment_set_value(adjust, MIN(pos, max));
2208 break;
2209 case XT_MOVE_PAGEUP:
2210 pos -= pi;
2211 gtk_adjustment_set_value(adjust, MAX(pos, lower));
2212 break;
2213 case XT_MOVE_HALFDOWN:
2214 pos += pi / 2;
2215 gtk_adjustment_set_value(adjust, MIN(pos, max));
2216 break;
2217 case XT_MOVE_HALFUP:
2218 pos -= pi / 2;
2219 gtk_adjustment_set_value(adjust, MAX(pos, lower));
2220 break;
2221 case XT_MOVE_CENTER:
2222 args->s = g_strdup("50.0");
2223 /* FALLTHROUGH */
2224 case XT_MOVE_PERCENT:
2225 percent = atoi(args->s) / 100.0;
2226 pos = max * percent;
2227 if (pos < 0.0 || pos > max)
2228 break;
2229 gtk_adjustment_set_value(adjust, pos);
2230 break;
2231 default:
2232 return (XT_CB_PASSTHROUGH);
2235 DNPRINTF(XT_D_MOVE, "move: new pos %f %f\n", pos, MIN(pos, max));
2237 return (XT_CB_HANDLED);
2240 void
2241 url_set_visibility(void)
2243 struct tab *t;
2245 TAILQ_FOREACH(t, &tabs, entry)
2246 if (show_url == 0) {
2247 gtk_widget_hide(t->toolbar);
2248 focus_webview(t);
2249 } else
2250 gtk_widget_show(t->toolbar);
2253 void
2254 notebook_tab_set_visibility(void)
2256 if (show_tabs == 0) {
2257 gtk_widget_hide(tab_bar);
2258 gtk_notebook_set_show_tabs(notebook, FALSE);
2259 } else {
2260 if (tab_style == XT_TABS_NORMAL) {
2261 gtk_widget_hide(tab_bar);
2262 gtk_notebook_set_show_tabs(notebook, TRUE);
2263 } else if (tab_style == XT_TABS_COMPACT) {
2264 gtk_widget_show(tab_bar);
2265 gtk_notebook_set_show_tabs(notebook, FALSE);
2270 void
2271 statusbar_set_visibility(void)
2273 struct tab *t;
2275 TAILQ_FOREACH(t, &tabs, entry){
2276 if (show_statusbar == 0)
2277 gtk_widget_hide(t->statusbar_box);
2278 else
2279 gtk_widget_show(t->statusbar_box);
2281 focus_webview(t);
2285 void
2286 url_set(struct tab *t, int enable_url_entry)
2288 GdkPixbuf *pixbuf;
2289 int progress;
2291 show_url = enable_url_entry;
2293 if (enable_url_entry) {
2294 gtk_entry_set_icon_from_icon_name(GTK_ENTRY(t->sbe.statusbar),
2295 GTK_ENTRY_ICON_PRIMARY, NULL);
2296 gtk_entry_set_progress_fraction(GTK_ENTRY(t->sbe.statusbar), 0);
2297 } else {
2298 pixbuf = gtk_entry_get_icon_pixbuf(GTK_ENTRY(t->uri_entry),
2299 GTK_ENTRY_ICON_PRIMARY);
2300 progress =
2301 gtk_entry_get_progress_fraction(GTK_ENTRY(t->uri_entry));
2302 gtk_entry_set_icon_from_pixbuf(GTK_ENTRY(t->sbe.statusbar),
2303 GTK_ENTRY_ICON_PRIMARY, pixbuf);
2304 gtk_entry_set_progress_fraction(GTK_ENTRY(t->sbe.statusbar),
2305 progress);
2310 fullscreen(struct tab *t, struct karg *args)
2312 DNPRINTF(XT_D_TAB, "%s: %p %d\n", __func__, t, args->i);
2314 if (t == NULL)
2315 return (XT_CB_PASSTHROUGH);
2317 if (show_url == 0) {
2318 url_set(t, 1);
2319 show_tabs = 1;
2320 } else {
2321 url_set(t, 0);
2322 show_tabs = 0;
2325 url_set_visibility();
2326 notebook_tab_set_visibility();
2328 return (XT_CB_HANDLED);
2332 statustoggle(struct tab *t, struct karg *args)
2334 DNPRINTF(XT_D_TAB, "%s: %p %d\n", __func__, t, args->i);
2336 if (show_statusbar == 1) {
2337 show_statusbar = 0;
2338 statusbar_set_visibility();
2339 } else if (show_statusbar == 0) {
2340 show_statusbar = 1;
2341 statusbar_set_visibility();
2343 return (XT_CB_HANDLED);
2347 urlaction(struct tab *t, struct karg *args)
2349 int rv = XT_CB_HANDLED;
2351 DNPRINTF(XT_D_TAB, "%s: %p %d\n", __func__, t, args->i);
2353 if (t == NULL)
2354 return (XT_CB_PASSTHROUGH);
2356 switch (args->i) {
2357 case XT_URL_SHOW:
2358 if (show_url == 0) {
2359 url_set(t, 1);
2360 url_set_visibility();
2362 break;
2363 case XT_URL_HIDE:
2364 if (show_url == 1) {
2365 url_set(t, 0);
2366 url_set_visibility();
2368 break;
2370 return (rv);
2374 tabaction(struct tab *t, struct karg *args)
2376 int rv = XT_CB_HANDLED;
2377 char *url = args->s;
2378 struct undo *u;
2379 struct tab *tt;
2381 DNPRINTF(XT_D_TAB, "tabaction: %p %d\n", t, args->i);
2383 if (t == NULL)
2384 return (XT_CB_PASSTHROUGH);
2386 switch (args->i) {
2387 case XT_TAB_NEW:
2388 if (strlen(url) > 0)
2389 create_new_tab(url, NULL, 1, args->precount);
2390 else
2391 create_new_tab(NULL, NULL, 1, args->precount);
2392 break;
2393 case XT_TAB_DELETE:
2394 if (args->precount < 0)
2395 delete_tab(t);
2396 else
2397 TAILQ_FOREACH(tt, &tabs, entry)
2398 if (tt->tab_id == args->precount - 1) {
2399 delete_tab(tt);
2400 break;
2402 break;
2403 case XT_TAB_DELQUIT:
2404 if (gtk_notebook_get_n_pages(notebook) > 1)
2405 delete_tab(t);
2406 else
2407 quit(t, args);
2408 break;
2409 case XT_TAB_OPEN:
2410 if (strlen(url) > 0)
2412 else {
2413 rv = XT_CB_PASSTHROUGH;
2414 goto done;
2416 load_uri(t, url);
2417 break;
2418 case XT_TAB_SHOW:
2419 if (show_tabs == 0) {
2420 show_tabs = 1;
2421 notebook_tab_set_visibility();
2423 break;
2424 case XT_TAB_HIDE:
2425 if (show_tabs == 1) {
2426 show_tabs = 0;
2427 notebook_tab_set_visibility();
2429 break;
2430 case XT_TAB_NEXTSTYLE:
2431 if (tab_style == XT_TABS_NORMAL) {
2432 tab_style = XT_TABS_COMPACT;
2433 recolor_compact_tabs();
2435 else
2436 tab_style = XT_TABS_NORMAL;
2437 notebook_tab_set_visibility();
2438 break;
2439 case XT_TAB_UNDO_CLOSE:
2440 if (undo_count == 0) {
2441 DNPRINTF(XT_D_TAB, "%s: no tabs to undo close",
2442 __func__);
2443 goto done;
2444 } else {
2445 undo_count--;
2446 u = TAILQ_FIRST(&undos);
2447 create_new_tab(u->uri, u, 1, -1);
2449 TAILQ_REMOVE(&undos, u, entry);
2450 g_free(u->uri);
2451 /* u->history is freed in create_new_tab() */
2452 g_free(u);
2454 break;
2455 case XT_TAB_LOAD_IMAGES:
2457 if (!auto_load_images) {
2459 /* Enable auto-load images (this will load all
2460 * previously unloaded images). */
2461 g_object_set(G_OBJECT(t->settings),
2462 "auto-load-images", TRUE, (char *)NULL);
2463 webkit_web_view_set_settings(t->wv, t->settings);
2465 webkit_web_view_reload(t->wv);
2467 /* Webkit triggers an event when we change the setting,
2468 * so we can't disable the auto-loading at once.
2470 * Unfortunately, webkit does not tell us when it's done.
2471 * Instead, we wait until the next request, and then
2472 * disable autoloading again.
2474 t->load_images = TRUE;
2476 break;
2477 default:
2478 rv = XT_CB_PASSTHROUGH;
2479 goto done;
2482 done:
2483 if (args->s) {
2484 g_free(args->s);
2485 args->s = NULL;
2488 return (rv);
2492 resizetab(struct tab *t, struct karg *args)
2494 if (t == NULL || args == NULL) {
2495 show_oops(NULL, "resizetab invalid parameters");
2496 return (XT_CB_PASSTHROUGH);
2499 DNPRINTF(XT_D_TAB, "resizetab: tab %d %d\n",
2500 t->tab_id, args->i);
2502 setzoom_webkit(t, args->i);
2504 return (XT_CB_HANDLED);
2508 movetab(struct tab *t, struct karg *args)
2510 int n, dest;
2512 if (t == NULL || args == NULL) {
2513 show_oops(NULL, "movetab invalid parameters");
2514 return (XT_CB_PASSTHROUGH);
2517 DNPRINTF(XT_D_TAB, "movetab: tab %d opcode %d\n",
2518 t->tab_id, args->i);
2520 if (args->i >= XT_TAB_INVALID)
2521 return (XT_CB_PASSTHROUGH);
2523 if (TAILQ_EMPTY(&tabs))
2524 return (XT_CB_PASSTHROUGH);
2526 n = gtk_notebook_get_n_pages(notebook);
2527 dest = gtk_notebook_get_current_page(notebook);
2529 switch (args->i) {
2530 case XT_TAB_NEXT:
2531 if (args->precount < 0)
2532 dest = dest == n - 1 ? 0 : dest + 1;
2533 else
2534 dest = args->precount - 1;
2536 break;
2537 case XT_TAB_PREV:
2538 if (args->precount < 0)
2539 dest -= 1;
2540 else
2541 dest -= args->precount % n;
2543 if (dest < 0)
2544 dest += n;
2546 break;
2547 case XT_TAB_FIRST:
2548 dest = 0;
2549 break;
2550 case XT_TAB_LAST:
2551 dest = n - 1;
2552 break;
2553 default:
2554 return (XT_CB_PASSTHROUGH);
2557 if (dest < 0 || dest >= n)
2558 return (XT_CB_PASSTHROUGH);
2559 if (t->tab_id == dest) {
2560 DNPRINTF(XT_D_TAB, "movetab: do nothing\n");
2561 return (XT_CB_HANDLED);
2564 set_current_tab(dest);
2566 return (XT_CB_HANDLED);
2569 int cmd_prefix = 0;
2573 command(struct tab *t, struct karg *args)
2575 char *s = NULL, *ss = NULL;
2576 GdkColor color;
2577 const gchar *uri;
2578 struct karg a;
2580 if (t == NULL || args == NULL) {
2581 show_oops(NULL, "command invalid parameters");
2582 return (XT_CB_PASSTHROUGH);
2585 switch (args->i) {
2586 case '/':
2587 s = "/";
2588 break;
2589 case '?':
2590 s = "?";
2591 break;
2592 case ':':
2593 if (cmd_prefix == 0)
2594 s = ":";
2595 else {
2596 ss = g_strdup_printf(":%d", cmd_prefix);
2597 s = ss;
2598 cmd_prefix = 0;
2600 break;
2601 case '.':
2602 t->mode = XT_MODE_HINT;
2603 bzero(&a, sizeof a);
2604 a.i = 0;
2605 hint(t, &a);
2606 s = ".";
2607 break;
2608 case ',':
2609 t->mode = XT_MODE_HINT;
2610 bzero(&a, sizeof a);
2611 a.i = XT_HINT_NEWTAB;
2612 hint(t, &a);
2613 s = ",";
2614 break;
2615 case XT_CMD_OPEN:
2616 s = ":open ";
2617 break;
2618 case XT_CMD_TABNEW:
2619 s = ":tabnew ";
2620 break;
2621 case XT_CMD_OPEN_CURRENT:
2622 s = ":open ";
2623 /* FALL THROUGH */
2624 case XT_CMD_TABNEW_CURRENT:
2625 if (!s) /* FALL THROUGH? */
2626 s = ":tabnew ";
2627 if ((uri = get_uri(t)) != NULL) {
2628 ss = g_strdup_printf("%s%s", s, uri);
2629 s = ss;
2631 break;
2632 default:
2633 show_oops(t, "command: invalid opcode %d", args->i);
2634 return (XT_CB_PASSTHROUGH);
2637 DNPRINTF(XT_D_CMD, "%s: tab %d type %s\n", __func__, t->tab_id, s);
2639 gtk_entry_set_text(GTK_ENTRY(t->cmd), s);
2640 gdk_color_parse(XT_COLOR_WHITE, &color);
2641 gtk_widget_modify_base(t->cmd, GTK_STATE_NORMAL, &color);
2642 show_cmd(t);
2643 gtk_widget_grab_focus(GTK_WIDGET(t->cmd));
2644 gtk_editable_set_position(GTK_EDITABLE(t->cmd), -1);
2646 if (ss)
2647 g_free(ss);
2649 return (XT_CB_HANDLED);
2653 search(struct tab *t, struct karg *args)
2655 gboolean d;
2657 if (t == NULL || args == NULL) {
2658 show_oops(NULL, "search invalid parameters");
2659 return (1);
2662 switch (args->i) {
2663 case XT_SEARCH_NEXT:
2664 d = t->search_forward;
2665 break;
2666 case XT_SEARCH_PREV:
2667 d = !t->search_forward;
2668 break;
2669 default:
2670 return (XT_CB_PASSTHROUGH);
2673 if (t->search_text == NULL) {
2674 if (global_search == NULL)
2675 return (XT_CB_PASSTHROUGH);
2676 else {
2677 d = t->search_forward = TRUE;
2678 t->search_text = g_strdup(global_search);
2679 webkit_web_view_mark_text_matches(t->wv, global_search, FALSE, 0);
2680 webkit_web_view_set_highlight_text_matches(t->wv, TRUE);
2684 DNPRINTF(XT_D_CMD, "search: tab %d opc %d forw %d text %s\n",
2685 t->tab_id, args->i, t->search_forward, t->search_text);
2687 webkit_web_view_search_text(t->wv, t->search_text, FALSE, d, TRUE);
2689 return (XT_CB_HANDLED);
2693 session_save(struct tab *t, char *filename)
2695 struct karg a;
2696 int rv = 1;
2697 struct session *s;
2699 if (strlen(filename) == 0)
2700 goto done;
2702 if (filename[0] == '.' || filename[0] == '/')
2703 goto done;
2705 a.s = filename;
2706 if (save_tabs(t, &a))
2707 goto done;
2708 strlcpy(named_session, filename, sizeof named_session);
2710 /* add the new session to the list of sessions */
2711 s = g_malloc(sizeof(struct session));
2712 s->name = g_strdup(filename);
2713 TAILQ_INSERT_TAIL(&sessions, s, entry);
2715 rv = 0;
2716 done:
2717 return (rv);
2721 session_open(struct tab *t, char *filename)
2723 struct karg a;
2724 int rv = 1;
2726 if (strlen(filename) == 0)
2727 goto done;
2729 if (filename[0] == '.' || filename[0] == '/')
2730 goto done;
2732 a.s = filename;
2733 a.i = XT_SES_CLOSETABS;
2734 if (open_tabs(t, &a))
2735 goto done;
2737 strlcpy(named_session, filename, sizeof named_session);
2739 rv = 0;
2740 done:
2741 return (rv);
2745 session_delete(struct tab *t, char *filename)
2747 char file[PATH_MAX];
2748 int rv = 1;
2749 struct session *s;
2751 if (strlen(filename) == 0)
2752 goto done;
2754 if (filename[0] == '.' || filename[0] == '/')
2755 goto done;
2757 snprintf(file, sizeof file, "%s" PS "%s", sessions_dir, filename);
2758 if (unlink(file))
2759 goto done;
2761 if (!strcmp(filename, named_session))
2762 strlcpy(named_session, XT_SAVED_TABS_FILE,
2763 sizeof named_session);
2765 /* remove session from sessions list */
2766 TAILQ_FOREACH(s, &sessions, entry) {
2767 if (!strcmp(s->name, filename))
2768 break;
2770 if (s == NULL)
2771 goto done;
2772 TAILQ_REMOVE(&sessions, s, entry);
2773 g_free((gpointer) s->name);
2774 g_free(s);
2776 rv = 0;
2777 done:
2778 return (rv);
2782 session_cmd(struct tab *t, struct karg *args)
2784 char *filename = args->s;
2786 if (t == NULL)
2787 return (1);
2789 if (args->i & XT_SHOW)
2790 show_oops(t, "Current session: %s", named_session[0] == '\0' ?
2791 XT_SAVED_TABS_FILE : named_session);
2792 else if (args->i & XT_SAVE) {
2793 if (session_save(t, filename)) {
2794 show_oops(t, "Can't save session: %s",
2795 filename ? filename : "INVALID");
2796 goto done;
2798 } else if (args->i & XT_OPEN) {
2799 if (session_open(t, filename)) {
2800 show_oops(t, "Can't open session: %s",
2801 filename ? filename : "INVALID");
2802 goto done;
2804 } else if (args->i & XT_DELETE) {
2805 if (session_delete(t, filename)) {
2806 show_oops(t, "Can't delete session: %s",
2807 filename ? filename : "INVALID");
2808 goto done;
2811 done:
2812 return (XT_CB_PASSTHROUGH);
2816 script_cmd(struct tab *t, struct karg *args)
2818 struct stat sb;
2819 FILE *f = NULL;
2820 char *buf = NULL;
2822 if (t == NULL)
2823 goto done;
2825 if ((f = fopen(args->s, "r")) == NULL) {
2826 show_oops(t, "Can't open script file: %s", args->s);
2827 goto done;
2830 if (fstat(fileno(f), &sb) == -1) {
2831 show_oops(t, "Can't stat script file: %s", args->s);
2832 goto done;
2835 buf = g_malloc0(sb.st_size + 1);
2836 if (fread(buf, 1, sb.st_size, f) != sb.st_size) {
2837 show_oops(t, "Can't read script file: %s", args->s);
2838 goto done;
2841 DNPRINTF(XT_D_JS, "%s: about to run script\n", __func__);
2842 run_script(t, buf);
2844 done:
2845 if (f)
2846 fclose(f);
2847 if (buf)
2848 g_free(buf);
2850 return (XT_CB_PASSTHROUGH);
2854 * Make a hardcopy of the page
2857 print_page(struct tab *t, struct karg *args)
2859 WebKitWebFrame *frame;
2860 GtkPageSetup *ps;
2861 GtkPrintOperation *op;
2862 GtkPrintOperationAction action;
2863 GtkPrintOperationResult print_res;
2864 GError *g_err = NULL;
2865 int marg_l, marg_r, marg_t, marg_b;
2867 DNPRINTF(XT_D_PRINTING, "%s:", __func__);
2869 ps = gtk_page_setup_new();
2870 op = gtk_print_operation_new();
2871 action = GTK_PRINT_OPERATION_ACTION_PRINT_DIALOG;
2872 frame = webkit_web_view_get_main_frame(t->wv);
2874 /* the default margins are too small, so we will bump them */
2875 marg_l = gtk_page_setup_get_left_margin(ps, GTK_UNIT_MM) +
2876 XT_PRINT_EXTRA_MARGIN;
2877 marg_r = gtk_page_setup_get_right_margin(ps, GTK_UNIT_MM) +
2878 XT_PRINT_EXTRA_MARGIN;
2879 marg_t = gtk_page_setup_get_top_margin(ps, GTK_UNIT_MM) +
2880 XT_PRINT_EXTRA_MARGIN;
2881 marg_b = gtk_page_setup_get_bottom_margin(ps, GTK_UNIT_MM) +
2882 XT_PRINT_EXTRA_MARGIN;
2884 /* set margins */
2885 gtk_page_setup_set_left_margin(ps, marg_l, GTK_UNIT_MM);
2886 gtk_page_setup_set_right_margin(ps, marg_r, GTK_UNIT_MM);
2887 gtk_page_setup_set_top_margin(ps, marg_t, GTK_UNIT_MM);
2888 gtk_page_setup_set_bottom_margin(ps, marg_b, GTK_UNIT_MM);
2890 gtk_print_operation_set_default_page_setup(op, ps);
2892 /* this appears to free 'op' and 'ps' */
2893 print_res = webkit_web_frame_print_full(frame, op, action, &g_err);
2895 /* check it worked */
2896 if (print_res == GTK_PRINT_OPERATION_RESULT_ERROR) {
2897 show_oops(NULL, "can't print: %s", g_err->message);
2898 g_error_free (g_err);
2899 return (1);
2902 return (0);
2906 go_home(struct tab *t, struct karg *args)
2908 load_uri(t, home);
2909 return (0);
2913 set_encoding(struct tab *t, struct karg *args)
2915 const gchar *e;
2917 if (args->s && strlen(g_strstrip(args->s)) == 0) {
2918 e = webkit_web_view_get_custom_encoding(t->wv);
2919 if (e == NULL)
2920 e = webkit_web_view_get_encoding(t->wv);
2921 show_oops(t, "encoding: %s", e ? e : "N/A");
2922 } else
2923 webkit_web_view_set_custom_encoding(t->wv, args->s);
2925 return (0);
2929 restart(struct tab *t, struct karg *args)
2931 struct karg a;
2933 a.s = XT_RESTART_TABS_FILE;
2934 save_tabs(t, &a);
2935 execvp(start_argv[0], start_argv);
2936 /* NOTREACHED */
2938 return (0);
2941 char *http_proxy_save; /* not a setting, used to toggle */
2944 proxy_cmd(struct tab *t, struct karg *args)
2946 DNPRINTF(XT_D_CMD, "%s: tab %d\n", __func__, t->tab_id);
2948 if (t == NULL)
2949 return (1);
2951 /* setup */
2952 if (http_proxy) {
2953 if (http_proxy_save)
2954 g_free(http_proxy_save);
2955 http_proxy_save = g_strdup(http_proxy);
2958 if (args->i & XT_PRXY_SHOW) {
2959 if (http_proxy)
2960 show_oops(t, "http_proxy = %s", http_proxy);
2961 else
2962 show_oops(t, "proxy is currently disabled");
2963 } else if (args->i & XT_PRXY_TOGGLE) {
2964 if (http_proxy_save == NULL && http_proxy == NULL) {
2965 show_oops(t, "can't toggle proxy");
2966 goto done;
2968 if (http_proxy)
2969 setup_proxy(NULL);
2970 else
2971 setup_proxy(http_proxy_save);
2973 done:
2974 return (XT_CB_PASSTHROUGH);
2976 struct cmd {
2977 char *cmd;
2978 int level;
2979 int (*func)(struct tab *, struct karg *);
2980 int arg;
2981 int type;
2982 } cmds[] = {
2983 { "command_mode", 0, command_mode, XT_MODE_COMMAND, 0 },
2984 { "insert_mode", 0, command_mode, XT_MODE_INSERT, 0 },
2985 { "command", 0, command, ':', 0 },
2986 { "search", 0, command, '/', 0 },
2987 { "searchb", 0, command, '?', 0 },
2988 { "hinting", 0, command, '.', 0 },
2989 { "hinting_newtab", 0, command, ',', 0 },
2990 { "togglesrc", 0, toggle_src, 0, 0 },
2991 { "editsrc", 0, edit_src, 0, 0 },
2992 { "editelement", 0, edit_element, 0, 0 },
2993 { "passthrough", 0, passthrough, 0, 0 },
2995 /* yanking and pasting */
2996 { "yankuri", 0, yank_uri, 0, 0 },
2997 /* XXX: pasteuri{cur,new} do not work from the cmd_entry? */
2998 { "pasteuricur", 0, paste_uri, XT_PASTE_CURRENT_TAB, 0 },
2999 { "pasteurinew", 0, paste_uri, XT_PASTE_NEW_TAB, 0 },
3001 /* search */
3002 { "searchnext", 0, search, XT_SEARCH_NEXT, 0 },
3003 { "searchprevious", 0, search, XT_SEARCH_PREV, 0 },
3005 /* focus */
3006 { "focusaddress", 0, focus, XT_FOCUS_URI, 0 },
3007 { "focussearch", 0, focus, XT_FOCUS_SEARCH, 0 },
3009 /* hinting */
3010 { "hinting", 0, hint, 0, 0 },
3011 { "hinting_newtab", 0, hint, XT_HINT_NEWTAB, 0 },
3013 /* custom stylesheet */
3014 { "userstyle", 0, userstyle, XT_STYLE_CURRENT_TAB, 0 },
3015 { "userstyle_global", 0, userstyle, XT_STYLE_GLOBAL, 0 },
3017 /* navigation */
3018 { "goback", 0, navaction, XT_NAV_BACK, 0 },
3019 { "goforward", 0, navaction, XT_NAV_FORWARD, 0 },
3020 { "reload", 0, navaction, XT_NAV_RELOAD, 0 },
3021 { "stop", 0, navaction, XT_NAV_STOP, 0 },
3023 /* vertical movement */
3024 { "scrolldown", 0, move, XT_MOVE_DOWN, 0 },
3025 { "scrollup", 0, move, XT_MOVE_UP, 0 },
3026 { "scrollbottom", 0, move, XT_MOVE_BOTTOM, 0 },
3027 { "scrolltop", 0, move, XT_MOVE_TOP, 0 },
3028 { "1", 0, move, XT_MOVE_TOP, 0 },
3029 { "scrollhalfdown", 0, move, XT_MOVE_HALFDOWN, 0 },
3030 { "scrollhalfup", 0, move, XT_MOVE_HALFUP, 0 },
3031 { "scrollpagedown", 0, move, XT_MOVE_PAGEDOWN, 0 },
3032 { "scrollpageup", 0, move, XT_MOVE_PAGEUP, 0 },
3033 /* horizontal movement */
3034 { "scrollright", 0, move, XT_MOVE_RIGHT, 0 },
3035 { "scrollleft", 0, move, XT_MOVE_LEFT, 0 },
3036 { "scrollfarright", 0, move, XT_MOVE_FARRIGHT, 0 },
3037 { "scrollfarleft", 0, move, XT_MOVE_FARLEFT, 0 },
3039 { "favorites", 0, xtp_page_fl, 0, 0 },
3040 { "fav", 0, xtp_page_fl, 0, 0 },
3041 { "favadd", 0, add_favorite, 0, 0 },
3043 { "qall", 0, quit, 0, 0 },
3044 { "quitall", 0, quit, 0, 0 },
3045 { "w", 0, save_tabs, 0, 0 },
3046 { "wq", 0, save_tabs_and_quit, 0, 0 },
3047 { "help", 0, help, 0, 0 },
3048 { "about", 0, about, 0, 0 },
3049 { "stats", 0, stats, 0, 0 },
3050 { "version", 0, about, 0, 0 },
3052 /* js command */
3053 { "js", 0, js_cmd, XT_SHOW | XT_WL_PERSISTENT | XT_WL_SESSION, 0 },
3054 { "save", 1, js_cmd, XT_SAVE | XT_WL_FQDN, 0 },
3055 { "domain", 2, js_cmd, XT_SAVE | XT_WL_TOPLEVEL, 0 },
3056 { "fqdn", 2, js_cmd, XT_SAVE | XT_WL_FQDN, 0 },
3057 { "show", 1, js_cmd, XT_SHOW | XT_WL_PERSISTENT | XT_WL_SESSION, 0 },
3058 { "all", 2, js_cmd, XT_SHOW | XT_WL_PERSISTENT | XT_WL_SESSION, 0 },
3059 { "persistent", 2, js_cmd, XT_SHOW | XT_WL_PERSISTENT, 0 },
3060 { "session", 2, js_cmd, XT_SHOW | XT_WL_SESSION, 0 },
3061 { "toggle", 1, js_cmd, XT_WL_TOGGLE | XT_WL_FQDN, 0 },
3062 { "domain", 2, js_cmd, XT_WL_TOGGLE | XT_WL_TOPLEVEL, 0 },
3063 { "fqdn", 2, js_cmd, XT_WL_TOGGLE | XT_WL_FQDN, 0 },
3065 /* cookie command */
3066 { "cookie", 0, cookie_cmd, XT_SHOW | XT_WL_PERSISTENT | XT_WL_SESSION, 0 },
3067 { "save", 1, cookie_cmd, XT_SAVE | XT_WL_FQDN, 0 },
3068 { "domain", 2, cookie_cmd, XT_SAVE | XT_WL_TOPLEVEL, 0 },
3069 { "fqdn", 2, cookie_cmd, XT_SAVE | XT_WL_FQDN, 0 },
3070 { "show", 1, cookie_cmd, XT_SHOW | XT_WL_PERSISTENT | XT_WL_SESSION, 0 },
3071 { "all", 2, cookie_cmd, XT_SHOW | XT_WL_PERSISTENT | XT_WL_SESSION, 0 },
3072 { "persistent", 2, cookie_cmd, XT_SHOW | XT_WL_PERSISTENT, 0 },
3073 { "session", 2, cookie_cmd, XT_SHOW | XT_WL_SESSION, 0 },
3074 { "toggle", 1, cookie_cmd, XT_WL_TOGGLE | XT_WL_FQDN, 0 },
3075 { "domain", 2, cookie_cmd, XT_WL_TOGGLE | XT_WL_TOPLEVEL, 0 },
3076 { "fqdn", 2, cookie_cmd, XT_WL_TOGGLE | XT_WL_FQDN, 0 },
3077 { "purge", 1, cookie_cmd, XT_DELETE, 0 },
3079 /* plugin command */
3080 { "plugin", 0, pl_cmd, XT_SHOW | XT_WL_PERSISTENT | XT_WL_SESSION, 0 },
3081 { "save", 1, pl_cmd, XT_SAVE | XT_WL_FQDN, 0 },
3082 { "domain", 2, pl_cmd, XT_SAVE | XT_WL_TOPLEVEL, 0 },
3083 { "fqdn", 2, pl_cmd, XT_SAVE | XT_WL_FQDN, 0 },
3084 { "show", 1, pl_cmd, XT_SHOW | XT_WL_PERSISTENT | XT_WL_SESSION, 0 },
3085 { "all", 2, pl_cmd, XT_SHOW | XT_WL_PERSISTENT | XT_WL_SESSION, 0 },
3086 { "persistent", 2, pl_cmd, XT_SHOW | XT_WL_PERSISTENT, 0 },
3087 { "session", 2, pl_cmd, XT_SHOW | XT_WL_SESSION, 0 },
3088 { "toggle", 1, pl_cmd, XT_WL_TOGGLE | XT_WL_FQDN, 0 },
3089 { "domain", 2, pl_cmd, XT_WL_TOGGLE | XT_WL_TOPLEVEL, 0 },
3090 { "fqdn", 2, pl_cmd, XT_WL_TOGGLE | XT_WL_FQDN, 0 },
3092 /* toplevel (domain) command */
3093 { "toplevel", 0, toplevel_cmd, XT_WL_TOGGLE | XT_WL_TOPLEVEL | XT_WL_RELOAD, 0 },
3094 { "toggle", 1, toplevel_cmd, XT_WL_TOGGLE | XT_WL_TOPLEVEL | XT_WL_RELOAD, 0 },
3096 /* cookie jar */
3097 { "cookiejar", 0, xtp_page_cl, 0, 0 },
3099 /* cert command */
3100 { "cert", 0, cert_cmd, XT_SHOW, 0 },
3101 { "save", 1, cert_cmd, XT_SAVE, 0 },
3102 { "show", 1, cert_cmd, XT_SHOW, 0 },
3104 { "ca", 0, ca_cmd, 0, 0 },
3105 { "downloadmgr", 0, xtp_page_dl, 0, 0 },
3106 { "dl", 0, xtp_page_dl, 0, 0 },
3107 { "h", 0, xtp_page_hl, 0, 0 },
3108 { "history", 0, xtp_page_hl, 0, 0 },
3109 { "home", 0, go_home, 0, 0 },
3110 { "restart", 0, restart, 0, 0 },
3111 { "urlhide", 0, urlaction, XT_URL_HIDE, 0 },
3112 { "urlshow", 0, urlaction, XT_URL_SHOW, 0 },
3113 { "statustoggle", 0, statustoggle, 0, 0 },
3114 { "run_script", 0, run_page_script, 0, XT_USERARG },
3116 { "print", 0, print_page, 0, 0 },
3118 /* tabs */
3119 { "focusin", 0, resizetab, XT_ZOOM_IN, 0 },
3120 { "focusout", 0, resizetab, XT_ZOOM_OUT, 0 },
3121 { "focusreset", 0, resizetab, XT_ZOOM_NORMAL, 0 },
3122 { "q", 0, tabaction, XT_TAB_DELQUIT, 0 },
3123 { "quit", 0, tabaction, XT_TAB_DELQUIT, 0 },
3124 { "open", 0, tabaction, XT_TAB_OPEN, XT_URLARG },
3125 { "tabclose", 0, tabaction, XT_TAB_DELETE, XT_PREFIX | XT_INTARG},
3126 { "tabedit", 0, tabaction, XT_TAB_NEW, XT_PREFIX | XT_URLARG },
3127 { "tabfirst", 0, movetab, XT_TAB_FIRST, 0 },
3128 { "tabhide", 0, tabaction, XT_TAB_HIDE, 0 },
3129 { "tablast", 0, movetab, XT_TAB_LAST, 0 },
3130 { "tabnew", 0, tabaction, XT_TAB_NEW, XT_PREFIX | XT_URLARG },
3131 { "tabnext", 0, movetab, XT_TAB_NEXT, XT_PREFIX | XT_INTARG},
3132 { "tabnextstyle", 0, tabaction, XT_TAB_NEXTSTYLE, 0 },
3133 { "tabprevious", 0, movetab, XT_TAB_PREV, XT_PREFIX | XT_INTARG},
3134 { "tabrewind", 0, movetab, XT_TAB_FIRST, 0 },
3135 { "tabshow", 0, tabaction, XT_TAB_SHOW, 0 },
3136 { "tabs", 0, buffers, 0, 0 },
3137 { "tabundoclose", 0, tabaction, XT_TAB_UNDO_CLOSE, 0 },
3138 { "buffers", 0, buffers, 0, 0 },
3139 { "ls", 0, buffers, 0, 0 },
3140 { "encoding", 0, set_encoding, 0, XT_USERARG },
3141 { "loadimages", 0, tabaction, XT_TAB_LOAD_IMAGES, 0 },
3143 /* command aliases (handy when -S flag is used) */
3144 { "promptopen", 0, command, XT_CMD_OPEN, 0 },
3145 { "promptopencurrent", 0, command, XT_CMD_OPEN_CURRENT, 0 },
3146 { "prompttabnew", 0, command, XT_CMD_TABNEW, 0 },
3147 { "prompttabnewcurrent",0, command, XT_CMD_TABNEW_CURRENT, 0 },
3149 /* settings */
3150 { "set", 0, set, 0, XT_SETARG },
3152 { "fullscreen", 0, fullscreen, 0, 0 },
3153 { "f", 0, fullscreen, 0, 0 },
3155 /* sessions */
3156 { "session", 0, session_cmd, XT_SHOW, 0 },
3157 { "delete", 1, session_cmd, XT_DELETE, XT_SESSARG },
3158 { "open", 1, session_cmd, XT_OPEN, XT_SESSARG },
3159 { "save", 1, session_cmd, XT_SAVE, XT_USERARG },
3160 { "show", 1, session_cmd, XT_SHOW, 0 },
3162 /* external javascript */
3163 { "script", 0, script_cmd, XT_EJS_SHOW, XT_USERARG },
3165 /* inspector */
3166 { "inspector", 0, inspector_cmd, XT_INS_SHOW, 0 },
3167 { "show", 1, inspector_cmd, XT_INS_SHOW, 0 },
3168 { "hide", 1, inspector_cmd, XT_INS_HIDE, 0 },
3170 /* proxy */
3171 { "proxy", 0, proxy_cmd, XT_PRXY_SHOW, 0 },
3172 { "show", 1, proxy_cmd, XT_PRXY_SHOW, 0 },
3173 { "toggle", 1, proxy_cmd, XT_PRXY_TOGGLE, 0 },
3176 struct {
3177 int index;
3178 int len;
3179 gchar *list[256];
3180 } cmd_status = {-1, 0};
3182 gboolean
3183 wv_release_button_cb(GtkWidget *btn, GdkEventButton *e, struct tab *t)
3186 if (e->type == GDK_BUTTON_RELEASE && e->button == 1)
3187 btn_down = 0;
3189 return (FALSE);
3192 gboolean
3193 wv_button_cb(GtkWidget *btn, GdkEventButton *e, struct tab *t)
3195 struct karg a;
3196 WebKitHitTestResult *hit_test_result;
3197 guint context;
3199 hit_test_result = webkit_web_view_get_hit_test_result(t->wv, e);
3200 g_object_get(hit_test_result, "context", &context, NULL);
3202 hide_oops(t);
3203 hide_buffers(t);
3205 if (context & WEBKIT_HIT_TEST_RESULT_CONTEXT_EDITABLE)
3206 t->mode = XT_MODE_INSERT;
3207 else
3208 t->mode = XT_MODE_COMMAND;
3210 if (e->type == GDK_BUTTON_PRESS && e->button == 1)
3211 btn_down = 1;
3212 else if (e->type == GDK_BUTTON_PRESS && e->button == 8 /* btn 4 */) {
3213 /* go backward */
3214 a.i = XT_NAV_BACK;
3215 navaction(t, &a);
3217 return (TRUE);
3218 } else if (e->type == GDK_BUTTON_PRESS && e->button == 9 /* btn 5 */) {
3219 /* go forward */
3220 a.i = XT_NAV_FORWARD;
3221 navaction(t, &a);
3223 return (TRUE);
3226 return (FALSE);
3229 gboolean
3230 tab_close_cb(GtkWidget *btn, GdkEventButton *e, struct tab *t)
3232 DNPRINTF(XT_D_TAB, "tab_close_cb: tab %d\n", t->tab_id);
3234 if (e->type == GDK_BUTTON_PRESS && e->button == 1)
3235 delete_tab(t);
3237 return (FALSE);
3242 void
3243 activate_uri_entry_cb(GtkWidget* entry, struct tab *t)
3245 const gchar *uri = gtk_entry_get_text(GTK_ENTRY(entry));
3247 DNPRINTF(XT_D_URL, "activate_uri_entry_cb: %s\n", uri);
3249 if (t == NULL) {
3250 show_oops(NULL, "activate_uri_entry_cb invalid parameters");
3251 return;
3254 if (uri == NULL) {
3255 show_oops(t, "activate_uri_entry_cb no uri");
3256 return;
3259 uri += strspn(uri, "\t ");
3261 /* if xxxt:// treat specially */
3262 if (parse_xtp_url(t, uri))
3263 return;
3265 /* otherwise continue to load page normally */
3266 load_uri(t, (gchar *)uri);
3267 focus_webview(t);
3270 void
3271 activate_search_entry_cb(GtkWidget* entry, struct tab *t)
3273 const gchar *search = gtk_entry_get_text(GTK_ENTRY(entry));
3274 char *newuri = NULL;
3275 gchar *enc_search;
3277 DNPRINTF(XT_D_URL, "activate_search_entry_cb: %s\n", search);
3279 if (t == NULL) {
3280 show_oops(NULL, "activate_search_entry_cb invalid parameters");
3281 return;
3284 if (search_string == NULL) {
3285 show_oops(t, "no search_string");
3286 return;
3289 t->xtp_meaning = XT_XTP_TAB_MEANING_NORMAL;
3291 enc_search = soup_uri_encode(search, XT_RESERVED_CHARS);
3292 newuri = g_strdup_printf(search_string, enc_search);
3293 g_free(enc_search);
3295 marks_clear(t);
3296 webkit_web_view_load_uri(t->wv, newuri);
3297 focus_webview(t);
3299 if (newuri)
3300 g_free(newuri);
3303 void
3304 check_and_set_cookie(const gchar *uri, struct tab *t)
3306 struct domain *d = NULL;
3307 int es = 0;
3309 if (uri == NULL || t == NULL)
3310 return;
3312 if ((d = wl_find_uri(uri, &c_wl)) == NULL)
3313 es = 0;
3314 else
3315 es = 1;
3317 DNPRINTF(XT_D_COOKIE, "check_and_set_cookie: %s %s\n",
3318 es ? "enable" : "disable", uri);
3320 g_object_set(G_OBJECT(t->settings),
3321 "enable-html5-local-storage", es, (char *)NULL);
3322 webkit_web_view_set_settings(t->wv, t->settings);
3325 void
3326 check_and_set_js(const gchar *uri, struct tab *t)
3328 struct domain *d = NULL;
3329 int es = 0;
3331 if (uri == NULL || t == NULL)
3332 return;
3334 if ((d = wl_find_uri(uri, &js_wl)) == NULL)
3335 es = 0;
3336 else
3337 es = 1;
3339 DNPRINTF(XT_D_JS, "check_and_set_js: %s %s\n",
3340 es ? "enable" : "disable", uri);
3342 g_object_set(G_OBJECT(t->settings),
3343 "enable-scripts", es, (char *)NULL);
3344 g_object_set(G_OBJECT(t->settings),
3345 "javascript-can-open-windows-automatically", es, (char *)NULL);
3346 webkit_web_view_set_settings(t->wv, t->settings);
3348 button_set_stockid(t->js_toggle,
3349 es ? GTK_STOCK_MEDIA_PLAY : GTK_STOCK_MEDIA_PAUSE);
3352 void
3353 check_and_set_pl(const gchar *uri, struct tab *t)
3355 struct domain *d = NULL;
3356 int es = 0;
3358 if (uri == NULL || t == NULL)
3359 return;
3361 if ((d = wl_find_uri(uri, &pl_wl)) == NULL)
3362 es = 0;
3363 else
3364 es = 1;
3366 DNPRINTF(XT_D_JS, "check_and_set_pl: %s %s\n",
3367 es ? "enable" : "disable", uri);
3369 g_object_set(G_OBJECT(t->settings),
3370 "enable-plugins", es, (char *)NULL);
3371 webkit_web_view_set_settings(t->wv, t->settings);
3374 void
3375 color_address_bar(gpointer p)
3377 GdkColor color;
3378 struct tab *tt, *t = p;
3379 gchar *col_str = XT_COLOR_WHITE;
3380 const gchar *uri, *u = NULL, *error_str = NULL;
3382 #ifdef USE_THREADS
3383 gdk_threads_enter();
3384 #endif
3385 DNPRINTF(XT_D_URL, "%s:\n", __func__);
3387 /* make sure t still exists */
3388 if (t == NULL)
3389 return;
3390 TAILQ_FOREACH(tt, &tabs, entry)
3391 if (t == tt)
3392 break;
3393 if (t != tt)
3394 goto done;
3396 if ((uri = get_uri(t)) == NULL)
3397 goto white;
3398 u = g_strdup(uri);
3400 #ifdef USE_THREADS
3401 gdk_threads_leave();
3402 #endif
3404 col_str = XT_COLOR_YELLOW;
3405 switch (load_compare_cert(u, &error_str)) {
3406 case CERT_LOCAL:
3407 col_str = XT_COLOR_BLUE;
3408 break;
3409 case CERT_TRUSTED:
3410 col_str = XT_COLOR_GREEN;
3411 break;
3412 case CERT_UNTRUSTED:
3413 col_str = XT_COLOR_YELLOW;
3414 break;
3415 case CERT_BAD:
3416 col_str = XT_COLOR_RED;
3417 break;
3420 #ifdef USE_THREADS
3421 gdk_threads_enter();
3422 #endif
3423 /* make sure t isn't deleted */
3424 TAILQ_FOREACH(tt, &tabs, entry)
3425 if (t == tt)
3426 break;
3427 if (t != tt)
3428 goto done;
3430 #ifdef USE_THREADS
3431 /* test to see if the user navigated away and canceled the thread */
3432 if (t->thread != g_thread_self())
3433 goto done;
3434 if ((uri = get_uri(t)) == NULL) {
3435 t->thread = NULL;
3436 goto done;
3438 if (strcmp(uri, u)) {
3439 /* make sure we are still the same url */
3440 t->thread = NULL;
3441 goto done;
3443 #endif
3444 white:
3445 gdk_color_parse(col_str, &color);
3446 gtk_widget_modify_base(t->uri_entry, GTK_STATE_NORMAL, &color);
3448 if (!strcmp(col_str, XT_COLOR_WHITE))
3449 statusbar_modify_attr(t, col_str, XT_COLOR_BLACK);
3450 else
3451 statusbar_modify_attr(t, XT_COLOR_BLACK, col_str);
3453 if (error_str && error_str[0] != '\0')
3454 show_oops(t, "%s", error_str);
3455 #ifdef USE_THREADS
3456 t->thread = NULL;
3457 #endif
3458 done:
3459 /* t is invalid at this point */
3460 if (u)
3461 g_free((gpointer)u);
3462 #ifdef USE_THREADS
3463 gdk_threads_leave();
3464 #endif
3467 void
3468 show_ca_status(struct tab *t, const char *uri)
3470 GdkColor color;
3471 gchar *col_str = XT_COLOR_WHITE;
3473 DNPRINTF(XT_D_URL, "show_ca_status: %d %s %s\n",
3474 ssl_strict_certs, ssl_ca_file, uri);
3476 if (t == NULL)
3477 return;
3479 if (uri == NULL)
3480 goto done;
3481 if (ssl_ca_file == NULL) {
3482 if (g_str_has_prefix(uri, "http://"))
3483 goto done;
3484 if (g_str_has_prefix(uri, "https://")) {
3485 col_str = XT_COLOR_RED;
3486 goto done;
3488 return;
3490 if (g_str_has_prefix(uri, "http://") ||
3491 !g_str_has_prefix(uri, "https://"))
3492 goto done;
3493 #ifdef USE_THREADS
3495 * It is not necessary to see if the thread is already running.
3496 * If the thread is in progress setting it to something else aborts it
3497 * on the way out.
3500 /* thread the coloring of the address bar */
3501 t->thread = g_thread_create((GThreadFunc)color_address_bar, t, TRUE, NULL);
3502 #else
3503 color_address_bar(t);
3504 #endif
3505 return;
3507 done:
3508 if (col_str) {
3509 gdk_color_parse(col_str, &color);
3510 gtk_widget_modify_base(t->uri_entry, GTK_STATE_NORMAL, &color);
3512 if (!strcmp(col_str, XT_COLOR_WHITE))
3513 statusbar_modify_attr(t, col_str, XT_COLOR_BLACK);
3514 else
3515 statusbar_modify_attr(t, XT_COLOR_BLACK, col_str);
3519 void
3520 free_favicon(struct tab *t)
3522 DNPRINTF(XT_D_DOWNLOAD, "%s: down %p req %p\n",
3523 __func__, t->icon_download, t->icon_request);
3525 if (t->icon_request)
3526 g_object_unref(t->icon_request);
3527 if (t->icon_dest_uri)
3528 g_free(t->icon_dest_uri);
3530 t->icon_request = NULL;
3531 t->icon_dest_uri = NULL;
3534 void
3535 xt_icon_from_name(struct tab *t, gchar *name)
3537 if (!enable_favicon_entry)
3538 return;
3540 gtk_entry_set_icon_from_icon_name(GTK_ENTRY(t->uri_entry),
3541 GTK_ENTRY_ICON_PRIMARY, "text-html");
3542 if (show_url == 0)
3543 gtk_entry_set_icon_from_icon_name(GTK_ENTRY(t->sbe.statusbar),
3544 GTK_ENTRY_ICON_PRIMARY, "text-html");
3545 else
3546 gtk_entry_set_icon_from_icon_name(GTK_ENTRY(t->sbe.statusbar),
3547 GTK_ENTRY_ICON_PRIMARY, NULL);
3550 void
3551 xt_icon_from_pixbuf(struct tab *t, GdkPixbuf *pb)
3553 GdkPixbuf *pb_scaled;
3555 if (gdk_pixbuf_get_width(pb) > 16 || gdk_pixbuf_get_height(pb) > 16)
3556 pb_scaled = gdk_pixbuf_scale_simple(pb, 16, 16,
3557 GDK_INTERP_BILINEAR);
3558 else
3559 pb_scaled = pb;
3561 if (enable_favicon_entry) {
3563 /* Classic tabs. */
3564 gtk_entry_set_icon_from_pixbuf(GTK_ENTRY(t->uri_entry),
3565 GTK_ENTRY_ICON_PRIMARY, pb_scaled);
3567 /* Minimal tabs. */
3568 if (show_url == 0) {
3569 gtk_entry_set_icon_from_pixbuf(GTK_ENTRY(t->sbe.statusbar),
3570 GTK_ENTRY_ICON_PRIMARY, pb_scaled);
3571 } else
3572 gtk_entry_set_icon_from_icon_name(GTK_ENTRY(t->sbe.statusbar),
3573 GTK_ENTRY_ICON_PRIMARY, NULL);
3576 /* XXX: Only supports the minimal tabs atm. */
3577 if (enable_favicon_tabs)
3578 gtk_image_set_from_pixbuf(GTK_IMAGE(t->tab_elems.favicon),
3579 pb_scaled);
3581 if (pb_scaled != pb)
3582 g_object_unref(pb_scaled);
3585 void
3586 xt_icon_from_file(struct tab *t, char *file)
3588 GdkPixbuf *pb;
3590 if (g_str_has_prefix(file, "file://"))
3591 file += strlen("file://");
3593 pb = gdk_pixbuf_new_from_file(file, NULL);
3594 if (pb) {
3595 xt_icon_from_pixbuf(t, pb);
3596 g_object_unref(pb);
3597 } else
3598 xt_icon_from_name(t, "text-html");
3601 gboolean
3602 is_valid_icon(char *file)
3604 gboolean valid = 0;
3605 const char *mime_type;
3606 GFileInfo *fi;
3607 GFile *gf;
3609 gf = g_file_new_for_path(file);
3610 fi = g_file_query_info(gf, G_FILE_ATTRIBUTE_STANDARD_CONTENT_TYPE, 0,
3611 NULL, NULL);
3612 mime_type = g_file_info_get_content_type(fi);
3613 valid = g_strcmp0(mime_type, "image/x-ico") == 0 ||
3614 g_strcmp0(mime_type, "image/vnd.microsoft.icon") == 0 ||
3615 g_strcmp0(mime_type, "image/png") == 0 ||
3616 g_strcmp0(mime_type, "image/gif") == 0 ||
3617 g_strcmp0(mime_type, "application/octet-stream") == 0;
3618 g_object_unref(fi);
3619 g_object_unref(gf);
3621 return (valid);
3624 void
3625 set_favicon_from_file(struct tab *t, char *file)
3627 struct stat sb;
3629 if (t == NULL || file == NULL)
3630 return;
3632 if (g_str_has_prefix(file, "file://"))
3633 file += strlen("file://");
3634 DNPRINTF(XT_D_DOWNLOAD, "%s: loading %s\n", __func__, file);
3636 if (!stat(file, &sb)) {
3637 if (sb.st_size == 0 || !is_valid_icon(file)) {
3638 /* corrupt icon so trash it */
3639 DNPRINTF(XT_D_DOWNLOAD, "%s: corrupt icon %s\n",
3640 __func__, file);
3641 unlink(file);
3642 /* no need to set icon to default here */
3643 return;
3646 xt_icon_from_file(t, file);
3649 void
3650 favicon_download_status_changed_cb(WebKitDownload *download, GParamSpec *spec,
3651 WebKitWebView *wv)
3653 WebKitDownloadStatus status = webkit_download_get_status(download);
3654 struct tab *tt = NULL, *t = NULL;
3657 * find the webview instead of passing in the tab as it could have been
3658 * deleted from underneath us.
3660 TAILQ_FOREACH(tt, &tabs, entry) {
3661 if (tt->wv == wv) {
3662 t = tt;
3663 break;
3666 if (t == NULL)
3667 return;
3669 DNPRINTF(XT_D_DOWNLOAD, "%s: tab %d status %d\n",
3670 __func__, t->tab_id, status);
3672 switch (status) {
3673 case WEBKIT_DOWNLOAD_STATUS_ERROR:
3674 /* -1 */
3675 t->icon_download = NULL;
3676 free_favicon(t);
3677 break;
3678 case WEBKIT_DOWNLOAD_STATUS_CREATED:
3679 /* 0 */
3680 break;
3681 case WEBKIT_DOWNLOAD_STATUS_STARTED:
3682 /* 1 */
3683 break;
3684 case WEBKIT_DOWNLOAD_STATUS_CANCELLED:
3685 /* 2 */
3686 DNPRINTF(XT_D_DOWNLOAD, "%s: freeing favicon %d\n",
3687 __func__, t->tab_id);
3688 t->icon_download = NULL;
3689 free_favicon(t);
3690 break;
3691 case WEBKIT_DOWNLOAD_STATUS_FINISHED:
3692 /* 3 */
3694 DNPRINTF(XT_D_DOWNLOAD, "%s: setting icon to %s\n",
3695 __func__, t->icon_dest_uri);
3696 set_favicon_from_file(t, t->icon_dest_uri);
3697 /* these will be freed post callback */
3698 t->icon_request = NULL;
3699 t->icon_download = NULL;
3700 break;
3701 default:
3702 break;
3706 void
3707 abort_favicon_download(struct tab *t)
3709 DNPRINTF(XT_D_DOWNLOAD, "%s: down %p\n", __func__, t->icon_download);
3711 #if !WEBKIT_CHECK_VERSION(1, 4, 0)
3712 if (t->icon_download) {
3713 g_signal_handlers_disconnect_by_func(G_OBJECT(t->icon_download),
3714 G_CALLBACK(favicon_download_status_changed_cb), t->wv);
3715 webkit_download_cancel(t->icon_download);
3716 t->icon_download = NULL;
3717 } else
3718 free_favicon(t);
3719 #endif
3721 xt_icon_from_name(t, "text-html");
3724 void
3725 notify_icon_loaded_cb(WebKitWebView *wv, gchar *uri, struct tab *t)
3727 DNPRINTF(XT_D_DOWNLOAD, "%s %s\n", __func__, uri);
3729 if (uri == NULL || t == NULL)
3730 return;
3732 #if WEBKIT_CHECK_VERSION(1, 4, 0)
3733 /* take icon from WebKitIconDatabase */
3734 GdkPixbuf *pb;
3736 pb = webkit_web_view_get_icon_pixbuf(wv);
3737 if (pb) {
3738 xt_icon_from_pixbuf(t, pb);
3739 g_object_unref(pb);
3740 } else
3741 xt_icon_from_name(t, "text-html");
3742 #elif WEBKIT_CHECK_VERSION(1, 1, 18)
3743 /* download icon to cache dir */
3744 gchar *name_hash, file[PATH_MAX];
3745 struct stat sb;
3747 if (t->icon_request) {
3748 DNPRINTF(XT_D_DOWNLOAD, "%s: download in progress\n", __func__);
3749 return;
3752 /* check to see if we got the icon in cache */
3753 name_hash = g_compute_checksum_for_string(G_CHECKSUM_SHA256, uri, -1);
3754 snprintf(file, sizeof file, "%s" PS "%s.ico", cache_dir, name_hash);
3755 g_free(name_hash);
3757 if (!stat(file, &sb)) {
3758 if (sb.st_size > 0) {
3759 DNPRINTF(XT_D_DOWNLOAD, "%s: loading from cache %s\n",
3760 __func__, file);
3761 set_favicon_from_file(t, file);
3762 return;
3765 /* corrupt icon so trash it */
3766 DNPRINTF(XT_D_DOWNLOAD, "%s: corrupt icon %s\n",
3767 __func__, file);
3768 unlink(file);
3771 /* create download for icon */
3772 t->icon_request = webkit_network_request_new(uri);
3773 if (t->icon_request == NULL) {
3774 DNPRINTF(XT_D_DOWNLOAD, "%s: invalid uri %s\n",
3775 __func__, uri);
3776 return;
3779 t->icon_download = webkit_download_new(t->icon_request);
3780 if (t->icon_download == NULL)
3781 return;
3783 /* we have to free icon_dest_uri later */
3784 t->icon_dest_uri = g_strdup_printf("file://%s", file);
3785 webkit_download_set_destination_uri(t->icon_download,
3786 t->icon_dest_uri);
3788 if (webkit_download_get_status(t->icon_download) ==
3789 WEBKIT_DOWNLOAD_STATUS_ERROR) {
3790 g_object_unref(t->icon_request);
3791 g_free(t->icon_dest_uri);
3792 t->icon_request = NULL;
3793 t->icon_dest_uri = NULL;
3794 return;
3797 g_signal_connect(G_OBJECT(t->icon_download), "notify::status",
3798 G_CALLBACK(favicon_download_status_changed_cb), t->wv);
3800 webkit_download_start(t->icon_download);
3801 #endif
3804 void
3805 notify_load_status_cb(WebKitWebView* wview, GParamSpec* pspec, struct tab *t)
3807 const gchar *uri = NULL;
3808 struct history *h, find;
3809 struct karg a;
3810 GdkColor color;
3812 DNPRINTF(XT_D_URL, "notify_load_status_cb: %d %s\n",
3813 webkit_web_view_get_load_status(wview),
3814 get_uri(t) ? get_uri(t) : "NOTHING");
3816 if (t == NULL) {
3817 show_oops(NULL, "notify_load_status_cb invalid parameters");
3818 return;
3821 switch (webkit_web_view_get_load_status(wview)) {
3822 case WEBKIT_LOAD_PROVISIONAL:
3823 /* 0 */
3824 abort_favicon_download(t);
3825 #if GTK_CHECK_VERSION(2, 20, 0)
3826 gtk_widget_show(t->spinner);
3827 gtk_spinner_start(GTK_SPINNER(t->spinner));
3828 #endif
3829 gtk_label_set_text(GTK_LABEL(t->label), "Loading");
3831 gtk_widget_set_sensitive(GTK_WIDGET(t->stop), TRUE);
3833 /* assume we are a new address */
3834 gdk_color_parse("white", &color);
3835 gtk_widget_modify_base(t->uri_entry, GTK_STATE_NORMAL, &color);
3836 statusbar_modify_attr(t, "white", XT_COLOR_BLACK);
3838 /* take focus if we are visible */
3839 focus_webview(t);
3840 t->focus_wv = 1;
3842 marks_clear(t);
3843 #ifdef USE_THREAD
3844 /* kill color thread */
3845 t->thread = NULL;
3846 #endif
3847 break;
3849 case WEBKIT_LOAD_COMMITTED:
3850 /* 1 */
3851 uri = get_uri(t);
3852 if (uri == NULL)
3853 return;
3854 gtk_entry_set_text(GTK_ENTRY(t->uri_entry), uri);
3856 if (t->status) {
3857 g_free(t->status);
3858 t->status = NULL;
3860 set_status(t, (char *)uri, XT_STATUS_LOADING);
3862 /* check if js white listing is enabled */
3863 if (enable_plugin_whitelist)
3864 check_and_set_pl(uri, t);
3865 if (enable_cookie_whitelist)
3866 check_and_set_cookie(uri, t);
3867 if (enable_js_whitelist)
3868 check_and_set_js(uri, t);
3870 if (t->styled)
3871 apply_style(t);
3874 /* we know enough to autosave the session */
3875 if (session_autosave) {
3876 a.s = NULL;
3877 save_tabs(t, &a);
3880 show_ca_status(t, uri);
3881 run_script(t, JS_HINTING);
3882 if (enable_autoscroll)
3883 run_script(t, JS_AUTOSCROLL);
3884 break;
3886 case WEBKIT_LOAD_FIRST_VISUALLY_NON_EMPTY_LAYOUT:
3887 /* 3 */
3888 if (color_visited_uris) {
3889 color_visited(t, color_visited_helper());
3891 /* This colors the links you middle-click (open in new
3892 * tab) in the current tab. */
3893 if (t->tab_id != gtk_notebook_get_current_page(notebook) &&
3894 (uri = get_uri(t)) != NULL)
3895 color_visited(get_current_tab(),
3896 g_strdup_printf("{'%s' : 'dummy'}", uri));
3898 break;
3900 case WEBKIT_LOAD_FINISHED:
3901 /* 2 */
3902 if ((uri = get_uri(t)) == NULL)
3903 return;
3905 if (!strncmp(uri, "http://", strlen("http://")) ||
3906 !strncmp(uri, "https://", strlen("https://")) ||
3907 !strncmp(uri, "file://", strlen("file://"))) {
3908 find.uri = (gchar *)uri;
3909 h = RB_FIND(history_list, &hl, &find);
3910 if (!h)
3911 insert_history_item(uri,
3912 get_title(t, FALSE), time(NULL));
3913 else
3914 h->time = time(NULL);
3917 set_status(t, (char *)uri, XT_STATUS_URI);
3918 #if WEBKIT_CHECK_VERSION(1, 1, 18)
3919 case WEBKIT_LOAD_FAILED:
3920 /* 4 */
3921 #endif
3922 #if GTK_CHECK_VERSION(2, 20, 0)
3923 gtk_spinner_stop(GTK_SPINNER(t->spinner));
3924 gtk_widget_hide(t->spinner);
3925 #endif
3926 default:
3927 gtk_widget_set_sensitive(GTK_WIDGET(t->stop), FALSE);
3928 break;
3931 if (t->item)
3932 gtk_widget_set_sensitive(GTK_WIDGET(t->backward), TRUE);
3933 else
3934 gtk_widget_set_sensitive(GTK_WIDGET(t->backward),
3935 can_go_back_for_real(t));
3937 gtk_widget_set_sensitive(GTK_WIDGET(t->forward),
3938 can_go_forward_for_real(t));
3941 void
3942 notify_title_cb(WebKitWebView* wview, GParamSpec* pspec, struct tab *t)
3944 const gchar *title = NULL, *win_title = NULL;
3946 title = get_title(t, FALSE);
3947 win_title = get_title(t, TRUE);
3948 if (title) {
3949 gtk_label_set_text(GTK_LABEL(t->label), title);
3950 gtk_label_set_text(GTK_LABEL(t->tab_elems.label), title);
3953 if (win_title && t->tab_id == gtk_notebook_get_current_page(notebook))
3954 gtk_window_set_title(GTK_WINDOW(main_window), win_title);
3957 char *
3958 get_domain(const gchar *host)
3960 size_t x;
3961 char *p;
3963 /* handle silly domains like .co.uk */
3965 if ((x = strlen(host)) <= 6)
3966 return (g_strdup(host));
3968 if (host[x - 3] == '.' && host[x - 6] == '.') {
3969 x = x - 7;
3970 while (x > 0)
3971 if (host[x] != '.')
3972 x--;
3973 else
3974 return (g_strdup(&host[x + 1]));
3977 /* find first . */
3978 p = g_strrstr(host, ".");
3979 if (p == NULL)
3980 return (g_strdup(""));
3981 p--;
3982 while (p > host)
3983 if (*p != '.')
3984 p--;
3985 else
3986 return (g_strdup(p + 1));
3988 return (g_strdup(host));
3991 void
3992 js_autorun(struct tab *t)
3994 SoupURI *su = NULL;
3995 const gchar *uri;
3996 size_t got_default = 0, got_host = 0;
3997 struct stat sb;
3998 char deff[PATH_MAX], hostf[PATH_MAX];
3999 char *js = NULL, *jsat, *domain = NULL;
4000 FILE *deffile = NULL, *hostfile = NULL;
4002 if (js_autorun_enabled == 0)
4003 return;
4005 uri = get_uri(t);
4006 if (uri &&
4007 !(g_str_has_prefix(uri, "http://") ||
4008 g_str_has_prefix(uri, "https://")))
4009 goto done;
4011 su = soup_uri_new(uri);
4012 if (su == NULL)
4013 goto done;
4014 if (!SOUP_URI_VALID_FOR_HTTP(su))
4015 goto done;
4017 DNPRINTF(XT_D_JS, "%s: host: %s domain: %s\n", __func__,
4018 su->host, domain);
4019 domain = get_domain(su->host);
4021 snprintf(deff, sizeof deff, "%s" PS "default.js", js_dir);
4022 if ((deffile = fopen(deff, "r")) != NULL) {
4023 if (fstat(fileno(deffile), &sb) == -1) {
4024 show_oops(t, "can't stat default JS file");
4025 goto done;
4027 got_default = sb.st_size;
4030 /* try host first followed by domain */
4031 snprintf(hostf, sizeof hostf, "%s" PS "%s.js", js_dir, su->host);
4032 DNPRINTF(XT_D_JS, "trying file: %s\n", hostf);
4033 if ((hostfile = fopen(hostf, "r")) == NULL) {
4034 snprintf(hostf, sizeof hostf, "%s" PS "%s.js", js_dir, domain);
4035 DNPRINTF(XT_D_JS, "trying file: %s\n", hostf);
4036 if ((hostfile = fopen(hostf, "r")) == NULL)
4037 goto nofile;
4039 DNPRINTF(XT_D_JS, "file: %s\n", hostf);
4040 if (fstat(fileno(hostfile), &sb) == -1) {
4041 show_oops(t, "can't stat %s JS file", hostf);
4042 goto done;
4044 got_host = sb.st_size;
4046 nofile:
4047 if (got_default + got_host == 0)
4048 goto done;
4050 js = g_malloc0(got_default + got_host + 1);
4051 jsat = js;
4053 if (got_default) {
4054 if (fread(js, got_default, 1, deffile) != 1) {
4055 show_oops(t, "default file read error");
4056 goto done;
4058 jsat = js + got_default;
4061 if (got_host) {
4062 if (fread(jsat, got_host, 1, hostfile) != 1) {
4063 show_oops(t, "host file read error");
4064 goto done;
4068 DNPRINTF(XT_D_JS, "%s: about to run script\n", __func__);
4069 run_script(t, js);
4071 done:
4072 if (su)
4073 soup_uri_free(su);
4074 if (js)
4075 g_free(js);
4076 if (deffile)
4077 fclose(deffile);
4078 if (hostfile)
4079 fclose(hostfile);
4080 if (domain)
4081 g_free(domain);
4084 void
4085 webview_load_finished_cb(WebKitWebView *wv, WebKitWebFrame *wf, struct tab *t)
4087 /* autorun some js if enabled */
4088 js_autorun(t);
4090 input_autofocus(t);
4094 void
4095 webview_progress_changed_cb(WebKitWebView *wv, int progress, struct tab *t)
4097 gtk_entry_set_progress_fraction(GTK_ENTRY(t->uri_entry),
4098 progress == 100 ? 0 : (double)progress / 100);
4099 if (show_url == 0) {
4100 gtk_entry_set_progress_fraction(GTK_ENTRY(t->sbe.statusbar),
4101 progress == 100 ? 0 : (double)progress / 100);
4104 update_statusbar_position(NULL, NULL);
4108 strict_transport_rb_cmp(struct strict_transport *a, struct strict_transport *b)
4110 char *p1, *p2;
4111 int l1, l2;
4113 /* compare strings from the end */
4114 l1 = strlen(a->host);
4115 l2 = strlen(b->host);
4117 p1 = a->host + l1;
4118 p2 = b->host + l2;
4119 for (; *p1 == *p2 && p1 > a->host && p2 > b->host;
4120 p1--, p2--)
4124 * Check if we need to do pattern expansion,
4125 * or if we're just keeping the tree in order
4127 if (a->flags & XT_STS_FLAGS_EXPAND &&
4128 b->flags & XT_STS_FLAGS_INCLUDE_SUBDOMAINS) {
4129 /* Check if we're matching the
4130 * 'host.xyz' part in '*.host.xyz'
4132 if (p2 == b->host && (p1 == a->host || *(p1-1) == '.')) {
4133 return (0);
4137 if (p1 == a->host && p2 == b->host)
4138 return (0);
4139 if (p1 == a->host)
4140 return (1);
4141 if (p2 == b->host)
4142 return (-1);
4144 if (*p1 < *p2)
4145 return (-1);
4146 if (*p1 > *p2)
4147 return (1);
4149 return (0);
4151 RB_GENERATE(strict_transport_tree, strict_transport, entry,
4152 strict_transport_rb_cmp);
4155 strict_transport_add(const char *domain, time_t timeout, int subdomains)
4157 struct strict_transport *d, find;
4158 time_t now;
4159 FILE *f;
4161 if (enable_strict_transport == FALSE)
4162 return (0);
4164 DPRINTF("strict_transport_add(%s,%ld,%d)\n", domain, timeout,
4165 subdomains);
4167 now = time(NULL);
4168 if (timeout < now)
4169 return (0);
4171 find.host = (char *)domain;
4172 find.flags = 0;
4173 d = RB_FIND(strict_transport_tree, &st_tree, &find);
4175 /* update flags */
4176 if (d) {
4177 /* check if update is needed */
4178 if (d->timeout == timeout &&
4179 (d->flags & XT_STS_FLAGS_INCLUDE_SUBDOMAINS) == subdomains)
4180 return (0);
4182 d->timeout = timeout;
4183 if (subdomains)
4184 d->flags |= XT_STS_FLAGS_INCLUDE_SUBDOMAINS;
4186 /* We're still initializing */
4187 if (strict_transport_file == NULL)
4188 return (0);
4190 if ((f = fopen(strict_transport_file, "w")) == NULL) {
4191 show_oops(NULL,
4192 "can't open strict-transport rules file");
4193 return (1);
4196 fprintf(f, "# Generated file - do not update unless you know "
4197 "what you're doing\n");
4198 RB_FOREACH(d, strict_transport_tree, &st_tree) {
4199 if (d->timeout < now)
4200 continue;
4201 fprintf(f, "%s\t%d\t%d\n", d->host, (int)d->timeout,
4202 d->flags & XT_STS_FLAGS_INCLUDE_SUBDOMAINS);
4204 fclose(f);
4205 } else {
4206 d = g_malloc(sizeof *d);
4207 d->host= g_strdup(domain);
4208 d->timeout = timeout;
4209 if (subdomains)
4210 d->flags = XT_STS_FLAGS_INCLUDE_SUBDOMAINS;
4211 else
4212 d->flags = 0;
4213 RB_INSERT(strict_transport_tree, &st_tree, d);
4215 /* We're still initializing */
4216 if (strict_transport_file == NULL)
4217 return (0);
4219 if ((f = fopen(strict_transport_file, "a+")) == NULL) {
4220 show_oops(NULL,
4221 "can't open strict-transport rules file");
4222 return (1);
4225 fseek(f, 0, SEEK_END);
4226 fprintf(f,"%s\t%d\t%d\n", d->host, (int)timeout, subdomains);
4227 fclose(f);
4229 return (0);
4233 strict_transport_check(const char *host)
4235 static struct strict_transport *d = NULL;
4236 struct strict_transport find;
4238 if (enable_strict_transport == FALSE)
4239 return (0);
4241 find.host = (char *)host;
4243 /* match for domains that include subdomains */
4244 find.flags = XT_STS_FLAGS_EXPAND;
4246 /* First, check if we're already at the right node */
4247 if (d != NULL && strict_transport_rb_cmp(&find, d) == 0) {
4248 return (1);
4251 d = RB_FIND(strict_transport_tree, &st_tree, &find);
4252 if (d != NULL)
4253 return (1);
4255 return (0);
4259 strict_transport_init()
4261 char file[PATH_MAX];
4262 char delim[3];
4263 char *rule;
4264 char *ptr;
4265 FILE *f;
4266 size_t len;
4267 time_t timeout, now;
4268 int subdomains;
4270 snprintf(file, sizeof file, "%s" PS "%s", work_dir, XT_STS_FILE);
4271 if ((f = fopen(file, "r")) == NULL) {
4272 strict_transport_file = g_strdup(file);
4273 return (0);
4276 delim[0] = '\\';
4277 delim[1] = '\\';
4278 delim[2] = '#';
4279 rule = NULL;
4280 now = time(NULL);
4282 for (;;) {
4283 if ((rule = fparseln(f, &len, NULL, delim, 0)) == NULL) {
4284 if (!feof(f) || ferror(f))
4285 goto corrupt_file;
4286 else
4287 break;
4290 /* get second entry */
4291 if ((ptr = strpbrk(rule, " \t")) == NULL)
4292 goto corrupt_file;
4294 *ptr++ = '\0';
4295 timeout = atoi(ptr);
4297 /* get third entry */
4298 if ((ptr = strpbrk(ptr, " \t")) == NULL)
4299 goto corrupt_file;
4301 ptr ++;
4302 subdomains = atoi(ptr);
4304 if (timeout > now)
4305 strict_transport_add(rule, timeout, subdomains);
4306 free(rule);
4309 fclose(f);
4310 strict_transport_file = g_strdup(file);
4311 return (0);
4313 corrupt_file:
4314 startpage_add("strict-transport rules file ('%s') is corrupt", file);
4315 if (rule)
4316 free(rule);
4317 fclose(f);
4318 return (1);
4321 void
4322 strict_transport_security_cb(SoupMessage *msg, gpointer data)
4324 SoupURI *uri;
4325 const char *sts;
4326 char *ptr;
4327 int timeout = 0;
4328 int subdomains = FALSE;
4330 if (msg == NULL)
4331 return;
4333 sts = soup_message_headers_get_one(msg->response_headers,
4334 "Strict-Transport-Security");
4335 uri = soup_message_get_uri(msg);
4337 if (sts == NULL || uri == NULL)
4338 return;
4340 if ((ptr = strcasestr(sts, "max-age="))) {
4341 ptr += strlen("max-age=");
4342 timeout = atoi(ptr);
4343 } else
4344 return; /* malformed header - max-age must be included */
4346 if ((ptr = strcasestr(sts, "includeSubDomains")))
4347 subdomains = TRUE;
4349 strict_transport_add(uri->host, timeout + time(NULL), subdomains);
4352 void
4353 session_rq_cb(SoupSession *s, SoupMessage *msg, SoupSocket *socket,
4354 gpointer data)
4356 SoupURI *dest;
4357 const char *ref;
4359 if (s == NULL || msg == NULL)
4360 return;
4362 if (referer_mode == XT_REFERER_ALWAYS)
4363 return;
4365 /* Check if referer is set - and what the user requested for referers */
4366 ref = soup_message_headers_get_one(msg->request_headers, "Referer");
4367 if (ref) {
4368 DNPRINTF(XT_D_NAV, "session_rq_cb: Referer: %s\n", ref);
4369 switch (referer_mode) {
4370 case XT_REFERER_NEVER:
4371 DNPRINTF(XT_D_NAV, "session_rq_cb: removing referer\n");
4372 soup_message_headers_remove(msg->request_headers,
4373 "Referer");
4374 break;
4375 case XT_REFERER_SAME_DOMAIN:
4376 dest = soup_message_get_uri(msg);
4378 if (dest && !strstr(ref, dest->host)) {
4379 soup_message_headers_remove(msg->request_headers,
4380 "Referer");
4381 DNPRINTF(XT_D_NAV, "session_rq_cb: removing "
4382 "referer (not same domain) (should be %s)\n",
4383 dest->host);
4385 break;
4386 case XT_REFERER_CUSTOM:
4387 DNPRINTF(XT_D_NAV, "session_rq_cb: setting referer "
4388 "to %s\n", referer_custom);
4389 soup_message_headers_replace(msg->request_headers,
4390 "Referer", referer_custom);
4391 break;
4395 if (enable_strict_transport) {
4396 soup_message_add_header_handler(msg, "finished",
4397 "Strict-Transport-Security",
4398 G_CALLBACK(strict_transport_security_cb), NULL);
4403 webview_npd_cb(WebKitWebView *wv, WebKitWebFrame *wf,
4404 WebKitNetworkRequest *request, WebKitWebNavigationAction *na,
4405 WebKitWebPolicyDecision *pd, struct tab *t)
4407 char *uri;
4408 WebKitWebNavigationReason reason;
4409 struct domain *d = NULL;
4411 if (t == NULL) {
4412 show_oops(NULL, "webview_npd_cb invalid parameters");
4413 return (FALSE);
4416 DNPRINTF(XT_D_NAV, "webview_npd_cb: ctrl_click %d %s\n",
4417 t->ctrl_click,
4418 webkit_network_request_get_uri(request));
4420 uri = (char *)webkit_network_request_get_uri(request);
4422 if (!auto_load_images && t->load_images) {
4424 /* Disable autoloading of images, now that we're done loading
4425 * them. */
4426 g_object_set(G_OBJECT(t->settings),
4427 "auto-load-images", FALSE, (char *)NULL);
4428 webkit_web_view_set_settings(t->wv, t->settings);
4430 t->load_images = FALSE;
4433 /* If this is an xtp url, we don't load anything else. */
4434 if (parse_xtp_url(t, uri))
4435 return (TRUE);
4437 if ((t->mode == XT_MODE_HINT && t->new_tab) || t->ctrl_click) {
4438 t->ctrl_click = 0;
4439 create_new_tab(uri, NULL, ctrl_click_focus, -1);
4440 webkit_web_policy_decision_ignore(pd);
4441 return (TRUE); /* we made the decission */
4444 /* Change user agent if more than one has been given. */
4445 if (user_agent_count > 1) {
4446 struct user_agent *ua;
4448 if ((ua = TAILQ_NEXT(user_agent, entry)) == NULL)
4449 user_agent = TAILQ_FIRST(&ua_list);
4450 else
4451 user_agent = ua;
4453 free(t->user_agent);
4454 t->user_agent = g_strdup(user_agent->value);
4456 DNPRINTF(XT_D_NAV, "user-agent: %s\n", t->user_agent);
4458 g_object_set(G_OBJECT(t->settings),
4459 "user-agent", t->user_agent, (char *)NULL);
4461 webkit_web_view_set_settings(wv, t->settings);
4465 * This is a little hairy but it comes down to this:
4466 * when we run in whitelist mode we have to assist the browser in
4467 * opening the URL that it would have opened in a new tab.
4469 reason = webkit_web_navigation_action_get_reason(na);
4470 if (reason == WEBKIT_WEB_NAVIGATION_REASON_LINK_CLICKED) {
4471 t->xtp_meaning = XT_XTP_TAB_MEANING_NORMAL;
4472 if (enable_scripts == 0 && enable_cookie_whitelist == 1)
4473 if (uri && (d = wl_find_uri(uri, &js_wl)) == NULL)
4474 load_uri(t, uri);
4475 webkit_web_policy_decision_use(pd);
4476 return (TRUE); /* we made the decision */
4479 return (FALSE);
4482 void
4483 webview_rrs_cb(WebKitWebView *wv, WebKitWebFrame *wf, WebKitWebResource *res,
4484 WebKitNetworkRequest *request, WebKitNetworkResponse *response,
4485 struct tab *t)
4487 SoupMessage *msg;
4488 SoupURI *uri;
4490 msg = webkit_network_request_get_message(request);
4491 if (!msg) return;
4493 uri = soup_message_get_uri(msg);
4494 if (!uri) return;
4496 if (strcmp(soup_uri_get_scheme(uri), SOUP_URI_SCHEME_HTTP) == 0) {
4497 if (strict_transport_check(uri->host)) {
4498 DNPRINTF(XT_D_NAV, "webview_rrs_cb: force https for %s\n",
4499 uri->host);
4500 soup_uri_set_scheme(uri, SOUP_URI_SCHEME_HTTPS);
4505 WebKitWebView *
4506 webview_cwv_cb(WebKitWebView *wv, WebKitWebFrame *wf, struct tab *t)
4508 struct tab *tt;
4509 struct domain *d = NULL;
4510 const gchar *uri;
4511 WebKitWebView *webview = NULL;
4512 int x = 1;
4514 DNPRINTF(XT_D_NAV, "webview_cwv_cb: %s\n",
4515 webkit_web_view_get_uri(wv));
4517 if (tabless) {
4518 /* open in current tab */
4519 webview = t->wv;
4520 } else if (enable_scripts == 0 && enable_js_whitelist == 1) {
4521 uri = webkit_web_view_get_uri(wv);
4522 if (uri && (d = wl_find_uri(uri, &js_wl)) == NULL)
4523 return (NULL);
4525 if (t->ctrl_click) {
4526 x = ctrl_click_focus;
4527 t->ctrl_click = 0;
4529 tt = create_new_tab(NULL, NULL, x, -1);
4530 webview = tt->wv;
4531 } else if (enable_scripts == 1) {
4532 if (t->ctrl_click) {
4533 x = ctrl_click_focus;
4534 t->ctrl_click = 0;
4536 tt = create_new_tab(NULL, NULL, x, -1);
4537 webview = tt->wv;
4540 return (webview);
4543 gboolean
4544 webview_closewv_cb(WebKitWebView *wv, struct tab *t)
4546 const gchar *uri;
4547 struct domain *d = NULL;
4549 DNPRINTF(XT_D_NAV, "webview_close_cb: %d\n", t->tab_id);
4551 if (enable_scripts == 0 && enable_cookie_whitelist == 1) {
4552 uri = webkit_web_view_get_uri(wv);
4553 if (uri && (d = wl_find_uri(uri, &js_wl)) == NULL)
4554 return (FALSE);
4556 delete_tab(t);
4557 } else if (enable_scripts == 1)
4558 delete_tab(t);
4560 return (TRUE);
4564 webview_event_cb(GtkWidget *w, GdkEventButton *e, struct tab *t)
4566 /* we can not eat the event without throwing gtk off so defer it */
4568 /* catch middle click */
4569 if (e->type == GDK_BUTTON_RELEASE && e->button == 2) {
4570 t->ctrl_click = 1;
4571 goto done;
4574 /* catch ctrl click */
4575 if (e->type == GDK_BUTTON_RELEASE &&
4576 CLEAN(e->state) == GDK_CONTROL_MASK)
4577 t->ctrl_click = 1;
4578 else
4579 t->ctrl_click = 0;
4580 done:
4581 return (XT_CB_PASSTHROUGH);
4585 run_mimehandler(struct tab *t, char *mime_type, WebKitNetworkRequest *request)
4587 struct mime_type *m;
4589 m = find_mime_type(mime_type);
4590 if (m == NULL)
4591 return (1);
4592 if (m->mt_download)
4593 return (1);
4595 return (fork_exec(t, m->mt_action,
4596 webkit_network_request_get_uri(request),
4597 "can't launch MIME handler", 0));
4600 char *
4601 get_mime_type(const char *file)
4603 const gchar *m;
4604 char *mime_type = NULL;
4605 GFileInfo *fi;
4606 GFile *gf;
4608 if (g_str_has_prefix(file, "file://"))
4609 file += strlen("file://");
4611 gf = g_file_new_for_path(file);
4612 fi = g_file_query_info(gf, G_FILE_ATTRIBUTE_STANDARD_CONTENT_TYPE, 0,
4613 NULL, NULL);
4614 if ((m = g_file_info_get_content_type(fi)) != NULL)
4615 mime_type = g_strdup(m);
4616 g_object_unref(fi);
4617 g_object_unref(gf);
4619 return (mime_type);
4623 run_download_mimehandler(char *mime_type, char *file)
4625 struct mime_type *m;
4627 m = find_mime_type(mime_type);
4628 if (m == NULL)
4629 return (1);
4631 return (fork_exec(NULL, m->mt_action, file,
4632 "can't launch download MIME handler", 0));
4635 void
4636 download_status_changed_cb(WebKitDownload *download, GParamSpec *spec,
4637 WebKitWebView *wv)
4639 WebKitDownloadStatus status;
4640 const char *file = NULL;
4641 char *mime = NULL;
4643 if (download == NULL)
4644 return;
4645 status = webkit_download_get_status(download);
4646 if (status != WEBKIT_DOWNLOAD_STATUS_FINISHED)
4647 return;
4649 file = webkit_download_get_destination_uri(download);
4650 if (file == NULL)
4651 return;
4652 mime = get_mime_type(file);
4653 if (mime == NULL)
4654 return;
4656 if (g_str_has_prefix(file, "file://"))
4657 file += strlen("file://");
4658 run_download_mimehandler((char *)mime, (char *)file);
4659 g_free(mime);
4663 webview_mimetype_cb(WebKitWebView *wv, WebKitWebFrame *frame,
4664 WebKitNetworkRequest *request, char *mime_type,
4665 WebKitWebPolicyDecision *decision, struct tab *t)
4667 if (t == NULL) {
4668 show_oops(NULL, "webview_mimetype_cb invalid parameters");
4669 return (FALSE);
4672 DNPRINTF(XT_D_DOWNLOAD, "webview_mimetype_cb: tab %d mime %s\n",
4673 t->tab_id, mime_type);
4675 if (run_mimehandler(t, mime_type, request) == 0) {
4676 webkit_web_policy_decision_ignore(decision);
4677 focus_webview(t);
4678 return (TRUE);
4681 if (webkit_web_view_can_show_mime_type(wv, mime_type) == FALSE) {
4682 webkit_web_policy_decision_download(decision);
4683 return (TRUE);
4686 return (FALSE);
4690 download_start(struct tab *t, struct download *d, int flag)
4692 WebKitNetworkRequest *req;
4693 struct stat sb;
4694 const gchar *suggested_name;
4695 gchar *filename = NULL;
4696 char *uri = NULL;
4697 int ret = TRUE;
4698 int i;
4700 if (d == NULL || t == NULL) {
4701 show_oops(NULL, "%s invalid parameters", __func__);
4702 return (FALSE);
4705 suggested_name = webkit_download_get_suggested_filename(d->download);
4706 if (suggested_name == NULL)
4707 return (FALSE); /* abort download */
4709 i = 0;
4710 do {
4711 if (filename) {
4712 g_free(filename);
4713 filename = NULL;
4715 if (i) {
4716 g_free(uri);
4717 uri = NULL;
4718 filename = g_strdup_printf("%d%s", i, suggested_name);
4720 #ifdef __MINGW32__
4721 uri = g_strdup_printf("%s\\%s", download_dir, i ?
4722 filename : suggested_name);
4723 #else
4724 uri = g_strdup_printf("file://%s/%s", download_dir, i ?
4725 filename : suggested_name);
4726 #endif
4727 i++;
4728 #ifdef __MINGW32__
4729 } while (!stat(uri, &sb));
4730 #else
4731 } while (!stat(uri + strlen("file://"), &sb)); /* XXX is the + strlen right? */
4732 #endif
4734 DNPRINTF(XT_D_DOWNLOAD, "%s: tab %d filename %s "
4735 "local %s\n", __func__, t->tab_id, filename, uri);
4737 /* if we're restarting the download, or starting
4738 * it after doing something else, we need to recreate
4739 * the download request.
4741 if (flag == XT_DL_RESTART) {
4742 req = webkit_network_request_new(webkit_download_get_uri(d->download));
4743 webkit_download_cancel(d->download);
4744 g_object_unref(d->download);
4745 d->download = webkit_download_new(req);
4748 webkit_download_set_destination_uri(d->download, uri);
4750 if (webkit_download_get_status(d->download) ==
4751 WEBKIT_DOWNLOAD_STATUS_ERROR) {
4752 show_oops(t, "%s: download failed to start", __func__);
4753 ret = FALSE;
4754 gtk_label_set_text(GTK_LABEL(t->label), "Download Failed");
4755 } else {
4756 /* connect "download first" mime handler */
4757 g_signal_connect(G_OBJECT(d->download), "notify::status",
4758 G_CALLBACK(download_status_changed_cb), NULL);
4760 /* get from history */
4761 g_object_ref(d->download);
4762 gtk_label_set_text(GTK_LABEL(t->label), "Downloading");
4763 show_oops(t, "Download of '%s' started...",
4764 basename((char *)webkit_download_get_destination_uri(d->download)));
4767 if (flag != XT_DL_START)
4768 webkit_download_start(d->download);
4770 DNPRINTF(XT_D_DOWNLOAD, "download status : %d",
4771 webkit_download_get_status(d->download));
4773 /* sync other download manager tabs */
4774 update_download_tabs(NULL);
4776 if (uri)
4777 g_free(uri);
4779 if (filename)
4780 g_free(filename);
4782 return (ret);
4786 download_ask_cb(struct tab *t, GdkEventKey *e, gpointer data)
4788 struct download *d = data;
4790 /* unset mode */
4791 t->mode_cb = NULL;
4792 t->mode_cb_data = NULL;
4794 if (!e || !d) {
4795 e->keyval = GDK_Escape;
4796 return (XT_CB_PASSTHROUGH);
4799 DPRINTF("download_ask_cb: User pressed %c\n", e->keyval);
4800 if (e->keyval == 'y' || e->keyval == 'Y' || e->keyval == GDK_Return)
4801 /* We need to do a RESTART, because we're not calling from
4802 * webview_download_cb
4804 download_start(t, d, XT_DL_RESTART);
4806 /* for all other keyvals, we just let the download be */
4807 e->keyval = GDK_Escape;
4808 return (XT_CB_HANDLED);
4812 download_ask(struct tab *t, struct download *d)
4814 const gchar *suggested_name;
4816 suggested_name = webkit_download_get_suggested_filename(d->download);
4817 if (suggested_name == NULL)
4818 return (FALSE); /* abort download */
4820 show_oops(t, "download file %s [y/n] ?", suggested_name);
4821 t->mode_cb = download_ask_cb;
4822 t->mode_cb_data = d;
4824 return (TRUE);
4828 webview_download_cb(WebKitWebView *wv, WebKitDownload *wk_download,
4829 struct tab *t)
4831 const gchar *suggested_name;
4832 struct download *download_entry;
4833 int ret = TRUE;
4835 if (wk_download == NULL || t == NULL) {
4836 show_oops(NULL, "%s invalid parameters", __func__);
4837 return (FALSE);
4840 suggested_name = webkit_download_get_suggested_filename(wk_download);
4841 if (suggested_name == NULL)
4842 return (FALSE); /* abort download */
4844 download_entry = g_malloc(sizeof(struct download));
4845 download_entry->download = wk_download;
4846 download_entry->tab = t;
4847 download_entry->id = next_download_id++;
4848 RB_INSERT(download_list, &downloads, download_entry);
4850 if (download_mode == XT_DM_START)
4851 ret = download_start(t, download_entry, XT_DL_START);
4852 else if (download_mode == XT_DM_ASK)
4853 ret = download_ask(t, download_entry);
4854 else if (download_mode == XT_DM_ADD)
4855 show_oops(t, "added %s to download manager",
4856 suggested_name);
4858 /* sync other download manager tabs */
4859 update_download_tabs(NULL);
4862 * NOTE: never redirect/render the current tab before this
4863 * function returns. This will cause the download to never start.
4865 return (ret); /* start download */
4868 void
4869 webview_hover_cb(WebKitWebView *wv, gchar *title, gchar *uri, struct tab *t)
4871 DNPRINTF(XT_D_KEY, "webview_hover_cb: %s %s\n", title, uri);
4873 if (t == NULL) {
4874 show_oops(NULL, "webview_hover_cb");
4875 return;
4878 if (uri)
4879 set_status(t, uri, XT_STATUS_LINK);
4880 else {
4881 if (t->status)
4882 set_status(t, t->status, XT_STATUS_NOTHING);
4887 mark(struct tab *t, struct karg *arg)
4889 char mark;
4890 int index;
4892 mark = arg->s[1];
4893 if ((index = marktoindex(mark)) == -1)
4894 return (-1);
4896 if (arg->i == XT_MARK_SET)
4897 t->mark[index] = gtk_adjustment_get_value(t->adjust_v);
4898 else if (arg->i == XT_MARK_GOTO) {
4899 if (t->mark[index] == XT_INVALID_MARK) {
4900 show_oops(t, "mark '%c' does not exist", mark);
4901 return (-1);
4903 /* XXX t->mark[index] can be bigger than the maximum if ajax or
4904 something changes the document size */
4905 gtk_adjustment_set_value(t->adjust_v, t->mark[index]);
4908 return (0);
4911 void
4912 marks_clear(struct tab *t)
4914 int i;
4916 for (i = 0; i < LENGTH(t->mark); i++)
4917 t->mark[i] = XT_INVALID_MARK;
4921 qmarks_load(void)
4923 char file[PATH_MAX];
4924 char *line = NULL, *p;
4925 int index, i;
4926 FILE *f;
4927 size_t linelen;
4929 snprintf(file, sizeof file, "%s" PS "%s", work_dir, XT_QMARKS_FILE);
4930 if ((f = fopen(file, "r+")) == NULL) {
4931 show_oops(NULL, "Can't open quickmarks file: %s", strerror(errno));
4932 return (1);
4935 for (i = 1; ; i++) {
4936 if ((line = fparseln(f, &linelen, NULL, NULL, 0)) == NULL)
4937 break;
4938 if (strlen(line) == 0 || line[0] == '#') {
4939 free(line);
4940 line = NULL;
4941 continue;
4944 p = strtok(line, " \t");
4946 if (p == NULL || strlen(p) != 1 ||
4947 (index = marktoindex(*p)) == -1) {
4948 warnx("corrupt quickmarks file, line %d", i);
4949 break;
4952 p = strtok(NULL, " \t");
4953 if (qmarks[index] != NULL)
4954 g_free(qmarks[index]);
4955 qmarks[index] = g_strdup(p);
4958 fclose(f);
4960 return (0);
4964 qmarks_save(void)
4966 char file[PATH_MAX];
4967 int i;
4968 FILE *f;
4970 snprintf(file, sizeof file, "%s" PS "%s", work_dir, XT_QMARKS_FILE);
4971 if ((f = fopen(file, "r+")) == NULL) {
4972 show_oops(NULL, "Can't open quickmarks file: %s", strerror(errno));
4973 return (1);
4976 for (i = 0; i < XT_NOMARKS; i++)
4977 if (qmarks[i] != NULL)
4978 fprintf(f, "%c %s\n", indextomark(i), qmarks[i]);
4980 fclose(f);
4982 return (0);
4986 qmark(struct tab *t, struct karg *arg)
4988 char mark;
4989 int index;
4991 mark = arg->s[strlen(arg->s)-1];
4992 index = marktoindex(mark);
4993 if (index == -1)
4994 return (-1);
4996 switch (arg->i) {
4997 case XT_QMARK_SET:
4998 if (qmarks[index] != NULL) {
4999 g_free(qmarks[index]);
5000 qmarks[index] = NULL;
5003 qmarks_load(); /* sync if multiple instances */
5004 qmarks[index] = g_strdup(get_uri(t));
5005 qmarks_save();
5006 break;
5007 case XT_QMARK_OPEN:
5008 if (qmarks[index] != NULL)
5009 load_uri(t, qmarks[index]);
5010 else {
5011 show_oops(t, "quickmark \"%c\" does not exist",
5012 mark);
5013 return (-1);
5015 break;
5016 case XT_QMARK_TAB:
5017 if (qmarks[index] != NULL)
5018 create_new_tab(qmarks[index], NULL, 1, -1);
5019 else {
5020 show_oops(t, "quickmark \"%c\" does not exist",
5021 mark);
5022 return (-1);
5024 break;
5027 return (0);
5031 go_up(struct tab *t, struct karg *args)
5033 int levels;
5034 int lastidx;
5035 char *uri;
5036 char *tmp;
5037 char *p;
5039 if (args->i == XT_GO_UP_ROOT)
5040 levels = XT_GO_UP_ROOT;
5041 else if ((levels = atoi(args->s)) == 0)
5042 levels = 1;
5044 uri = g_strdup(get_uri(t));
5046 if ((tmp = strstr(uri, XT_PROTO_DELIM)) == NULL)
5047 return (1);
5049 tmp += strlen(XT_PROTO_DELIM);
5051 /* if an uri starts with a slash, leave it alone (for file:///) */
5052 if (tmp[0] == '/')
5053 tmp++;
5055 /* it makes no sense to strip the last slash from ".../dir/", skip it */
5056 lastidx = strlen(tmp) - 1;
5057 if (lastidx >= 0) {
5058 if (tmp[lastidx] == '/')
5059 tmp[lastidx] = '\0';
5062 while (levels--) {
5063 p = strrchr(tmp, '/');
5064 if (p != NULL)
5065 *p = '\0';
5066 else
5067 break;
5070 load_uri(t, uri);
5071 g_free(uri);
5073 return (0);
5077 gototab(struct tab *t, struct karg *args)
5079 int tab;
5080 struct karg arg = {0, NULL, -1};
5082 tab = atoi(args->s);
5084 if (args->i == 0)
5085 arg.i = XT_TAB_NEXT;
5086 else
5087 arg.i = args->i;
5089 arg.precount = tab;
5091 movetab(t, &arg);
5093 return (0);
5097 zoom_amount(struct tab *t, struct karg *arg)
5099 struct karg narg = {0, NULL, -1};
5101 narg.i = atoi(arg->s);
5102 resizetab(t, &narg);
5104 return (0);
5108 flip_colon(struct tab *t, struct karg *arg)
5110 struct karg narg = {0, NULL, -1};
5111 char *p;
5113 if (t == NULL || arg == NULL)
5114 return (1);
5116 p = strstr(arg->s, ":");
5117 if (p == NULL)
5118 return (1);
5119 *p = '\0';
5121 narg.i = ':';
5122 narg.s = arg->s;
5123 command(t, &narg);
5125 return (0);
5128 /* buffer commands receive the regex that triggered them in arg.s */
5129 char bcmd[XT_BUFCMD_SZ];
5130 struct buffercmd {
5131 char *regex;
5132 int precount;
5133 #define XT_PRE_NO (0)
5134 #define XT_PRE_YES (1)
5135 #define XT_PRE_MAYBE (2)
5136 char *cmd;
5137 int (*func)(struct tab *, struct karg *);
5138 int arg;
5139 regex_t cregex;
5140 } buffercmds[] = {
5141 { "^[0-9]*gu$", XT_PRE_MAYBE, "gu", go_up, 0 },
5142 { "^gU$", XT_PRE_NO, "gU", go_up, XT_GO_UP_ROOT },
5143 { "^gg$", XT_PRE_NO, "gg", move, XT_MOVE_TOP },
5144 { "^gG$", XT_PRE_NO, "gG", move, XT_MOVE_BOTTOM },
5145 { "^[0-9]+%$", XT_PRE_YES, "%", move, XT_MOVE_PERCENT },
5146 { "^zz$", XT_PRE_NO, "zz", move, XT_MOVE_CENTER },
5147 { "^gh$", XT_PRE_NO, "gh", go_home, 0 },
5148 { "^m[a-zA-Z0-9]$", XT_PRE_NO, "m", mark, XT_MARK_SET },
5149 { "^['][a-zA-Z0-9]$", XT_PRE_NO, "'", mark, XT_MARK_GOTO },
5150 { "^[0-9]+t$", XT_PRE_YES, "t", gototab, 0 },
5151 { "^g0$", XT_PRE_YES, "g0", movetab, XT_TAB_FIRST },
5152 { "^g[$]$", XT_PRE_YES, "g$", movetab, XT_TAB_LAST },
5153 { "^[0-9]*gt$", XT_PRE_YES, "t", movetab, XT_TAB_NEXT },
5154 { "^[0-9]*gT$", XT_PRE_YES, "T", movetab, XT_TAB_PREV },
5155 { "^M[a-zA-Z0-9]$", XT_PRE_NO, "M", qmark, XT_QMARK_SET },
5156 { "^go[a-zA-Z0-9]$", XT_PRE_NO, "go", qmark, XT_QMARK_OPEN },
5157 { "^gn[a-zA-Z0-9]$", XT_PRE_NO, "gn", qmark, XT_QMARK_TAB },
5158 { "^ZR$", XT_PRE_NO, "ZR", restart, 0 },
5159 { "^ZZ$", XT_PRE_NO, "ZZ", quit, 0 },
5160 { "^zi$", XT_PRE_NO, "zi", resizetab, XT_ZOOM_IN },
5161 { "^zo$", XT_PRE_NO, "zo", resizetab, XT_ZOOM_OUT },
5162 { "^z0$", XT_PRE_NO, "z0", resizetab, XT_ZOOM_NORMAL },
5163 { "^[0-9]+Z$", XT_PRE_YES, "Z", zoom_amount, 0 },
5164 { "^[0-9]+:$", XT_PRE_YES, ":", flip_colon, 0 },
5167 void
5168 buffercmd_init(void)
5170 int i;
5172 for (i = 0; i < LENGTH(buffercmds); i++)
5173 if (regcomp(&buffercmds[i].cregex, buffercmds[i].regex,
5174 REG_EXTENDED | REG_NOSUB))
5175 startpage_add("invalid buffercmd regex %s",
5176 buffercmds[i].regex);
5179 void
5180 buffercmd_abort(struct tab *t)
5182 int i;
5184 if (t == NULL)
5185 return;
5187 DNPRINTF(XT_D_BUFFERCMD, "%s: clearing buffer\n", __func__);
5189 for (i = 0; i < LENGTH(bcmd); i++)
5190 bcmd[i] = '\0';
5192 cmd_prefix = 0; /* clear prefix for non-buffer commands */
5193 gtk_entry_set_text(GTK_ENTRY(t->sbe.buffercmd), bcmd);
5196 void
5197 buffercmd_execute(struct tab *t, struct buffercmd *cmd)
5199 struct karg arg = {0, NULL, -1};
5201 arg.i = cmd->arg;
5202 arg.s = g_strdup(bcmd);
5204 DNPRINTF(XT_D_BUFFERCMD, "buffercmd_execute: buffer \"%s\" "
5205 "matches regex \"%s\", executing\n", bcmd, cmd->regex);
5206 cmd->func(t, &arg);
5208 if (arg.s)
5209 g_free(arg.s);
5211 buffercmd_abort(t);
5214 gboolean
5215 buffercmd_addkey(struct tab *t, guint keyval)
5217 int i, c, match ;
5218 char s[XT_BUFCMD_SZ];
5220 if (gtk_widget_get_visible(GTK_WIDGET(t->buffers))) {
5221 buffercmd_abort(t);
5222 return (XT_CB_PASSTHROUGH);
5225 if (keyval == GDK_Escape) {
5226 buffercmd_abort(t);
5227 return (XT_CB_HANDLED);
5230 /* key with modifier or non-ascii character */
5231 if (!isascii(keyval)) {
5233 * XXX this looks wrong but fixes some sites like
5234 * http://www.seslisozluk.com/
5235 * that eat a shift or ctrl and end putting default focus in js
5236 * instead of ignoring the keystroke
5237 * so instead of return (XT_CB_PASSTHROUGH); eat the key
5239 return (XT_CB_HANDLED);
5242 DNPRINTF(XT_D_BUFFERCMD, "buffercmd_addkey: adding key \"%c\" "
5243 "to buffer \"%s\"\n", keyval, bcmd);
5245 for (i = 0; i < LENGTH(bcmd); i++)
5246 if (bcmd[i] == '\0') {
5247 bcmd[i] = keyval;
5248 break;
5251 /* buffer full, ignore input */
5252 if (i >= LENGTH(bcmd) -1) {
5253 DNPRINTF(XT_D_BUFFERCMD, "buffercmd_addkey: buffer full\n");
5254 buffercmd_abort(t);
5255 return (XT_CB_HANDLED);
5258 gtk_entry_set_text(GTK_ENTRY(t->sbe.buffercmd), bcmd);
5260 /* find exact match */
5261 for (i = 0; i < LENGTH(buffercmds); i++)
5262 if (regexec(&buffercmds[i].cregex, bcmd,
5263 (size_t) 0, NULL, 0) == 0) {
5264 buffercmd_execute(t, &buffercmds[i]);
5265 goto done;
5268 /* find non exact matches to see if we need to abort ot not */
5269 for (i = 0, match = 0; i < LENGTH(buffercmds); i++) {
5270 DNPRINTF(XT_D_BUFFERCMD, "trying: %s\n", bcmd);
5271 c = -1;
5272 s[0] = '\0';
5273 if (buffercmds[i].precount == XT_PRE_MAYBE) {
5274 if (isdigit(bcmd[0])) {
5275 if (sscanf(bcmd, "%d%s", &c, s) == 0)
5276 continue;
5277 } else {
5278 c = 0;
5279 if (sscanf(bcmd, "%s", s) == 0)
5280 continue;
5282 } else if (buffercmds[i].precount == XT_PRE_YES) {
5283 if (sscanf(bcmd, "%d%s", &c, s) == 0)
5284 continue;
5285 } else {
5286 if (sscanf(bcmd, "%s", s) == 0)
5287 continue;
5289 if (c == -1 && buffercmds[i].precount)
5290 continue;
5291 if (!strncmp(s, buffercmds[i].cmd, strlen(s)))
5292 match++;
5294 DNPRINTF(XT_D_BUFFERCMD, "got[%d] %d <%s>: %d %s\n",
5295 i, match, buffercmds[i].cmd, c, s);
5297 if (match == 0) {
5298 DNPRINTF(XT_D_BUFFERCMD, "aborting: %s\n", bcmd);
5299 buffercmd_abort(t);
5302 done:
5303 return (XT_CB_HANDLED);
5306 gboolean
5307 handle_keypress(struct tab *t, GdkEventKey *e, int entry)
5309 struct key_binding *k;
5311 /* handle keybindings if buffercmd is empty.
5312 if not empty, allow commands like C-n */
5313 if (bcmd[0] == '\0' || ((e->state & (CTRL | MOD1)) != 0))
5314 TAILQ_FOREACH(k, &kbl, entry)
5315 if (e->keyval == k->key
5316 && (entry ? k->use_in_entry : 1)) {
5317 /* when we are edditing eat ctrl/mod keys */
5318 if (edit_mode == XT_EM_VI &&
5319 t->mode == XT_MODE_INSERT &&
5320 (e->state & CTRL || e->state & MOD1))
5321 return (XT_CB_PASSTHROUGH);
5323 if (k->mask == 0) {
5324 if ((e->state & (CTRL | MOD1)) == 0)
5325 return (cmd_execute(t, k->cmd));
5326 } else if ((e->state & k->mask) == k->mask) {
5327 return (cmd_execute(t, k->cmd));
5331 if (!entry && ((e->state & (CTRL | MOD1)) == 0))
5332 return buffercmd_addkey(t, e->keyval);
5334 return (XT_CB_PASSTHROUGH);
5338 wv_keypress_cb(GtkEntry *w, GdkEventKey *e, struct tab *t)
5340 char s[2];
5342 /* don't use w directly; use t->whatever instead */
5344 if (t == NULL) {
5345 show_oops(NULL, "wv_keypress_cb");
5346 return (XT_CB_PASSTHROUGH);
5349 hide_oops(t);
5351 if (t->mode_cb)
5352 return t->mode_cb(t, e, t->mode_cb_data);
5354 DNPRINTF(XT_D_KEY, "wv_keypress_cb: mode %d keyval 0x%x mask "
5355 "0x%x tab %d\n", t->mode, e->keyval, e->state, t->tab_id);
5357 /* Hide buffers, if they are visible, with escape. */
5358 if (gtk_widget_get_visible(GTK_WIDGET(t->buffers)) &&
5359 CLEAN(e->state) == 0 && e->keyval == GDK_Escape) {
5360 gtk_widget_grab_focus(GTK_WIDGET(t->wv));
5361 hide_buffers(t);
5362 return (XT_CB_HANDLED);
5365 if (t->mode == XT_MODE_HINT)
5366 return (XT_CB_HANDLED);
5368 if ((CLEAN(e->state) == 0 && e->keyval == GDK_Tab) ||
5369 (CLEAN(e->state) == SHFT && e->keyval == GDK_Tab))
5370 /* something focussy is about to happen */
5371 return (XT_CB_PASSTHROUGH);
5373 /* check if we are some sort of text input thing in the dom */
5374 input_check_mode(t);
5376 if (t->mode == XT_MODE_HINT) {
5377 /* XXX make sure cmd entry is enabled */
5378 return (XT_CB_HANDLED);
5379 } else if (t->mode == XT_MODE_PASSTHROUGH) {
5380 if (CLEAN(e->state) == 0 && e->keyval == GDK_Escape)
5381 t->mode = XT_MODE_COMMAND;
5382 return (XT_CB_PASSTHROUGH);
5383 } else if (t->mode == XT_MODE_COMMAND) {
5384 /* prefix input */
5385 snprintf(s, sizeof s, "%c", e->keyval);
5386 if (CLEAN(e->state) == 0 && isdigit(s[0]))
5387 cmd_prefix = 10 * cmd_prefix + atoi(s);
5388 return (handle_keypress(t, e, 0));
5389 } else {
5390 /* insert mode */
5391 return (handle_keypress(t, e, 1));
5394 /* NOTREACHED */
5395 return (XT_CB_PASSTHROUGH);
5398 gboolean
5399 hint_continue(struct tab *t)
5401 const gchar *c = gtk_entry_get_text(GTK_ENTRY(t->cmd));
5402 char *s;
5403 const gchar *errstr = NULL;
5404 gboolean rv = TRUE;
5405 int i;
5407 if (!(c[0] == '.' || c[0] == ','))
5408 goto done;
5409 if (strlen(c) == 1) {
5410 /* XXX should not happen */
5411 rv = TRUE;
5412 goto done;
5415 if (isdigit(c[1])) {
5416 /* numeric input */
5417 i = strtonum(&c[1], 1, 4096, &errstr);
5418 if (errstr) {
5419 show_oops(t, "invalid numerical hint %s", &c[1]);
5420 goto done;
5422 s = g_strdup_printf("hints.updateHints(%d);", i);
5423 run_script(t, s);
5424 g_free(s);
5425 } else {
5426 /* alphanumeric input */
5427 s = g_strdup_printf("hints.createHints('%s', '%c');",
5428 &c[1], c[0] == '.' ? 'f' : 'F');
5429 run_script(t, s);
5430 g_free(s);
5433 rv = FALSE;
5434 done:
5435 return (rv);
5438 gboolean
5439 search_continue(struct tab *t)
5441 const gchar *c = gtk_entry_get_text(GTK_ENTRY(t->cmd));
5442 gboolean rv = FALSE;
5444 if (c[0] == ':' || c[0] == '.' || c[0] == ',')
5445 goto done;
5446 if (strlen(c) == 1) {
5447 webkit_web_view_unmark_text_matches(t->wv);
5448 goto done;
5451 if (c[0] == '/')
5452 t->search_forward = TRUE;
5453 else if (c[0] == '?')
5454 t->search_forward = FALSE;
5455 else
5456 goto done;
5458 rv = TRUE;
5459 done:
5460 return (rv);
5463 gboolean
5464 search_cb(struct tab *t)
5466 const gchar *c = gtk_entry_get_text(GTK_ENTRY(t->cmd));
5467 GdkColor color;
5469 if (search_continue(t) == FALSE)
5470 goto done;
5472 /* search */
5473 if (webkit_web_view_search_text(t->wv, &c[1], FALSE, t->search_forward,
5474 TRUE) == FALSE) {
5475 /* not found, mark red */
5476 gdk_color_parse(XT_COLOR_RED, &color);
5477 gtk_widget_modify_base(t->cmd, GTK_STATE_NORMAL, &color);
5478 /* unmark and remove selection */
5479 webkit_web_view_unmark_text_matches(t->wv);
5480 /* my kingdom for a way to unselect text in webview */
5481 } else {
5482 /* found, highlight all */
5483 webkit_web_view_unmark_text_matches(t->wv);
5484 webkit_web_view_mark_text_matches(t->wv, &c[1], FALSE, 0);
5485 webkit_web_view_set_highlight_text_matches(t->wv, TRUE);
5486 gdk_color_parse(XT_COLOR_WHITE, &color);
5487 gtk_widget_modify_base(t->cmd, GTK_STATE_NORMAL, &color);
5489 done:
5490 t->search_id = 0;
5491 return (FALSE);
5495 cmd_keyrelease_cb(GtkEntry *w, GdkEventKey *e, struct tab *t)
5497 const gchar *c = gtk_entry_get_text(w);
5499 if (t == NULL) {
5500 show_oops(NULL, "cmd_keyrelease_cb invalid parameters");
5501 return (XT_CB_PASSTHROUGH);
5504 DNPRINTF(XT_D_CMD, "cmd_keyrelease_cb: keyval 0x%x mask 0x%x tab %d\n",
5505 e->keyval, e->state, t->tab_id);
5507 /* hinting */
5508 if (!(e->keyval == GDK_Tab || e->keyval == GDK_ISO_Left_Tab)) {
5509 if (hint_continue(t) == FALSE)
5510 goto done;
5513 /* search */
5514 if (search_continue(t) == FALSE)
5515 goto done;
5517 /* if search length is > 4 then no longer play timeout games */
5518 if (strlen(c) > 4) {
5519 if (t->search_id) {
5520 g_source_remove(t->search_id);
5521 t->search_id = 0;
5523 search_cb(t);
5524 goto done;
5527 /* reestablish a new timer if the user types fast */
5528 if (t->search_id)
5529 g_source_remove(t->search_id);
5530 t->search_id = g_timeout_add(250, (GSourceFunc)search_cb, (gpointer)t);
5532 done:
5533 return (XT_CB_PASSTHROUGH);
5536 gboolean
5537 match_uri(const gchar *uri, const gchar *key) {
5538 gchar *voffset;
5539 size_t len;
5540 gboolean match = FALSE;
5542 len = strlen(key);
5544 if (!strncmp(key, uri, len))
5545 match = TRUE;
5546 else {
5547 voffset = strstr(uri, "/") + 2;
5548 if (!strncmp(key, voffset, len))
5549 match = TRUE;
5550 else if (g_str_has_prefix(voffset, "www.")) {
5551 voffset = voffset + strlen("www.");
5552 if (!strncmp(key, voffset, len))
5553 match = TRUE;
5557 return (match);
5560 gboolean
5561 match_session(const gchar *name, const gchar *key) {
5562 char *sub;
5564 sub = strcasestr(name, key);
5566 return sub == name;
5569 void
5570 cmd_getlist(int id, char *key)
5572 int i, dep, c = 0;
5573 struct history *h;
5574 struct session *s;
5576 if (id >= 0) {
5577 if (cmds[id].type & XT_URLARG) {
5578 RB_FOREACH_REVERSE(h, history_list, &hl)
5579 if (match_uri(h->uri, key)) {
5580 cmd_status.list[c] = (char *)h->uri;
5581 if (++c > 255)
5582 break;
5584 cmd_status.len = c;
5585 return;
5586 } else if (cmds[id].type & XT_SESSARG) {
5587 TAILQ_FOREACH(s, &sessions, entry)
5588 if (match_session(s->name, key)) {
5589 cmd_status.list[c] = (char *)s->name;
5590 if (++c > 255)
5591 break;
5593 cmd_status.len = c;
5594 return;
5595 } else if (cmds[id].type & XT_SETARG) {
5596 for (i = 0; i < get_settings_size(); i++)
5597 if (!strncmp(key, get_setting_name(i),
5598 strlen(key)))
5599 cmd_status.list[c++] =
5600 get_setting_name(i);
5601 cmd_status.len = c;
5602 return;
5606 dep = (id == -1) ? 0 : cmds[id].level + 1;
5608 for (i = id + 1; i < LENGTH(cmds); i++) {
5609 if (cmds[i].level < dep)
5610 break;
5611 if (cmds[i].level == dep && !strncmp(key, cmds[i].cmd,
5612 strlen(key)) && !isdigit(cmds[i].cmd[0]))
5613 cmd_status.list[c++] = cmds[i].cmd;
5617 cmd_status.len = c;
5620 char *
5621 cmd_getnext(int dir)
5623 cmd_status.index += dir;
5625 if (cmd_status.index < 0)
5626 cmd_status.index = cmd_status.len - 1;
5627 else if (cmd_status.index >= cmd_status.len)
5628 cmd_status.index = 0;
5630 return cmd_status.list[cmd_status.index];
5634 cmd_tokenize(char *s, char *tokens[])
5636 int i = 0;
5637 char *tok, *last = NULL;
5638 size_t len = strlen(s);
5639 bool blank;
5641 blank = len == 0 || (len > 0 && s[len - 1] == ' ');
5642 for (tok = strtok_r(s, " ", &last); tok && i < 3;
5643 tok = strtok_r(NULL, " ", &last), i++)
5644 tokens[i] = tok;
5646 if (blank && i < 3)
5647 tokens[i++] = "";
5649 return (i);
5652 void
5653 cmd_complete(struct tab *t, char *str, int dir)
5655 GtkEntry *w = GTK_ENTRY(t->cmd);
5656 int i, j, levels, c = 0, dep = 0, parent = -1;
5657 int matchcount = 0;
5658 char *tok, *match, *s = g_strdup(str);
5659 char *tokens[3];
5660 char res[XT_MAX_URL_LENGTH + 32] = ":";
5661 char *sc = s;
5663 DNPRINTF(XT_D_CMD, "%s: complete %s\n", __func__, str);
5665 /* copy prefix*/
5666 for (i = 0; isdigit(s[i]); i++)
5667 res[i + 1] = s[i];
5669 for (; isspace(s[i]); i++)
5670 res[i + 1] = s[i];
5672 s += i;
5674 levels = cmd_tokenize(s, tokens);
5676 for (i = 0; i < levels - 1; i++) {
5677 tok = tokens[i];
5678 matchcount = 0;
5679 for (j = c; j < LENGTH(cmds); j++) {
5680 if (cmds[j].level < dep)
5681 break;
5682 if (cmds[j].level == dep && !strncmp(tok, cmds[j].cmd,
5683 strlen(tok))) {
5684 matchcount++;
5685 c = j + 1;
5686 if (strlen(tok) == strlen(cmds[j].cmd)) {
5687 matchcount = 1;
5688 break;
5693 if (matchcount == 1) {
5694 strlcat(res, tok, sizeof res);
5695 strlcat(res, " ", sizeof res);
5696 dep++;
5697 } else {
5698 g_free(sc);
5699 return;
5702 parent = c - 1;
5705 if (cmd_status.index == -1)
5706 cmd_getlist(parent, tokens[i]);
5708 if (cmd_status.len > 0) {
5709 match = cmd_getnext(dir);
5710 strlcat(res, match, sizeof res);
5711 gtk_entry_set_text(w, res);
5712 gtk_editable_set_position(GTK_EDITABLE(w), -1);
5715 g_free(sc);
5718 gboolean
5719 cmd_execute(struct tab *t, char *str)
5721 struct cmd *cmd = NULL;
5722 char *tok, *last = NULL, *s = g_strdup(str), *sc;
5723 char prefixstr[4];
5724 int j, len, c = 0, dep = 0, matchcount = 0;
5725 int prefix = -1, rv = XT_CB_PASSTHROUGH;
5726 struct karg arg = {0, NULL, -1};
5728 sc = s;
5730 /* copy prefix*/
5731 for (j = 0; j<3 && isdigit(s[j]); j++)
5732 prefixstr[j]=s[j];
5734 prefixstr[j]='\0';
5736 s += j;
5737 while (isspace(s[0]))
5738 s++;
5740 if (strlen(s) > 0 && strlen(prefixstr) > 0)
5741 prefix = atoi(prefixstr);
5742 else
5743 s = sc;
5745 for (tok = strtok_r(s, " ", &last); tok;
5746 tok = strtok_r(NULL, " ", &last)) {
5747 matchcount = 0;
5748 for (j = c; j < LENGTH(cmds); j++) {
5749 if (cmds[j].level < dep)
5750 break;
5751 len = (tok[strlen(tok) - 1] == '!') ? strlen(tok) - 1 :
5752 strlen(tok);
5753 if (cmds[j].level == dep &&
5754 !strncmp(tok, cmds[j].cmd, len)) {
5755 matchcount++;
5756 c = j + 1;
5757 cmd = &cmds[j];
5758 if (len == strlen(cmds[j].cmd)) {
5759 matchcount = 1;
5760 break;
5764 if (matchcount == 1) {
5765 if (cmd->type > 0)
5766 goto execute_cmd;
5767 dep++;
5768 } else {
5769 show_oops(t, "Invalid command: %s", str);
5770 goto done;
5773 execute_cmd:
5774 if (cmd == NULL) {
5775 show_oops(t, "Empty command");
5776 goto done;
5778 arg.i = cmd->arg;
5780 if (prefix != -1)
5781 arg.precount = prefix;
5782 else if (cmd_prefix > 0)
5783 arg.precount = cmd_prefix;
5785 if (j > 0 && !(cmd->type & XT_PREFIX) && arg.precount > -1) {
5786 show_oops(t, "No prefix allowed: %s", str);
5787 goto done;
5789 if (cmd->type > 1)
5790 arg.s = last ? g_strdup(last) : g_strdup("");
5791 if (cmd->type & XT_INTARG && last && strlen(last) > 0) {
5792 if (arg.s == NULL) {
5793 show_oops(t, "Invalid command");
5794 goto done;
5796 arg.precount = atoi(arg.s);
5797 if (arg.precount <= 0) {
5798 if (arg.s[0] == '0')
5799 show_oops(t, "Zero count");
5800 else
5801 show_oops(t, "Trailing characters");
5802 goto done;
5806 DNPRINTF(XT_D_CMD, "%s: prefix %d arg %s\n",
5807 __func__, arg.precount, arg.s);
5809 cmd->func(t, &arg);
5811 rv = XT_CB_HANDLED;
5812 done:
5813 if (j > 0)
5814 cmd_prefix = 0;
5815 g_free(sc);
5816 if (arg.s)
5817 g_free(arg.s);
5819 return (rv);
5823 entry_key_cb(GtkEntry *w, GdkEventKey *e, struct tab *t)
5825 if (t == NULL) {
5826 show_oops(NULL, "entry_key_cb invalid parameters");
5827 return (XT_CB_PASSTHROUGH);
5830 DNPRINTF(XT_D_CMD, "entry_key_cb: keyval 0x%x mask 0x%x tab %d\n",
5831 e->keyval, e->state, t->tab_id);
5833 hide_oops(t);
5835 if (e->keyval == GDK_Escape) {
5836 /* don't use focus_webview(t) because we want to type :cmds */
5837 gtk_widget_grab_focus(GTK_WIDGET(t->wv));
5840 return (handle_keypress(t, e, 1));
5843 struct command_entry *
5844 history_prev(struct command_list *l, struct command_entry *at)
5846 if (at == NULL)
5847 at = TAILQ_LAST(l, command_list);
5848 else {
5849 at = TAILQ_PREV(at, command_list, entry);
5850 if (at == NULL)
5851 at = TAILQ_LAST(l, command_list);
5854 return (at);
5857 struct command_entry *
5858 history_next(struct command_list *l, struct command_entry *at)
5860 if (at == NULL)
5861 at = TAILQ_FIRST(l);
5862 else {
5863 at = TAILQ_NEXT(at, entry);
5864 if (at == NULL)
5865 at = TAILQ_FIRST(l);
5868 return (at);
5872 cmd_keypress_cb(GtkEntry *w, GdkEventKey *e, struct tab *t)
5874 int rv = XT_CB_HANDLED;
5875 const gchar *c = gtk_entry_get_text(w);
5876 char *s;
5878 if (t == NULL) {
5879 show_oops(NULL, "cmd_keypress_cb parameters");
5880 return (XT_CB_PASSTHROUGH);
5883 DNPRINTF(XT_D_CMD, "cmd_keypress_cb: keyval 0x%x mask 0x%x tab %d\n",
5884 e->keyval, e->state, t->tab_id);
5886 /* sanity */
5887 if (c == NULL)
5888 e->keyval = GDK_Escape;
5889 else if (!(c[0] == ':' || c[0] == '/' || c[0] == '?' ||
5890 c[0] == '.' || c[0] == ','))
5891 e->keyval = GDK_Escape;
5893 if (e->keyval != GDK_Tab && e->keyval != GDK_Shift_L &&
5894 e->keyval != GDK_ISO_Left_Tab)
5895 cmd_status.index = -1;
5897 switch (e->keyval) {
5898 case GDK_Tab:
5899 if (c[0] == ':')
5900 cmd_complete(t, (char *)&c[1], 1);
5901 else if (c[0] == '.' || c[0] == ',')
5902 run_script(t, "hints.focusNextHint();");
5903 goto done;
5904 case GDK_ISO_Left_Tab:
5905 if (c[0] == ':')
5906 cmd_complete(t, (char *)&c[1], -1);
5907 else if (c[0] == '.' || c[0] == ',')
5908 run_script(t, "hints.focusPreviousHint();");
5909 goto done;
5910 case GDK_Down:
5911 if (c[0] == '?') {
5912 if ((search_at = history_next(&shl, search_at))) {
5913 search_at->line[0] = c[0];
5914 gtk_entry_set_text(w, search_at->line);
5915 gtk_editable_set_position(GTK_EDITABLE(w), -1);
5917 } else if (c[0] == '/') {
5918 if ((search_at = history_prev(&shl, search_at))) {
5919 search_at->line[0] = c[0];
5920 gtk_entry_set_text(w, search_at->line);
5921 gtk_editable_set_position(GTK_EDITABLE(w), -1);
5923 } if (c[0] == ':') {
5924 if ((history_at = history_prev(&chl, history_at))) {
5925 history_at->line[0] = c[0];
5926 gtk_entry_set_text(w, history_at->line);
5927 gtk_editable_set_position(GTK_EDITABLE(w), -1);
5930 goto done;
5931 case GDK_Up:
5932 if (c[0] == '/') {
5933 if ((search_at = history_next(&shl, search_at))) {
5934 search_at->line[0] = c[0];
5935 gtk_entry_set_text(w, search_at->line);
5936 gtk_editable_set_position(GTK_EDITABLE(w), -1);
5938 } else if (c[0] == '?') {
5939 if ((search_at = history_prev(&shl, search_at))) {
5940 search_at->line[0] = c[0];
5941 gtk_entry_set_text(w, search_at->line);
5942 gtk_editable_set_position(GTK_EDITABLE(w), -1);
5944 } if (c[0] == ':') {
5945 if ((history_at = history_next(&chl, history_at))) {
5946 history_at->line[0] = c[0];
5947 gtk_entry_set_text(w, history_at->line);
5948 gtk_editable_set_position(GTK_EDITABLE(w), -1);
5951 goto done;
5952 case GDK_BackSpace:
5953 if (!(!strcmp(c, ":") || !strcmp(c, "/") || !strcmp(c, "?") ||
5954 !strcmp(c, ".") || !strcmp(c, ","))) {
5955 /* see if we are doing hinting and reset it */
5956 if (c[0] == '.' || c[0] == ',') {
5957 /* recreate hints */
5958 s = g_strdup_printf("hints.createHints('', "
5959 "'%c');", c[0] == '.' ? 'f' : 'F');
5960 run_script(t, s);
5961 g_free(s);
5963 break;
5966 /* FALLTHROUGH */
5967 case GDK_Escape:
5968 hide_cmd(t);
5969 focus_webview(t);
5971 /* cancel search */
5972 if (c != NULL && (c[0] == '/' || c[0] == '?'))
5973 webkit_web_view_unmark_text_matches(t->wv);
5975 /* no need to cancel hints */
5976 goto done;
5979 rv = XT_CB_PASSTHROUGH;
5980 done:
5981 return (rv);
5984 void
5985 wv_popup_cb(GtkEntry *entry, GtkMenu *menu, struct tab *t)
5987 DNPRINTF(XT_D_CMD, "wv_popup_cb: tab %d\n", t->tab_id);
5990 void
5991 cmd_popup_cb(GtkEntry *entry, GtkMenu *menu, struct tab *t)
5993 /* popup menu enabled */
5994 t->popup = 1;
5998 cmd_focusout_cb(GtkWidget *w, GdkEventFocus *e, struct tab *t)
6000 if (t == NULL) {
6001 show_oops(NULL, "cmd_focusout_cb invalid parameters");
6002 return (XT_CB_PASSTHROUGH);
6005 DNPRINTF(XT_D_CMD, "cmd_focusout_cb: tab %d popup %d\n",
6006 t->tab_id, t->popup);
6008 /* if popup is enabled don't lose focus */
6009 if (t->popup) {
6010 t->popup = 0;
6011 return (XT_CB_PASSTHROUGH);
6014 hide_cmd(t);
6015 hide_oops(t);
6016 disable_hints(t);
6018 if (show_url == 0 || t->focus_wv)
6019 focus_webview(t);
6020 else
6021 gtk_widget_grab_focus(GTK_WIDGET(t->uri_entry));
6023 return (XT_CB_PASSTHROUGH);
6026 void
6027 cmd_activate_cb(GtkEntry *entry, struct tab *t)
6029 char *s;
6030 const gchar *c = gtk_entry_get_text(entry);
6032 if (t == NULL) {
6033 show_oops(NULL, "cmd_activate_cb invalid parameters");
6034 return;
6037 DNPRINTF(XT_D_CMD, "cmd_activate_cb: tab %d %s\n", t->tab_id, c);
6039 /* sanity */
6040 if (c == NULL)
6041 goto done;
6042 else if (!(c[0] == ':' || c[0] == '/' || c[0] == '?' ||
6043 c[0] == '.' || c[0] == ','))
6044 goto done;
6045 if (strlen(c) < 1)
6046 goto done;
6047 s = (char *)&c[1];
6049 if (c[0] == '/' || c[0] == '?') {
6050 /* see if there is a timer pending */
6051 if (t->search_id) {
6052 g_source_remove(t->search_id);
6053 t->search_id = 0;
6054 search_cb(t);
6057 if (t->search_text) {
6058 g_free(t->search_text);
6059 t->search_text = NULL;
6062 t->search_text = g_strdup(s);
6063 if (global_search)
6064 g_free(global_search);
6065 global_search = g_strdup(s);
6066 t->search_forward = c[0] == '/';
6068 history_add(&shl, search_file, s, &search_history_count);
6069 } else if (c[0] == '.' || c[0] == ',') {
6070 run_script(t, "hints.fire();");
6071 /* XXX history for link following? */
6072 } else if (c[0] == ':') {
6073 history_add(&chl, command_file, s, &cmd_history_count);
6074 /* can't call hide_cmd after cmd_execute */
6075 hide_cmd(t);
6076 cmd_execute(t, s);
6077 return;
6080 done:
6081 hide_cmd(t);
6084 void
6085 backward_cb(GtkWidget *w, struct tab *t)
6087 struct karg a;
6089 if (t == NULL) {
6090 show_oops(NULL, "backward_cb invalid parameters");
6091 return;
6094 DNPRINTF(XT_D_NAV, "backward_cb: tab %d\n", t->tab_id);
6096 a.i = XT_NAV_BACK;
6097 navaction(t, &a);
6100 void
6101 forward_cb(GtkWidget *w, struct tab *t)
6103 struct karg a;
6105 if (t == NULL) {
6106 show_oops(NULL, "forward_cb invalid parameters");
6107 return;
6110 DNPRINTF(XT_D_NAV, "forward_cb: tab %d\n", t->tab_id);
6112 a.i = XT_NAV_FORWARD;
6113 navaction(t, &a);
6116 void
6117 home_cb(GtkWidget *w, struct tab *t)
6119 if (t == NULL) {
6120 show_oops(NULL, "home_cb invalid parameters");
6121 return;
6124 DNPRINTF(XT_D_NAV, "home_cb: tab %d\n", t->tab_id);
6126 load_uri(t, home);
6129 void
6130 stop_cb(GtkWidget *w, struct tab *t)
6132 WebKitWebFrame *frame;
6134 if (t == NULL) {
6135 show_oops(NULL, "stop_cb invalid parameters");
6136 return;
6139 DNPRINTF(XT_D_NAV, "stop_cb: tab %d\n", t->tab_id);
6141 frame = webkit_web_view_get_main_frame(t->wv);
6142 if (frame == NULL) {
6143 show_oops(t, "stop_cb: no frame");
6144 return;
6147 webkit_web_frame_stop_loading(frame);
6148 abort_favicon_download(t);
6151 void
6152 setup_webkit(struct tab *t)
6154 if (is_g_object_setting(G_OBJECT(t->settings), "enable-dns-prefetching"))
6155 g_object_set(G_OBJECT(t->settings), "enable-dns-prefetching",
6156 FALSE, (char *)NULL);
6157 else
6158 warnx("webkit does not have \"enable-dns-prefetching\" property");
6159 g_object_set(G_OBJECT(t->settings),
6160 "user-agent", t->user_agent, (char *)NULL);
6161 g_object_set(G_OBJECT(t->settings),
6162 "enable-scripts", enable_scripts, (char *)NULL);
6163 g_object_set(G_OBJECT(t->settings),
6164 "enable-plugins", enable_plugins, (char *)NULL);
6165 g_object_set(G_OBJECT(t->settings),
6166 "javascript-can-open-windows-automatically", enable_scripts,
6167 (char *)NULL);
6168 g_object_set(G_OBJECT(t->settings),
6169 "enable-html5-database", FALSE, (char *)NULL);
6170 g_object_set(G_OBJECT(t->settings),
6171 "enable-html5-local-storage", enable_localstorage, (char *)NULL);
6172 g_object_set(G_OBJECT(t->settings),
6173 "enable_spell_checking", enable_spell_checking, (char *)NULL);
6174 g_object_set(G_OBJECT(t->settings),
6175 "spell_checking_languages", spell_check_languages, (char *)NULL);
6176 g_object_set(G_OBJECT(t->settings),
6177 "enable-developer-extras", TRUE, (char *)NULL);
6178 g_object_set(G_OBJECT(t->wv),
6179 "full-content-zoom", TRUE, (char *)NULL);
6180 g_object_set(G_OBJECT(t->settings),
6181 "auto-load-images", auto_load_images, (char *)NULL);
6183 webkit_web_view_set_settings(t->wv, t->settings);
6186 gboolean
6187 update_statusbar_position(GtkAdjustment* adjustment, gpointer data)
6189 struct tab *ti, *t = NULL;
6190 gdouble view_size, value, max;
6191 gchar *position;
6193 TAILQ_FOREACH(ti, &tabs, entry)
6194 if (ti->tab_id == gtk_notebook_get_current_page(notebook)) {
6195 t = ti;
6196 break;
6199 if (t == NULL)
6200 return FALSE;
6202 if (adjustment == NULL)
6203 adjustment = gtk_scrolled_window_get_vadjustment(
6204 GTK_SCROLLED_WINDOW(t->browser_win));
6206 view_size = gtk_adjustment_get_page_size(adjustment);
6207 value = gtk_adjustment_get_value(adjustment);
6208 max = gtk_adjustment_get_upper(adjustment) - view_size;
6210 if (max == 0)
6211 position = g_strdup("All");
6212 else if (value == max)
6213 position = g_strdup("Bot");
6214 else if (value == 0)
6215 position = g_strdup("Top");
6216 else
6217 position = g_strdup_printf("%d%%", (int) ((value / max) * 100));
6219 gtk_entry_set_text(GTK_ENTRY(t->sbe.position), position);
6220 g_free(position);
6222 return (TRUE);
6225 GtkWidget *
6226 create_window(const gchar *name)
6228 GtkWidget *w;
6230 w = gtk_window_new(GTK_WINDOW_TOPLEVEL);
6231 if (window_maximize)
6232 gtk_window_maximize(GTK_WINDOW(w));
6233 else
6234 gtk_window_set_default_size(GTK_WINDOW(w), window_width, window_height);
6235 gtk_widget_set_name(w, name);
6236 gtk_window_set_wmclass(GTK_WINDOW(w), name, "XXXTerm");
6238 return (w);
6241 GtkWidget *
6242 create_browser(struct tab *t)
6244 GtkWidget *w;
6245 gchar *strval;
6246 GtkAdjustment *adjustment;
6248 if (t == NULL) {
6249 show_oops(NULL, "create_browser invalid parameters");
6250 return (NULL);
6253 t->sb_h = GTK_SCROLLBAR(gtk_hscrollbar_new(NULL));
6254 t->sb_v = GTK_SCROLLBAR(gtk_vscrollbar_new(NULL));
6255 t->adjust_h = gtk_range_get_adjustment(GTK_RANGE(t->sb_h));
6256 t->adjust_v = gtk_range_get_adjustment(GTK_RANGE(t->sb_v));
6258 w = gtk_scrolled_window_new(t->adjust_h, t->adjust_v);
6259 gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(w),
6260 GTK_POLICY_AUTOMATIC, GTK_POLICY_AUTOMATIC);
6262 t->wv = WEBKIT_WEB_VIEW(webkit_web_view_new());
6263 gtk_container_add(GTK_CONTAINER(w), GTK_WIDGET(t->wv));
6265 /* set defaults */
6266 t->settings = webkit_web_settings_new();
6268 g_object_set(t->settings, "default-encoding", encoding, (char *)NULL);
6270 if (user_agent == NULL) {
6271 g_object_get(G_OBJECT(t->settings), "user-agent", &strval,
6272 (char *)NULL);
6273 t->user_agent = g_strdup_printf("%s %s+", strval, version);
6274 g_free(strval);
6275 } else
6276 t->user_agent = g_strdup(user_agent->value);
6278 t->stylesheet = g_strdup_printf("file://%s/style.css", resource_dir);
6279 t->load_images = auto_load_images;
6281 adjustment =
6282 gtk_scrolled_window_get_vadjustment(GTK_SCROLLED_WINDOW(w));
6283 g_signal_connect(G_OBJECT(adjustment), "value-changed",
6284 G_CALLBACK(update_statusbar_position), NULL);
6286 setup_webkit(t);
6287 setup_inspector(t);
6289 return (w);
6292 GtkWidget *
6293 create_kiosk_toolbar(struct tab *t)
6295 GtkWidget *toolbar = NULL, *b;
6297 b = gtk_hbox_new(FALSE, 0);
6298 toolbar = b;
6299 gtk_container_set_border_width(GTK_CONTAINER(toolbar), 0);
6301 /* backward button */
6302 t->backward = create_button("Back", GTK_STOCK_GO_BACK, 0);
6303 gtk_widget_set_sensitive(t->backward, FALSE);
6304 g_signal_connect(G_OBJECT(t->backward), "clicked",
6305 G_CALLBACK(backward_cb), t);
6306 gtk_box_pack_start(GTK_BOX(b), t->backward, TRUE, TRUE, 0);
6308 /* forward button */
6309 t->forward = create_button("Forward", GTK_STOCK_GO_FORWARD, 0);
6310 gtk_widget_set_sensitive(t->forward, FALSE);
6311 g_signal_connect(G_OBJECT(t->forward), "clicked",
6312 G_CALLBACK(forward_cb), t);
6313 gtk_box_pack_start(GTK_BOX(b), t->forward, TRUE, TRUE, 0);
6315 /* home button */
6316 t->gohome = create_button("Home", GTK_STOCK_HOME, 0);
6317 gtk_widget_set_sensitive(t->gohome, true);
6318 g_signal_connect(G_OBJECT(t->gohome), "clicked",
6319 G_CALLBACK(home_cb), t);
6320 gtk_box_pack_start(GTK_BOX(b), t->gohome, TRUE, TRUE, 0);
6322 /* create widgets but don't use them */
6323 t->uri_entry = gtk_entry_new();
6324 t->stop = create_button("Stop", GTK_STOCK_STOP, 0);
6325 t->js_toggle = create_button("JS-Toggle", enable_scripts ?
6326 GTK_STOCK_MEDIA_PLAY : GTK_STOCK_MEDIA_PAUSE, 0);
6328 return (toolbar);
6331 GtkWidget *
6332 create_toolbar(struct tab *t)
6334 GtkWidget *toolbar = NULL, *b, *eb1;
6336 b = gtk_hbox_new(FALSE, 0);
6337 toolbar = b;
6338 gtk_container_set_border_width(GTK_CONTAINER(toolbar), 0);
6340 /* backward button */
6341 t->backward = create_button("Back", GTK_STOCK_GO_BACK, 0);
6342 gtk_widget_set_sensitive(t->backward, FALSE);
6343 g_signal_connect(G_OBJECT(t->backward), "clicked",
6344 G_CALLBACK(backward_cb), t);
6345 gtk_box_pack_start(GTK_BOX(b), t->backward, FALSE, FALSE, 0);
6347 /* forward button */
6348 t->forward = create_button("Forward",GTK_STOCK_GO_FORWARD, 0);
6349 gtk_widget_set_sensitive(t->forward, FALSE);
6350 g_signal_connect(G_OBJECT(t->forward), "clicked",
6351 G_CALLBACK(forward_cb), t);
6352 gtk_box_pack_start(GTK_BOX(b), t->forward, FALSE,
6353 FALSE, 0);
6355 /* stop button */
6356 t->stop = create_button("Stop", GTK_STOCK_STOP, 0);
6357 gtk_widget_set_sensitive(t->stop, FALSE);
6358 g_signal_connect(G_OBJECT(t->stop), "clicked",
6359 G_CALLBACK(stop_cb), t);
6360 gtk_box_pack_start(GTK_BOX(b), t->stop, FALSE,
6361 FALSE, 0);
6363 /* JS button */
6364 t->js_toggle = create_button("JS-Toggle", enable_scripts ?
6365 GTK_STOCK_MEDIA_PLAY : GTK_STOCK_MEDIA_PAUSE, 0);
6366 gtk_widget_set_sensitive(t->js_toggle, TRUE);
6367 g_signal_connect(G_OBJECT(t->js_toggle), "clicked",
6368 G_CALLBACK(js_toggle_cb), t);
6369 gtk_box_pack_start(GTK_BOX(b), t->js_toggle, FALSE, FALSE, 0);
6371 t->uri_entry = gtk_entry_new();
6372 g_signal_connect(G_OBJECT(t->uri_entry), "activate",
6373 G_CALLBACK(activate_uri_entry_cb), t);
6374 g_signal_connect(G_OBJECT(t->uri_entry), "key-press-event",
6375 G_CALLBACK(entry_key_cb), t);
6376 completion_add(t);
6377 eb1 = gtk_hbox_new(FALSE, 0);
6378 gtk_container_set_border_width(GTK_CONTAINER(eb1), 1);
6379 gtk_box_pack_start(GTK_BOX(eb1), t->uri_entry, TRUE, TRUE, 0);
6380 gtk_box_pack_start(GTK_BOX(b), eb1, TRUE, TRUE, 0);
6382 /* search entry */
6383 if (search_string) {
6384 GtkWidget *eb2;
6385 t->search_entry = gtk_entry_new();
6386 gtk_entry_set_width_chars(GTK_ENTRY(t->search_entry), 30);
6387 g_signal_connect(G_OBJECT(t->search_entry), "activate",
6388 G_CALLBACK(activate_search_entry_cb), t);
6389 g_signal_connect(G_OBJECT(t->search_entry), "key-press-event",
6390 G_CALLBACK(entry_key_cb), t);
6391 gtk_widget_set_size_request(t->search_entry, -1, -1);
6392 eb2 = gtk_hbox_new(FALSE, 0);
6393 gtk_container_set_border_width(GTK_CONTAINER(eb2), 1);
6394 gtk_box_pack_start(GTK_BOX(eb2), t->search_entry, TRUE, TRUE,
6396 gtk_box_pack_start(GTK_BOX(b), eb2, FALSE, FALSE, 0);
6399 return (toolbar);
6402 GtkWidget *
6403 create_buffers(struct tab *t)
6405 GtkCellRenderer *renderer;
6406 GtkWidget *view;
6408 view = gtk_tree_view_new();
6410 gtk_tree_view_set_headers_visible(GTK_TREE_VIEW(view), FALSE);
6412 renderer = gtk_cell_renderer_text_new();
6413 gtk_tree_view_insert_column_with_attributes
6414 (GTK_TREE_VIEW(view), -1, "Id", renderer, "text", COL_ID, (char *)NULL);
6416 renderer = gtk_cell_renderer_pixbuf_new();
6417 gtk_tree_view_insert_column_with_attributes
6418 (GTK_TREE_VIEW(view), -1, "Favicon", renderer, "pixbuf", COL_FAVICON,
6419 (char *)NULL);
6421 renderer = gtk_cell_renderer_text_new();
6422 gtk_tree_view_insert_column_with_attributes
6423 (GTK_TREE_VIEW(view), -1, "Title", renderer, "text", COL_TITLE,
6424 (char *)NULL);
6426 gtk_tree_view_set_model
6427 (GTK_TREE_VIEW(view), GTK_TREE_MODEL(buffers_store));
6429 return (view);
6432 void
6433 row_activated_cb(GtkTreeView *view, GtkTreePath *path,
6434 GtkTreeViewColumn *col, struct tab *t)
6436 GtkTreeIter iter;
6437 guint id;
6439 gtk_widget_grab_focus(GTK_WIDGET(t->wv));
6441 if (gtk_tree_model_get_iter(GTK_TREE_MODEL(buffers_store), &iter,
6442 path)) {
6443 gtk_tree_model_get
6444 (GTK_TREE_MODEL(buffers_store), &iter, COL_ID, &id, -1);
6445 set_current_tab(id - 1);
6448 hide_buffers(t);
6451 /* after tab reordering/creation/removal */
6452 void
6453 recalc_tabs(void)
6455 struct tab *t;
6456 int maxid = 0;
6458 TAILQ_FOREACH(t, &tabs, entry) {
6459 t->tab_id = gtk_notebook_page_num(notebook, t->vbox);
6460 if (t->tab_id > maxid)
6461 maxid = t->tab_id;
6463 gtk_widget_show(t->tab_elems.sep);
6466 TAILQ_FOREACH(t, &tabs, entry) {
6467 if (t->tab_id == maxid) {
6468 gtk_widget_hide(t->tab_elems.sep);
6469 break;
6474 /* after active tab change */
6475 void
6476 recolor_compact_tabs(void)
6478 struct tab *t;
6479 int curid = 0;
6480 GdkColor color;
6482 gdk_color_parse(XT_COLOR_CT_INACTIVE, &color);
6483 TAILQ_FOREACH(t, &tabs, entry)
6484 gtk_widget_modify_fg(t->tab_elems.label, GTK_STATE_NORMAL,
6485 &color);
6487 curid = gtk_notebook_get_current_page(notebook);
6488 TAILQ_FOREACH(t, &tabs, entry)
6489 if (t->tab_id == curid) {
6490 gdk_color_parse(XT_COLOR_CT_ACTIVE, &color);
6491 gtk_widget_modify_fg(t->tab_elems.label,
6492 GTK_STATE_NORMAL, &color);
6493 break;
6497 void
6498 set_current_tab(int page_num)
6500 buffercmd_abort(get_current_tab());
6501 gtk_notebook_set_current_page(notebook, page_num);
6502 recolor_compact_tabs();
6506 undo_close_tab_save(struct tab *t)
6508 int m, n;
6509 const gchar *uri;
6510 struct undo *u1, *u2;
6511 GList *items;
6512 WebKitWebHistoryItem *item;
6514 if ((uri = get_uri(t)) == NULL)
6515 return (1);
6517 u1 = g_malloc0(sizeof(struct undo));
6518 u1->uri = g_strdup(uri);
6520 t->bfl = webkit_web_view_get_back_forward_list(t->wv);
6522 m = webkit_web_back_forward_list_get_forward_length(t->bfl);
6523 n = webkit_web_back_forward_list_get_back_length(t->bfl);
6524 u1->back = n;
6526 /* forward history */
6527 items = webkit_web_back_forward_list_get_forward_list_with_limit(t->bfl, m);
6529 while (items) {
6530 item = items->data;
6531 u1->history = g_list_prepend(u1->history,
6532 webkit_web_history_item_copy(item));
6533 items = g_list_next(items);
6536 /* current item */
6537 if (m) {
6538 item = webkit_web_back_forward_list_get_current_item(t->bfl);
6539 u1->history = g_list_prepend(u1->history,
6540 webkit_web_history_item_copy(item));
6543 /* back history */
6544 items = webkit_web_back_forward_list_get_back_list_with_limit(t->bfl, n);
6546 while (items) {
6547 item = items->data;
6548 u1->history = g_list_prepend(u1->history,
6549 webkit_web_history_item_copy(item));
6550 items = g_list_next(items);
6553 TAILQ_INSERT_HEAD(&undos, u1, entry);
6555 if (undo_count > XT_MAX_UNDO_CLOSE_TAB) {
6556 u2 = TAILQ_LAST(&undos, undo_tailq);
6557 TAILQ_REMOVE(&undos, u2, entry);
6558 g_free(u2->uri);
6559 g_list_free(u2->history);
6560 g_free(u2);
6561 } else
6562 undo_count++;
6564 return (0);
6567 void
6568 delete_tab(struct tab *t)
6570 struct karg a;
6572 DNPRINTF(XT_D_TAB, "delete_tab: %p\n", t);
6574 if (t == NULL)
6575 return;
6578 * no need to join thread here because it won't access t on completion
6581 TAILQ_REMOVE(&tabs, t, entry);
6582 buffercmd_abort(t);
6584 /* Halt all webkit activity. */
6585 abort_favicon_download(t);
6586 webkit_web_view_stop_loading(t->wv);
6588 /* Save the tab, so we can undo the close. */
6589 undo_close_tab_save(t);
6591 /* just in case */
6592 if (t->search_id)
6593 g_source_remove(t->search_id);
6595 /* inspector */
6596 bzero(&a, sizeof a);
6597 a.i = XT_INS_CLOSE;
6598 inspector_cmd(t, &a);
6600 if (browser_mode == XT_BM_KIOSK) {
6601 gtk_widget_destroy(t->uri_entry);
6602 gtk_widget_destroy(t->stop);
6603 gtk_widget_destroy(t->js_toggle);
6606 gtk_widget_destroy(t->tab_elems.eventbox);
6607 gtk_widget_destroy(t->vbox);
6609 g_free(t->user_agent);
6610 g_free(t->stylesheet);
6611 g_free(t->tmp_uri);
6612 g_free(t);
6613 t = NULL;
6615 if (TAILQ_EMPTY(&tabs)) {
6616 if (browser_mode == XT_BM_KIOSK)
6617 create_new_tab(home, NULL, 1, -1);
6618 else
6619 create_new_tab(NULL, NULL, 1, -1);
6622 /* recreate session */
6623 if (session_autosave) {
6624 bzero(&a, sizeof a);
6625 a.s = NULL;
6626 save_tabs(NULL, &a);
6629 recalc_tabs();
6630 recolor_compact_tabs();
6633 void
6634 update_statusbar_zoom(struct tab *t)
6636 gfloat zoom;
6637 char s[16] = { '\0' };
6639 g_object_get(G_OBJECT(t->wv), "zoom-level", &zoom, (char *)NULL);
6640 if ((zoom <= 0.99 || zoom >= 1.01))
6641 snprintf(s, sizeof s, "%d%%", (int)(zoom * 100));
6642 gtk_entry_set_text(GTK_ENTRY(t->sbe.zoom), s);
6645 void
6646 setzoom_webkit(struct tab *t, int adjust)
6648 #define XT_ZOOMPERCENT 0.04
6650 gfloat zoom;
6652 if (t == NULL) {
6653 show_oops(NULL, "setzoom_webkit invalid parameters");
6654 return;
6657 g_object_get(G_OBJECT(t->wv), "zoom-level", &zoom, (char *)NULL);
6658 if (adjust == XT_ZOOM_IN)
6659 zoom += XT_ZOOMPERCENT;
6660 else if (adjust == XT_ZOOM_OUT)
6661 zoom -= XT_ZOOMPERCENT;
6662 else if (adjust > 0)
6663 zoom = default_zoom_level + adjust / 100.0 - 1.0;
6664 else {
6665 show_oops(t, "setzoom_webkit invalid zoom value");
6666 return;
6669 if (zoom < XT_ZOOMPERCENT)
6670 zoom = XT_ZOOMPERCENT;
6671 g_object_set(G_OBJECT(t->wv), "zoom-level", zoom, (char *)NULL);
6672 update_statusbar_zoom(t);
6675 gboolean
6676 tab_clicked_cb(GtkWidget *widget, GdkEventButton *event, gpointer data)
6678 struct tab *t = (struct tab *) data;
6680 DNPRINTF(XT_D_TAB, "tab_clicked_cb: tab: %d\n", t->tab_id);
6682 switch (event->button) {
6683 case 1:
6684 set_current_tab(t->tab_id);
6685 break;
6686 case 2:
6687 delete_tab(t);
6688 break;
6691 return TRUE;
6694 void
6695 append_tab(struct tab *t)
6697 if (t == NULL)
6698 return;
6700 TAILQ_INSERT_TAIL(&tabs, t, entry);
6701 t->tab_id = gtk_notebook_append_page(notebook, t->vbox, t->tab_content);
6704 GtkWidget *
6705 create_sbe(int width)
6707 GtkWidget *sbe;
6709 sbe = gtk_entry_new();
6710 gtk_entry_set_inner_border(GTK_ENTRY(sbe), NULL);
6711 gtk_entry_set_has_frame(GTK_ENTRY(sbe), FALSE);
6712 gtk_widget_set_can_focus(GTK_WIDGET(sbe), FALSE);
6713 gtk_widget_modify_font(GTK_WIDGET(sbe), statusbar_font);
6714 gtk_entry_set_alignment(GTK_ENTRY(sbe), 1.0);
6715 gtk_widget_set_size_request(sbe, width, -1);
6717 return sbe;
6720 struct tab *
6721 create_new_tab(char *title, struct undo *u, int focus, int position)
6723 struct tab *t;
6724 int load = 1, id;
6725 GtkWidget *b, *bb;
6726 WebKitWebHistoryItem *item;
6727 GList *items;
6728 GdkColor color;
6729 char *p;
6730 int sbe_p = 0, sbe_b = 0,
6731 sbe_z = 0;
6733 DNPRINTF(XT_D_TAB, "create_new_tab: title %s focus %d\n", title, focus);
6735 if (tabless && !TAILQ_EMPTY(&tabs)) {
6736 DNPRINTF(XT_D_TAB, "create_new_tab: new tab rejected\n");
6737 return (NULL);
6740 t = g_malloc0(sizeof *t);
6742 if (title == NULL) {
6743 title = "(untitled)";
6744 load = 0;
6747 t->vbox = gtk_vbox_new(FALSE, 0);
6749 /* label + button for tab */
6750 b = gtk_hbox_new(FALSE, 0);
6751 t->tab_content = b;
6753 #if GTK_CHECK_VERSION(2, 20, 0)
6754 t->spinner = gtk_spinner_new();
6755 #endif
6756 t->label = gtk_label_new(title);
6757 bb = create_button("Close", GTK_STOCK_CLOSE, 1);
6758 gtk_widget_set_size_request(t->label, 100, 0);
6759 gtk_label_set_max_width_chars(GTK_LABEL(t->label), 20);
6760 gtk_label_set_ellipsize(GTK_LABEL(t->label), PANGO_ELLIPSIZE_END);
6761 gtk_widget_set_size_request(b, 130, 0);
6763 gtk_box_pack_start(GTK_BOX(b), bb, FALSE, FALSE, 0);
6764 gtk_box_pack_start(GTK_BOX(b), t->label, FALSE, FALSE, 0);
6765 #if GTK_CHECK_VERSION(2, 20, 0)
6766 gtk_box_pack_start(GTK_BOX(b), t->spinner, FALSE, FALSE, 0);
6767 #endif
6769 /* toolbar */
6770 if (browser_mode == XT_BM_KIOSK) {
6771 t->toolbar = create_kiosk_toolbar(t);
6772 gtk_box_pack_start(GTK_BOX(t->vbox), t->toolbar, FALSE, FALSE,
6774 } else {
6775 t->toolbar = create_toolbar(t);
6776 if (fancy_bar)
6777 gtk_box_pack_start(GTK_BOX(t->vbox), t->toolbar, FALSE,
6778 FALSE, 0);
6781 /* marks */
6782 marks_clear(t);
6784 /* browser */
6785 t->browser_win = create_browser(t);
6786 gtk_box_pack_start(GTK_BOX(t->vbox), t->browser_win, TRUE, TRUE, 0);
6788 /* oops message for user feedback */
6789 t->oops = gtk_entry_new();
6790 gtk_entry_set_inner_border(GTK_ENTRY(t->oops), NULL);
6791 gtk_entry_set_has_frame(GTK_ENTRY(t->oops), FALSE);
6792 gtk_widget_set_can_focus(GTK_WIDGET(t->oops), FALSE);
6793 gdk_color_parse(XT_COLOR_RED, &color);
6794 gtk_widget_modify_base(t->oops, GTK_STATE_NORMAL, &color);
6795 gtk_box_pack_end(GTK_BOX(t->vbox), t->oops, FALSE, FALSE, 0);
6796 gtk_widget_modify_font(GTK_WIDGET(t->oops), oops_font);
6798 /* command entry */
6799 t->cmd = gtk_entry_new();
6800 gtk_entry_set_inner_border(GTK_ENTRY(t->cmd), NULL);
6801 gtk_entry_set_has_frame(GTK_ENTRY(t->cmd), FALSE);
6802 gtk_box_pack_end(GTK_BOX(t->vbox), t->cmd, FALSE, FALSE, 0);
6803 gtk_widget_modify_font(GTK_WIDGET(t->cmd), cmd_font);
6805 /* status bar */
6806 t->statusbar_box = gtk_hbox_new(FALSE, 0);
6808 t->sbe.statusbar = gtk_entry_new();
6809 gtk_entry_set_inner_border(GTK_ENTRY(t->sbe.statusbar), NULL);
6810 gtk_entry_set_has_frame(GTK_ENTRY(t->sbe.statusbar), FALSE);
6811 gtk_widget_set_can_focus(GTK_WIDGET(t->sbe.statusbar), FALSE);
6812 gtk_widget_modify_font(GTK_WIDGET(t->sbe.statusbar), statusbar_font);
6814 /* create these widgets only if specified in statusbar_elems */
6816 t->sbe.position = create_sbe(40);
6817 t->sbe.zoom = create_sbe(40);
6818 t->sbe.buffercmd = create_sbe(60);
6820 statusbar_modify_attr(t, XT_COLOR_WHITE, XT_COLOR_BLACK);
6822 gtk_box_pack_start(GTK_BOX(t->statusbar_box), t->sbe.statusbar, TRUE,
6823 TRUE, FALSE);
6825 /* gtk widgets cannot be added to a box twice. sbe_* variables
6826 make sure of this */
6827 for (p = statusbar_elems; *p != '\0'; p++) {
6828 switch (*p) {
6829 case '|':
6831 GtkWidget *sep = gtk_vseparator_new();
6833 gdk_color_parse(XT_COLOR_SB_SEPARATOR, &color);
6834 gtk_widget_modify_bg(sep, GTK_STATE_NORMAL, &color);
6835 gtk_box_pack_start(GTK_BOX(t->statusbar_box), sep,
6836 FALSE, FALSE, FALSE);
6837 break;
6839 case 'P':
6840 if (sbe_p) {
6841 warnx("flag \"%c\" specified more than "
6842 "once in statusbar_elems\n", *p);
6843 break;
6845 sbe_p = 1;
6846 gtk_box_pack_start(GTK_BOX(t->statusbar_box),
6847 t->sbe.position, FALSE, FALSE, FALSE);
6848 break;
6849 case 'B':
6850 if (sbe_b) {
6851 warnx("flag \"%c\" specified more than "
6852 "once in statusbar_elems\n", *p);
6853 break;
6855 sbe_b = 1;
6856 gtk_box_pack_start(GTK_BOX(t->statusbar_box),
6857 t->sbe.buffercmd, FALSE, FALSE, FALSE);
6858 break;
6859 case 'Z':
6860 if (sbe_z) {
6861 warnx("flag \"%c\" specified more than "
6862 "once in statusbar_elems\n", *p);
6863 break;
6865 sbe_z = 1;
6866 gtk_box_pack_start(GTK_BOX(t->statusbar_box),
6867 t->sbe.zoom, FALSE, FALSE, FALSE);
6868 break;
6869 default:
6870 warnx("illegal flag \"%c\" in statusbar_elems\n", *p);
6871 break;
6875 gtk_box_pack_end(GTK_BOX(t->vbox), t->statusbar_box, FALSE, FALSE, 0);
6877 /* buffer list */
6878 t->buffers = create_buffers(t);
6879 gtk_box_pack_end(GTK_BOX(t->vbox), t->buffers, FALSE, FALSE, 0);
6881 /* xtp meaning is normal by default */
6882 t->xtp_meaning = XT_XTP_TAB_MEANING_NORMAL;
6884 /* set empty favicon */
6885 xt_icon_from_name(t, "text-html");
6887 /* and show it all */
6888 gtk_widget_show_all(b);
6889 gtk_widget_show_all(t->vbox);
6891 /* compact tab bar */
6892 t->tab_elems.label = gtk_label_new(title);
6893 t->tab_elems.favicon = gtk_image_new();
6894 gtk_label_set_width_chars(GTK_LABEL(t->tab_elems.label), 1.0);
6895 gtk_misc_set_alignment(GTK_MISC(t->tab_elems.label), 0.0, 0.0);
6896 gtk_misc_set_padding(GTK_MISC(t->tab_elems.label), 4.0, 4.0);
6897 gtk_widget_modify_font(GTK_WIDGET(t->tab_elems.label), tabbar_font);
6899 t->tab_elems.eventbox = gtk_event_box_new();
6900 t->tab_elems.box = gtk_hbox_new(FALSE, 0);
6901 t->tab_elems.sep = gtk_vseparator_new();
6903 gdk_color_parse(XT_COLOR_CT_BACKGROUND, &color);
6904 gtk_widget_modify_bg(t->tab_elems.eventbox, GTK_STATE_NORMAL, &color);
6905 gdk_color_parse(XT_COLOR_CT_INACTIVE, &color);
6906 gtk_widget_modify_fg(t->tab_elems.label, GTK_STATE_NORMAL, &color);
6907 gdk_color_parse(XT_COLOR_CT_SEPARATOR, &color);
6908 gtk_widget_modify_bg(t->tab_elems.sep, GTK_STATE_NORMAL, &color);
6910 gtk_box_pack_start(GTK_BOX(t->tab_elems.box), t->tab_elems.favicon, FALSE,
6911 FALSE, 0);
6912 gtk_box_pack_start(GTK_BOX(t->tab_elems.box), t->tab_elems.label, TRUE,
6913 TRUE, 0);
6914 gtk_box_pack_start(GTK_BOX(t->tab_elems.box), t->tab_elems.sep, FALSE,
6915 FALSE, 0);
6916 gtk_container_add(GTK_CONTAINER(t->tab_elems.eventbox),
6917 t->tab_elems.box);
6919 gtk_box_pack_start(GTK_BOX(tab_bar), t->tab_elems.eventbox, TRUE,
6920 TRUE, 0);
6921 gtk_widget_show_all(t->tab_elems.eventbox);
6923 if (append_next == 0 || gtk_notebook_get_n_pages(notebook) == 0)
6924 append_tab(t);
6925 else {
6926 id = position >= 0 ? position :
6927 gtk_notebook_get_current_page(notebook) + 1;
6928 if (id > gtk_notebook_get_n_pages(notebook))
6929 append_tab(t);
6930 else {
6931 TAILQ_INSERT_TAIL(&tabs, t, entry);
6932 gtk_notebook_insert_page(notebook, t->vbox, b, id);
6933 gtk_box_reorder_child(GTK_BOX(tab_bar),
6934 t->tab_elems.eventbox, id);
6935 recalc_tabs();
6939 #if GTK_CHECK_VERSION(2, 20, 0)
6940 /* turn spinner off if we are a new tab without uri */
6941 if (!load) {
6942 gtk_spinner_stop(GTK_SPINNER(t->spinner));
6943 gtk_widget_hide(t->spinner);
6945 #endif
6946 /* make notebook tabs reorderable */
6947 gtk_notebook_set_tab_reorderable(notebook, t->vbox, TRUE);
6949 /* compact tabs clickable */
6950 g_signal_connect(G_OBJECT(t->tab_elems.eventbox),
6951 "button_press_event", G_CALLBACK(tab_clicked_cb), t);
6953 g_object_connect(G_OBJECT(t->cmd),
6954 "signal::key-press-event", G_CALLBACK(cmd_keypress_cb), t,
6955 "signal::key-release-event", G_CALLBACK(cmd_keyrelease_cb), t,
6956 "signal::focus-out-event", G_CALLBACK(cmd_focusout_cb), t,
6957 "signal::activate", G_CALLBACK(cmd_activate_cb), t,
6958 "signal::populate-popup", G_CALLBACK(cmd_popup_cb), t,
6959 (char *)NULL);
6961 /* reuse wv_button_cb to hide oops */
6962 g_object_connect(G_OBJECT(t->oops),
6963 "signal::button_press_event", G_CALLBACK(wv_button_cb), t,
6964 (char *)NULL);
6966 g_signal_connect(t->buffers,
6967 "row-activated", G_CALLBACK(row_activated_cb), t);
6968 g_object_connect(G_OBJECT(t->buffers),
6969 "signal::key-press-event", G_CALLBACK(wv_keypress_cb), t, (char *)NULL);
6971 g_object_connect(G_OBJECT(t->wv),
6972 "signal::key-press-event", G_CALLBACK(wv_keypress_cb), t,
6973 "signal::hovering-over-link", G_CALLBACK(webview_hover_cb), t,
6974 "signal::download-requested", G_CALLBACK(webview_download_cb), t,
6975 "signal::mime-type-policy-decision-requested", G_CALLBACK(webview_mimetype_cb), t,
6976 "signal::navigation-policy-decision-requested", G_CALLBACK(webview_npd_cb), t,
6977 "signal::new-window-policy-decision-requested", G_CALLBACK(webview_npd_cb), t,
6978 "signal::resource-request-starting", G_CALLBACK(webview_rrs_cb), t,
6979 "signal::create-web-view", G_CALLBACK(webview_cwv_cb), t,
6980 "signal::close-web-view", G_CALLBACK(webview_closewv_cb), t,
6981 "signal::event", G_CALLBACK(webview_event_cb), t,
6982 "signal::load-finished", G_CALLBACK(webview_load_finished_cb), t,
6983 "signal::load-progress-changed", G_CALLBACK(webview_progress_changed_cb), t,
6984 "signal::icon-loaded", G_CALLBACK(notify_icon_loaded_cb), t,
6985 "signal::button_press_event", G_CALLBACK(wv_button_cb), t,
6986 "signal::button_release_event", G_CALLBACK(wv_release_button_cb), t,
6987 "signal::populate-popup", G_CALLBACK(wv_popup_cb), t,
6988 (char *)NULL);
6989 g_signal_connect(t->wv,
6990 "notify::load-status", G_CALLBACK(notify_load_status_cb), t);
6991 g_signal_connect(t->wv,
6992 "notify::title", G_CALLBACK(notify_title_cb), t);
6994 /* hijack the unused keys as if we were the browser */
6995 //g_object_connect(G_OBJECT(t->toolbar),
6996 // "signal-after::key-press-event", G_CALLBACK(wv_keypress_after_cb), t,
6997 // (char *)NULL);
6999 g_signal_connect(G_OBJECT(bb), "button_press_event",
7000 G_CALLBACK(tab_close_cb), t);
7002 /* setup history */
7003 t->bfl = webkit_web_view_get_back_forward_list(t->wv);
7004 /* restore the tab's history */
7005 if (u && u->history) {
7006 items = u->history;
7007 while (items) {
7008 item = items->data;
7009 webkit_web_back_forward_list_add_item(t->bfl, item);
7010 items = g_list_next(items);
7013 item = g_list_nth_data(u->history, u->back);
7014 if (item)
7015 webkit_web_view_go_to_back_forward_item(t->wv, item);
7017 g_list_free(items);
7018 g_list_free(u->history);
7019 } else
7020 webkit_web_back_forward_list_clear(t->bfl);
7022 /* hide stuff */
7023 hide_cmd(t);
7024 hide_oops(t);
7025 hide_buffers(t);
7026 url_set_visibility();
7027 statusbar_set_visibility();
7029 if (focus) {
7030 set_current_tab(t->tab_id);
7031 DNPRINTF(XT_D_TAB, "create_new_tab: going to tab: %d\n",
7032 t->tab_id);
7034 if (load) {
7035 gtk_entry_set_text(GTK_ENTRY(t->uri_entry), title);
7036 load_uri(t, title);
7037 } else {
7038 if (show_url == 1)
7039 gtk_widget_grab_focus(GTK_WIDGET(t->uri_entry));
7040 else
7041 focus_webview(t);
7043 } else if (load)
7044 load_uri(t, title);
7046 if (userstyle_global)
7047 apply_style(t);
7049 recolor_compact_tabs();
7050 setzoom_webkit(t, XT_ZOOM_NORMAL);
7051 return (t);
7054 void
7055 notebook_switchpage_cb(GtkNotebook *nb, GtkWidget *nbp, guint pn,
7056 gpointer *udata)
7058 struct tab *t;
7059 const gchar *uri;
7061 DNPRINTF(XT_D_TAB, "notebook_switchpage_cb: tab: %d\n", pn);
7063 if (gtk_notebook_get_current_page(notebook) == -1)
7064 recalc_tabs();
7066 TAILQ_FOREACH(t, &tabs, entry) {
7067 if (t->tab_id == pn) {
7068 DNPRINTF(XT_D_TAB, "notebook_switchpage_cb: going to "
7069 "%d\n", pn);
7071 uri = get_title(t, TRUE);
7072 gtk_window_set_title(GTK_WINDOW(main_window), uri);
7074 hide_cmd(t);
7075 hide_oops(t);
7077 if (t->focus_wv) {
7078 /* can't use focus_webview here */
7079 gtk_widget_grab_focus(GTK_WIDGET(t->wv));
7085 void
7086 notebook_pagereordered_cb(GtkNotebook *nb, GtkWidget *nbp, guint pn,
7087 gpointer *udata)
7089 struct tab *t = NULL, *tt;
7091 recalc_tabs();
7093 TAILQ_FOREACH(tt, &tabs, entry)
7094 if (tt->tab_id == pn) {
7095 t = tt;
7096 break;
7098 if (t == NULL)
7099 return;
7100 DNPRINTF(XT_D_TAB, "page_reordered_cb: tab: %d\n", t->tab_id);
7102 gtk_box_reorder_child(GTK_BOX(tab_bar), t->tab_elems.eventbox,
7103 t->tab_id);
7106 void
7107 menuitem_response(struct tab *t)
7109 gtk_notebook_set_current_page(notebook, t->tab_id);
7112 gboolean
7113 arrow_cb(GtkWidget *w, GdkEventButton *event, gpointer user_data)
7115 GtkWidget *menu, *menu_items;
7116 GdkEventButton *bevent;
7117 const gchar *uri;
7118 struct tab *ti;
7120 if (event->type == GDK_BUTTON_PRESS) {
7121 bevent = (GdkEventButton *) event;
7122 menu = gtk_menu_new();
7124 TAILQ_FOREACH(ti, &tabs, entry) {
7125 if ((uri = get_uri(ti)) == NULL)
7126 /* XXX make sure there is something to print */
7127 /* XXX add gui pages in here to look purdy */
7128 uri = "(untitled)";
7129 menu_items = gtk_menu_item_new_with_label(uri);
7130 gtk_menu_shell_append(GTK_MENU_SHELL(menu), menu_items);
7131 gtk_widget_show(menu_items);
7133 g_signal_connect_swapped((menu_items),
7134 "activate", G_CALLBACK(menuitem_response),
7135 (gpointer)ti);
7138 gtk_menu_popup(GTK_MENU(menu), NULL, NULL, NULL, NULL,
7139 bevent->button, bevent->time);
7141 /* unref object so it'll free itself when popped down */
7142 #if !GTK_CHECK_VERSION(3, 0, 0)
7143 /* XXX does not need unref with gtk+3? */
7144 g_object_ref_sink(menu);
7145 g_object_unref(menu);
7146 #endif
7148 return (TRUE /* eat event */);
7151 return (FALSE /* propagate */);
7155 icon_size_map(int iconsz)
7157 if (iconsz <= GTK_ICON_SIZE_INVALID ||
7158 iconsz > GTK_ICON_SIZE_DIALOG)
7159 return (GTK_ICON_SIZE_SMALL_TOOLBAR);
7161 return (iconsz);
7164 GtkWidget *
7165 create_button(char *name, char *stockid, int size)
7167 GtkWidget *button, *image;
7168 gchar *rcstring;
7169 int gtk_icon_size;
7171 rcstring = g_strdup_printf(
7172 "style \"%s-style\"\n"
7173 "{\n"
7174 " GtkWidget::focus-padding = 0\n"
7175 " GtkWidget::focus-line-width = 0\n"
7176 " xthickness = 0\n"
7177 " ythickness = 0\n"
7178 "}\n"
7179 "widget \"*.%s\" style \"%s-style\"", name, name, name);
7180 gtk_rc_parse_string(rcstring);
7181 g_free(rcstring);
7182 button = gtk_button_new();
7183 gtk_button_set_focus_on_click(GTK_BUTTON(button), FALSE);
7184 gtk_icon_size = icon_size_map(size ? size : icon_size);
7186 image = gtk_image_new_from_stock(stockid, gtk_icon_size);
7187 gtk_widget_set_size_request(GTK_WIDGET(image), -1, -1);
7188 gtk_container_set_border_width(GTK_CONTAINER(button), 1);
7189 gtk_container_add(GTK_CONTAINER(button), GTK_WIDGET(image));
7190 gtk_widget_set_name(button, name);
7191 gtk_button_set_relief(GTK_BUTTON(button), GTK_RELIEF_NONE);
7193 return (button);
7196 void
7197 button_set_stockid(GtkWidget *button, char *stockid)
7199 GtkWidget *image;
7201 image = gtk_image_new_from_stock(stockid, icon_size_map(icon_size));
7202 gtk_widget_set_size_request(GTK_WIDGET(image), -1, -1);
7203 gtk_button_set_image(GTK_BUTTON(button), image);
7206 void
7207 clipb_primary_cb(GtkClipboard *primary, GdkEvent *event, gpointer notused)
7209 gchar *p = NULL;
7210 GdkAtom atom = gdk_atom_intern("CUT_BUFFER0", FALSE);
7211 gint len;
7213 if (xterm_workaround == 0)
7214 return;
7217 * xterm doesn't play nice with clipboards because it clears the
7218 * primary when clicked. We rely on primary being set to properly
7219 * handle middle mouse button clicks (paste). So when someone clears
7220 * primary copy whatever is in CUT_BUFFER0 into primary to simualte
7221 * other application behavior (as in DON'T clear primary).
7224 p = gtk_clipboard_wait_for_text(primary);
7225 if (p == NULL) {
7226 if (gdk_property_get(gdk_get_default_root_window(),
7227 atom,
7228 gdk_atom_intern("STRING", FALSE),
7230 1024 * 1024 /* picked out of my butt */,
7231 FALSE,
7232 NULL,
7233 NULL,
7234 &len,
7235 (guchar **)&p)) {
7236 if (p == NULL)
7237 return;
7238 /* yes sir, we need to NUL the string */
7239 p[len] = '\0';
7240 gtk_clipboard_set_text(primary, p, -1);
7244 if (p)
7245 g_free(p);
7248 void
7249 create_canvas(void)
7251 GtkWidget *vbox;
7252 GList *l = NULL;
7253 GdkPixbuf *pb;
7254 char file[PATH_MAX];
7255 int i;
7257 vbox = gtk_vbox_new(FALSE, 0);
7258 gtk_box_set_spacing(GTK_BOX(vbox), 0);
7259 notebook = GTK_NOTEBOOK(gtk_notebook_new());
7260 #if !GTK_CHECK_VERSION(3, 0, 0)
7261 /* XXX seems to be needed with gtk+2 */
7262 gtk_notebook_set_tab_hborder(notebook, 0);
7263 gtk_notebook_set_tab_vborder(notebook, 0);
7264 #endif
7265 gtk_notebook_set_scrollable(notebook, TRUE);
7266 gtk_notebook_set_show_border(notebook, FALSE);
7267 gtk_widget_set_can_focus(GTK_WIDGET(notebook), FALSE);
7269 abtn = gtk_button_new();
7270 arrow = gtk_arrow_new(GTK_ARROW_DOWN, GTK_SHADOW_NONE);
7271 gtk_widget_set_size_request(arrow, -1, -1);
7272 gtk_container_add(GTK_CONTAINER(abtn), arrow);
7273 gtk_widget_set_size_request(abtn, -1, 20);
7275 #if GTK_CHECK_VERSION(2, 20, 0)
7276 gtk_notebook_set_action_widget(notebook, abtn, GTK_PACK_END);
7277 #endif
7278 gtk_widget_set_size_request(GTK_WIDGET(notebook), -1, -1);
7280 /* compact tab bar */
7281 tab_bar = gtk_hbox_new(TRUE, 0);
7283 gtk_box_pack_start(GTK_BOX(vbox), tab_bar, FALSE, FALSE, 0);
7284 gtk_box_pack_start(GTK_BOX(vbox), GTK_WIDGET(notebook), TRUE, TRUE, 0);
7285 gtk_widget_set_size_request(vbox, -1, -1);
7287 g_object_connect(G_OBJECT(notebook),
7288 "signal::switch-page", G_CALLBACK(notebook_switchpage_cb), NULL,
7289 (char *)NULL);
7290 g_object_connect(G_OBJECT(notebook),
7291 "signal::page-reordered", G_CALLBACK(notebook_pagereordered_cb),
7292 NULL, (char *)NULL);
7293 g_signal_connect(G_OBJECT(abtn), "button_press_event",
7294 G_CALLBACK(arrow_cb), NULL);
7296 main_window = create_window("xxxterm");
7297 gtk_container_add(GTK_CONTAINER(main_window), vbox);
7298 g_signal_connect(G_OBJECT(main_window), "delete_event",
7299 G_CALLBACK(gtk_main_quit), NULL);
7301 /* icons */
7302 for (i = 0; i < LENGTH(icons); i++) {
7303 snprintf(file, sizeof file, "%s" PS "%s", resource_dir, icons[i]);
7304 pb = gdk_pixbuf_new_from_file(file, NULL);
7305 l = g_list_append(l, pb);
7307 gtk_window_set_default_icon_list(l);
7309 /* clipboard work around */
7310 if (xterm_workaround)
7311 g_signal_connect(
7312 G_OBJECT(gtk_clipboard_get(GDK_SELECTION_PRIMARY)),
7313 "owner-change", G_CALLBACK(clipb_primary_cb), NULL);
7315 gtk_widget_show_all(abtn);
7316 gtk_widget_show_all(main_window);
7317 notebook_tab_set_visibility();
7320 #ifndef XT_SOCKET_DISABLE
7322 send_cmd_to_socket(char *cmd)
7324 int s, len, rv = 1;
7325 struct sockaddr_un sa;
7327 if ((s = socket(AF_UNIX, SOCK_STREAM, 0)) == -1) {
7328 warnx("%s: socket", __func__);
7329 return (rv);
7332 sa.sun_family = AF_UNIX;
7333 snprintf(sa.sun_path, sizeof(sa.sun_path), "%s" PS "%s",
7334 work_dir, XT_SOCKET_FILE);
7335 len = SUN_LEN(&sa);
7337 if (connect(s, (struct sockaddr *)&sa, len) == -1) {
7338 warnx("%s: connect", __func__);
7339 goto done;
7342 if (send(s, cmd, strlen(cmd) + 1, 0) == -1) {
7343 warnx("%s: send", __func__);
7344 goto done;
7347 rv = 0;
7348 done:
7349 close(s);
7350 return (rv);
7353 gboolean
7354 socket_watcher(GIOChannel *source, GIOCondition condition, gpointer data)
7356 int s, n;
7357 char str[XT_MAX_URL_LENGTH];
7358 socklen_t t = sizeof(struct sockaddr_un);
7359 struct sockaddr_un sa;
7360 struct passwd *p;
7361 uid_t uid;
7362 gid_t gid;
7363 struct tab *tt;
7364 gint fd = g_io_channel_unix_get_fd(source);
7366 if ((s = accept(fd, (struct sockaddr *)&sa, &t)) == -1) {
7367 warn("accept");
7368 return (FALSE);
7371 if (getpeereid(s, &uid, &gid) == -1) {
7372 warn("getpeereid");
7373 return (FALSE);
7375 if (uid != getuid() || gid != getgid()) {
7376 warnx("unauthorized user");
7377 return (FALSE);
7380 p = getpwuid(uid);
7381 if (p == NULL) {
7382 warnx("not a valid user");
7383 return (FALSE);
7386 n = recv(s, str, sizeof(str), 0);
7387 if (n <= 0)
7388 return (TRUE);
7390 tt = TAILQ_LAST(&tabs, tab_list);
7391 cmd_execute(tt, str);
7392 return (TRUE);
7396 is_running(void)
7398 int s, len, rv = 1;
7399 struct sockaddr_un sa;
7401 if ((s = socket(AF_UNIX, SOCK_STREAM, 0)) == -1) {
7402 warn("is_running: socket");
7403 return (-1);
7406 sa.sun_family = AF_UNIX;
7407 snprintf(sa.sun_path, sizeof(sa.sun_path), "%s" PS "%s",
7408 work_dir, XT_SOCKET_FILE);
7409 len = SUN_LEN(&sa);
7411 /* connect to see if there is a listener */
7412 if (connect(s, (struct sockaddr *)&sa, len) == -1)
7413 rv = 0; /* not running */
7414 else
7415 rv = 1; /* already running */
7417 close(s);
7419 return (rv);
7423 build_socket(void)
7425 int s, len;
7426 struct sockaddr_un sa;
7428 if ((s = socket(AF_UNIX, SOCK_STREAM, 0)) == -1) {
7429 warn("build_socket: socket");
7430 return (-1);
7433 sa.sun_family = AF_UNIX;
7434 snprintf(sa.sun_path, sizeof(sa.sun_path), "%s" PS "%s",
7435 work_dir, XT_SOCKET_FILE);
7436 len = SUN_LEN(&sa);
7438 /* connect to see if there is a listener */
7439 if (connect(s, (struct sockaddr *)&sa, len) == -1) {
7440 /* no listener so we will */
7441 unlink(sa.sun_path);
7443 if (bind(s, (struct sockaddr *)&sa, len) == -1) {
7444 warn("build_socket: bind");
7445 goto done;
7448 if (listen(s, 1) == -1) {
7449 warn("build_socket: listen");
7450 goto done;
7453 return (s);
7456 done:
7457 close(s);
7458 return (-1);
7460 #endif
7462 void
7463 xxx_dir(char *dir)
7465 struct stat sb;
7467 if (stat(dir, &sb)) {
7468 #if defined __MINGW32__
7469 printf("making: %s\n", dir);
7470 if (mkdir(dir) == -1)
7471 #else
7472 if (mkdir(dir, S_IRWXU) == -1)
7473 #endif
7474 err(1, "mkdir %s", dir);
7475 if (stat(dir, &sb))
7476 err(1, "stat %s", dir);
7478 if (S_ISDIR(sb.st_mode) == 0)
7479 errx(1, "%s not a dir", dir);
7480 #if !defined __MINGW32__
7481 if (((sb.st_mode & (S_IRWXU | S_IRWXG | S_IRWXO))) != S_IRWXU) {
7482 warnx("fixing invalid permissions on %s", dir);
7483 if (chmod(dir, S_IRWXU) == -1)
7484 err(1, "chmod %s", dir);
7486 #endif
7489 void
7490 usage(void)
7492 fprintf(stderr,
7493 "%s [-nSTVt][-f file][-s session] url ...\n", __progname);
7494 exit(0);
7497 GStaticRecMutex my_gdk_mtx = G_STATIC_REC_MUTEX_INIT;
7498 volatile int mtx_depth;
7499 int mtx_complain;
7502 * The linux flash plugin violates the gdk locking mechanism.
7503 * Work around the issue by using a recursive mutex with some match applied
7504 * to see if we hit a buggy condition.
7506 * The following code is painful so just don't read it. It really doesn't
7507 * make much sense but seems to work.
7509 void
7510 mtx_lock(void)
7512 g_static_rec_mutex_lock(&my_gdk_mtx);
7513 mtx_depth++;
7515 if (mtx_depth <= 0) {
7516 /* should not happen */
7517 show_oops(NULL, "negative mutex locking bug, trying to "
7518 "correct");
7519 fprintf(stderr, "negative mutex locking bug, trying to "
7520 "correct\n");
7521 g_static_rec_mutex_unlock_full(&my_gdk_mtx);
7522 g_static_rec_mutex_lock(&my_gdk_mtx);
7523 mtx_depth = 1;
7524 return;
7527 if (mtx_depth != 1) {
7528 /* decrease mutext depth to 1 */
7529 do {
7530 g_static_rec_mutex_unlock(&my_gdk_mtx);
7531 mtx_depth--;
7532 } while (mtx_depth > 1);
7536 void
7537 mtx_unlock(void)
7539 guint x;
7541 /* if mutex depth isn't 1 then something went bad */
7542 if (mtx_depth != 1) {
7543 x = g_static_rec_mutex_unlock_full(&my_gdk_mtx);
7544 if (x != 1) {
7545 /* should not happen */
7546 show_oops(NULL, "mutex unlocking bug, trying to "
7547 "correct");
7548 fprintf(stderr, "mutex unlocking bug, trying to "
7549 "correct\n");
7551 mtx_depth = 0;
7552 if (mtx_complain == 0) {
7553 show_oops(NULL, "buggy mutex implementation detected, "
7554 "work around implemented");
7555 fprintf(stderr, "buggy mutex implementation detected, "
7556 "work around implemented");
7557 mtx_complain = 1;
7559 return;
7562 mtx_depth--;
7563 g_static_rec_mutex_unlock(&my_gdk_mtx);
7566 void
7567 welcome(void)
7569 startpage_add("<b>Welcome to xxxterm %s!</b><p>", version);
7570 startpage_add("Beware that this is the final version that will use the"
7571 " xxxterm name.<br>Moving forward the browser will be called "
7572 "xombrero.<p>", version);
7573 startpage_add("Details will soon appear on the "
7574 "<a href=https://opensource.conformal.com/wiki/xombrero>xombrero "
7575 "wiki page</a>");
7579 main(int argc, char **argv)
7581 struct stat sb;
7582 int c, optn = 0, opte = 0, focus = 1;
7583 char conf[PATH_MAX] = { '\0' };
7584 char file[PATH_MAX];
7585 char sodversion[32];
7586 char *env_proxy = NULL;
7587 FILE *f = NULL;
7588 struct karg a;
7590 start_argv = (char * const *)argv;
7592 /* prepare gtk */
7593 #ifdef USE_THREADS
7594 g_thread_init(NULL);
7595 gdk_threads_set_lock_functions(mtx_lock, mtx_unlock);
7596 gdk_threads_init();
7597 gdk_threads_enter();
7599 gcry_control (GCRYCTL_SET_THREAD_CBS, &gcry_threads_pthread);
7600 #endif
7601 gtk_init(&argc, &argv);
7603 gnutls_global_init();
7605 strlcpy(named_session, XT_SAVED_TABS_FILE, sizeof named_session);
7607 RB_INIT(&hl);
7608 RB_INIT(&js_wl);
7609 RB_INIT(&pl_wl);
7610 RB_INIT(&downloads);
7611 RB_INIT(&st_tree);
7613 TAILQ_INIT(&sessions);
7614 TAILQ_INIT(&tabs);
7615 TAILQ_INIT(&mtl);
7616 TAILQ_INIT(&aliases);
7617 TAILQ_INIT(&undos);
7618 TAILQ_INIT(&kbl);
7619 TAILQ_INIT(&spl);
7620 TAILQ_INIT(&chl);
7621 TAILQ_INIT(&shl);
7622 TAILQ_INIT(&ua_list);
7624 #ifndef XT_RESOURCE_LIMITS_DISABLE
7625 struct rlimit rlp;
7626 char *cmd = NULL;
7627 int s;
7628 GIOChannel *channel;
7630 /* fiddle with ulimits */
7631 if (getrlimit(RLIMIT_NOFILE, &rlp) == -1)
7632 warn("getrlimit");
7633 else {
7634 /* just use them all */
7635 rlp.rlim_cur = rlp.rlim_max;
7636 if (setrlimit(RLIMIT_NOFILE, &rlp) == -1)
7637 warn("setrlimit");
7638 if (getrlimit(RLIMIT_NOFILE, &rlp) == -1)
7639 warn("getrlimit");
7640 else if (rlp.rlim_cur <= 1024)
7641 startpage_add("%s requires at least 1024 "
7642 "(2048 recommended) file " "descriptors, "
7643 "currently it has up to %d available",
7644 __progname, rlp.rlim_cur);
7646 #endif
7648 while ((c = getopt(argc, argv, "STVf:s:tne")) != -1) {
7649 switch (c) {
7650 case 'S':
7651 show_url = 0;
7652 break;
7653 case 'T':
7654 show_tabs = 0;
7655 break;
7656 case 'V':
7657 #ifdef XXXTERM_BUILDSTR
7658 errx(0 , "Version: %s Build: %s",
7659 version, XXXTERM_BUILDSTR);
7660 #else
7661 errx(0 , "Version: %s", version);
7662 #endif
7663 break;
7664 case 'f':
7665 strlcpy(conf, optarg, sizeof(conf));
7666 break;
7667 case 's':
7668 strlcpy(named_session, optarg, sizeof(named_session));
7669 break;
7670 case 't':
7671 tabless = 1;
7672 break;
7673 case 'n':
7674 optn = 1;
7675 break;
7676 case 'e':
7677 opte = 1;
7678 break;
7679 default:
7680 usage();
7681 /* NOTREACHED */
7684 argc -= optind;
7685 argv += optind;
7687 init_keybindings();
7689 xtp_generate_keys();
7691 /* XXX this hammer is way too big but treat all signaling the same */
7692 #ifndef XT_SIGNALS_DISABLE
7693 /* signals */
7694 struct sigaction sact;
7696 bzero(&sact, sizeof(sact));
7697 sigemptyset(&sact.sa_mask);
7698 sact.sa_handler = sigchild;
7699 sact.sa_flags = SA_NOCLDSTOP;
7700 sigaction(SIGCHLD, &sact, NULL);
7701 #endif
7703 /* set download dir */
7704 pwd = getpwuid(getuid());
7705 if (pwd == NULL)
7706 errx(1, "invalid user %d", getuid());
7707 strlcpy(download_dir, pwd->pw_dir, sizeof download_dir);
7709 /* compile buffer command regexes */
7710 buffercmd_init();
7712 /* set default string settings */
7713 home = g_strdup("https://www.cyphertite.com");
7714 search_string = g_strdup("https://ssl.scroogle.org/cgi-bin/nbbwssl.cgi?Gw=%s");
7715 resource_dir = g_strdup("/usr/local/share/xxxterm/");
7716 strlcpy(runtime_settings, "runtime", sizeof runtime_settings);
7717 cmd_font_name = g_strdup("monospace normal 9");
7718 oops_font_name = g_strdup("monospace normal 9");
7719 statusbar_font_name = g_strdup("monospace normal 9");
7720 tabbar_font_name = g_strdup("monospace normal 9");
7721 statusbar_elems = g_strdup("BP");
7722 spell_check_languages = g_strdup("en_US");
7723 encoding = g_strdup("UTF-8");
7725 /* read config file */
7726 if (strlen(conf) == 0)
7727 snprintf(conf, sizeof conf, "%s" PS ".%s",
7728 pwd->pw_dir, XT_CONF_FILE);
7729 config_parse(conf, 0);
7731 /* init fonts */
7732 cmd_font = pango_font_description_from_string(cmd_font_name);
7733 oops_font = pango_font_description_from_string(oops_font_name);
7734 statusbar_font = pango_font_description_from_string(statusbar_font_name);
7735 tabbar_font = pango_font_description_from_string(tabbar_font_name);
7737 /* working directory */
7738 if (strlen(work_dir) == 0)
7739 snprintf(work_dir, sizeof work_dir, "%s" PS "%s",
7740 pwd->pw_dir, XT_DIR);
7741 xxx_dir(work_dir);
7743 /* icon cache dir */
7744 snprintf(cache_dir, sizeof cache_dir, "%s" PS "%s", work_dir, XT_CACHE_DIR);
7745 xxx_dir(cache_dir);
7747 /* certs dir */
7748 snprintf(certs_dir, sizeof certs_dir, "%s" PS "%s", work_dir, XT_CERT_DIR);
7749 xxx_dir(certs_dir);
7751 /* sessions dir */
7752 snprintf(sessions_dir, sizeof sessions_dir, "%s" PS "%s",
7753 work_dir, XT_SESSIONS_DIR);
7754 xxx_dir(sessions_dir);
7756 /* js dir */
7757 snprintf(js_dir, sizeof js_dir, "%s" PS "%s", work_dir, XT_JS_DIR);
7758 xxx_dir(js_dir);
7760 /* temp dir */
7761 snprintf(temp_dir, sizeof temp_dir, "%s" PS "%s", work_dir, XT_TEMP_DIR);
7762 xxx_dir(temp_dir);
7764 /* runtime settings that can override config file */
7765 if (runtime_settings[0] != '\0')
7766 config_parse(runtime_settings, 1);
7768 /* download dir */
7769 if (!strcmp(download_dir, pwd->pw_dir))
7770 strlcat(download_dir, PS "downloads", sizeof download_dir);
7771 xxx_dir(download_dir);
7773 /* first start file */
7774 snprintf(file, sizeof file, "%s" PS "%s", work_dir, XT_SOD_FILE);
7775 if (stat(file, &sb)) {
7776 warnx("start of day file doesn't exist, creating it");
7777 if ((f = fopen(file, "w")) == NULL)
7778 err(1, "startofday");
7779 if (fputs(version, f))
7780 err(1, "fputs");
7781 fclose(f);
7783 /* welcome user */
7784 welcome();
7785 } else {
7786 if ((f = fopen(file, "r")) == NULL)
7787 err(1, "startofday");
7788 if (fgets(sodversion, sizeof sodversion, f) == NULL)
7789 err(1, "fgets");
7790 if (strcmp(version, sodversion)) {
7791 /* upgrade, say something smart */
7792 welcome();
7794 fclose(f);
7797 /* favorites file */
7798 snprintf(file, sizeof file, "%s" PS "%s", work_dir, XT_FAVS_FILE);
7799 if (stat(file, &sb)) {
7800 warnx("favorites file doesn't exist, creating it");
7801 if ((f = fopen(file, "w")) == NULL)
7802 err(1, "favorites");
7803 fclose(f);
7806 /* quickmarks file */
7807 snprintf(file, sizeof file, "%s" PS "%s", work_dir, XT_QMARKS_FILE);
7808 if (stat(file, &sb)) {
7809 warnx("quickmarks file doesn't exist, creating it");
7810 if ((f = fopen(file, "w")) == NULL)
7811 err(1, "quickmarks");
7812 fclose(f);
7815 /* search history */
7816 if (history_autosave) {
7817 snprintf(search_file, sizeof search_file, "%s" PS "%s",
7818 work_dir, XT_SEARCH_FILE);
7819 if (stat(search_file, &sb)) {
7820 warnx("search history file doesn't exist, creating it");
7821 if ((f = fopen(search_file, "w")) == NULL)
7822 err(1, "search_history");
7823 fclose(f);
7825 history_read(&shl, search_file, &search_history_count);
7828 /* command history */
7829 if (history_autosave) {
7830 snprintf(command_file, sizeof command_file, "%s" PS "%s",
7831 work_dir, XT_COMMAND_FILE);
7832 if (stat(command_file, &sb)) {
7833 warnx("command history file doesn't exist, creating it");
7834 if ((f = fopen(command_file, "w")) == NULL)
7835 err(1, "command_history");
7836 fclose(f);
7838 history_read(&chl, command_file, &cmd_history_count);
7841 /* cookies */
7842 session = webkit_get_default_session();
7843 setup_cookies();
7845 /* certs */
7846 if (ssl_ca_file) {
7847 if (stat(ssl_ca_file, &sb)) {
7848 warnx("no CA file: %s", ssl_ca_file);
7849 g_free(ssl_ca_file);
7850 ssl_ca_file = NULL;
7851 } else
7852 g_object_set(session,
7853 SOUP_SESSION_SSL_CA_FILE, ssl_ca_file,
7854 SOUP_SESSION_SSL_STRICT, ssl_strict_certs,
7855 (void *)NULL);
7858 /* guess_search regex */
7859 if (url_regex == NULL)
7860 url_regex = g_strdup(XT_URL_REGEX);
7861 if (url_regex)
7862 if (regcomp(&url_re, url_regex, REG_EXTENDED | REG_NOSUB))
7863 startpage_add("invalid url regex %s", url_regex);
7865 /* proxy */
7866 env_proxy = getenv("http_proxy");
7867 if (env_proxy)
7868 setup_proxy(env_proxy);
7869 else {
7870 env_proxy = getenv("HTTP_PROXY");
7871 if (env_proxy)
7872 setup_proxy(env_proxy);
7873 else
7874 setup_proxy(http_proxy);
7876 #ifndef XT_SOCKET_DISABLE
7877 if (opte) {
7878 send_cmd_to_socket(argv[0]);
7879 exit(0);
7881 #else
7882 opte = opte; /* shut mingw up */
7883 #endif
7884 /* set some connection parameters */
7885 g_object_set(session, "max-conns", max_connections, (char *)NULL);
7886 g_object_set(session, "max-conns-per-host", max_host_connections,
7887 (char *)NULL);
7889 g_signal_connect(session, "request-queued", G_CALLBACK(session_rq_cb),
7890 NULL);
7892 #ifndef XT_SOCKET_DISABLE
7893 /* see if there is already an xxxterm running */
7894 if (single_instance && is_running()) {
7895 optn = 1;
7896 warnx("already running");
7899 if (optn) {
7900 while (argc) {
7901 cmd = g_strdup_printf("%s %s", "tabnew", argv[0]);
7902 send_cmd_to_socket(cmd);
7903 if (cmd)
7904 g_free(cmd);
7906 argc--;
7907 argv++;
7909 exit(0);
7911 #else
7912 optn = optn; /* shut mingw up */
7913 #endif
7914 /* tld list */
7915 tld_tree_init();
7917 if (enable_strict_transport)
7918 strict_transport_init();
7920 /* uri completion */
7921 completion_model = gtk_list_store_new(1, G_TYPE_STRING);
7923 /* buffers */
7924 buffers_store = gtk_list_store_new
7925 (NUM_COLS, G_TYPE_UINT, GDK_TYPE_PIXBUF, G_TYPE_STRING);
7927 qmarks_load();
7929 /* go graphical */
7930 create_canvas();
7931 notebook_tab_set_visibility();
7933 if (save_global_history)
7934 restore_global_history();
7936 /* restore session list */
7937 restore_sessions_list();
7939 if (!strcmp(named_session, XT_SAVED_TABS_FILE))
7940 restore_saved_tabs();
7941 else {
7942 a.s = named_session;
7943 a.i = XT_SES_DONOTHING;
7944 open_tabs(NULL, &a);
7947 /* see if we have an exception */
7948 if (!TAILQ_EMPTY(&spl)) {
7949 create_new_tab("about:startpage", NULL, focus, -1);
7950 focus = 0;
7953 while (argc) {
7954 create_new_tab(argv[0], NULL, focus, -1);
7955 focus = 0;
7957 argc--;
7958 argv++;
7961 if (TAILQ_EMPTY(&tabs))
7962 create_new_tab(home, NULL, 1, -1);
7963 #ifndef XT_SOCKET_DISABLE
7964 if (enable_socket)
7965 if ((s = build_socket()) != -1) {
7966 channel = g_io_channel_unix_new(s);
7967 g_io_add_watch(channel, G_IO_IN, socket_watcher, NULL);
7969 #endif
7971 gtk_main();
7973 #ifdef USE_THREADS
7974 gdk_threads_leave();
7975 g_static_rec_mutex_unlock_full(&my_gdk_mtx); /* just in case */
7976 #endif
7978 gnutls_global_deinit();
7980 if (url_regex)
7981 regfree(&url_re);
7983 return (0);