Redo the back/forward list hack
[xombrero.git] / xombrero.c
blob1049c5ad320a3d208cc2c6f72dbc538de11536b6
1 /*
2 * Copyright (c) 2010, 2011 Marco Peereboom <marco@peereboom.us>
3 * Copyright (c) 2011 Stevan Andjelkovic <stevan@student.chalmers.se>
4 * Copyright (c) 2010, 2011, 2012 Edd Barrett <vext01@gmail.com>
5 * Copyright (c) 2011 Todd T. Fries <todd@fries.net>
6 * Copyright (c) 2011 Raphael Graf <r@undefined.ch>
7 * Copyright (c) 2011 Michal Mazurek <akfaew@jasminek.net>
8 * Copyright (c) 2012 Josh Rickmar <jrick@devio.us>
10 * Permission to use, copy, modify, and distribute this software for any
11 * purpose with or without fee is hereby granted, provided that the above
12 * copyright notice and this permission notice appear in all copies.
14 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
15 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
16 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
17 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
18 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
19 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
20 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
23 #include <xombrero.h>
24 #include "version.h"
26 char *version = XOMBRERO_VERSION;
28 #ifdef XT_DEBUG
29 uint32_t swm_debug = 0
30 | XT_D_MOVE
31 | XT_D_KEY
32 | XT_D_TAB
33 | XT_D_URL
34 | XT_D_CMD
35 | XT_D_NAV
36 | XT_D_DOWNLOAD
37 | XT_D_CONFIG
38 | XT_D_JS
39 | XT_D_FAVORITE
40 | XT_D_PRINTING
41 | XT_D_COOKIE
42 | XT_D_KEYBINDING
43 | XT_D_CLIP
44 | XT_D_BUFFERCMD
45 | XT_D_INSPECTOR
46 | XT_D_VISITED
47 | XT_D_HISTORY
49 #endif
51 #ifdef USE_THREADS
52 GCRY_THREAD_OPTION_PTHREAD_IMPL;
53 #endif
55 char *icons[] = {
56 "xombreroicon16.png",
57 "xombreroicon32.png",
58 "xombreroicon48.png",
59 "xombreroicon64.png",
60 "xombreroicon128.png"
63 struct session {
64 TAILQ_ENTRY(session) entry;
65 const gchar *name;
67 TAILQ_HEAD(session_list, session);
69 struct undo {
70 TAILQ_ENTRY(undo) entry;
71 gchar *uri;
72 GList *history;
73 int back; /* Keeps track of how many back
74 * history items there are. */
76 TAILQ_HEAD(undo_tailq, undo);
78 struct command_entry {
79 char *line;
80 TAILQ_ENTRY(command_entry) entry;
82 TAILQ_HEAD(command_list, command_entry);
84 /* defines */
85 #define XT_CACHE_DIR ("cache")
86 #define XT_CERT_DIR ("certs")
87 #define XT_CERT_CACHE_DIR ("certs_cache")
88 #define XT_JS_DIR ("js")
89 #define XT_SESSIONS_DIR ("sessions")
90 #define XT_TEMP_DIR ("tmp")
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_PRINT_EXTRA_MARGIN 10
102 #define XT_URL_REGEX ("^[[:blank:]]*[^[:blank:]]*([[:alnum:]-]+\\.)+[[:alnum:]-][^[:blank:]]*[[:blank:]]*$")
103 #define XT_INVALID_MARK (-1) /* XXX this is a double, maybe use something else, like a nan */
105 /* colors */
106 #define XT_COLOR_RED "#cc0000"
107 #define XT_COLOR_YELLOW "#ffff66"
108 #define XT_COLOR_BLUE "lightblue"
109 #define XT_COLOR_GREEN "#99ff66"
110 #define XT_COLOR_WHITE "white"
111 #define XT_COLOR_BLACK "black"
113 #define XT_COLOR_CT_BACKGROUND "#000000"
114 #define XT_COLOR_CT_INACTIVE "#dddddd"
115 #define XT_COLOR_CT_ACTIVE "#bbbb00"
116 #define XT_COLOR_CT_SEPARATOR "#555555"
118 #define XT_COLOR_SB_SEPARATOR "#555555"
120 /* CSS element names */
121 #define XT_CSS_NORMAL ""
122 #define XT_CSS_RED "red"
123 #define XT_CSS_YELLOW "yellow"
124 #define XT_CSS_GREEN "green"
125 #define XT_CSS_BLUE "blue"
126 #define XT_CSS_HIDDEN "hidden"
127 #define XT_CSS_ACTIVE "active"
129 #define XT_PROTO_DELIM "://"
131 /* actions */
132 #define XT_MOVE_INVALID (0)
133 #define XT_MOVE_DOWN (1)
134 #define XT_MOVE_UP (2)
135 #define XT_MOVE_BOTTOM (3)
136 #define XT_MOVE_TOP (4)
137 #define XT_MOVE_PAGEDOWN (5)
138 #define XT_MOVE_PAGEUP (6)
139 #define XT_MOVE_HALFDOWN (7)
140 #define XT_MOVE_HALFUP (8)
141 #define XT_MOVE_LEFT (9)
142 #define XT_MOVE_FARLEFT (10)
143 #define XT_MOVE_RIGHT (11)
144 #define XT_MOVE_FARRIGHT (12)
145 #define XT_MOVE_PERCENT (13)
146 #define XT_MOVE_CENTER (14)
148 #define XT_QMARK_SET (0)
149 #define XT_QMARK_OPEN (1)
150 #define XT_QMARK_TAB (2)
152 #define XT_MARK_SET (0)
153 #define XT_MARK_GOTO (1)
155 #define XT_GO_UP_ROOT (999)
157 #define XT_NAV_INVALID (0)
158 #define XT_NAV_BACK (1)
159 #define XT_NAV_FORWARD (2)
160 #define XT_NAV_RELOAD (3)
161 #define XT_NAV_STOP (4)
163 #define XT_FOCUS_INVALID (0)
164 #define XT_FOCUS_URI (1)
165 #define XT_FOCUS_SEARCH (2)
167 #define XT_SEARCH_INVALID (0)
168 #define XT_SEARCH_NEXT (1)
169 #define XT_SEARCH_PREV (2)
171 #define XT_PASTE_CURRENT_TAB (0)
172 #define XT_PASTE_NEW_TAB (1)
174 #define XT_ZOOM_IN (-1)
175 #define XT_ZOOM_OUT (-2)
176 #define XT_ZOOM_NORMAL (100)
178 #define XT_SES_DONOTHING (0)
179 #define XT_SES_CLOSETABS (1)
181 #define XT_PREFIX (1<<0)
182 #define XT_USERARG (1<<1)
183 #define XT_URLARG (1<<2)
184 #define XT_INTARG (1<<3)
185 #define XT_SESSARG (1<<4)
186 #define XT_SETARG (1<<5)
188 #define XT_HINT_NEWTAB (1<<0)
190 #define XT_BUFCMD_SZ (8)
192 #define XT_EJS_SHOW (1<<0)
194 GtkWidget * create_button(char *, char *, int);
196 void recalc_tabs(void);
197 void recolor_compact_tabs(void);
198 void set_current_tab(int page_num);
199 gboolean update_statusbar_position(GtkAdjustment*, gpointer);
200 void marks_clear(struct tab *t);
202 /* globals */
203 extern char *__progname;
204 char * const *start_argv;
205 struct passwd *pwd;
206 GtkWidget *main_window;
207 GtkNotebook *notebook;
208 GtkWidget *tab_bar;
209 GtkWidget *tab_bar_box;
210 GtkWidget *arrow, *abtn;
211 GdkEvent *fevent = NULL;
212 struct tab_list tabs;
213 struct history_list hl;
214 int hl_purge_count = 0;
215 struct session_list sessions;
216 struct domain_list c_wl;
217 struct domain_list js_wl;
218 struct domain_list pl_wl;
219 struct domain_list force_https;
220 struct domain_list svil;
221 struct strict_transport_tree st_tree;
222 struct undo_tailq undos;
223 struct keybinding_list kbl;
224 struct sp_list spl;
225 struct user_agent_list ua_list;
226 struct http_accept_list ha_list;
227 struct cmd_alias_list cal;
228 struct custom_uri_list cul;
229 struct command_list chl;
230 struct command_list shl;
231 struct command_entry *history_at;
232 struct command_entry *search_at;
233 struct secviolation_list svl;
234 struct set_reject_list srl;
235 int undo_count;
236 int cmd_history_count = 0;
237 int search_history_count = 0;
238 char *global_search;
239 uint64_t blocked_cookies = 0;
240 char named_session[PATH_MAX];
241 GtkListStore *completion_model;
242 GtkListStore *buffers_store;
243 char *stylesheet;
245 char *qmarks[XT_NOQMARKS];
246 int btn_down; /* M1 down in any wv */
247 regex_t url_re; /* guess_search regex */
249 /* starts from 1 to catch atoi() failures when calling xtp_handle_dl() */
250 int next_download_id = 1;
252 void xxx_dir(char *);
253 int icon_size_map(int);
254 void activate_uri_entry_cb(GtkWidget*, struct tab *);
256 void
257 history_delete(struct command_list *l, int *counter)
259 struct command_entry *c;
261 if (l == NULL || counter == NULL)
262 return;
264 c = TAILQ_LAST(l, command_list);
265 if (c == NULL)
266 return;
268 TAILQ_REMOVE(l, c, entry);
269 *counter -= 1;
270 g_free(c->line);
271 g_free(c);
274 void
275 history_add(struct command_list *list, char *file, char *l, int *counter)
277 struct command_entry *c;
278 FILE *f;
280 if (list == NULL || l == NULL || counter == NULL)
281 return;
283 /* don't add the same line */
284 c = TAILQ_FIRST(list);
285 if (c)
286 if (!strcmp(c->line + 1 /* skip space */, l))
287 return;
289 c = g_malloc0(sizeof *c);
290 c->line = g_strdup_printf(" %s", l);
292 *counter += 1;
293 TAILQ_INSERT_HEAD(list, c, entry);
295 if (*counter > 1000)
296 history_delete(list, counter);
298 if (history_autosave && file) {
299 f = fopen(file, "w");
300 if (f == NULL) {
301 show_oops(NULL, "couldn't write history %s", file);
302 return;
305 TAILQ_FOREACH_REVERSE(c, list, command_list, entry) {
306 c->line[0] = ' ';
307 fprintf(f, "%s\n", c->line);
310 fclose(f);
315 history_read(struct command_list *list, char *file, int *counter)
317 FILE *f;
318 char *s, line[65536];
320 if (list == NULL || file == NULL)
321 return (1);
323 f = fopen(file, "r");
324 if (f == NULL) {
325 startpage_add("couldn't open history file %s", file);
326 return (1);
329 for (;;) {
330 s = fgets(line, sizeof line, f);
331 if (s == NULL || feof(f) || ferror(f))
332 break;
333 if ((s = strchr(line, '\n')) == NULL) {
334 startpage_add("invalid history file %s", file);
335 fclose(f);
336 return (1);
338 *s = '\0';
340 history_add(list, NULL, line + 1, counter);
343 fclose(f);
345 return (0);
348 /* marks array storage. */
349 char
350 indextomark(int i)
352 if (i < 0 || i >= XT_NOMARKS)
353 return (0);
355 return XT_MARKS[i];
359 marktoindex(char m)
361 char *ret;
363 if ((ret = strchr(XT_MARKS, m)) != NULL)
364 return ret - XT_MARKS;
366 return (-1);
369 /* quickmarks array storage. */
370 char
371 indextoqmark(int i)
373 if (i < 0 || i >= XT_NOQMARKS)
374 return (0);
376 return XT_QMARKS[i];
380 qmarktoindex(char m)
382 char *ret;
384 if ((ret = strchr(XT_QMARKS, m)) != NULL)
385 return ret - XT_QMARKS;
387 return (-1);
391 is_g_object_setting(GObject *o, char *str)
393 guint n_props = 0, i;
394 GParamSpec **proplist;
395 int rv = 0;
397 if (!G_IS_OBJECT(o))
398 return (0);
400 proplist = g_object_class_list_properties(G_OBJECT_GET_CLASS(o),
401 &n_props);
403 for (i = 0; i < n_props; i++) {
404 if (! strcmp(proplist[i]->name, str)) {
405 rv = 1;
406 break;
410 g_free(proplist);
411 return (rv);
414 struct tab *
415 get_current_tab(void)
417 struct tab *t;
419 TAILQ_FOREACH(t, &tabs, entry) {
420 if (t->tab_id == gtk_notebook_get_current_page(notebook))
421 return (t);
424 warnx("%s: no current tab", __func__);
426 return (NULL);
430 set_ssl_ca_file(struct settings *s, char *file)
432 struct stat sb;
434 if (file == NULL || strlen(file) == 0)
435 return (-1);
436 if (stat(file, &sb)) {
437 warnx("no CA file: %s", file);
438 return (-1);
440 expand_tilde(ssl_ca_file, sizeof ssl_ca_file, file);
441 g_object_set(session,
442 SOUP_SESSION_SSL_CA_FILE, ssl_ca_file,
443 SOUP_SESSION_SSL_STRICT, ssl_strict_certs,
444 (void *)NULL);
445 return (0);
448 void
449 set_status(struct tab *t, gchar *fmt, ...)
451 va_list ap;
452 gchar *status;
454 va_start(ap, fmt);
456 status = g_strdup_vprintf(fmt, ap);
458 gtk_entry_set_text(GTK_ENTRY(t->sbe.uri), status);
460 if (!t->status)
461 t->status = status;
462 else if (strcmp(t->status, status)) {
463 /* set new status */
464 g_free(t->status);
465 t->status = status;
466 } else
467 g_free(status);
469 va_end(ap);
472 void
473 hide_cmd(struct tab *t)
475 DNPRINTF(XT_D_CMD, "%s: tab %d\n", __func__, t->tab_id);
477 history_at = NULL; /* just in case */
478 search_at = NULL; /* just in case */
479 gtk_widget_set_can_focus(t->cmd, FALSE);
480 gtk_widget_hide(t->cmd);
483 void
484 show_cmd(struct tab *t)
486 DNPRINTF(XT_D_CMD, "%s: tab %d\n", __func__, t->tab_id);
488 /* without this you can't middle click in t->cmd to paste */
489 gtk_entry_set_text(GTK_ENTRY(t->cmd), "");
491 history_at = NULL;
492 search_at = NULL;
493 gtk_widget_hide(t->oops);
494 gtk_widget_set_can_focus(t->cmd, TRUE);
495 gtk_widget_show(t->cmd);
498 void
499 hide_buffers(struct tab *t)
501 gtk_widget_hide(t->buffers);
502 gtk_widget_set_can_focus(t->buffers, FALSE);
503 gtk_list_store_clear(buffers_store);
506 enum {
507 COL_ID = 0,
508 COL_FAVICON,
509 COL_TITLE,
510 NUM_COLS
514 sort_tabs_by_page_num(struct tab ***stabs)
516 int num_tabs = 0;
517 struct tab *t;
519 num_tabs = gtk_notebook_get_n_pages(notebook);
521 *stabs = g_malloc0(num_tabs * sizeof(struct tab *));
523 TAILQ_FOREACH(t, &tabs, entry)
524 (*stabs)[gtk_notebook_page_num(notebook, t->vbox)] = t;
526 return (num_tabs);
529 void
530 buffers_make_list(void)
532 int i, num_tabs;
533 const gchar *title = NULL;
534 GtkTreeIter iter;
535 struct tab **stabs = NULL;
537 num_tabs = sort_tabs_by_page_num(&stabs);
539 for (i = 0; i < num_tabs; i++)
540 if (stabs[i]) {
541 gtk_list_store_append(buffers_store, &iter);
542 title = get_title(stabs[i], FALSE);
543 gtk_list_store_set(buffers_store, &iter,
544 COL_ID, i + 1, /* Enumerate the tabs starting from 1
545 * rather than 0. */
546 COL_FAVICON, gtk_image_get_pixbuf
547 (GTK_IMAGE(stabs[i]->tab_elems.favicon)),
548 COL_TITLE, title,
549 -1);
552 g_free(stabs);
555 void
556 show_buffers(struct tab *t)
558 GtkTreeIter iter;
559 GtkTreeSelection *sel;
560 GtkTreePath *path;
561 int index;
563 if (gtk_widget_get_visible(GTK_WIDGET(t->buffers)))
564 return;
566 buffers_make_list();
568 sel = gtk_tree_view_get_selection(GTK_TREE_VIEW(t->buffers));
569 index = gtk_notebook_get_current_page(notebook);
570 path = gtk_tree_path_new_from_indices(index, -1);
571 if (gtk_tree_model_get_iter(GTK_TREE_MODEL(buffers_store), &iter, path))
572 gtk_tree_selection_select_iter(sel, &iter);
573 gtk_tree_path_free(path);
575 gtk_widget_show(t->buffers);
576 gtk_widget_set_can_focus(t->buffers, TRUE);
577 gtk_widget_grab_focus(GTK_WIDGET(t->buffers));
580 void
581 toggle_buffers(struct tab *t)
583 if (gtk_widget_get_visible(t->buffers))
584 hide_buffers(t);
585 else
586 show_buffers(t);
590 buffers(struct tab *t, struct karg *args)
592 show_buffers(t);
594 return (0);
598 set_scrollbar_visibility(struct tab *t, int visible)
600 #if GTK_CHECK_VERSION(3, 0, 0)
601 GtkWidget *h_scrollbar, *v_scrollbar;
603 h_scrollbar = gtk_scrolled_window_get_hscrollbar(
604 GTK_SCROLLED_WINDOW(t->browser_win));
605 v_scrollbar = gtk_scrolled_window_get_vscrollbar(
606 GTK_SCROLLED_WINDOW(t->browser_win));
608 if (visible == 0) {
609 gtk_widget_set_name(h_scrollbar, XT_CSS_HIDDEN);
610 gtk_widget_set_name(v_scrollbar, XT_CSS_HIDDEN);
611 } else {
612 gtk_widget_set_name(h_scrollbar, "");
613 gtk_widget_set_name(v_scrollbar, "");
616 return (0);
617 #else
618 return (visible == 0);
619 #endif
622 void
623 hide_oops(struct tab *t)
625 gtk_widget_hide(t->oops);
628 void
629 show_oops(struct tab *at, const char *fmt, ...)
631 va_list ap;
632 char *msg = NULL;
633 struct tab *t = NULL;
635 if (fmt == NULL)
636 return;
638 if (at == NULL) {
639 if ((t = get_current_tab()) == NULL)
640 return;
641 } else
642 t = at;
644 va_start(ap, fmt);
645 if ((msg = g_strdup_vprintf(fmt, ap)) == NULL)
646 errx(1, "show_oops failed");
647 va_end(ap);
649 gtk_entry_set_text(GTK_ENTRY(t->oops), msg);
650 gtk_widget_hide(t->cmd);
651 gtk_widget_show(t->oops);
653 if (msg)
654 g_free(msg);
657 char work_dir[PATH_MAX];
658 char certs_dir[PATH_MAX];
659 char certs_cache_dir[PATH_MAX];
660 char js_dir[PATH_MAX];
661 char cache_dir[PATH_MAX];
662 char sessions_dir[PATH_MAX];
663 char temp_dir[PATH_MAX];
664 char cookie_file[PATH_MAX];
665 char *strict_transport_file = NULL;
666 SoupSession *session;
667 SoupCookieJar *s_cookiejar;
668 SoupCookieJar *p_cookiejar;
669 char rc_fname[PATH_MAX];
671 struct mime_type_list mtl;
672 struct alias_list aliases;
674 /* protos */
675 struct tab *create_new_tab(char *, struct undo *, int, int);
676 void delete_tab(struct tab *);
677 void setzoom_webkit(struct tab *, int);
678 int download_rb_cmp(struct download *, struct download *);
679 gboolean cmd_execute(struct tab *t, char *str);
682 history_rb_cmp(struct history *h1, struct history *h2)
684 return (strcmp(h1->uri, h2->uri));
686 RB_GENERATE(history_list, history, entry, history_rb_cmp);
689 domain_rb_cmp(struct domain *d1, struct domain *d2)
691 return (strcmp(d1->d, d2->d));
693 RB_GENERATE(domain_list, domain, entry, domain_rb_cmp);
696 download_rb_cmp(struct download *e1, struct download *e2)
698 return (e1->id < e2->id ? -1 : e1->id > e2->id);
700 RB_GENERATE(download_list, download, entry, download_rb_cmp);
703 secviolation_rb_cmp(struct secviolation *s1, struct secviolation *s2)
705 return (s1->xtp_arg < s2->xtp_arg ? -1 : s1->xtp_arg > s2->xtp_arg);
707 RB_GENERATE(secviolation_list, secviolation, entry, secviolation_rb_cmp);
710 user_agent_rb_cmp(struct user_agent *ua1, struct user_agent *ua2)
712 return (ua1->id < ua2->id ? -1 : ua1->id > ua2->id);
714 RB_GENERATE(user_agent_list, user_agent, entry, user_agent_rb_cmp);
717 http_accept_rb_cmp(struct http_accept *ha1, struct http_accept *ha2)
719 return (ha1->id < ha2->id ? -1 : ha1->id > ha2->id);
721 RB_GENERATE(http_accept_list, http_accept, entry, http_accept_rb_cmp);
723 struct valid_url_types {
724 char *type;
725 } vut[] = {
726 { "http://" },
727 { "https://" },
728 { "ftp://" },
729 { "file://" },
730 { XT_URI_ABOUT },
731 { XT_XTP_STR },
735 valid_url_type(char *url)
737 int i;
739 for (i = 0; i < LENGTH(vut); i++)
740 if (!strncasecmp(vut[i].type, url, strlen(vut[i].type)))
741 return (0);
743 return (1);
746 char *
747 match_alias(char *url_in)
749 struct alias *a;
750 char *arg;
751 char *url_out = NULL, *search, *enc_arg;
752 char **sv;
754 search = g_strdup(url_in);
755 arg = search;
756 if (strsep(&arg, " \t") == NULL) {
757 show_oops(NULL, "match_alias: NULL URL");
758 goto done;
761 TAILQ_FOREACH(a, &aliases, entry) {
762 if (!strcmp(search, a->a_name))
763 break;
766 if (a != NULL) {
767 DNPRINTF(XT_D_URL, "match_alias: matched alias %s\n",
768 a->a_name);
769 enc_arg = soup_uri_encode(arg, XT_RESERVED_CHARS);
770 sv = g_strsplit(a->a_uri, "%s", 2);
771 if (arg != NULL)
772 url_out = g_strjoinv(enc_arg, sv);
773 else
774 url_out = g_strjoinv("", sv);
775 g_free(enc_arg);
776 g_strfreev(sv);
778 done:
779 g_free(search);
780 return (url_out);
783 char *
784 guess_url_type(char *url_in)
786 struct stat sb;
787 char cwd[PATH_MAX] = {0};
788 char *url_out = NULL, *enc_search = NULL;
789 char *path = NULL;
790 char **sv = NULL;
791 int i;
794 /* substitute aliases */
795 url_out = match_alias(url_in);
796 if (url_out != NULL)
797 return (url_out);
799 /* see if we are an about page */
800 if (!strncmp(url_in, XT_URI_ABOUT, XT_URI_ABOUT_LEN))
801 for (i = 0; i < about_list_size(); i++)
802 if (!strcmp(&url_in[XT_URI_ABOUT_LEN],
803 about_list[i].name)) {
804 url_out = g_strdup(url_in);
805 goto done;
808 if (guess_search && url_regex &&
809 !(g_str_has_prefix(url_in, "http://") ||
810 g_str_has_prefix(url_in, "https://"))) {
811 if (regexec(&url_re, url_in, 0, NULL, 0)) {
812 /* invalid URI so search instead */
813 enc_search = soup_uri_encode(url_in, XT_RESERVED_CHARS);
814 sv = g_strsplit(search_string, "%s", 2);
815 url_out = g_strjoinv(enc_search, sv);
816 g_free(enc_search);
817 g_strfreev(sv);
818 goto done;
822 /* XXX not sure about this heuristic */
823 if (stat(url_in, &sb) == 0) {
824 if (url_in[0] == '/')
825 url_out = g_filename_to_uri(url_in, NULL, NULL);
826 else {
827 if (getcwd(cwd, PATH_MAX) != NULL) {
828 path = g_strdup_printf("%s" PS "%s", cwd,
829 url_in);
830 url_out = g_filename_to_uri(path, NULL, NULL);
831 g_free(path);
834 } else
835 url_out = g_strdup_printf("http://%s", url_in); /* guess http */
836 done:
837 DNPRINTF(XT_D_URL, "guess_url_type: guessed %s\n", url_out);
839 return (url_out);
842 void
843 set_normal_tab_meaning(struct tab *t)
845 if (t == NULL)
846 return;
848 t->xtp_meaning = XT_XTP_TAB_MEANING_NORMAL;
849 if (t->session_key != NULL) {
850 g_free(t->session_key);
851 t->session_key = NULL;
855 void
856 load_uri(struct tab *t, gchar *uri)
858 struct karg args;
859 gchar *newuri = NULL;
860 int i;
862 if (uri == NULL)
863 return;
865 /* Strip leading spaces. */
866 while (*uri && isspace(*uri))
867 uri++;
869 if (strlen(uri) == 0) {
870 blank(t, NULL);
871 return;
874 set_normal_tab_meaning(t);
876 if (valid_url_type(uri)) {
877 newuri = guess_url_type(uri);
878 uri = newuri;
881 if (!strncmp(uri, XT_URI_ABOUT, XT_URI_ABOUT_LEN)) {
882 for (i = 0; i < about_list_size(); i++)
883 if (!strcmp(&uri[XT_URI_ABOUT_LEN], about_list[i].name) &&
884 about_list[i].func != NULL) {
885 bzero(&args, sizeof args);
886 about_list[i].func(t, &args);
887 gtk_widget_set_sensitive(GTK_WIDGET(t->stop),
888 FALSE);
889 goto done;
891 show_oops(t, "invalid about page");
892 goto done;
895 set_status(t, "Loading: %s", (char *)uri);
896 marks_clear(t);
897 webkit_web_view_load_uri(t->wv, uri);
898 done:
899 if (newuri)
900 g_free(newuri);
903 const gchar *
904 get_uri(struct tab *t)
906 const gchar *uri = NULL;
908 if (webkit_web_view_get_load_status(t->wv) == WEBKIT_LOAD_FAILED &&
909 !t->download_requested)
910 return (NULL);
911 if (t->xtp_meaning == XT_XTP_TAB_MEANING_NORMAL) {
912 uri = webkit_web_view_get_uri(t->wv);
913 } else {
914 /* use tmp_uri to make sure it is g_freed */
915 if (t->tmp_uri)
916 g_free(t->tmp_uri);
917 t->tmp_uri = g_strdup_printf("%s%s", XT_URI_ABOUT,
918 about_list[t->xtp_meaning].name);
919 uri = t->tmp_uri;
921 return uri;
924 const gchar *
925 get_title(struct tab *t, bool window)
927 const gchar *set = NULL, *title = NULL;
928 WebKitLoadStatus status = webkit_web_view_get_load_status(t->wv);
930 if (status == WEBKIT_LOAD_PROVISIONAL ||
931 (status == WEBKIT_LOAD_FAILED && !t->download_requested) ||
932 t->xtp_meaning == XT_XTP_TAB_MEANING_BL)
933 goto notitle;
935 title = webkit_web_view_get_title(t->wv);
936 if ((set = title ? title : get_uri(t)))
937 return set;
939 notitle:
940 set = window ? XT_NAME : "(untitled)";
942 return set;
945 struct mime_type *
946 find_mime_type(char *mime_type)
948 struct mime_type *m, *def = NULL, *rv = NULL;
950 TAILQ_FOREACH(m, &mtl, entry) {
951 if (m->mt_default &&
952 !strncmp(mime_type, m->mt_type, strlen(m->mt_type)))
953 def = m;
955 if (m->mt_default == 0 && !strcmp(mime_type, m->mt_type)) {
956 rv = m;
957 break;
961 if (rv == NULL)
962 rv = def;
964 return (rv);
968 * This only escapes the & and < characters, as per the discussion found here:
969 * http://lists.apple.com/archives/Webkitsdk-dev/2007/May/msg00056.html
971 char *
972 html_escape(const char *val)
974 char *s, *sp;
975 char **sv;
977 if (val == NULL)
978 return NULL;
980 sv = g_strsplit(val, "&", -1);
981 s = g_strjoinv("&amp;", sv);
982 g_strfreev(sv);
983 sp = s;
984 sv = g_strsplit(val, "<", -1);
985 s = g_strjoinv("&lt;", sv);
986 g_strfreev(sv);
987 g_free(sp);
988 return (s);
991 struct domain *
992 wl_find_uri(const gchar *s, struct domain_list *wl)
994 int i;
995 char *ss;
996 struct domain *r;
998 if (s == NULL || wl == NULL)
999 return (NULL);
1001 if (!strncmp(s, "http://", strlen("http://")))
1002 s = &s[strlen("http://")];
1003 else if (!strncmp(s, "https://", strlen("https://")))
1004 s = &s[strlen("https://")];
1006 if (strlen(s) < 2)
1007 return (NULL);
1009 for (i = 0; i < strlen(s) + 1 /* yes er need this */; i++)
1010 /* chop string at first slash */
1011 if (s[i] == '/' || s[i] == ':' || s[i] == '\0') {
1012 ss = g_strdup(s);
1013 ss[i] = '\0';
1014 r = wl_find(ss, wl);
1015 g_free(ss);
1016 return (r);
1019 return (NULL);
1022 char *
1023 js_ref_to_string(JSContextRef context, JSValueRef ref)
1025 char *s = NULL;
1026 size_t l;
1027 JSStringRef jsref;
1029 jsref = JSValueToStringCopy(context, ref, NULL);
1030 if (jsref == NULL)
1031 return (NULL);
1033 l = JSStringGetMaximumUTF8CStringSize(jsref);
1034 s = g_malloc(l);
1035 if (s)
1036 JSStringGetUTF8CString(jsref, s, l);
1037 JSStringRelease(jsref);
1039 return (s);
1042 #define XT_JS_DONE ("done;")
1043 #define XT_JS_DONE_LEN (strlen(XT_JS_DONE))
1044 #define XT_JS_INSERT ("insert;")
1045 #define XT_JS_INSERT_LEN (strlen(XT_JS_INSERT))
1048 run_script(struct tab *t, char *s)
1050 JSGlobalContextRef ctx;
1051 WebKitWebFrame *frame;
1052 JSStringRef str;
1053 JSValueRef val, exception;
1054 char *es;
1056 DNPRINTF(XT_D_JS, "%s: tab %d %s\n", __func__,
1057 t->tab_id, s == (char *)JS_HINTING ? "JS_HINTING" : s);
1059 frame = webkit_web_view_get_main_frame(t->wv);
1060 ctx = webkit_web_frame_get_global_context(frame);
1062 str = JSStringCreateWithUTF8CString(s);
1063 val = JSEvaluateScript(ctx, str, JSContextGetGlobalObject(ctx),
1064 NULL, 0, &exception);
1065 JSStringRelease(str);
1067 DNPRINTF(XT_D_JS, "%s: val %p\n", __func__, val);
1068 if (val == NULL) {
1069 es = js_ref_to_string(ctx, exception);
1070 if (es) {
1071 DNPRINTF(XT_D_JS, "%s: exception %s\n", __func__, es);
1072 g_free(es);
1074 return (1);
1075 } else {
1076 es = js_ref_to_string(ctx, val);
1077 #if 0
1078 /* return values */
1079 if (!strncmp(es, XT_JS_DONE, XT_JS_DONE_LEN))
1080 ; /* do nothing */
1081 if (!strncmp(es, XT_JS_INSERT, XT_JS_INSERT_LEN))
1082 ; /* do nothing */
1083 #endif
1084 if (es) {
1085 DNPRINTF(XT_D_JS, "%s: val %s\n", __func__, es);
1086 g_free(es);
1090 return (0);
1094 run_script_locked(struct tab *t, char *s)
1096 int rv;
1097 #ifdef USE_THREADS
1098 gdk_threads_enter();
1099 #endif
1100 rv = run_script(t, s);
1101 #ifdef USE_THREADS
1102 GDK_FLUSH();
1103 gdk_threads_leave();
1104 #endif
1105 return (rv);
1108 void
1109 enable_hints(struct tab *t)
1111 DNPRINTF(XT_D_JS, "%s: tab %d\n", __func__, t->tab_id);
1113 if (t->new_tab)
1114 run_script(t, "hints.createHints('', 'F');");
1115 else
1116 run_script(t, "hints.createHints('', 'f');");
1117 t->mode = XT_MODE_HINT;
1120 void
1121 disable_hints(struct tab *t)
1123 DNPRINTF(XT_D_JS, "%s: tab %d\n", __func__, t->tab_id);
1125 run_script(t, "hints.clearHints();");
1126 t->mode = XT_MODE_COMMAND;
1127 t->new_tab = 0;
1131 passthrough(struct tab *t, struct karg *args)
1133 t->mode = XT_MODE_PASSTHROUGH;
1134 return (0);
1138 modurl(struct tab *t, struct karg *args)
1140 const gchar *uri = NULL;
1141 char *u = NULL;
1143 /* XXX kind of a bad hack, but oh well */
1144 if (gtk_widget_has_focus(t->uri_entry)) {
1145 if ((uri = gtk_entry_get_text(GTK_ENTRY(t->uri_entry))) &&
1146 (strlen(uri))) {
1147 u = g_strdup_printf("www.%s.com", uri);
1148 gtk_entry_set_text(GTK_ENTRY(t->uri_entry), u);
1149 g_free(u);
1150 activate_uri_entry_cb(t->uri_entry, t);
1153 return (0);
1157 hint(struct tab *t, struct karg *args)
1160 DNPRINTF(XT_D_JS, "hint: tab %d args %d\n", t->tab_id, args->i);
1162 if (t->mode == XT_MODE_HINT) {
1163 if (args->i == XT_HINT_NEWTAB)
1164 t->new_tab = 1;
1165 enable_hints(t);
1166 } else
1167 disable_hints(t);
1169 return (0);
1172 void
1173 apply_style(struct tab *t)
1175 t->styled = 1;
1176 g_object_set(G_OBJECT(t->settings),
1177 "user-stylesheet-uri", t->stylesheet, (char *)NULL);
1180 void
1181 remove_style(struct tab *t)
1183 t->styled = 0;
1184 g_object_set(G_OBJECT(t->settings),
1185 "user-stylesheet-uri", NULL, (char *)NULL);
1189 userstyle_cmd(struct tab *t, struct karg *args)
1191 char script[PATH_MAX] = {'\0'};
1192 char *script_uri;
1193 struct tab *tt;
1195 DNPRINTF(XT_D_JS, "userstyle_cmd: tab %d\n", t->tab_id);
1197 if (args->s != NULL && strlen(args->s)) {
1198 expand_tilde(script, sizeof script, args->s);
1199 script_uri = g_filename_to_uri(script, NULL, NULL);
1200 } else
1201 script_uri = g_strdup(userstyle);
1203 if (script_uri == NULL)
1204 return (1);
1206 switch (args->i) {
1207 case XT_STYLE_CURRENT_TAB:
1208 if (t->styled && !strcmp(script_uri, t->stylesheet))
1209 remove_style(t);
1210 else {
1211 if (t->stylesheet)
1212 g_free(t->stylesheet);
1213 t->stylesheet = g_strdup(script_uri);
1214 apply_style(t);
1216 break;
1217 case XT_STYLE_GLOBAL:
1218 if (userstyle_global && !strcmp(script_uri, t->stylesheet)) {
1219 userstyle_global = 0;
1220 TAILQ_FOREACH(tt, &tabs, entry)
1221 remove_style(tt);
1222 } else {
1223 userstyle_global = 1;
1225 /* need to save this stylesheet for new tabs */
1226 if (stylesheet)
1227 g_free(stylesheet);
1228 stylesheet = g_strdup(script_uri);
1230 TAILQ_FOREACH(tt, &tabs, entry) {
1231 if (tt->stylesheet)
1232 g_free(tt->stylesheet);
1233 tt->stylesheet = g_strdup(script_uri);
1234 apply_style(tt);
1237 break;
1240 g_free(script_uri);
1242 return (0);
1246 quit(struct tab *t, struct karg *args)
1248 if (save_global_history)
1249 save_global_history_to_disk(t);
1251 gtk_main_quit();
1253 return (1);
1256 void
1257 restore_sessions_list(void)
1259 DIR *sdir = NULL;
1260 struct dirent *dp = NULL;
1261 struct session *s;
1262 int reg;
1264 sdir = opendir(sessions_dir);
1265 if (sdir) {
1266 while ((dp = readdir(sdir)) != NULL) {
1267 #if defined __MINGW32__
1268 reg = 1; /* windows only has regular files */
1269 #else
1270 reg = dp->d_type == DT_REG;
1271 #endif
1272 if (dp && reg) {
1273 s = g_malloc(sizeof(struct session));
1274 s->name = g_strdup(dp->d_name);
1275 TAILQ_INSERT_TAIL(&sessions, s, entry);
1278 closedir(sdir);
1283 open_tabs(struct tab *t, struct karg *a)
1285 char file[PATH_MAX];
1286 FILE *f = NULL;
1287 char *uri = NULL;
1288 int rv = 1;
1289 struct tab *ti, *tt;
1291 if (a == NULL)
1292 goto done;
1294 ti = TAILQ_LAST(&tabs, tab_list);
1296 snprintf(file, sizeof file, "%s" PS "%s", sessions_dir, a->s);
1297 if ((f = fopen(file, "r")) == NULL)
1298 goto done;
1300 for (;;) {
1301 if ((uri = fparseln(f, NULL, NULL, "\0\0\0", 0)) == NULL)
1302 if (feof(f) || ferror(f))
1303 break;
1305 /* retrieve session name */
1306 if (uri && g_str_has_prefix(uri, XT_SAVE_SESSION_ID)) {
1307 strlcpy(named_session,
1308 &uri[strlen(XT_SAVE_SESSION_ID)],
1309 sizeof named_session);
1310 continue;
1313 if (uri && strlen(uri))
1314 create_new_tab(uri, NULL, 1, -1);
1316 free(uri);
1317 uri = NULL;
1320 /* close open tabs */
1321 if (a->i == XT_SES_CLOSETABS && ti != NULL) {
1322 for (;;) {
1323 tt = TAILQ_FIRST(&tabs);
1324 if (tt == NULL)
1325 break;
1326 if (tt != ti) {
1327 delete_tab(tt);
1328 continue;
1330 delete_tab(tt);
1331 break;
1335 rv = 0;
1336 done:
1337 if (f)
1338 fclose(f);
1340 return (rv);
1344 restore_saved_tabs(void)
1346 char file[PATH_MAX];
1347 int unlink_file = 0;
1348 struct stat sb;
1349 struct karg a;
1350 int rv = 0;
1352 snprintf(file, sizeof file, "%s" PS "%s",
1353 sessions_dir, XT_RESTART_TABS_FILE);
1354 if (stat(file, &sb) == -1)
1355 a.s = XT_SAVED_TABS_FILE;
1356 else {
1357 unlink_file = 1;
1358 a.s = XT_RESTART_TABS_FILE;
1361 a.i = XT_SES_DONOTHING;
1362 rv = open_tabs(NULL, &a);
1364 if (unlink_file)
1365 unlink(file);
1367 return (rv);
1371 save_tabs(struct tab *t, struct karg *a)
1373 char file[PATH_MAX];
1374 FILE *f;
1375 int num_tabs = 0, i;
1376 struct tab **stabs = NULL;
1378 /* tab may be null here */
1380 if (a == NULL)
1381 return (1);
1382 if (a->s == NULL)
1383 snprintf(file, sizeof file, "%s" PS "%s",
1384 sessions_dir, named_session);
1385 else
1386 snprintf(file, sizeof file, "%s" PS "%s", sessions_dir, a->s);
1388 if ((f = fopen(file, "w")) == NULL) {
1389 show_oops(t, "Can't open save_tabs file: %s", strerror(errno));
1390 return (1);
1393 /* save session name */
1394 fprintf(f, "%s%s\n", XT_SAVE_SESSION_ID, named_session);
1396 /* Save tabs, in the order they are arranged in the notebook. */
1397 num_tabs = sort_tabs_by_page_num(&stabs);
1399 for (i = 0; i < num_tabs; i++)
1400 if (stabs[i]) {
1401 if (get_uri(stabs[i]) != NULL)
1402 fprintf(f, "%s\n", get_uri(stabs[i]));
1403 else if (gtk_entry_get_text(GTK_ENTRY(
1404 stabs[i]->uri_entry)))
1405 fprintf(f, "%s\n", gtk_entry_get_text(GTK_ENTRY(
1406 stabs[i]->uri_entry)));
1409 g_free(stabs);
1411 /* try and make sure this gets to disk NOW. XXX Backup first? */
1412 if (fflush(f) != 0 || fsync(fileno(f)) != 0) {
1413 show_oops(t, "May not have managed to save session: %s",
1414 strerror(errno));
1417 fclose(f);
1419 return (0);
1423 save_tabs_and_quit(struct tab *t, struct karg *args)
1425 struct karg a;
1427 a.s = NULL;
1428 save_tabs(t, &a);
1429 quit(t, NULL);
1431 return (1);
1434 void
1435 expand_tilde(char *path, size_t len, const char *s)
1437 struct passwd *pwd;
1438 int i;
1439 char user[LOGIN_NAME_MAX];
1440 const char *sc = s;
1442 if (path == NULL || s == NULL)
1443 errx(1, "expand_tilde");
1445 if (s[0] != '~') {
1446 strlcpy(path, sc, len);
1447 return;
1450 ++s;
1451 for (i = 0; s[i] != PSC && s[i] != '\0'; ++i)
1452 user[i] = s[i];
1453 user[i] = '\0';
1454 s = &s[i];
1456 pwd = strlen(user) == 0 ? getpwuid(getuid()) : getpwnam(user);
1457 if (pwd == NULL)
1458 strlcpy(path, sc, len);
1459 else
1460 snprintf(path, len, "%s%s", pwd->pw_dir, s);
1464 run_page_script(struct tab *t, struct karg *args)
1466 const gchar *uri;
1467 char *tmp, script[PATH_MAX];
1468 char *sv[3];
1470 tmp = args->s != NULL && strlen(args->s) > 0 ? args->s : default_script;
1471 if (tmp[0] == '\0') {
1472 show_oops(t, "no script specified");
1473 return (1);
1476 if ((uri = get_uri(t)) == NULL) {
1477 show_oops(t, "tab is empty, not running script");
1478 return (1);
1481 expand_tilde(script, sizeof script, tmp);
1483 sv[0] = script;
1484 sv[1] = (char *)uri;
1485 sv[2] = NULL;
1486 if (!g_spawn_async(NULL, sv, NULL, G_SPAWN_SEARCH_PATH, NULL, NULL,
1487 NULL, NULL)) {
1488 show_oops(t, "%s: could not spawn process: %s %s", __func__,
1489 sv[0], sv[1]);
1490 return (1);
1491 } else
1492 show_oops(t, "running: %s %s", sv[0], sv[1]);
1494 return (0);
1498 yank_uri(struct tab *t, struct karg *args)
1500 const gchar *uri;
1501 GtkClipboard *clipboard, *primary;
1503 if ((uri = get_uri(t)) == NULL)
1504 return (1);
1506 primary = gtk_clipboard_get(GDK_SELECTION_PRIMARY);
1507 clipboard = gtk_clipboard_get(GDK_SELECTION_CLIPBOARD);
1508 gtk_clipboard_set_text(primary, uri, -1);
1509 gtk_clipboard_set_text(clipboard, uri, -1);
1511 return (0);
1515 paste_uri(struct tab *t, struct karg *args)
1517 GtkClipboard *clipboard, *primary;
1518 gchar *c = NULL, *p = NULL, *uri;
1519 int i;
1521 clipboard = gtk_clipboard_get(GDK_SELECTION_CLIPBOARD);
1522 primary = gtk_clipboard_get(GDK_SELECTION_PRIMARY);
1523 c = gtk_clipboard_wait_for_text(clipboard);
1524 p = gtk_clipboard_wait_for_text(primary);
1526 if (c || p) {
1527 #ifdef __MINGW32__
1528 /* Windows try clipboard first */
1529 uri = c ? c : p;
1530 #else
1531 /* UNIX try primary first */
1532 uri = p ? p : c;
1533 #endif
1534 /* replace all newlines with spaces */
1535 for (i = 0; uri[i] != '\0'; ++i)
1536 if (uri[i] == '\n')
1537 uri[i] = ' ';
1539 while (*uri && isspace(*uri))
1540 uri++;
1541 if (strlen(uri) == 0) {
1542 show_oops(t, "empty paste buffer");
1543 goto done;
1545 if (guess_search == 0 && valid_url_type(uri)) {
1546 /* we can be clever and paste this in search box */
1547 show_oops(t, "not a valid URL");
1548 goto done;
1551 if (args->i == XT_PASTE_CURRENT_TAB)
1552 load_uri(t, uri);
1553 else if (args->i == XT_PASTE_NEW_TAB)
1554 create_new_tab(uri, NULL, 1, -1);
1557 done:
1558 if (c)
1559 g_free(c);
1560 if (p)
1561 g_free(p);
1563 return (0);
1566 void
1567 js_toggle_cb(GtkWidget *w, struct tab *t)
1569 struct karg a;
1570 int es, set;
1572 g_object_get(G_OBJECT(t->settings),
1573 "enable-scripts", &es, (char *)NULL);
1574 es = !es;
1575 if (es)
1576 set = XT_WL_ENABLE;
1577 else
1578 set = XT_WL_DISABLE;
1580 a.i = set | XT_WL_TOPLEVEL;
1581 toggle_pl(t, &a);
1583 a.i = set | XT_WL_TOPLEVEL;
1584 toggle_cwl(t, &a);
1586 a.i = XT_WL_TOGGLE | XT_WL_TOPLEVEL | XT_WL_RELOAD;
1587 toggle_js(t, &a);
1591 toggle_src(struct tab *t, struct karg *args)
1593 gboolean mode;
1595 if (t == NULL)
1596 return (0);
1598 mode = webkit_web_view_get_view_source_mode(t->wv);
1599 webkit_web_view_set_view_source_mode(t->wv, !mode);
1600 webkit_web_view_reload(t->wv);
1602 return (0);
1605 void
1606 focus_webview(struct tab *t)
1608 if (t == NULL)
1609 return;
1611 /* only grab focus if we are visible */
1612 if (gtk_notebook_get_current_page(notebook) == t->tab_id)
1613 gtk_widget_grab_focus(GTK_WIDGET(t->wv));
1617 focus(struct tab *t, struct karg *args)
1619 if (t == NULL || args == NULL)
1620 return (1);
1622 if (show_url == 0)
1623 return (0);
1625 if (args->i == XT_FOCUS_URI)
1626 gtk_widget_grab_focus(GTK_WIDGET(t->uri_entry));
1627 else if (args->i == XT_FOCUS_SEARCH)
1628 gtk_widget_grab_focus(GTK_WIDGET(t->search_entry));
1630 return (0);
1634 connect_socket_from_uri(const gchar *uri, const gchar **error_str, char *domain,
1635 size_t domain_sz)
1637 SoupURI *su = NULL;
1638 struct addrinfo hints, *res = NULL, *ai;
1639 int rv = -1, s = -1, on, error;
1640 char port[8];
1641 static gchar myerror[256]; /* this is not thread safe */
1643 myerror[0] = '\0';
1644 *error_str = myerror;
1645 if (uri && !g_str_has_prefix(uri, "https://")) {
1646 *error_str = "invalid URI";
1647 goto done;
1650 su = soup_uri_new(uri);
1651 if (su == NULL) {
1652 *error_str = "invalid soup URI";
1653 goto done;
1655 if (!SOUP_URI_VALID_FOR_HTTP(su)) {
1656 *error_str = "invalid HTTPS URI";
1657 goto done;
1660 snprintf(port, sizeof port, "%d", su->port);
1661 bzero(&hints, sizeof(struct addrinfo));
1662 hints.ai_flags = AI_CANONNAME;
1663 hints.ai_family = AF_UNSPEC;
1664 hints.ai_socktype = SOCK_STREAM;
1666 if ((error = getaddrinfo(su->host, port, &hints, &res))) {
1667 snprintf(myerror, sizeof myerror, "getaddrinfo failed: %s",
1668 gai_strerror(errno));
1669 goto done;
1672 for (ai = res; ai; ai = ai->ai_next) {
1673 if (s != -1) {
1674 close(s);
1675 s = -1;
1678 if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6)
1679 continue;
1680 s = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
1681 if (s == -1)
1682 continue;
1683 if (setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &on,
1684 sizeof(on)) == -1)
1685 continue;
1686 if (connect(s, ai->ai_addr, ai->ai_addrlen) == 0)
1687 break;
1689 if (s == -1) {
1690 snprintf(myerror, sizeof myerror,
1691 "could not obtain certificates from: %s",
1692 su->host);
1693 goto done;
1696 if (domain)
1697 strlcpy(domain, su->host, domain_sz);
1698 rv = s;
1699 done:
1700 if (su)
1701 soup_uri_free(su);
1702 if (res)
1703 freeaddrinfo(res);
1704 if (rv == -1 && s != -1)
1705 close(s);
1707 return (rv);
1710 #ifdef __MINGW32__
1711 static ssize_t
1712 custom_gnutls_push(void *s, const void *buf, size_t len)
1714 return send((size_t)s, buf, len, 0);
1717 static ssize_t
1718 custom_gnutls_pull(void *s, void *buf, size_t len)
1720 return recv((size_t)s, buf, len, 0);
1722 #endif
1725 stop_tls(gnutls_session_t gsession, gnutls_certificate_credentials_t xcred)
1727 if (gsession)
1728 gnutls_deinit(gsession);
1729 if (xcred)
1730 gnutls_certificate_free_credentials(xcred);
1732 return (0);
1736 start_tls(const gchar **error_str, int s, gnutls_session_t *gs,
1737 gnutls_certificate_credentials_t *xc)
1739 gnutls_certificate_credentials_t xcred;
1740 gnutls_session_t gsession;
1741 int rv = 1;
1742 static gchar myerror[1024]; /* this is not thread safe */
1744 if (gs == NULL || xc == NULL)
1745 goto done;
1747 myerror[0] = '\0';
1748 *gs = NULL;
1749 *xc = NULL;
1751 gnutls_certificate_allocate_credentials(&xcred);
1752 gnutls_certificate_set_x509_trust_file(xcred, ssl_ca_file,
1753 GNUTLS_X509_FMT_PEM);
1755 gnutls_init(&gsession, GNUTLS_CLIENT);
1756 gnutls_priority_set_direct(gsession, "PERFORMANCE", NULL);
1757 gnutls_credentials_set(gsession, GNUTLS_CRD_CERTIFICATE, xcred);
1758 gnutls_transport_set_ptr(gsession, (gnutls_transport_ptr_t)(long)s);
1759 #ifdef __MINGW32__
1760 /* sockets on windows don't use file descriptors */
1761 gnutls_transport_set_push_function(gsession, custom_gnutls_push);
1762 gnutls_transport_set_pull_function(gsession, custom_gnutls_pull);
1763 #endif
1764 if ((rv = gnutls_handshake(gsession)) < 0) {
1765 snprintf(myerror, sizeof myerror,
1766 "gnutls_handshake failed %d fatal %d %s",
1768 gnutls_error_is_fatal(rv),
1769 #if LIBGNUTLS_VERSION_MAJOR >= 2 && LIBGNUTLS_VERSION_MINOR >= 6
1770 gnutls_strerror_name(rv));
1771 #else
1772 "GNUTLS version is too old to provide human readable error");
1773 #endif
1774 stop_tls(gsession, xcred);
1775 goto done;
1778 gnutls_credentials_type_t cred;
1779 cred = gnutls_auth_get_type(gsession);
1780 if (cred != GNUTLS_CRD_CERTIFICATE) {
1781 snprintf(myerror, sizeof myerror,
1782 "gnutls_auth_get_type failed %d",
1783 (int)cred);
1784 stop_tls(gsession, xcred);
1785 goto done;
1788 *gs = gsession;
1789 *xc = xcred;
1790 rv = 0;
1791 done:
1792 *error_str = myerror;
1793 return (rv);
1797 get_connection_certs(gnutls_session_t gsession, gnutls_x509_crt_t **certs,
1798 size_t *cert_count)
1800 unsigned int len;
1801 const gnutls_datum_t *cl;
1802 gnutls_x509_crt_t *all_certs;
1803 int i, rv = 1;
1805 if (certs == NULL || cert_count == NULL)
1806 goto done;
1807 if (gnutls_certificate_type_get(gsession) != GNUTLS_CRT_X509)
1808 goto done;
1809 cl = gnutls_certificate_get_peers(gsession, &len);
1810 if (len == 0)
1811 goto done;
1813 all_certs = g_malloc(sizeof(gnutls_x509_crt_t) * len);
1814 for (i = 0; i < len; i++) {
1815 gnutls_x509_crt_init(&all_certs[i]);
1816 if (gnutls_x509_crt_import(all_certs[i], &cl[i],
1817 GNUTLS_X509_FMT_PEM < 0)) {
1818 g_free(all_certs);
1819 goto done;
1823 *certs = all_certs;
1824 *cert_count = len;
1825 rv = 0;
1826 done:
1827 return (rv);
1830 void
1831 free_connection_certs(gnutls_x509_crt_t *certs, size_t cert_count)
1833 int i;
1835 for (i = 0; i < cert_count; i++)
1836 gnutls_x509_crt_deinit(certs[i]);
1837 g_free(certs);
1840 #if GTK_CHECK_VERSION(3, 0, 0)
1841 void
1842 statusbar_modify_attr(struct tab *t, const char *css_name)
1844 gtk_widget_set_name(t->sbe.ebox, css_name);
1846 #else
1847 void
1848 statusbar_modify_attr(struct tab *t, const char *text, const char *base)
1850 GdkColor c_text, c_base;
1852 gdk_color_parse(text, &c_text);
1853 gdk_color_parse(base, &c_base);
1855 gtk_widget_modify_bg(t->sbe.ebox, GTK_STATE_NORMAL, &c_base);
1856 gtk_widget_modify_base(t->sbe.uri, GTK_STATE_NORMAL, &c_base);
1857 gtk_widget_modify_text(t->sbe.uri, GTK_STATE_NORMAL, &c_text);
1859 #endif
1861 void
1862 save_certs(struct tab *t, gnutls_x509_crt_t *certs,
1863 size_t cert_count, const char *domain, const char *dir)
1865 size_t cert_buf_sz;
1866 char cert_buf[64 * 1024], file[PATH_MAX];
1867 int i;
1868 FILE *f;
1870 if (t == NULL || certs == NULL || cert_count <= 0 || domain == NULL)
1871 return;
1873 snprintf(file, sizeof file, "%s" PS "%s", dir, domain);
1874 if ((f = fopen(file, "w")) == NULL) {
1875 show_oops(t, "Can't create cert file %s %s",
1876 file, strerror(errno));
1877 return;
1880 for (i = 0; i < cert_count; i++) {
1881 cert_buf_sz = sizeof cert_buf;
1882 if (gnutls_x509_crt_export(certs[i], GNUTLS_X509_FMT_PEM,
1883 cert_buf, &cert_buf_sz)) {
1884 show_oops(t, "gnutls_x509_crt_export failed");
1885 goto done;
1887 if (fwrite(cert_buf, cert_buf_sz, 1, f) != 1) {
1888 show_oops(t, "Can't write certs: %s", strerror(errno));
1889 goto done;
1893 done:
1894 fclose(f);
1897 enum cert_trust {
1898 CERT_LOCAL,
1899 CERT_TRUSTED,
1900 CERT_UNTRUSTED,
1901 CERT_BAD
1904 enum cert_trust
1905 load_compare_cert(const gchar *uri, const gchar **error_str, const char *dir)
1907 char domain[8182], file[PATH_MAX];
1908 char cert_buf[64 * 1024], r_cert_buf[64 * 1024];
1909 int s = -1, i;
1910 unsigned int error = 0;
1911 FILE *f = NULL;
1912 size_t cert_buf_sz, cert_count;
1913 enum cert_trust rv = CERT_UNTRUSTED;
1914 static gchar serr[80]; /* this isn't thread safe */
1915 gnutls_session_t gsession;
1916 gnutls_x509_crt_t *certs;
1917 gnutls_certificate_credentials_t xcred;
1919 DNPRINTF(XT_D_URL, "%s: %s\n", __func__, uri);
1921 serr[0] = '\0';
1922 *error_str = serr;
1923 if ((s = connect_socket_from_uri(uri, error_str, domain,
1924 sizeof domain)) == -1)
1925 return (rv);
1927 DNPRINTF(XT_D_URL, "%s: fd %d\n", __func__, s);
1929 /* go ssl/tls */
1930 if (start_tls(error_str, s, &gsession, &xcred))
1931 goto done;
1932 DNPRINTF(XT_D_URL, "%s: got tls\n", __func__);
1934 /* verify certs in case cert file doesn't exist */
1935 if (gnutls_certificate_verify_peers2(gsession, &error) !=
1936 GNUTLS_E_SUCCESS) {
1937 *error_str = "Invalid certificates";
1938 goto done;
1941 /* get certs */
1942 if (get_connection_certs(gsession, &certs, &cert_count)) {
1943 *error_str = "Can't get connection certificates";
1944 goto done;
1947 snprintf(file, sizeof file, "%s" PS "%s", dir, domain);
1948 if ((f = fopen(file, "r")) == NULL) {
1949 if (!error)
1950 rv = CERT_TRUSTED;
1951 goto freeit;
1954 for (i = 0; i < cert_count; i++) {
1955 cert_buf_sz = sizeof cert_buf;
1956 if (gnutls_x509_crt_export(certs[i], GNUTLS_X509_FMT_PEM,
1957 cert_buf, &cert_buf_sz)) {
1958 goto freeit;
1960 if (fread(r_cert_buf, cert_buf_sz, 1, f) != 1 && !feof(f)) {
1961 rv = CERT_BAD; /* critical */
1962 goto freeit;
1964 if (bcmp(r_cert_buf, cert_buf, cert_buf_sz)) {
1965 rv = CERT_BAD; /* critical */
1966 goto freeit;
1968 rv = CERT_LOCAL;
1971 freeit:
1972 if (f)
1973 fclose(f);
1974 free_connection_certs(certs, cert_count);
1975 done:
1976 /* we close the socket first for speed */
1977 if (s != -1)
1978 close(s);
1980 /* only complain if we didn't save it locally */
1981 if (strlen(ssl_ca_file) != 0 && error && rv != CERT_LOCAL) {
1982 strlcpy(serr, "Certificate exception(s): ", sizeof serr);
1983 if (error & GNUTLS_CERT_INVALID)
1984 strlcat(serr, "invalid, ", sizeof serr);
1985 if (error & GNUTLS_CERT_REVOKED)
1986 strlcat(serr, "revoked, ", sizeof serr);
1987 if (error & GNUTLS_CERT_SIGNER_NOT_FOUND)
1988 strlcat(serr, "signer not found, ", sizeof serr);
1989 if (error & GNUTLS_CERT_SIGNER_NOT_CA)
1990 strlcat(serr, "not signed by CA, ", sizeof serr);
1991 if (error & GNUTLS_CERT_INSECURE_ALGORITHM)
1992 strlcat(serr, "insecure algorithm, ", sizeof serr);
1993 #if LIBGNUTLS_VERSION_MAJOR >= 2 && LIBGNUTLS_VERSION_MINOR >= 6
1994 if (error & GNUTLS_CERT_NOT_ACTIVATED)
1995 strlcat(serr, "not activated, ", sizeof serr);
1996 if (error & GNUTLS_CERT_EXPIRED)
1997 strlcat(serr, "expired, ", sizeof serr);
1998 #endif
1999 for (i = strlen(serr) - 1; i > 0; i--)
2000 if (serr[i] == ',') {
2001 serr[i] = '\0';
2002 break;
2004 *error_str = serr;
2007 stop_tls(gsession, xcred);
2009 return (rv);
2012 gnutls_x509_crt_t *
2013 get_local_cert_chain(const char *uri, size_t *ncerts, const char **error_str,
2014 const char *dir)
2016 SoupURI *su;
2017 unsigned char cert_buf[64 * 1024] = {0};
2018 gnutls_datum_t data;
2019 unsigned int len = UINT_MAX;
2020 int bytes_read;
2021 char file[PATH_MAX];
2022 FILE *f;
2023 gnutls_x509_crt_t *certs;
2025 if ((su = soup_uri_new(uri)) == NULL) {
2026 *error_str = "Invalid URI";
2027 return (NULL);
2030 snprintf(file, sizeof file, "%s" PS "%s", dir, su->host);
2031 if ((f = fopen(file, "r")) == NULL) {
2032 *error_str = "Could not read local cert";
2033 return (NULL);
2036 bytes_read = fread(cert_buf, sizeof *cert_buf, sizeof cert_buf, f);
2037 if (bytes_read == 0) {
2038 *error_str = "Could not read local cert";
2039 return (NULL);
2042 data.data = cert_buf;
2043 data.size = bytes_read;
2044 certs = g_malloc(sizeof *certs);
2045 *ncerts = INT_MAX;
2046 if (gnutls_x509_crt_list_import(certs, &len, &data,
2047 GNUTLS_X509_FMT_PEM, 0) < 0) {
2048 *error_str = "Error reading local cert chain";
2049 return (NULL);
2052 *ncerts = len;
2053 return (certs);
2058 cert_cmd(struct tab *t, struct karg *args)
2060 const gchar *uri, *error_str = NULL;
2061 char domain[8182];
2062 int s = -1;
2063 size_t cert_count;
2064 gnutls_session_t gsession;
2065 gnutls_x509_crt_t *certs;
2066 gnutls_certificate_credentials_t xcred;
2067 #if !GTK_CHECK_VERSION(3, 0, 0)
2068 GdkColor color;
2069 #endif
2071 if (t == NULL)
2072 return (1);
2074 if (args->s != NULL)
2075 uri = args->s;
2076 else if ((uri = get_uri(t)) == NULL) {
2077 show_oops(t, "Invalid URI");
2078 return (1);
2082 * if we're only showing the local certs, don't open a socket and get
2083 * the remote certs
2085 if (args->i & XT_SHOW && args->i & XT_CACHE) {
2086 certs = get_local_cert_chain(uri, &cert_count, &error_str,
2087 certs_cache_dir);
2088 if (error_str == NULL) {
2089 show_certs(t, certs, cert_count, "Certificate Chain");
2090 free_connection_certs(certs, cert_count);
2091 } else {
2092 show_oops(t, "%s", error_str);
2093 return (1);
2095 return (0);
2098 if ((s = connect_socket_from_uri(uri, &error_str, domain,
2099 sizeof domain)) == -1) {
2100 show_oops(t, "%s", error_str);
2101 return (1);
2104 /* go ssl/tls */
2105 if (start_tls(&error_str, s, &gsession, &xcred))
2106 goto done;
2108 /* get certs */
2109 if (get_connection_certs(gsession, &certs, &cert_count)) {
2110 show_oops(t, "get_connection_certs failed");
2111 goto done;
2114 if (args->i & XT_SHOW)
2115 show_certs(t, certs, cert_count, "Certificate Chain");
2116 else if (args->i & XT_SAVE) {
2117 save_certs(t, certs, cert_count, domain, certs_dir);
2118 #if GTK_CHECK_VERSION(3, 0, 0)
2119 gtk_widget_set_name(t->uri_entry, XT_CSS_BLUE);
2120 statusbar_modify_attr(t, XT_CSS_BLUE);
2121 #else
2122 gdk_color_parse(XT_COLOR_BLUE, &color);
2123 gtk_widget_modify_base(t->uri_entry, GTK_STATE_NORMAL, &color);
2124 statusbar_modify_attr(t, XT_COLOR_BLACK, XT_COLOR_BLUE);
2125 #endif
2126 } else if (args->i & XT_CACHE)
2127 save_certs(t, certs, cert_count, domain, certs_cache_dir);
2129 free_connection_certs(certs, cert_count);
2130 done:
2131 /* we close the socket first for speed */
2132 if (s != -1)
2133 close(s);
2134 stop_tls(gsession, xcred);
2135 if (error_str && strlen(error_str))
2136 show_oops(t, "%s", error_str);
2137 return (0);
2141 * args must be allocated dynamically as the thread that added this function
2142 * to the idle loop no longer exists
2144 gboolean
2145 warn_cert_cache_differs_idle(struct karg *args)
2147 if (args == NULL) {
2148 show_oops(NULL, "%s: invalid parameters", __func__);
2149 /* return 0 to not re-add function to the idle loop */
2150 return (0);
2152 xtp_page_sv((struct tab *)args->ptr, args);
2153 g_free(args);
2154 return (0);
2158 check_cert_changes(struct tab *t, const char *uri)
2160 SoupURI *soupuri = NULL;
2161 struct karg args = {0};
2162 struct domain *d = NULL;
2163 const char *errstr = NULL;
2164 struct karg *argsp;
2166 if (!(warn_cert_changes && uri && g_str_has_prefix(uri, "https://")))
2167 return (0);
2169 switch (load_compare_cert(uri, &errstr, certs_cache_dir)) {
2170 case CERT_LOCAL:
2171 /* The cached certificate is identical */
2172 break;
2173 case CERT_TRUSTED: /* FALLTHROUGH */
2174 case CERT_UNTRUSTED:
2175 /* cache new certificate */
2176 args.i = XT_CACHE;
2177 cert_cmd(t, &args);
2178 break;
2179 case CERT_BAD:
2180 if ((soupuri = soup_uri_new(uri)) == NULL ||
2181 soupuri->host == NULL)
2182 break;
2183 if ((d = wl_find(soupuri->host, &svil)) != NULL)
2184 break;
2185 t->xtp_meaning = XT_XTP_TAB_MEANING_SV;
2186 argsp = g_malloc0(sizeof(struct karg));
2187 argsp->s = g_strdup((char *)uri);
2188 argsp->ptr = (void *)t;
2189 g_idle_add((GSourceFunc)warn_cert_cache_differs_idle, argsp);
2190 break;
2193 if (soupuri)
2194 soup_uri_free(soupuri);
2195 return (0);
2199 remove_cookie(int index)
2201 int i, rv = 1;
2202 GSList *cf;
2203 SoupCookie *c;
2205 DNPRINTF(XT_D_COOKIE, "remove_cookie: %d\n", index);
2207 cf = soup_cookie_jar_all_cookies(s_cookiejar);
2209 for (i = 1; cf; cf = cf->next, i++) {
2210 if (i != index)
2211 continue;
2212 c = cf->data;
2213 print_cookie("remove cookie", c);
2214 soup_cookie_jar_delete_cookie(s_cookiejar, c);
2215 rv = 0;
2216 break;
2219 soup_cookies_free(cf);
2221 return (rv);
2225 remove_cookie_domain(int domain_id)
2227 int domain_count, rv = 1;
2228 GSList *cf;
2229 SoupCookie *c;
2230 char *last_domain;
2232 DNPRINTF(XT_D_COOKIE, "remove_cookie_domain: %d\n", domain_id);
2234 last_domain = "";
2235 cf = soup_cookie_jar_all_cookies(s_cookiejar);
2237 for (domain_count = 0; cf; cf = cf->next) {
2238 c = cf->data;
2240 if (strcmp(last_domain, c->domain) != 0) {
2241 domain_count++;
2242 last_domain = c->domain;
2245 if (domain_count < domain_id)
2246 continue;
2247 else if (domain_count > domain_id)
2248 break;
2250 print_cookie("remove cookie", c);
2251 soup_cookie_jar_delete_cookie(s_cookiejar, c);
2252 rv = 0;
2255 soup_cookies_free(cf);
2257 return (rv);
2261 remove_cookie_all()
2263 int rv = 1;
2264 GSList *cf;
2265 SoupCookie *c;
2267 DNPRINTF(XT_D_COOKIE, "remove_cookie_all\n");
2269 cf = soup_cookie_jar_all_cookies(s_cookiejar);
2271 for (; cf; cf = cf->next) {
2272 c = cf->data;
2274 print_cookie("remove cookie", c);
2275 soup_cookie_jar_delete_cookie(s_cookiejar, c);
2276 rv = 0;
2279 soup_cookies_free(cf);
2281 return (rv);
2285 toplevel_cmd(struct tab *t, struct karg *args)
2287 js_toggle_cb(t->js_toggle, t);
2289 return (0);
2293 navaction(struct tab *t, struct karg *args)
2295 WebKitWebFrame *frame;
2297 DNPRINTF(XT_D_NAV, "navaction: tab %d opcode %d\n",
2298 t->tab_id, args->i);
2300 hide_oops(t);
2301 set_normal_tab_meaning(t);
2303 switch (args->i) {
2304 case XT_NAV_BACK:
2305 marks_clear(t);
2306 if (t->item)
2307 webkit_web_view_go_to_back_forward_item(t->wv, t->item);
2308 else
2309 webkit_web_view_go_back(t->wv);
2310 break;
2311 case XT_NAV_FORWARD:
2312 marks_clear(t);
2313 webkit_web_view_go_forward(t->wv);
2314 break;
2315 case XT_NAV_RELOAD:
2316 frame = webkit_web_view_get_main_frame(t->wv);
2317 webkit_web_frame_reload(frame);
2318 break;
2319 case XT_NAV_STOP:
2320 frame = webkit_web_view_get_main_frame(t->wv);
2321 webkit_web_frame_stop_loading(frame);
2322 break;
2324 return (XT_CB_PASSTHROUGH);
2328 move(struct tab *t, struct karg *args)
2330 GtkAdjustment *adjust;
2331 double pi, si, pos, ps, upper, lower, max;
2332 double percent;
2334 switch (args->i) {
2335 case XT_MOVE_DOWN:
2336 case XT_MOVE_UP:
2337 case XT_MOVE_BOTTOM:
2338 case XT_MOVE_TOP:
2339 case XT_MOVE_PAGEDOWN:
2340 case XT_MOVE_PAGEUP:
2341 case XT_MOVE_HALFDOWN:
2342 case XT_MOVE_HALFUP:
2343 case XT_MOVE_PERCENT:
2344 case XT_MOVE_CENTER:
2345 adjust = t->adjust_v;
2346 break;
2347 default:
2348 adjust = t->adjust_h;
2349 break;
2352 pos = gtk_adjustment_get_value(adjust);
2353 ps = gtk_adjustment_get_page_size(adjust);
2354 upper = gtk_adjustment_get_upper(adjust);
2355 lower = gtk_adjustment_get_lower(adjust);
2356 si = gtk_adjustment_get_step_increment(adjust);
2357 pi = gtk_adjustment_get_page_increment(adjust);
2358 max = upper - ps;
2360 DNPRINTF(XT_D_MOVE, "move: opcode %d %s pos %f ps %f upper %f lower %f "
2361 "max %f si %f pi %f\n",
2362 args->i, adjust == t->adjust_h ? "horizontal" : "vertical",
2363 pos, ps, upper, lower, max, si, pi);
2365 switch (args->i) {
2366 case XT_MOVE_DOWN:
2367 case XT_MOVE_RIGHT:
2368 pos += si;
2369 gtk_adjustment_set_value(adjust, MIN(pos, max));
2370 break;
2371 case XT_MOVE_UP:
2372 case XT_MOVE_LEFT:
2373 pos -= si;
2374 gtk_adjustment_set_value(adjust, MAX(pos, lower));
2375 break;
2376 case XT_MOVE_BOTTOM:
2377 case XT_MOVE_FARRIGHT:
2378 t->mark[marktoindex('\'')] = gtk_adjustment_get_value(t->adjust_v);
2379 gtk_adjustment_set_value(adjust, max);
2380 break;
2381 case XT_MOVE_TOP:
2382 case XT_MOVE_FARLEFT:
2383 t->mark[marktoindex('\'')] = gtk_adjustment_get_value(t->adjust_v);
2384 gtk_adjustment_set_value(adjust, lower);
2385 break;
2386 case XT_MOVE_PAGEDOWN:
2387 pos += pi;
2388 gtk_adjustment_set_value(adjust, MIN(pos, max));
2389 break;
2390 case XT_MOVE_PAGEUP:
2391 pos -= pi;
2392 gtk_adjustment_set_value(adjust, MAX(pos, lower));
2393 break;
2394 case XT_MOVE_HALFDOWN:
2395 pos += pi / 2;
2396 gtk_adjustment_set_value(adjust, MIN(pos, max));
2397 break;
2398 case XT_MOVE_HALFUP:
2399 pos -= pi / 2;
2400 gtk_adjustment_set_value(adjust, MAX(pos, lower));
2401 break;
2402 case XT_MOVE_CENTER:
2403 t->mark[marktoindex('\'')] = gtk_adjustment_get_value(t->adjust_v);
2404 args->s = g_strdup("50.0");
2405 /* FALLTHROUGH */
2406 case XT_MOVE_PERCENT:
2407 t->mark[marktoindex('\'')] = gtk_adjustment_get_value(t->adjust_v);
2408 percent = atoi(args->s) / 100.0;
2409 pos = max * percent;
2410 if (pos < 0.0 || pos > max)
2411 break;
2412 gtk_adjustment_set_value(adjust, pos);
2413 break;
2414 default:
2415 return (XT_CB_PASSTHROUGH);
2418 DNPRINTF(XT_D_MOVE, "move: new pos %f %f\n", pos, MIN(pos, max));
2420 return (XT_CB_HANDLED);
2423 void
2424 url_set_visibility(void)
2426 struct tab *t;
2428 TAILQ_FOREACH(t, &tabs, entry)
2429 if (show_url == 0) {
2430 gtk_widget_hide(t->toolbar);
2431 focus_webview(t);
2432 } else
2433 gtk_widget_show(t->toolbar);
2436 void
2437 notebook_tab_set_visibility(void)
2439 if (show_tabs == 0) {
2440 gtk_widget_hide(tab_bar);
2441 gtk_notebook_set_show_tabs(notebook, FALSE);
2442 } else {
2443 if (tab_style == XT_TABS_NORMAL) {
2444 gtk_widget_hide(tab_bar);
2445 gtk_notebook_set_show_tabs(notebook, TRUE);
2446 } else if (tab_style == XT_TABS_COMPACT) {
2447 gtk_widget_show(tab_bar);
2448 gtk_notebook_set_show_tabs(notebook, FALSE);
2453 void
2454 statusbar_set_visibility(void)
2456 struct tab *t;
2458 TAILQ_FOREACH(t, &tabs, entry){
2459 if (show_statusbar == 0)
2460 gtk_widget_hide(t->statusbar);
2461 else
2462 gtk_widget_show(t->statusbar);
2464 focus_webview(t);
2468 void
2469 url_set(struct tab *t, int enable_url_entry)
2471 GdkPixbuf *pixbuf;
2472 int progress;
2474 show_url = enable_url_entry;
2476 if (enable_url_entry) {
2477 gtk_entry_set_icon_from_icon_name(GTK_ENTRY(t->sbe.uri),
2478 GTK_ENTRY_ICON_PRIMARY, NULL);
2479 gtk_entry_set_progress_fraction(GTK_ENTRY(t->sbe.uri), 0);
2480 } else {
2481 pixbuf = gtk_entry_get_icon_pixbuf(GTK_ENTRY(t->uri_entry),
2482 GTK_ENTRY_ICON_PRIMARY);
2483 progress =
2484 gtk_entry_get_progress_fraction(GTK_ENTRY(t->uri_entry));
2485 gtk_entry_set_icon_from_pixbuf(GTK_ENTRY(t->sbe.uri),
2486 GTK_ENTRY_ICON_PRIMARY, pixbuf);
2487 gtk_entry_set_progress_fraction(GTK_ENTRY(t->sbe.uri),
2488 progress);
2493 fullscreen(struct tab *t, struct karg *args)
2495 DNPRINTF(XT_D_TAB, "%s: %p %d\n", __func__, t, args->i);
2497 if (t == NULL)
2498 return (XT_CB_PASSTHROUGH);
2500 if (show_url == 0) {
2501 url_set(t, 1);
2502 show_tabs = 1;
2503 } else {
2504 url_set(t, 0);
2505 show_tabs = 0;
2508 url_set_visibility();
2509 notebook_tab_set_visibility();
2511 return (XT_CB_HANDLED);
2515 statustoggle(struct tab *t, struct karg *args)
2517 DNPRINTF(XT_D_TAB, "%s: %p %d\n", __func__, t, args->i);
2519 if (show_statusbar == 1) {
2520 show_statusbar = 0;
2521 statusbar_set_visibility();
2522 } else if (show_statusbar == 0) {
2523 show_statusbar = 1;
2524 statusbar_set_visibility();
2526 return (XT_CB_HANDLED);
2530 urlaction(struct tab *t, struct karg *args)
2532 int rv = XT_CB_HANDLED;
2534 DNPRINTF(XT_D_TAB, "%s: %p %d\n", __func__, t, args->i);
2536 if (t == NULL)
2537 return (XT_CB_PASSTHROUGH);
2539 switch (args->i) {
2540 case XT_URL_SHOW:
2541 if (show_url == 0) {
2542 url_set(t, 1);
2543 url_set_visibility();
2545 break;
2546 case XT_URL_HIDE:
2547 if (show_url == 1) {
2548 url_set(t, 0);
2549 url_set_visibility();
2551 break;
2553 return (rv);
2557 tabaction(struct tab *t, struct karg *args)
2559 int rv = XT_CB_HANDLED;
2560 char *url = args->s;
2561 struct undo *u;
2562 struct tab *tt, *tv;
2564 DNPRINTF(XT_D_TAB, "tabaction: %p %d\n", t, args->i);
2566 if (t == NULL)
2567 return (XT_CB_PASSTHROUGH);
2569 switch (args->i) {
2570 case XT_TAB_NEW:
2571 if (strlen(url) > 0)
2572 create_new_tab(url, NULL, 1, args->precount);
2573 else
2574 create_new_tab(NULL, NULL, 1, args->precount);
2575 break;
2576 case XT_TAB_DELETE:
2577 if (args->precount < 0)
2578 delete_tab(t);
2579 else
2580 TAILQ_FOREACH(tt, &tabs, entry)
2581 if (tt->tab_id == args->precount - 1) {
2582 delete_tab(tt);
2583 break;
2585 break;
2586 case XT_TAB_DELQUIT:
2587 if (gtk_notebook_get_n_pages(notebook) > 1)
2588 delete_tab(t);
2589 else
2590 quit(t, args);
2591 break;
2592 case XT_TAB_ONLY:
2593 TAILQ_FOREACH_SAFE(tt, &tabs, entry, tv)
2594 if (t != tt)
2595 delete_tab(tt);
2596 break;
2597 case XT_TAB_OPEN:
2598 if (strlen(url) > 0)
2600 else {
2601 rv = XT_CB_PASSTHROUGH;
2602 goto done;
2604 load_uri(t, url);
2605 break;
2606 case XT_TAB_SHOW:
2607 if (show_tabs == 0) {
2608 show_tabs = 1;
2609 notebook_tab_set_visibility();
2611 break;
2612 case XT_TAB_HIDE:
2613 if (show_tabs == 1) {
2614 show_tabs = 0;
2615 notebook_tab_set_visibility();
2617 break;
2618 case XT_TAB_NEXTSTYLE:
2619 if (tab_style == XT_TABS_NORMAL) {
2620 tab_style = XT_TABS_COMPACT;
2621 recolor_compact_tabs();
2623 else
2624 tab_style = XT_TABS_NORMAL;
2625 notebook_tab_set_visibility();
2626 break;
2627 case XT_TAB_UNDO_CLOSE:
2628 if (undo_count == 0) {
2629 DNPRINTF(XT_D_TAB, "%s: no tabs to undo close",
2630 __func__);
2631 goto done;
2632 } else {
2633 undo_count--;
2634 u = TAILQ_FIRST(&undos);
2635 create_new_tab(u->uri, u, 1, -1);
2637 TAILQ_REMOVE(&undos, u, entry);
2638 g_free(u->uri);
2639 /* u->history is freed in create_new_tab() */
2640 g_free(u);
2642 break;
2643 case XT_TAB_LOAD_IMAGES:
2645 if (!auto_load_images) {
2647 /* Enable auto-load images (this will load all
2648 * previously unloaded images). */
2649 g_object_set(G_OBJECT(t->settings),
2650 "auto-load-images", TRUE, (char *)NULL);
2651 webkit_web_view_set_settings(t->wv, t->settings);
2653 webkit_web_view_reload(t->wv);
2655 /* Webkit triggers an event when we change the setting,
2656 * so we can't disable the auto-loading at once.
2658 * Unfortunately, webkit does not tell us when it's done.
2659 * Instead, we wait until the next request, and then
2660 * disable autoloading again.
2662 t->load_images = TRUE;
2664 break;
2665 default:
2666 rv = XT_CB_PASSTHROUGH;
2667 goto done;
2670 done:
2671 if (args->s) {
2672 g_free(args->s);
2673 args->s = NULL;
2676 return (rv);
2680 resizetab(struct tab *t, struct karg *args)
2682 if (t == NULL || args == NULL) {
2683 show_oops(NULL, "resizetab invalid parameters");
2684 return (XT_CB_PASSTHROUGH);
2687 DNPRINTF(XT_D_TAB, "resizetab: tab %d %d\n",
2688 t->tab_id, args->i);
2690 setzoom_webkit(t, args->i);
2692 return (XT_CB_HANDLED);
2696 movetab(struct tab *t, struct karg *args)
2698 int n, dest;
2700 if (t == NULL || args == NULL) {
2701 show_oops(NULL, "movetab invalid parameters");
2702 return (XT_CB_PASSTHROUGH);
2705 DNPRINTF(XT_D_TAB, "movetab: tab %d opcode %d\n",
2706 t->tab_id, args->i);
2708 if (args->i >= XT_TAB_INVALID)
2709 return (XT_CB_PASSTHROUGH);
2711 if (TAILQ_EMPTY(&tabs))
2712 return (XT_CB_PASSTHROUGH);
2714 n = gtk_notebook_get_n_pages(notebook);
2715 dest = gtk_notebook_get_current_page(notebook);
2717 switch (args->i) {
2718 case XT_TAB_NEXT:
2719 if (args->precount < 0)
2720 dest = dest == n - 1 ? 0 : dest + 1;
2721 else
2722 dest = args->precount - 1;
2724 break;
2725 case XT_TAB_PREV:
2726 if (args->precount < 0)
2727 dest -= 1;
2728 else
2729 dest -= args->precount % n;
2731 if (dest < 0)
2732 dest += n;
2734 break;
2735 case XT_TAB_FIRST:
2736 dest = 0;
2737 break;
2738 case XT_TAB_LAST:
2739 dest = n - 1;
2740 break;
2741 default:
2742 return (XT_CB_PASSTHROUGH);
2745 if (dest < 0 || dest >= n)
2746 return (XT_CB_PASSTHROUGH);
2747 if (t->tab_id == dest) {
2748 DNPRINTF(XT_D_TAB, "movetab: do nothing\n");
2749 return (XT_CB_HANDLED);
2752 set_current_tab(dest);
2754 return (XT_CB_HANDLED);
2757 int cmd_prefix = 0;
2759 struct prompt_sub {
2760 const char *s;
2761 const char *(*f)(struct tab *);
2762 } subs[] = {
2763 { "<uri>", get_uri },
2767 command(struct tab *t, struct karg *args)
2769 struct karg a = {0};
2770 int i;
2771 char *s = NULL, *sp = NULL, *sl = NULL;
2772 gchar **sv;
2774 if (t == NULL || args == NULL) {
2775 show_oops(NULL, "command invalid parameters");
2776 return (XT_CB_PASSTHROUGH);
2779 switch (args->i) {
2780 case '/':
2781 s = "/";
2782 break;
2783 case '?':
2784 s = "?";
2785 break;
2786 case ':':
2787 if (cmd_prefix == 0) {
2788 if (args->s != NULL && strlen(args->s) != 0) {
2789 sp = g_strdup_printf(":%s", args->s);
2790 s = sp;
2791 } else
2792 s = ":";
2793 } else {
2794 sp = g_strdup_printf(":%d", cmd_prefix);
2795 s = sp;
2796 cmd_prefix = 0;
2798 sl = g_strdup(s);
2799 if (sp) {
2800 g_free(sp);
2801 sp = NULL;
2803 s = sl;
2804 for (i = 0; i < LENGTH(subs); ++i) {
2805 sv = g_strsplit(sl, subs[i].s, -1);
2806 if (sl)
2807 g_free(sl);
2808 sl = g_strjoinv(subs[i].f(t), sv);
2809 g_strfreev(sv);
2810 s = sl;
2812 break;
2813 case '.':
2814 t->mode = XT_MODE_HINT;
2815 a.i = 0;
2816 hint(t, &a);
2817 s = ".";
2818 break;
2819 case ',':
2820 t->mode = XT_MODE_HINT;
2821 a.i = XT_HINT_NEWTAB;
2822 hint(t, &a);
2823 s = ",";
2824 break;
2825 default:
2826 show_oops(t, "command: invalid opcode %d", args->i);
2827 return (XT_CB_PASSTHROUGH);
2830 DNPRINTF(XT_D_CMD, "%s: tab %d type %s\n", __func__, t->tab_id, s);
2832 show_cmd(t);
2833 gtk_widget_grab_focus(GTK_WIDGET(t->cmd));
2834 #if GTK_CHECK_VERSION(3, 0, 0)
2835 gtk_widget_set_name(t->cmd, XT_CSS_NORMAL);
2836 #else
2837 gtk_widget_modify_base(t->cmd, GTK_STATE_NORMAL,
2838 &t->default_style->base[GTK_STATE_NORMAL]);
2839 #endif
2840 gtk_entry_set_text(GTK_ENTRY(t->cmd), s);
2841 gtk_editable_set_position(GTK_EDITABLE(t->cmd), -1);
2843 if (sp)
2844 g_free(sp);
2845 if (sl)
2846 g_free(sl);
2848 return (XT_CB_HANDLED);
2852 search(struct tab *t, struct karg *args)
2854 gboolean d;
2856 if (t == NULL || args == NULL) {
2857 show_oops(NULL, "search invalid parameters");
2858 return (1);
2861 switch (args->i) {
2862 case XT_SEARCH_NEXT:
2863 d = t->search_forward;
2864 break;
2865 case XT_SEARCH_PREV:
2866 d = !t->search_forward;
2867 break;
2868 default:
2869 return (XT_CB_PASSTHROUGH);
2872 if (t->search_text == NULL) {
2873 if (global_search == NULL)
2874 return (XT_CB_PASSTHROUGH);
2875 else {
2876 d = t->search_forward = TRUE;
2877 t->search_text = g_strdup(global_search);
2878 webkit_web_view_mark_text_matches(t->wv, global_search, FALSE, 0);
2879 webkit_web_view_set_highlight_text_matches(t->wv, TRUE);
2883 DNPRINTF(XT_D_CMD, "search: tab %d opc %d forw %d text %s\n",
2884 t->tab_id, args->i, t->search_forward, t->search_text);
2886 webkit_web_view_search_text(t->wv, t->search_text, FALSE, d, TRUE);
2888 return (XT_CB_HANDLED);
2892 session_save(struct tab *t, char *filename)
2894 struct karg a;
2895 int rv = 1;
2896 struct session *s;
2898 if (strlen(filename) == 0)
2899 goto done;
2901 if (filename[0] == '.' || filename[0] == '/')
2902 goto done;
2904 a.s = filename;
2905 if (save_tabs(t, &a))
2906 goto done;
2907 strlcpy(named_session, filename, sizeof named_session);
2909 /* add the new session to the list of sessions */
2910 s = g_malloc(sizeof(struct session));
2911 s->name = g_strdup(filename);
2912 TAILQ_INSERT_TAIL(&sessions, s, entry);
2914 rv = 0;
2915 done:
2916 return (rv);
2920 session_open(struct tab *t, char *filename)
2922 struct karg a;
2923 int rv = 1;
2925 if (strlen(filename) == 0)
2926 goto done;
2928 if (filename[0] == '.' || filename[0] == '/')
2929 goto done;
2931 a.s = filename;
2932 a.i = XT_SES_CLOSETABS;
2933 if (open_tabs(t, &a))
2934 goto done;
2936 strlcpy(named_session, filename, sizeof named_session);
2938 rv = 0;
2939 done:
2940 return (rv);
2944 session_delete(struct tab *t, char *filename)
2946 char file[PATH_MAX];
2947 int rv = 1;
2948 struct session *s;
2950 if (strlen(filename) == 0)
2951 goto done;
2953 if (filename[0] == '.' || filename[0] == '/')
2954 goto done;
2956 snprintf(file, sizeof file, "%s" PS "%s", sessions_dir, filename);
2957 if (unlink(file))
2958 goto done;
2960 if (!strcmp(filename, named_session))
2961 strlcpy(named_session, XT_SAVED_TABS_FILE,
2962 sizeof named_session);
2964 /* remove session from sessions list */
2965 TAILQ_FOREACH(s, &sessions, entry) {
2966 if (!strcmp(s->name, filename))
2967 break;
2969 if (s == NULL)
2970 goto done;
2971 TAILQ_REMOVE(&sessions, s, entry);
2972 g_free((gpointer) s->name);
2973 g_free(s);
2975 rv = 0;
2976 done:
2977 return (rv);
2981 session_cmd(struct tab *t, struct karg *args)
2983 char *filename = args->s;
2985 if (t == NULL)
2986 return (1);
2988 if (args->i & XT_SHOW)
2989 show_oops(t, "Current session: %s", named_session[0] == '\0' ?
2990 XT_SAVED_TABS_FILE : named_session);
2991 else if (args->i & XT_SAVE) {
2992 if (session_save(t, filename)) {
2993 show_oops(t, "Can't save session: %s",
2994 filename ? filename : "INVALID");
2995 goto done;
2997 } else if (args->i & XT_OPEN) {
2998 if (session_open(t, filename)) {
2999 show_oops(t, "Can't open session: %s",
3000 filename ? filename : "INVALID");
3001 goto done;
3003 } else if (args->i & XT_DELETE) {
3004 if (session_delete(t, filename)) {
3005 show_oops(t, "Can't delete session: %s",
3006 filename ? filename : "INVALID");
3007 goto done;
3010 done:
3011 return (XT_CB_PASSTHROUGH);
3015 script_cmd(struct tab *t, struct karg *args)
3017 struct stat sb;
3018 FILE *f = NULL;
3019 char *buf = NULL;
3021 if (t == NULL)
3022 goto done;
3024 if ((f = fopen(args->s, "r")) == NULL) {
3025 show_oops(t, "Can't open script file: %s", args->s);
3026 goto done;
3029 if (fstat(fileno(f), &sb) == -1) {
3030 show_oops(t, "Can't stat script file: %s", args->s);
3031 goto done;
3034 buf = g_malloc0(sb.st_size + 1);
3035 if (fread(buf, 1, sb.st_size, f) != sb.st_size) {
3036 show_oops(t, "Can't read script file: %s", args->s);
3037 goto done;
3040 DNPRINTF(XT_D_JS, "%s: about to run script\n", __func__);
3041 run_script(t, buf);
3043 done:
3044 if (f)
3045 fclose(f);
3046 if (buf)
3047 g_free(buf);
3049 return (XT_CB_PASSTHROUGH);
3053 * Make a hardcopy of the page
3056 print_page(struct tab *t, struct karg *args)
3058 WebKitWebFrame *frame;
3059 GtkPageSetup *ps;
3060 GtkPrintOperation *op;
3061 GtkPrintOperationAction action;
3062 GtkPrintOperationResult print_res;
3063 GError *g_err = NULL;
3064 int marg_l, marg_r, marg_t, marg_b;
3066 DNPRINTF(XT_D_PRINTING, "%s:", __func__);
3068 ps = gtk_page_setup_new();
3069 op = gtk_print_operation_new();
3070 action = GTK_PRINT_OPERATION_ACTION_PRINT_DIALOG;
3071 frame = webkit_web_view_get_main_frame(t->wv);
3073 /* the default margins are too small, so we will bump them */
3074 marg_l = gtk_page_setup_get_left_margin(ps, GTK_UNIT_MM) +
3075 XT_PRINT_EXTRA_MARGIN;
3076 marg_r = gtk_page_setup_get_right_margin(ps, GTK_UNIT_MM) +
3077 XT_PRINT_EXTRA_MARGIN;
3078 marg_t = gtk_page_setup_get_top_margin(ps, GTK_UNIT_MM) +
3079 XT_PRINT_EXTRA_MARGIN;
3080 marg_b = gtk_page_setup_get_bottom_margin(ps, GTK_UNIT_MM) +
3081 XT_PRINT_EXTRA_MARGIN;
3083 /* set margins */
3084 gtk_page_setup_set_left_margin(ps, marg_l, GTK_UNIT_MM);
3085 gtk_page_setup_set_right_margin(ps, marg_r, GTK_UNIT_MM);
3086 gtk_page_setup_set_top_margin(ps, marg_t, GTK_UNIT_MM);
3087 gtk_page_setup_set_bottom_margin(ps, marg_b, GTK_UNIT_MM);
3089 gtk_print_operation_set_default_page_setup(op, ps);
3091 /* this appears to free 'op' and 'ps' */
3092 print_res = webkit_web_frame_print_full(frame, op, action, &g_err);
3094 /* check it worked */
3095 if (print_res == GTK_PRINT_OPERATION_RESULT_ERROR) {
3096 show_oops(NULL, "can't print: %s", g_err->message);
3097 g_error_free (g_err);
3098 return (1);
3101 return (0);
3105 go_home(struct tab *t, struct karg *args)
3107 load_uri(t, home);
3108 return (0);
3112 set_encoding(struct tab *t, struct karg *args)
3114 const gchar *e;
3116 if (args->s && strlen(g_strstrip(args->s)) == 0) {
3117 e = webkit_web_view_get_custom_encoding(t->wv);
3118 if (e == NULL)
3119 e = webkit_web_view_get_encoding(t->wv);
3120 show_oops(t, "encoding: %s", e ? e : "N/A");
3121 } else
3122 webkit_web_view_set_custom_encoding(t->wv, args->s);
3124 return (0);
3128 restart(struct tab *t, struct karg *args)
3130 struct karg a;
3132 a.s = XT_RESTART_TABS_FILE;
3133 save_tabs(t, &a);
3134 execvp(start_argv[0], start_argv);
3135 /* NOTREACHED */
3137 return (0);
3140 char *http_proxy_save; /* not a setting, used to toggle */
3143 proxy_cmd(struct tab *t, struct karg *args)
3145 DNPRINTF(XT_D_CMD, "%s: tab %d\n", __func__, t->tab_id);
3147 if (t == NULL)
3148 return (1);
3150 /* setup */
3151 if (http_proxy) {
3152 if (http_proxy_save)
3153 g_free(http_proxy_save);
3154 http_proxy_save = g_strdup(http_proxy);
3157 if (args->i & XT_PRXY_SHOW) {
3158 if (http_proxy)
3159 show_oops(t, "http_proxy = %s", http_proxy);
3160 else
3161 show_oops(t, "proxy is currently disabled");
3162 } else if (args->i & XT_PRXY_TOGGLE) {
3163 if (http_proxy_save == NULL && http_proxy == NULL) {
3164 show_oops(t, "can't toggle proxy");
3165 goto done;
3167 if (http_proxy) {
3168 setup_proxy(NULL);
3169 show_oops(t, "http proxy disabled");
3170 } else {
3171 setup_proxy(http_proxy_save);
3172 show_oops(t, "http_proxy = %s", http_proxy);
3175 done:
3176 return (XT_CB_PASSTHROUGH);
3178 struct cmd {
3179 char *cmd;
3180 int level;
3181 int (*func)(struct tab *, struct karg *);
3182 int arg;
3183 int type;
3184 } cmds[] = {
3185 { "command_mode", 0, command_mode, XT_MODE_COMMAND, 0 },
3186 { "insert_mode", 0, command_mode, XT_MODE_INSERT, 0 },
3187 { "command", 0, command, ':', 0 },
3188 { "search", 0, command, '/', 0 },
3189 { "searchb", 0, command, '?', 0 },
3190 { "hinting", 0, command, '.', 0 },
3191 { "hinting_newtab", 0, command, ',', 0 },
3192 { "togglesrc", 0, toggle_src, 0, 0 },
3193 { "editsrc", 0, edit_src, 0, 0 },
3194 { "editelement", 0, edit_element, 0, 0 },
3195 { "passthrough", 0, passthrough, 0, 0 },
3196 { "modurl", 0, modurl, 0, 0 },
3198 /* yanking and pasting */
3199 { "yankuri", 0, yank_uri, 0, 0 },
3200 { "pasteuricur", 0, paste_uri, XT_PASTE_CURRENT_TAB, 0 },
3201 { "pasteurinew", 0, paste_uri, XT_PASTE_NEW_TAB, 0 },
3203 /* search */
3204 { "searchnext", 0, search, XT_SEARCH_NEXT, 0 },
3205 { "searchprevious", 0, search, XT_SEARCH_PREV, 0 },
3207 /* focus */
3208 { "focusaddress", 0, focus, XT_FOCUS_URI, 0 },
3209 { "focussearch", 0, focus, XT_FOCUS_SEARCH, 0 },
3211 /* hinting */
3212 { "hinting", 0, hint, 0, 0 },
3213 { "hinting_newtab", 0, hint, XT_HINT_NEWTAB, 0 },
3215 /* custom stylesheet */
3216 { "userstyle", 0, userstyle_cmd, XT_STYLE_CURRENT_TAB, XT_USERARG },
3217 { "userstyle_global", 0, userstyle_cmd, XT_STYLE_GLOBAL, XT_USERARG },
3219 /* navigation */
3220 { "goback", 0, navaction, XT_NAV_BACK, 0 },
3221 { "goforward", 0, navaction, XT_NAV_FORWARD, 0 },
3222 { "reload", 0, navaction, XT_NAV_RELOAD, 0 },
3223 { "stop", 0, navaction, XT_NAV_STOP, 0 },
3225 /* vertical movement */
3226 { "scrolldown", 0, move, XT_MOVE_DOWN, 0 },
3227 { "scrollup", 0, move, XT_MOVE_UP, 0 },
3228 { "scrollbottom", 0, move, XT_MOVE_BOTTOM, 0 },
3229 { "scrolltop", 0, move, XT_MOVE_TOP, 0 },
3230 { "1", 0, move, XT_MOVE_TOP, 0 },
3231 { "scrollhalfdown", 0, move, XT_MOVE_HALFDOWN, 0 },
3232 { "scrollhalfup", 0, move, XT_MOVE_HALFUP, 0 },
3233 { "scrollpagedown", 0, move, XT_MOVE_PAGEDOWN, 0 },
3234 { "scrollpageup", 0, move, XT_MOVE_PAGEUP, 0 },
3235 /* horizontal movement */
3236 { "scrollright", 0, move, XT_MOVE_RIGHT, 0 },
3237 { "scrollleft", 0, move, XT_MOVE_LEFT, 0 },
3238 { "scrollfarright", 0, move, XT_MOVE_FARRIGHT, 0 },
3239 { "scrollfarleft", 0, move, XT_MOVE_FARLEFT, 0 },
3241 { "favorites", 0, xtp_page_fl, XT_SHOW, 0 },
3242 { "fav", 0, xtp_page_fl, XT_SHOW, 0 },
3243 { "favedit", 0, xtp_page_fl, XT_SHOW|XT_DELETE, 0 },
3244 { "favadd", 0, add_favorite, 0, 0 },
3246 { "qall", 0, quit, 0, 0 },
3247 { "quitall", 0, quit, 0, 0 },
3248 { "w", 0, save_tabs, 0, 0 },
3249 { "wq", 0, save_tabs_and_quit, 0, 0 },
3250 { "help", 0, help, 0, 0 },
3251 { "about", 0, xtp_page_ab, 0, 0 },
3252 { "stats", 0, stats, 0, 0 },
3253 { "version", 0, xtp_page_ab, 0, 0 },
3255 /* js command */
3256 { "js", 0, js_cmd, XT_SHOW | XT_WL_PERSISTENT | XT_WL_SESSION, 0 },
3257 { "save", 1, js_cmd, XT_SAVE | XT_WL_FQDN, 0 },
3258 { "domain", 2, js_cmd, XT_SAVE | XT_WL_TOPLEVEL, 0 },
3259 { "fqdn", 2, js_cmd, XT_SAVE | XT_WL_FQDN, 0 },
3260 { "show", 1, js_cmd, XT_SHOW | XT_WL_PERSISTENT | XT_WL_SESSION, 0 },
3261 { "all", 2, js_cmd, XT_SHOW | XT_WL_PERSISTENT | XT_WL_SESSION, 0 },
3262 { "persistent", 2, js_cmd, XT_SHOW | XT_WL_PERSISTENT, 0 },
3263 { "session", 2, js_cmd, XT_SHOW | XT_WL_SESSION, 0 },
3264 { "toggle", 1, js_cmd, XT_WL_TOGGLE | XT_WL_FQDN, 0 },
3265 { "domain", 2, js_cmd, XT_WL_TOGGLE | XT_WL_TOPLEVEL, 0 },
3266 { "fqdn", 2, js_cmd, XT_WL_TOGGLE | XT_WL_FQDN, 0 },
3268 /* cookie command */
3269 { "cookie", 0, cookie_cmd, XT_SHOW | XT_WL_PERSISTENT | XT_WL_SESSION, 0 },
3270 { "save", 1, cookie_cmd, XT_SAVE | XT_WL_FQDN, 0 },
3271 { "domain", 2, cookie_cmd, XT_SAVE | XT_WL_TOPLEVEL, 0 },
3272 { "fqdn", 2, cookie_cmd, XT_SAVE | XT_WL_FQDN, 0 },
3273 { "show", 1, cookie_cmd, XT_SHOW | XT_WL_PERSISTENT | XT_WL_SESSION, 0 },
3274 { "all", 2, cookie_cmd, XT_SHOW | XT_WL_PERSISTENT | XT_WL_SESSION, 0 },
3275 { "persistent", 2, cookie_cmd, XT_SHOW | XT_WL_PERSISTENT, 0 },
3276 { "session", 2, cookie_cmd, XT_SHOW | XT_WL_SESSION, 0 },
3277 { "toggle", 1, cookie_cmd, XT_WL_TOGGLE | XT_WL_FQDN, 0 },
3278 { "domain", 2, cookie_cmd, XT_WL_TOGGLE | XT_WL_TOPLEVEL, 0 },
3279 { "fqdn", 2, cookie_cmd, XT_WL_TOGGLE | XT_WL_FQDN, 0 },
3280 { "purge", 1, cookie_cmd, XT_DELETE, 0 },
3282 /* plugin command */
3283 { "plugin", 0, pl_cmd, XT_SHOW | XT_WL_PERSISTENT | XT_WL_SESSION, 0 },
3284 { "save", 1, pl_cmd, XT_SAVE | XT_WL_FQDN, 0 },
3285 { "domain", 2, pl_cmd, XT_SAVE | XT_WL_TOPLEVEL, 0 },
3286 { "fqdn", 2, pl_cmd, XT_SAVE | XT_WL_FQDN, 0 },
3287 { "show", 1, pl_cmd, XT_SHOW | XT_WL_PERSISTENT | XT_WL_SESSION, 0 },
3288 { "all", 2, pl_cmd, XT_SHOW | XT_WL_PERSISTENT | XT_WL_SESSION, 0 },
3289 { "persistent", 2, pl_cmd, XT_SHOW | XT_WL_PERSISTENT, 0 },
3290 { "session", 2, pl_cmd, XT_SHOW | XT_WL_SESSION, 0 },
3291 { "toggle", 1, pl_cmd, XT_WL_TOGGLE | XT_WL_FQDN, 0 },
3292 { "domain", 2, pl_cmd, XT_WL_TOGGLE | XT_WL_TOPLEVEL, 0 },
3293 { "fqdn", 2, pl_cmd, XT_WL_TOGGLE | XT_WL_FQDN, 0 },
3295 /* https command */
3296 { "https", 0, https_cmd, XT_SHOW | XT_WL_PERSISTENT | XT_WL_SESSION, 0 },
3297 { "save", 1, https_cmd, XT_SAVE | XT_WL_FQDN, 0 },
3298 { "domain", 2, https_cmd, XT_SAVE | XT_WL_TOPLEVEL, 0 },
3299 { "fqdn", 2, https_cmd, XT_SAVE | XT_WL_FQDN, 0 },
3300 { "show", 1, https_cmd, XT_SHOW | XT_WL_PERSISTENT | XT_WL_SESSION, 0 },
3301 { "all", 2, https_cmd, XT_SHOW | XT_WL_PERSISTENT | XT_WL_SESSION, 0 },
3302 { "persistent", 2, https_cmd, XT_SHOW | XT_WL_PERSISTENT, 0 },
3303 { "session", 2, https_cmd, XT_SHOW | XT_WL_SESSION, 0 },
3304 { "toggle", 1, https_cmd, XT_WL_TOGGLE | XT_WL_FQDN, 0 },
3305 { "domain", 2, https_cmd, XT_WL_TOGGLE | XT_WL_TOPLEVEL, 0 },
3306 { "fqdn", 2, https_cmd, XT_WL_TOGGLE | XT_WL_FQDN, 0 },
3308 /* toplevel (domain) command */
3309 { "toplevel", 0, toplevel_cmd, XT_WL_TOGGLE | XT_WL_TOPLEVEL | XT_WL_RELOAD, 0 },
3310 { "toggle", 1, toplevel_cmd, XT_WL_TOGGLE | XT_WL_TOPLEVEL | XT_WL_RELOAD, 0 },
3312 /* cookie jar */
3313 { "cookiejar", 0, xtp_page_cl, 0, 0 },
3315 /* cert command */
3316 { "cert", 0, cert_cmd, XT_SHOW, 0 },
3317 { "save", 1, cert_cmd, XT_SAVE, 0 },
3318 { "show", 1, cert_cmd, XT_SHOW, 0 },
3320 { "ca", 0, ca_cmd, 0, 0 },
3321 { "downloadmgr", 0, xtp_page_dl, 0, 0 },
3322 { "dl", 0, xtp_page_dl, 0, 0 },
3323 { "h", 0, xtp_page_hl, 0, 0 },
3324 { "history", 0, xtp_page_hl, 0, 0 },
3325 { "home", 0, go_home, 0, 0 },
3326 { "restart", 0, restart, 0, 0 },
3327 { "urlhide", 0, urlaction, XT_URL_HIDE, 0 },
3328 { "urlshow", 0, urlaction, XT_URL_SHOW, 0 },
3329 { "statustoggle", 0, statustoggle, 0, 0 },
3330 { "run_script", 0, run_page_script, 0, XT_USERARG },
3332 { "print", 0, print_page, 0, 0 },
3334 /* tabs */
3335 { "focusin", 0, resizetab, XT_ZOOM_IN, 0 },
3336 { "focusout", 0, resizetab, XT_ZOOM_OUT, 0 },
3337 { "focusreset", 0, resizetab, XT_ZOOM_NORMAL, 0 },
3338 { "q", 0, tabaction, XT_TAB_DELQUIT, 0 },
3339 { "quit", 0, tabaction, XT_TAB_DELQUIT, 0 },
3340 { "open", 0, tabaction, XT_TAB_OPEN, XT_URLARG },
3341 { "tabclose", 0, tabaction, XT_TAB_DELETE, XT_PREFIX | XT_INTARG},
3342 { "tabedit", 0, tabaction, XT_TAB_NEW, XT_PREFIX | XT_URLARG },
3343 { "tabfirst", 0, movetab, XT_TAB_FIRST, 0 },
3344 { "tabhide", 0, tabaction, XT_TAB_HIDE, 0 },
3345 { "tablast", 0, movetab, XT_TAB_LAST, 0 },
3346 { "tabnew", 0, tabaction, XT_TAB_NEW, XT_PREFIX | XT_URLARG },
3347 { "tabnext", 0, movetab, XT_TAB_NEXT, XT_PREFIX | XT_INTARG},
3348 { "tabnextstyle", 0, tabaction, XT_TAB_NEXTSTYLE, 0 },
3349 { "tabonly", 0, tabaction, XT_TAB_ONLY, 0 },
3350 { "tabprevious", 0, movetab, XT_TAB_PREV, XT_PREFIX | XT_INTARG},
3351 { "tabrewind", 0, movetab, XT_TAB_FIRST, 0 },
3352 { "tabshow", 0, tabaction, XT_TAB_SHOW, 0 },
3353 { "tabs", 0, buffers, 0, 0 },
3354 { "tabundoclose", 0, tabaction, XT_TAB_UNDO_CLOSE, 0 },
3355 { "buffers", 0, buffers, 0, 0 },
3356 { "ls", 0, buffers, 0, 0 },
3357 { "encoding", 0, set_encoding, 0, XT_USERARG },
3358 { "loadimages", 0, tabaction, XT_TAB_LOAD_IMAGES, 0 },
3360 /* settings */
3361 { "set", 0, set, 0, XT_SETARG },
3362 { "runtime", 0, xtp_page_rt, 0, 0 },
3364 { "fullscreen", 0, fullscreen, 0, 0 },
3365 { "f", 0, fullscreen, 0, 0 },
3367 /* sessions */
3368 { "session", 0, session_cmd, XT_SHOW, 0 },
3369 { "delete", 1, session_cmd, XT_DELETE, XT_SESSARG },
3370 { "open", 1, session_cmd, XT_OPEN, XT_SESSARG },
3371 { "save", 1, session_cmd, XT_SAVE, XT_USERARG },
3372 { "show", 1, session_cmd, XT_SHOW, 0 },
3374 /* external javascript */
3375 { "script", 0, script_cmd, XT_EJS_SHOW, XT_USERARG },
3377 /* inspector */
3378 { "inspector", 0, inspector_cmd, XT_INS_SHOW, 0 },
3379 { "show", 1, inspector_cmd, XT_INS_SHOW, 0 },
3380 { "hide", 1, inspector_cmd, XT_INS_HIDE, 0 },
3382 /* proxy */
3383 { "proxy", 0, proxy_cmd, XT_PRXY_SHOW, 0 },
3384 { "show", 1, proxy_cmd, XT_PRXY_SHOW, 0 },
3385 { "toggle", 1, proxy_cmd, XT_PRXY_TOGGLE, 0 },
3388 struct {
3389 int index;
3390 int len;
3391 gchar *list[256];
3392 } cmd_status = {-1, 0};
3394 gboolean
3395 wv_release_button_cb(GtkWidget *btn, GdkEventButton *e, struct tab *t)
3398 if (e->type == GDK_BUTTON_RELEASE && e->button == 1)
3399 btn_down = 0;
3401 return (FALSE);
3404 gboolean
3405 wv_button_cb(GtkWidget *btn, GdkEventButton *e, struct tab *t)
3407 struct karg a;
3408 WebKitHitTestResult *hit_test_result;
3409 guint context;
3411 hit_test_result = webkit_web_view_get_hit_test_result(t->wv, e);
3412 g_object_get(hit_test_result, "context", &context, NULL);
3414 hide_oops(t);
3415 hide_buffers(t);
3417 if (context & WEBKIT_HIT_TEST_RESULT_CONTEXT_EDITABLE)
3418 t->mode = XT_MODE_INSERT;
3419 else
3420 t->mode = XT_MODE_COMMAND;
3422 if (e->type == GDK_BUTTON_PRESS && e->button == 1)
3423 btn_down = 1;
3424 else if (e->type == GDK_BUTTON_PRESS && e->button == 8 /* btn 4 */) {
3425 /* go backward */
3426 a.i = XT_NAV_BACK;
3427 navaction(t, &a);
3429 return (TRUE);
3430 } else if (e->type == GDK_BUTTON_PRESS && e->button == 9 /* btn 5 */) {
3431 /* go forward */
3432 a.i = XT_NAV_FORWARD;
3433 navaction(t, &a);
3435 return (TRUE);
3438 return (FALSE);
3441 gboolean
3442 tab_close_cb(GtkWidget *btn, GdkEventButton *e, struct tab *t)
3444 DNPRINTF(XT_D_TAB, "tab_close_cb: tab %d\n", t->tab_id);
3446 if (e->type == GDK_BUTTON_PRESS && e->button == 1)
3447 delete_tab(t);
3449 return (FALSE);
3453 parse_custom_uri(struct tab *t, const char *uri)
3455 struct custom_uri *u;
3456 int handled = 0;
3457 char *sv[3];
3459 TAILQ_FOREACH(u, &cul, entry) {
3460 if (strncmp(uri, u->uri, strlen(u->uri)))
3461 continue;
3463 handled = 1;
3464 sv[0] = u->cmd;
3465 sv[1] = (char *)uri;
3466 sv[2] = NULL;
3467 if (!g_spawn_async(NULL, sv, NULL, G_SPAWN_SEARCH_PATH, NULL,
3468 NULL, NULL, NULL))
3469 show_oops(t, "%s: could not spawn process", __func__);
3472 return (handled);
3475 void
3476 activate_uri_entry_cb(GtkWidget* entry, struct tab *t)
3478 const gchar *uri = gtk_entry_get_text(GTK_ENTRY(entry));
3480 DNPRINTF(XT_D_URL, "activate_uri_entry_cb: %s\n", uri);
3482 if (t == NULL) {
3483 show_oops(NULL, "activate_uri_entry_cb invalid parameters");
3484 return;
3487 if (uri == NULL) {
3488 show_oops(t, "activate_uri_entry_cb no uri");
3489 return;
3492 uri += strspn(uri, "\t ");
3494 if (parse_custom_uri(t, uri))
3495 return;
3497 /* otherwise continue to load page normally */
3498 load_uri(t, (gchar *)uri);
3499 focus_webview(t);
3502 void
3503 activate_search_entry_cb(GtkWidget* entry, struct tab *t)
3505 const gchar *search = gtk_entry_get_text(GTK_ENTRY(entry));
3506 char *newuri = NULL;
3507 gchar *enc_search;
3508 char **sv;
3510 DNPRINTF(XT_D_URL, "activate_search_entry_cb: %s\n", search);
3512 if (t == NULL) {
3513 show_oops(NULL, "activate_search_entry_cb invalid parameters");
3514 return;
3517 if (search_string == NULL || strlen(search_string) == 0) {
3518 show_oops(t, "no search_string");
3519 return;
3522 set_normal_tab_meaning(t);
3524 enc_search = soup_uri_encode(search, XT_RESERVED_CHARS);
3525 sv = g_strsplit(search_string, "%s", 2);
3526 newuri = g_strjoinv(enc_search, sv);
3527 g_free(enc_search);
3528 g_strfreev(sv);
3530 marks_clear(t);
3531 load_uri(t, newuri);
3532 focus_webview(t);
3534 if (newuri)
3535 g_free(newuri);
3538 void
3539 check_and_set_cookie(const gchar *uri, struct tab *t)
3541 struct domain *d = NULL;
3542 int es = 0;
3544 if (uri == NULL || t == NULL)
3545 return;
3547 if ((d = wl_find_uri(uri, &c_wl)) == NULL)
3548 es = 0;
3549 else
3550 es = 1;
3552 DNPRINTF(XT_D_COOKIE, "check_and_set_cookie: %s %s\n",
3553 es ? "enable" : "disable", uri);
3555 g_object_set(G_OBJECT(t->settings),
3556 "enable-html5-local-storage", es, (char *)NULL);
3557 webkit_web_view_set_settings(t->wv, t->settings);
3560 void
3561 check_and_set_js(const gchar *uri, struct tab *t)
3563 struct domain *d = NULL;
3564 int es = 0;
3566 if (uri == NULL || t == NULL)
3567 return;
3569 if ((d = wl_find_uri(uri, &js_wl)) == NULL)
3570 es = 0;
3571 else
3572 es = 1;
3574 DNPRINTF(XT_D_JS, "check_and_set_js: %s %s\n",
3575 es ? "enable" : "disable", uri);
3577 g_object_set(G_OBJECT(t->settings),
3578 "enable-scripts", es, (char *)NULL);
3579 g_object_set(G_OBJECT(t->settings),
3580 "javascript-can-open-windows-automatically", es, (char *)NULL);
3581 webkit_web_view_set_settings(t->wv, t->settings);
3583 button_set_stockid(t->js_toggle,
3584 es ? GTK_STOCK_MEDIA_PLAY : GTK_STOCK_MEDIA_PAUSE);
3587 void
3588 check_and_set_pl(const gchar *uri, struct tab *t)
3590 struct domain *d = NULL;
3591 int es = 0;
3593 if (uri == NULL || t == NULL)
3594 return;
3596 if ((d = wl_find_uri(uri, &pl_wl)) == NULL)
3597 es = 0;
3598 else
3599 es = 1;
3601 DNPRINTF(XT_D_JS, "check_and_set_pl: %s %s\n",
3602 es ? "enable" : "disable", uri);
3604 g_object_set(G_OBJECT(t->settings),
3605 "enable-plugins", es, (char *)NULL);
3606 webkit_web_view_set_settings(t->wv, t->settings);
3609 #if GTK_CHECK_VERSION(3, 0, 0)
3610 /* A lot of this can be removed when gtk2 is dropped on the floor */
3611 char *
3612 get_css_name(const char *col_str)
3614 char *name = NULL;
3616 if (!strcmp(col_str, XT_COLOR_WHITE))
3617 name = g_strdup(XT_CSS_NORMAL);
3618 else if (!strcmp(col_str, XT_COLOR_RED))
3619 name = g_strdup(XT_CSS_RED);
3620 else if (!strcmp(col_str, XT_COLOR_YELLOW))
3621 name = g_strdup(XT_CSS_YELLOW);
3622 else if (!strcmp(col_str, XT_COLOR_GREEN))
3623 name = g_strdup(XT_CSS_GREEN);
3624 else if (!strcmp(col_str, XT_COLOR_BLUE))
3625 name = g_strdup(XT_CSS_BLUE);
3626 return (name);
3628 #endif
3630 void
3631 color_address_bar(gpointer p)
3633 struct tab *tt, *t = p;
3634 gchar *col_str = XT_COLOR_WHITE;
3635 const gchar *uri, *u = NULL, *error_str = NULL;
3636 #if GTK_CHECK_VERSION(3, 0, 0)
3637 char *name;
3638 #else
3639 GdkColor color;
3640 gchar *text, *base;
3641 #endif
3643 #ifdef USE_THREADS
3644 gdk_threads_enter();
3645 #endif
3646 DNPRINTF(XT_D_URL, "%s:\n", __func__);
3648 /* make sure t still exists */
3649 if (t == NULL)
3650 goto done;
3651 TAILQ_FOREACH(tt, &tabs, entry)
3652 if (t == tt)
3653 break;
3654 if (t != tt)
3655 goto done;
3657 if ((uri = get_uri(t)) == NULL)
3658 goto white;
3659 u = g_strdup(uri);
3661 #ifdef USE_THREADS
3662 GDK_FLUSH();
3663 gdk_threads_leave();
3664 #endif
3666 col_str = XT_COLOR_YELLOW;
3667 switch (load_compare_cert(u, &error_str, certs_dir)) {
3668 case CERT_LOCAL:
3669 col_str = XT_COLOR_BLUE;
3670 break;
3671 case CERT_TRUSTED:
3672 col_str = (strlen(ssl_ca_file) == 0) ? XT_COLOR_RED
3673 : XT_COLOR_GREEN;
3674 break;
3675 case CERT_UNTRUSTED:
3676 col_str = (strlen(ssl_ca_file) == 0) ? XT_COLOR_RED
3677 : XT_COLOR_YELLOW;
3678 break;
3679 case CERT_BAD:
3680 col_str = XT_COLOR_RED;
3681 break;
3684 #ifdef USE_THREADS
3685 gdk_threads_enter();
3686 #endif
3687 /* make sure t isn't deleted */
3688 TAILQ_FOREACH(tt, &tabs, entry)
3689 if (t == tt)
3690 break;
3691 if (t != tt)
3692 goto done;
3694 #ifdef USE_THREADS
3695 /* test to see if the user navigated away and canceled the thread */
3696 if (t->thread != g_thread_self())
3697 goto done;
3698 if ((uri = get_uri(t)) == NULL) {
3699 t->thread = NULL;
3700 goto done;
3702 if (strcmp(uri, u)) {
3703 /* make sure we are still the same url */
3704 t->thread = NULL;
3705 goto done;
3707 #endif
3708 white:
3710 if (!strcmp(col_str, XT_COLOR_WHITE)) {
3711 #if GTK_CHECK_VERSION(3, 0, 0)
3712 gtk_widget_set_name(t->uri_entry, XT_CSS_NORMAL);
3713 statusbar_modify_attr(t, XT_CSS_NORMAL);
3714 #else
3715 text = gdk_color_to_string(
3716 &t->default_style->text[GTK_STATE_NORMAL]);
3717 base = gdk_color_to_string(
3718 &t->default_style->base[GTK_STATE_NORMAL]);
3719 gtk_widget_modify_base(t->uri_entry, GTK_STATE_NORMAL,
3720 &t->default_style->base[GTK_STATE_NORMAL]);
3721 statusbar_modify_attr(t, text, base);
3722 g_free(text);
3723 g_free(base);
3724 #endif
3725 } else {
3726 #if GTK_CHECK_VERSION(3, 0, 0)
3727 name = get_css_name(col_str);
3728 gtk_widget_set_name(t->uri_entry, name);
3729 statusbar_modify_attr(t, name);
3730 g_free(name);
3731 #else
3732 gdk_color_parse(col_str, &color);
3733 gtk_widget_modify_base(t->uri_entry, GTK_STATE_NORMAL, &color);
3734 statusbar_modify_attr(t, XT_COLOR_BLACK, col_str);
3735 #endif
3738 if (error_str && error_str[0] != '\0')
3739 show_oops(t, "%s", error_str);
3740 #ifdef USE_THREADS
3741 t->thread = NULL;
3742 #endif
3743 done:
3744 /* t is invalid at this point */
3745 if (u)
3746 g_free((gpointer)u);
3747 #ifdef USE_THREADS
3748 GDK_FLUSH();
3749 gdk_threads_leave();
3750 #endif
3753 void
3754 check_certs(gpointer p)
3756 color_address_bar((struct tab *)p);
3757 check_cert_changes((struct tab *)p, get_uri((struct tab *)p));
3760 void
3761 show_ca_status(struct tab *t, const char *uri)
3763 gchar *col_str = XT_COLOR_WHITE;
3764 #if GTK_CHECK_VERSION(3, 0, 0)
3765 char *name;
3766 #else
3767 GdkColor color;
3768 gchar *text, *base;
3769 #endif
3771 DNPRINTF(XT_D_URL, "show_ca_status: %d %s %s\n",
3772 ssl_strict_certs, ssl_ca_file, uri);
3774 if (t == NULL)
3775 return;
3777 if (uri == NULL || g_str_has_prefix(uri, "http://") ||
3778 !g_str_has_prefix(uri, "https://"))
3779 goto done;
3781 #ifdef USE_THREADS
3783 * It is not necessary to see if the thread is already running.
3784 * If the thread is in progress setting it to something else aborts it
3785 * on the way out.
3788 /* thread the coloring of the address bar */
3789 t->thread = g_thread_create((GThreadFunc)check_certs, t, TRUE, NULL);
3790 #else
3791 check_certs(t);
3792 #endif
3793 return;
3795 done:
3796 if (col_str) {
3797 if (!strcmp(col_str, XT_COLOR_WHITE)) {
3798 #if GTK_CHECK_VERSION(3, 0, 0)
3799 gtk_widget_set_name(t->uri_entry, XT_CSS_NORMAL);
3800 statusbar_modify_attr(t, XT_CSS_NORMAL);
3801 #else
3802 text = gdk_color_to_string(
3803 &t->default_style->text[GTK_STATE_NORMAL]);
3804 base = gdk_color_to_string(
3805 &t->default_style->base[GTK_STATE_NORMAL]);
3806 gtk_widget_modify_base(t->uri_entry, GTK_STATE_NORMAL,
3807 &t->default_style->base[GTK_STATE_NORMAL]);
3808 statusbar_modify_attr(t, text, base);
3809 g_free(text);
3810 g_free(base);
3811 #endif
3812 } else {
3813 #if GTK_CHECK_VERSION(3, 0, 0)
3814 name = get_css_name(col_str);
3815 gtk_widget_set_name(t->uri_entry, name);
3816 statusbar_modify_attr(t, name);
3817 g_free(name);
3818 #else
3819 gdk_color_parse(col_str, &color);
3820 gtk_widget_modify_base(t->uri_entry, GTK_STATE_NORMAL, &color);
3821 statusbar_modify_attr(t, XT_COLOR_BLACK, col_str);
3822 #endif
3827 void
3828 free_favicon(struct tab *t)
3830 DNPRINTF(XT_D_DOWNLOAD, "%s: down %p req %p\n",
3831 __func__, t->icon_download, t->icon_request);
3833 if (t->icon_request)
3834 g_object_unref(t->icon_request);
3835 if (t->icon_dest_uri)
3836 g_free(t->icon_dest_uri);
3838 t->icon_request = NULL;
3839 t->icon_dest_uri = NULL;
3842 void
3843 xt_icon_from_name(struct tab *t, gchar *name)
3845 if (!enable_favicon_entry)
3846 return;
3848 gtk_entry_set_icon_from_icon_name(GTK_ENTRY(t->uri_entry),
3849 GTK_ENTRY_ICON_PRIMARY, "text-html");
3850 if (show_url == 0)
3851 gtk_entry_set_icon_from_icon_name(GTK_ENTRY(t->sbe.uri),
3852 GTK_ENTRY_ICON_PRIMARY, "text-html");
3853 else
3854 gtk_entry_set_icon_from_icon_name(GTK_ENTRY(t->sbe.uri),
3855 GTK_ENTRY_ICON_PRIMARY, NULL);
3858 void
3859 xt_icon_from_pixbuf(struct tab *t, GdkPixbuf *pb)
3861 GdkPixbuf *pb_scaled;
3863 if (gdk_pixbuf_get_width(pb) > 16 || gdk_pixbuf_get_height(pb) > 16)
3864 pb_scaled = gdk_pixbuf_scale_simple(pb, 16, 16,
3865 GDK_INTERP_BILINEAR);
3866 else
3867 pb_scaled = pb;
3869 if (enable_favicon_entry) {
3871 /* Classic tabs. */
3872 gtk_entry_set_icon_from_pixbuf(GTK_ENTRY(t->uri_entry),
3873 GTK_ENTRY_ICON_PRIMARY, pb_scaled);
3875 /* Minimal tabs. */
3876 if (show_url == 0) {
3877 gtk_entry_set_icon_from_pixbuf(GTK_ENTRY(t->sbe.uri),
3878 GTK_ENTRY_ICON_PRIMARY, pb_scaled);
3879 } else
3880 gtk_entry_set_icon_from_icon_name(GTK_ENTRY(t->sbe.uri),
3881 GTK_ENTRY_ICON_PRIMARY, NULL);
3884 /* XXX: Only supports the minimal tabs atm. */
3885 if (enable_favicon_tabs)
3886 gtk_image_set_from_pixbuf(GTK_IMAGE(t->tab_elems.favicon),
3887 pb_scaled);
3889 if (pb_scaled != pb)
3890 g_object_unref(pb_scaled);
3893 void
3894 xt_icon_from_file(struct tab *t, char *uri)
3896 GdkPixbuf *pb;
3897 char *file;
3899 if (uri != NULL && g_str_has_prefix(uri, "file://"))
3900 file = g_filename_from_uri(uri, NULL, NULL);
3901 else
3902 file = g_strdup(uri);
3904 if (file == NULL)
3905 return;
3907 pb = gdk_pixbuf_new_from_file(file, NULL);
3908 if (pb) {
3909 xt_icon_from_pixbuf(t, pb);
3910 g_object_unref(pb);
3911 } else
3912 xt_icon_from_name(t, "text-html");
3914 g_free(file);
3917 gboolean
3918 is_valid_icon(char *file)
3920 gboolean valid = 0;
3921 const char *mime_type;
3922 GFileInfo *fi;
3923 GFile *gf;
3925 gf = g_file_new_for_path(file);
3926 fi = g_file_query_info(gf, G_FILE_ATTRIBUTE_STANDARD_CONTENT_TYPE, 0,
3927 NULL, NULL);
3928 mime_type = g_file_info_get_content_type(fi);
3929 valid = g_strcmp0(mime_type, "image/x-ico") == 0 ||
3930 g_strcmp0(mime_type, "image/vnd.microsoft.icon") == 0 ||
3931 g_strcmp0(mime_type, "image/png") == 0 ||
3932 g_strcmp0(mime_type, "image/gif") == 0 ||
3933 g_strcmp0(mime_type, "application/octet-stream") == 0;
3934 g_object_unref(fi);
3935 g_object_unref(gf);
3937 return (valid);
3940 void
3941 set_favicon_from_file(struct tab *t, char *uri)
3943 struct stat sb;
3944 char *file;
3946 if (t == NULL || uri == NULL)
3947 return;
3949 if (uri != NULL && g_str_has_prefix(uri, "file://"))
3950 file = g_filename_from_uri(uri, NULL, NULL);
3951 else
3952 file = g_strdup(uri);
3954 if (file == NULL)
3955 return;
3957 DNPRINTF(XT_D_DOWNLOAD, "%s: loading %s\n", __func__, file);
3959 if (!stat(file, &sb)) {
3960 if (sb.st_size == 0 || !is_valid_icon(file)) {
3961 /* corrupt icon so trash it */
3962 DNPRINTF(XT_D_DOWNLOAD, "%s: corrupt icon %s\n",
3963 __func__, file);
3964 unlink(file);
3965 /* no need to set icon to default here */
3966 goto done;
3969 xt_icon_from_file(t, file);
3970 done:
3971 g_free(file);
3974 void
3975 favicon_download_status_changed_cb(WebKitDownload *download, GParamSpec *spec,
3976 WebKitWebView *wv)
3978 WebKitDownloadStatus status = webkit_download_get_status(download);
3979 struct tab *tt = NULL, *t = NULL;
3982 * find the webview instead of passing in the tab as it could have been
3983 * deleted from underneath us.
3985 TAILQ_FOREACH(tt, &tabs, entry) {
3986 if (tt->wv == wv) {
3987 t = tt;
3988 break;
3991 if (t == NULL)
3992 return;
3994 DNPRINTF(XT_D_DOWNLOAD, "%s: tab %d status %d\n",
3995 __func__, t->tab_id, status);
3997 switch (status) {
3998 case WEBKIT_DOWNLOAD_STATUS_ERROR:
3999 /* -1 */
4000 t->icon_download = NULL;
4001 free_favicon(t);
4002 break;
4003 case WEBKIT_DOWNLOAD_STATUS_CREATED:
4004 /* 0 */
4005 break;
4006 case WEBKIT_DOWNLOAD_STATUS_STARTED:
4007 /* 1 */
4008 break;
4009 case WEBKIT_DOWNLOAD_STATUS_CANCELLED:
4010 /* 2 */
4011 DNPRINTF(XT_D_DOWNLOAD, "%s: freeing favicon %d\n",
4012 __func__, t->tab_id);
4013 t->icon_download = NULL;
4014 free_favicon(t);
4015 break;
4016 case WEBKIT_DOWNLOAD_STATUS_FINISHED:
4017 /* 3 */
4019 DNPRINTF(XT_D_DOWNLOAD, "%s: setting icon to %s\n",
4020 __func__, t->icon_dest_uri);
4021 set_favicon_from_file(t, t->icon_dest_uri);
4022 /* these will be freed post callback */
4023 t->icon_request = NULL;
4024 t->icon_download = NULL;
4025 break;
4026 default:
4027 break;
4031 void
4032 abort_favicon_download(struct tab *t)
4034 DNPRINTF(XT_D_DOWNLOAD, "%s: down %p\n", __func__, t->icon_download);
4036 #if !WEBKIT_CHECK_VERSION(1, 4, 0)
4037 if (t->icon_download) {
4038 g_signal_handlers_disconnect_by_func(G_OBJECT(t->icon_download),
4039 G_CALLBACK(favicon_download_status_changed_cb), t->wv);
4040 webkit_download_cancel(t->icon_download);
4041 t->icon_download = NULL;
4042 } else
4043 free_favicon(t);
4044 #endif
4046 xt_icon_from_name(t, "text-html");
4049 void
4050 notify_icon_loaded_cb(WebKitWebView *wv, gchar *uri, struct tab *t)
4052 DNPRINTF(XT_D_DOWNLOAD, "%s %s\n", __func__, uri);
4054 if (uri == NULL || t == NULL)
4055 return;
4057 #if WEBKIT_CHECK_VERSION(1, 4, 0)
4058 /* take icon from WebKitIconDatabase */
4059 GdkPixbuf *pb = NULL;
4061 /* webkit_web_view_get_icon_pixbuf is depreciated in 1.8 */
4062 #if WEBKIT_CHECK_VERSION(1, 8, 0)
4064 * If the page was not loaded (for example, via ssl_strict_certs), do
4065 * not attempt to get the webview's pixbuf. This prevents a CRITICAL
4066 * glib warning.
4068 if (wv && webkit_web_view_get_uri(wv))
4069 pb = webkit_web_view_try_get_favicon_pixbuf(wv, 0, 0);
4070 #else
4071 if (wv && webkit_web_view_get_uri(wv))
4072 pb = webkit_web_view_get_icon_pixbuf(wv);
4073 #endif
4074 if (pb) {
4075 xt_icon_from_pixbuf(t, pb);
4076 g_object_unref(pb);
4077 } else
4078 xt_icon_from_name(t, "text-html");
4079 #elif WEBKIT_CHECK_VERSION(1, 1, 18)
4080 /* download icon to cache dir */
4081 gchar *name_hash, file[PATH_MAX];
4082 struct stat sb;
4084 if (t->icon_request) {
4085 DNPRINTF(XT_D_DOWNLOAD, "%s: download in progress\n", __func__);
4086 return;
4089 /* check to see if we got the icon in cache */
4090 name_hash = g_compute_checksum_for_string(G_CHECKSUM_SHA256, uri, -1);
4091 snprintf(file, sizeof file, "%s" PS "%s.ico", cache_dir, name_hash);
4092 g_free(name_hash);
4094 if (!stat(file, &sb)) {
4095 if (sb.st_size > 0) {
4096 DNPRINTF(XT_D_DOWNLOAD, "%s: loading from cache %s\n",
4097 __func__, file);
4098 set_favicon_from_file(t, file);
4099 return;
4102 /* corrupt icon so trash it */
4103 DNPRINTF(XT_D_DOWNLOAD, "%s: corrupt icon %s\n",
4104 __func__, file);
4105 unlink(file);
4108 /* create download for icon */
4109 t->icon_request = webkit_network_request_new(uri);
4110 if (t->icon_request == NULL) {
4111 DNPRINTF(XT_D_DOWNLOAD, "%s: invalid uri %s\n",
4112 __func__, uri);
4113 return;
4116 t->icon_download = webkit_download_new(t->icon_request);
4117 if (t->icon_download == NULL)
4118 return;
4120 /* we have to free icon_dest_uri later */
4121 if ((t->icon_dest_uri = g_filename_to_uri(file, NULL, NULL)) == NULL)
4122 return;
4123 webkit_download_set_destination_uri(t->icon_download,
4124 t->icon_dest_uri);
4126 if (webkit_download_get_status(t->icon_download) ==
4127 WEBKIT_DOWNLOAD_STATUS_ERROR) {
4128 g_object_unref(t->icon_request);
4129 g_free(t->icon_dest_uri);
4130 t->icon_request = NULL;
4131 t->icon_dest_uri = NULL;
4132 return;
4135 g_signal_connect(G_OBJECT(t->icon_download), "notify::status",
4136 G_CALLBACK(favicon_download_status_changed_cb), t->wv);
4138 webkit_download_start(t->icon_download);
4139 #endif
4142 void
4143 notify_load_status_cb(WebKitWebView* wview, GParamSpec* pspec, struct tab *t)
4145 const gchar *uri = NULL;
4146 struct history *h, find;
4147 struct karg a;
4148 #if !GTK_CHECK_VERSION(3, 0, 0)
4149 gchar *text, *base;
4150 #endif
4152 DNPRINTF(XT_D_URL, "notify_load_status_cb: %d %s\n",
4153 webkit_web_view_get_load_status(wview),
4154 get_uri(t) ? get_uri(t) : "NOTHING");
4156 if (t == NULL) {
4157 show_oops(NULL, "notify_load_status_cb invalid parameters");
4158 return;
4161 switch (webkit_web_view_get_load_status(wview)) {
4162 case WEBKIT_LOAD_PROVISIONAL:
4163 /* 0 */
4164 abort_favicon_download(t);
4165 #if GTK_CHECK_VERSION(2, 20, 0)
4166 gtk_widget_show(t->spinner);
4167 gtk_spinner_start(GTK_SPINNER(t->spinner));
4168 #endif
4169 t->download_requested = 0;
4171 gtk_widget_set_sensitive(GTK_WIDGET(t->stop), TRUE);
4173 /* assume we are a new address */
4174 #if GTK_CHECK_VERSION(3, 0, 0)
4175 gtk_widget_set_name(t->uri_entry, XT_CSS_NORMAL);
4176 statusbar_modify_attr(t, XT_CSS_NORMAL);
4177 #else
4178 text = gdk_color_to_string(
4179 &t->default_style->text[GTK_STATE_NORMAL]);
4180 base = gdk_color_to_string(
4181 &t->default_style->base[GTK_STATE_NORMAL]);
4182 gtk_widget_modify_base(t->uri_entry, GTK_STATE_NORMAL,
4183 &t->default_style->base[GTK_STATE_NORMAL]);
4184 statusbar_modify_attr(t, text, base);
4185 g_free(text);
4186 g_free(base);
4187 #endif
4189 /* DOM is changing, unreference the previous focused element */
4190 #if WEBKIT_CHECK_VERSION(1, 5, 0)
4191 if (t->active)
4192 g_object_unref(t->active);
4193 t->active = NULL;
4194 if (t->active_text) {
4195 g_free(t->active_text);
4196 t->active_text = NULL;
4198 #endif
4200 /* take focus if we are visible */
4201 focus_webview(t);
4202 t->focus_wv = 1;
4204 marks_clear(t);
4205 #ifdef USE_THREAD
4206 /* kill color thread */
4207 t->thread = NULL;
4208 #endif
4209 break;
4211 case WEBKIT_LOAD_COMMITTED:
4212 /* 1 */
4213 uri = get_uri(t);
4214 if (uri == NULL)
4215 return;
4216 gtk_entry_set_text(GTK_ENTRY(t->uri_entry), uri);
4218 if (t->status) {
4219 g_free(t->status);
4220 t->status = NULL;
4222 set_status(t, "Loading: %s", (char *)uri);
4224 /* check if js white listing is enabled */
4225 if (enable_plugin_whitelist)
4226 check_and_set_pl(uri, t);
4227 if (enable_cookie_whitelist)
4228 check_and_set_cookie(uri, t);
4229 if (enable_js_whitelist)
4230 check_and_set_js(uri, t);
4232 if (t->styled)
4233 apply_style(t);
4236 /* we know enough to autosave the session */
4237 if (session_autosave) {
4238 a.s = NULL;
4239 save_tabs(t, &a);
4242 show_ca_status(t, uri);
4243 run_script(t, JS_HINTING);
4244 if (enable_autoscroll)
4245 run_script(t, JS_AUTOSCROLL);
4246 break;
4248 case WEBKIT_LOAD_FIRST_VISUALLY_NON_EMPTY_LAYOUT:
4249 /* 3 */
4250 if (color_visited_uris) {
4251 color_visited(t, color_visited_helper());
4253 /* This colors the links you middle-click (open in new
4254 * tab) in the current tab. */
4255 if (t->tab_id != gtk_notebook_get_current_page(notebook) &&
4256 (uri = get_uri(t)) != NULL)
4257 color_visited(get_current_tab(),
4258 g_strdup_printf("{'%s' : 'dummy'}", uri));
4260 break;
4262 case WEBKIT_LOAD_FINISHED:
4263 /* 2 */
4264 if ((uri = get_uri(t)) == NULL)
4265 return;
4267 if (!strncmp(uri, "http://", strlen("http://")) ||
4268 !strncmp(uri, "https://", strlen("https://")) ||
4269 !strncmp(uri, "file://", strlen("file://"))) {
4270 find.uri = (gchar *)uri;
4271 h = RB_FIND(history_list, &hl, &find);
4272 if (!h)
4273 insert_history_item(uri,
4274 get_title(t, FALSE), time(NULL));
4275 else
4276 h->time = time(NULL);
4279 if (statusbar_style == XT_STATUSBAR_URL)
4280 set_status(t, "%s", (char *)uri);
4281 else
4282 set_status(t, "%s", (char *)get_title(t, FALSE));
4283 gtk_widget_set_sensitive(GTK_WIDGET(t->stop), FALSE);
4284 #if GTK_CHECK_VERSION(2, 20, 0)
4285 gtk_spinner_stop(GTK_SPINNER(t->spinner));
4286 gtk_widget_hide(t->spinner);
4287 #endif
4288 break;
4290 #if WEBKIT_CHECK_VERSION(1, 1, 18)
4291 case WEBKIT_LOAD_FAILED:
4292 /* 4 */
4293 if (!t->download_requested) {
4294 gtk_label_set_text(GTK_LABEL(t->label),
4295 get_title(t, FALSE));
4296 gtk_label_set_text(GTK_LABEL(t->tab_elems.label),
4297 get_title(t, FALSE));
4298 set_status(t, "%s", (char *)get_title(t, FALSE));
4299 gtk_window_set_title(GTK_WINDOW(main_window),
4300 get_title(t, TRUE));
4301 } else {
4304 #endif
4305 default:
4306 #if GTK_CHECK_VERSION(2, 20, 0)
4307 gtk_spinner_stop(GTK_SPINNER(t->spinner));
4308 gtk_widget_hide(t->spinner);
4309 #endif
4310 gtk_widget_set_sensitive(GTK_WIDGET(t->stop), FALSE);
4311 break;
4314 gtk_widget_set_sensitive(GTK_WIDGET(t->backward),
4315 t->item || webkit_web_view_can_go_back(t->wv));
4317 gtk_widget_set_sensitive(GTK_WIDGET(t->forward),
4318 webkit_web_view_can_go_forward(t->wv));
4321 void
4322 notify_title_cb(WebKitWebView* wview, GParamSpec* pspec, struct tab *t)
4324 const gchar *title = NULL, *win_title = NULL;
4326 title = get_title(t, FALSE);
4327 win_title = get_title(t, TRUE);
4328 if (title) {
4329 gtk_label_set_text(GTK_LABEL(t->label), title);
4330 gtk_label_set_text(GTK_LABEL(t->tab_elems.label), title);
4333 if (win_title && t->tab_id == gtk_notebook_get_current_page(notebook))
4334 gtk_window_set_title(GTK_WINDOW(main_window), win_title);
4337 char *
4338 get_domain(const gchar *host)
4340 size_t x;
4341 char *p;
4343 /* handle silly domains like .co.uk */
4345 if ((x = strlen(host)) <= 6)
4346 return (g_strdup(host));
4348 if (host[x - 3] == '.' && host[x - 6] == '.') {
4349 x = x - 7;
4350 while (x > 0)
4351 if (host[x] != '.')
4352 x--;
4353 else
4354 return (g_strdup(&host[x + 1]));
4357 /* find first . */
4358 p = g_strrstr(host, ".");
4359 if (p == NULL)
4360 return (g_strdup(""));
4361 p--;
4362 while (p > host)
4363 if (*p != '.')
4364 p--;
4365 else
4366 return (g_strdup(p + 1));
4368 return (g_strdup(host));
4371 void
4372 js_autorun(struct tab *t)
4374 SoupURI *su = NULL;
4375 const gchar *uri;
4376 size_t got_default = 0, got_host = 0;
4377 struct stat sb;
4378 char deff[PATH_MAX], hostf[PATH_MAX];
4379 char *js = NULL, *jsat, *domain = NULL;
4380 FILE *deffile = NULL, *hostfile = NULL;
4382 if (enable_js_autorun == 0)
4383 return;
4385 uri = get_uri(t);
4386 if (uri &&
4387 !(g_str_has_prefix(uri, "http://") ||
4388 g_str_has_prefix(uri, "https://")))
4389 goto done;
4391 su = soup_uri_new(uri);
4392 if (su == NULL)
4393 goto done;
4394 if (!SOUP_URI_VALID_FOR_HTTP(su))
4395 goto done;
4397 DNPRINTF(XT_D_JS, "%s: host: %s domain: %s\n", __func__,
4398 su->host, domain);
4399 domain = get_domain(su->host);
4401 snprintf(deff, sizeof deff, "%s" PS "default.js", js_dir);
4402 if ((deffile = fopen(deff, "r")) != NULL) {
4403 if (fstat(fileno(deffile), &sb) == -1) {
4404 show_oops(t, "can't stat default JS file");
4405 goto done;
4407 got_default = sb.st_size;
4410 /* try host first followed by domain */
4411 snprintf(hostf, sizeof hostf, "%s" PS "%s.js", js_dir, su->host);
4412 DNPRINTF(XT_D_JS, "trying file: %s\n", hostf);
4413 if ((hostfile = fopen(hostf, "r")) == NULL) {
4414 snprintf(hostf, sizeof hostf, "%s" PS "%s.js", js_dir, domain);
4415 DNPRINTF(XT_D_JS, "trying file: %s\n", hostf);
4416 if ((hostfile = fopen(hostf, "r")) == NULL)
4417 goto nofile;
4419 DNPRINTF(XT_D_JS, "file: %s\n", hostf);
4420 if (fstat(fileno(hostfile), &sb) == -1) {
4421 show_oops(t, "can't stat %s JS file", hostf);
4422 goto done;
4424 got_host = sb.st_size;
4426 nofile:
4427 if (got_default + got_host == 0)
4428 goto done;
4430 js = g_malloc0(got_default + got_host + 1);
4431 jsat = js;
4433 if (got_default) {
4434 if (fread(js, got_default, 1, deffile) != 1) {
4435 show_oops(t, "default file read error");
4436 goto done;
4438 jsat = js + got_default;
4441 if (got_host) {
4442 if (fread(jsat, got_host, 1, hostfile) != 1) {
4443 show_oops(t, "host file read error");
4444 goto done;
4448 DNPRINTF(XT_D_JS, "%s: about to run script\n", __func__);
4449 run_script_locked(t, js);
4451 done:
4452 if (su)
4453 soup_uri_free(su);
4454 if (js)
4455 g_free(js);
4456 if (deffile)
4457 fclose(deffile);
4458 if (hostfile)
4459 fclose(hostfile);
4460 if (domain)
4461 g_free(domain);
4464 void
4465 webview_load_finished_cb(WebKitWebView *wv, WebKitWebFrame *wf, struct tab *t)
4467 /* autorun some js if enabled */
4468 js_autorun(t);
4470 input_autofocus(t);
4474 void
4475 webview_progress_changed_cb(WebKitWebView *wv, int progress, struct tab *t)
4477 gtk_entry_set_progress_fraction(GTK_ENTRY(t->sbe.uri),
4478 progress == 100 ? 0 : (double)progress / 100);
4479 gtk_entry_set_progress_fraction(GTK_ENTRY(t->uri_entry),
4480 progress == 100 ? 0 : (double)progress / 100);
4482 update_statusbar_position(NULL, NULL);
4486 strict_transport_rb_cmp(struct strict_transport *a, struct strict_transport *b)
4488 char *p1, *p2;
4489 int l1, l2;
4491 /* compare strings from the end */
4492 l1 = strlen(a->host);
4493 l2 = strlen(b->host);
4495 p1 = a->host + l1;
4496 p2 = b->host + l2;
4497 for (; *p1 == *p2 && p1 > a->host && p2 > b->host;
4498 p1--, p2--)
4502 * Check if we need to do pattern expansion,
4503 * or if we're just keeping the tree in order
4505 if (a->flags & XT_STS_FLAGS_EXPAND &&
4506 b->flags & XT_STS_FLAGS_INCLUDE_SUBDOMAINS) {
4507 /* Check if we're matching the
4508 * 'host.xyz' part in '*.host.xyz'
4510 if (p2 == b->host && (p1 == a->host || *(p1-1) == '.')) {
4511 return (0);
4515 if (p1 == a->host && p2 == b->host)
4516 return (0);
4517 if (p1 == a->host)
4518 return (1);
4519 if (p2 == b->host)
4520 return (-1);
4522 if (*p1 < *p2)
4523 return (-1);
4524 if (*p1 > *p2)
4525 return (1);
4527 return (0);
4529 RB_GENERATE(strict_transport_tree, strict_transport, entry,
4530 strict_transport_rb_cmp);
4533 strict_transport_add(const char *domain, time_t timeout, int subdomains)
4535 struct strict_transport *d, find;
4536 time_t now;
4537 FILE *f;
4539 if (enable_strict_transport == FALSE)
4540 return (0);
4542 DPRINTF("strict_transport_add(%s,%" PRIi64 ",%d)\n", domain,
4543 (uint64_t)timeout, subdomains);
4545 now = time(NULL);
4546 if (timeout < now)
4547 return (0);
4549 find.host = (char *)domain;
4550 find.flags = 0;
4551 d = RB_FIND(strict_transport_tree, &st_tree, &find);
4553 /* update flags */
4554 if (d) {
4555 /* check if update is needed */
4556 if (d->timeout == timeout &&
4557 (d->flags & XT_STS_FLAGS_INCLUDE_SUBDOMAINS) == subdomains)
4558 return (0);
4560 d->timeout = timeout;
4561 if (subdomains)
4562 d->flags |= XT_STS_FLAGS_INCLUDE_SUBDOMAINS;
4564 /* We're still initializing */
4565 if (strict_transport_file == NULL)
4566 return (0);
4568 if ((f = fopen(strict_transport_file, "w")) == NULL) {
4569 show_oops(NULL,
4570 "can't open strict-transport rules file");
4571 return (1);
4574 fprintf(f, "# Generated file - do not update unless you know "
4575 "what you're doing\n");
4576 RB_FOREACH(d, strict_transport_tree, &st_tree) {
4577 if (d->timeout < now)
4578 continue;
4579 fprintf(f, "%s\t%" PRIi64 "\t%d\n", d->host,
4580 (uint64_t)d->timeout,
4581 d->flags & XT_STS_FLAGS_INCLUDE_SUBDOMAINS);
4583 fclose(f);
4584 } else {
4585 d = g_malloc(sizeof *d);
4586 d->host= g_strdup(domain);
4587 d->timeout = timeout;
4588 if (subdomains)
4589 d->flags = XT_STS_FLAGS_INCLUDE_SUBDOMAINS;
4590 else
4591 d->flags = 0;
4592 RB_INSERT(strict_transport_tree, &st_tree, d);
4594 /* We're still initializing */
4595 if (strict_transport_file == NULL)
4596 return (0);
4598 if ((f = fopen(strict_transport_file, "a+")) == NULL) {
4599 show_oops(NULL,
4600 "can't open strict-transport rules file");
4601 return (1);
4604 fseek(f, 0, SEEK_END);
4605 fprintf(f,"%s\t%" PRIi64 "\t%d\n", d->host, (uint64_t)timeout,
4606 subdomains);
4607 fclose(f);
4609 return (0);
4613 strict_transport_check(const char *host)
4615 static struct strict_transport *d = NULL;
4616 struct strict_transport find;
4618 if (enable_strict_transport == FALSE)
4619 return (0);
4621 find.host = (char *)host;
4623 /* match for domains that include subdomains */
4624 find.flags = XT_STS_FLAGS_EXPAND;
4626 /* First, check if we're already at the right node */
4627 if (d != NULL && strict_transport_rb_cmp(&find, d) == 0) {
4628 return (1);
4631 d = RB_FIND(strict_transport_tree, &st_tree, &find);
4632 if (d != NULL)
4633 return (1);
4635 return (0);
4639 strict_transport_init()
4641 char file[PATH_MAX];
4642 char delim[3];
4643 char *rule;
4644 char *ptr;
4645 FILE *f;
4646 size_t len;
4647 time_t timeout, now;
4648 int subdomains;
4650 snprintf(file, sizeof file, "%s" PS "%s", work_dir, XT_STS_FILE);
4651 if ((f = fopen(file, "r")) == NULL) {
4652 strict_transport_file = g_strdup(file);
4653 return (0);
4656 delim[0] = '\\';
4657 delim[1] = '\\';
4658 delim[2] = '#';
4659 rule = NULL;
4660 now = time(NULL);
4662 for (;;) {
4663 if ((rule = fparseln(f, &len, NULL, delim, 0)) == NULL) {
4664 if (!feof(f) || ferror(f))
4665 goto corrupt_file;
4666 else
4667 break;
4670 /* get second entry */
4671 if ((ptr = strpbrk(rule, " \t")) == NULL)
4672 goto corrupt_file;
4674 *ptr++ = '\0';
4675 timeout = atoi(ptr);
4677 /* get third entry */
4678 if ((ptr = strpbrk(ptr, " \t")) == NULL)
4679 goto corrupt_file;
4681 ptr ++;
4682 subdomains = atoi(ptr);
4684 if (timeout > now)
4685 strict_transport_add(rule, timeout, subdomains);
4686 free(rule);
4689 fclose(f);
4690 strict_transport_file = g_strdup(file);
4691 return (0);
4693 corrupt_file:
4694 startpage_add("strict-transport rules file ('%s') is corrupt", file);
4695 if (rule)
4696 free(rule);
4697 fclose(f);
4698 return (1);
4702 force_https_check(const char *uri)
4704 struct domain *d = NULL;
4706 if (uri == NULL)
4707 return (0);
4709 if ((d = wl_find_uri(uri, &force_https)) == NULL)
4710 return (0);
4711 else
4712 return (1);
4715 void
4716 strict_transport_security_cb(SoupMessage *msg, gpointer data)
4718 SoupURI *uri;
4719 const char *sts;
4720 char *ptr;
4721 time_t timeout = 0;
4722 int subdomains = FALSE;
4724 if (msg == NULL)
4725 return;
4727 sts = soup_message_headers_get_one(msg->response_headers,
4728 "Strict-Transport-Security");
4729 uri = soup_message_get_uri(msg);
4731 if (sts == NULL || uri == NULL)
4732 return;
4734 if ((ptr = strcasestr(sts, "max-age="))) {
4735 ptr += strlen("max-age=");
4736 timeout = atoll(ptr);
4737 } else
4738 return; /* malformed header - max-age must be included */
4740 if ((ptr = strcasestr(sts, "includeSubDomains")))
4741 subdomains = TRUE;
4743 strict_transport_add(uri->host, timeout + time(NULL), subdomains);
4746 void
4747 session_rq_cb(SoupSession *s, SoupMessage *msg, SoupSocket *socket,
4748 gpointer data)
4750 SoupURI *dest;
4751 SoupURI *ref_uri;
4752 const char *ref;
4754 char *ref_suffix;
4755 char *dest_suffix;
4757 if (s == NULL || msg == NULL)
4758 return;
4760 if (enable_strict_transport) {
4761 soup_message_add_header_handler(msg, "finished",
4762 "Strict-Transport-Security",
4763 G_CALLBACK(strict_transport_security_cb), NULL);
4766 if (referer_mode == XT_REFERER_ALWAYS)
4767 return;
4769 /* Check if referer is set - and what the user requested for referers */
4770 ref = soup_message_headers_get_one(msg->request_headers, "Referer");
4771 if (ref) {
4772 DNPRINTF(XT_D_NAV, "session_rq_cb: Referer: %s\n", ref);
4773 switch (referer_mode) {
4774 case XT_REFERER_NEVER:
4775 DNPRINTF(XT_D_NAV, "session_rq_cb: removing referer\n");
4776 soup_message_headers_remove(msg->request_headers,
4777 "Referer");
4778 break;
4779 case XT_REFERER_SAME_DOMAIN:
4780 ref_uri = soup_uri_new(ref);
4781 dest = soup_message_get_uri(msg);
4783 ref_suffix = tld_get_suffix(ref_uri->host);
4784 dest_suffix = tld_get_suffix(dest->host);
4786 if (dest && ref_suffix && dest_suffix &&
4787 strcmp(ref_suffix, dest_suffix) != 0) {
4788 soup_message_headers_remove(msg->request_headers,
4789 "Referer");
4790 DNPRINTF(XT_D_NAV, "session_rq_cb: removing "
4791 "referer (not same domain) (suffixes: %s - %s)\n",
4792 ref_suffix, dest_suffix);
4794 soup_uri_free(ref_uri);
4795 break;
4796 case XT_REFERER_SAME_FQDN:
4797 ref_uri = soup_uri_new(ref);
4798 dest = soup_message_get_uri(msg);
4799 if (dest && strcmp(ref_uri->host, dest->host) != 0) {
4800 soup_message_headers_remove(msg->request_headers,
4801 "Referer");
4802 DNPRINTF(XT_D_NAV, "session_rq_cb: removing "
4803 "referer (not same fqdn) (should be %s)\n",
4804 dest->host);
4806 soup_uri_free(ref_uri);
4807 break;
4808 case XT_REFERER_CUSTOM:
4809 DNPRINTF(XT_D_NAV, "session_rq_cb: setting referer "
4810 "to %s\n", referer_custom);
4811 soup_message_headers_replace(msg->request_headers,
4812 "Referer", referer_custom);
4813 break;
4819 webview_npd_cb(WebKitWebView *wv, WebKitWebFrame *wf,
4820 WebKitNetworkRequest *request, WebKitWebNavigationAction *na,
4821 WebKitWebPolicyDecision *pd, struct tab *t)
4823 WebKitWebNavigationReason reason;
4824 struct user_agent ua_find, *ua;
4825 struct domain *d = NULL;
4826 char *uri;
4828 if (t == NULL) {
4829 show_oops(NULL, "webview_npd_cb invalid parameters");
4830 return (FALSE);
4833 DNPRINTF(XT_D_NAV, "webview_npd_cb: ctrl_click %d %s\n",
4834 t->ctrl_click,
4835 webkit_network_request_get_uri(request));
4837 uri = (char *)webkit_network_request_get_uri(request);
4839 /* clear t->item, except if we're switching to an about: page */
4840 if (t->item && !g_str_has_prefix(uri, "xxxt://")) {
4841 g_object_unref(t->item);
4842 t->item = NULL;
4845 if (!auto_load_images && t->load_images) {
4847 /* Disable autoloading of images, now that we're done loading
4848 * them. */
4849 g_object_set(G_OBJECT(t->settings),
4850 "auto-load-images", FALSE, (char *)NULL);
4851 webkit_web_view_set_settings(t->wv, t->settings);
4853 t->load_images = FALSE;
4856 /* If this is an xtp url, we don't load anything else. */
4857 if (parse_xtp_url(t, uri))
4858 return (TRUE);
4860 if (parse_custom_uri(t, uri))
4861 return (TRUE);
4863 if ((t->mode == XT_MODE_HINT && t->new_tab) || t->ctrl_click) {
4864 t->ctrl_click = 0;
4865 create_new_tab(uri, NULL, ctrl_click_focus, -1);
4866 webkit_web_policy_decision_ignore(pd);
4867 return (TRUE); /* we made the decission */
4870 /* Change user agent if more than one has been given. */
4871 if (!RB_EMPTY(&ua_list)) {
4872 ua_find.id = t->user_agent_id;
4874 if ((ua = RB_FIND(user_agent_list, &ua_list, &ua_find)) == NULL) {
4875 ua_find.id = 0;
4876 t->user_agent_id = 1;
4877 user_agent = RB_FIND(user_agent_list, &ua_list, &ua_find);
4878 } else {
4879 ++t->user_agent_id;
4880 user_agent = ua;
4883 g_free(t->user_agent);
4884 t->user_agent = g_strdup(user_agent->value);
4886 DNPRINTF(XT_D_NAV, "user-agent: %s\n", t->user_agent);
4888 g_object_set(G_OBJECT(t->settings),
4889 "user-agent", t->user_agent, (char *)NULL);
4891 webkit_web_view_set_settings(wv, t->settings);
4895 * This is a little hairy but it comes down to this:
4896 * when we run in whitelist mode we have to assist the browser in
4897 * opening the URL that it would have opened in a new tab.
4899 reason = webkit_web_navigation_action_get_reason(na);
4900 if (reason == WEBKIT_WEB_NAVIGATION_REASON_LINK_CLICKED) {
4901 set_normal_tab_meaning(t);
4902 if (enable_scripts == 0 && enable_cookie_whitelist == 1)
4903 if (uri && (d = wl_find_uri(uri, &js_wl)) == NULL)
4904 load_uri(t, uri);
4905 webkit_web_policy_decision_use(pd);
4906 return (TRUE); /* we made the decision */
4909 return (FALSE);
4912 void
4913 webview_rrs_cb(WebKitWebView *wv, WebKitWebFrame *wf, WebKitWebResource *res,
4914 WebKitNetworkRequest *request, WebKitNetworkResponse *response,
4915 struct tab *t)
4917 SoupMessage *msg = NULL;
4918 SoupURI *uri = NULL;
4919 struct http_accept ha_find, *ha = NULL;
4920 const char *accept = NULL;
4921 char *uri_s = NULL;
4923 msg = webkit_network_request_get_message(request);
4924 if (!msg) return;
4926 uri = soup_message_get_uri(msg);
4927 if (!uri)
4928 return;
4929 uri_s = soup_uri_to_string(uri, FALSE);
4931 if (strcmp(uri->scheme, SOUP_URI_SCHEME_HTTP) == 0) {
4932 if (strict_transport_check(uri->host) ||
4933 force_https_check(uri_s)) {
4934 DNPRINTF(XT_D_NAV, "webview_rrs_cb: force https for %s\n",
4935 uri->host);
4936 soup_uri_set_scheme(uri, SOUP_URI_SCHEME_HTTPS);
4940 if (do_not_track)
4941 soup_message_headers_append(msg->request_headers, "DNT", "1");
4943 /* Round-robin through HTTP Accept headers if any have been set */
4944 if (!RB_EMPTY(&ha_list)) {
4945 accept = soup_message_headers_get_list(msg->request_headers,
4946 "Accept");
4947 if (accept == NULL ||
4948 strncmp(accept, "text/html", strlen("text/html")))
4949 goto done;
4951 ha_find.id = t->http_accept_id;
4952 ha = RB_FIND(http_accept_list, &ha_list, &ha_find);
4953 if (ha == NULL) {
4954 ha_find.id = 0;
4955 t->http_accept_id = 1;
4956 http_accept = RB_FIND(http_accept_list, &ha_list,
4957 &ha_find);
4958 } else {
4959 ++t->http_accept_id;
4960 http_accept = ha;
4963 soup_message_headers_replace(msg->request_headers, "Accept",
4964 http_accept->value);
4966 done:
4967 if (uri_s)
4968 g_free(uri_s);
4971 WebKitWebView *
4972 webview_cwv_cb(WebKitWebView *wv, WebKitWebFrame *wf, struct tab *t)
4974 struct tab *tt;
4975 struct domain *d = NULL;
4976 const gchar *uri;
4977 WebKitWebView *webview = NULL;
4978 int x = 1;
4980 DNPRINTF(XT_D_NAV, "webview_cwv_cb: %s\n",
4981 webkit_web_view_get_uri(wv));
4983 if (tabless) {
4984 /* open in current tab */
4985 webview = t->wv;
4986 } else if (enable_scripts == 0 && enable_js_whitelist == 1) {
4987 uri = webkit_web_view_get_uri(wv);
4988 if (uri && (d = wl_find_uri(uri, &js_wl)) == NULL)
4989 return (NULL);
4991 if (t->ctrl_click) {
4992 x = ctrl_click_focus;
4993 t->ctrl_click = 0;
4995 tt = create_new_tab(NULL, NULL, x, -1);
4996 webview = tt->wv;
4997 } else if (enable_scripts == 1) {
4998 if (t->ctrl_click) {
4999 x = ctrl_click_focus;
5000 t->ctrl_click = 0;
5002 tt = create_new_tab(NULL, NULL, x, -1);
5003 webview = tt->wv;
5006 return (webview);
5009 gboolean
5010 webview_closewv_cb(WebKitWebView *wv, struct tab *t)
5012 const gchar *uri;
5013 struct domain *d = NULL;
5015 DNPRINTF(XT_D_NAV, "webview_close_cb: %d\n", t->tab_id);
5017 if (enable_scripts == 0 && enable_cookie_whitelist == 1) {
5018 uri = webkit_web_view_get_uri(wv);
5019 if (uri && (d = wl_find_uri(uri, &js_wl)) == NULL)
5020 return (FALSE);
5022 delete_tab(t);
5023 } else if (enable_scripts == 1)
5024 delete_tab(t);
5026 return (TRUE);
5030 webview_event_cb(GtkWidget *w, GdkEventButton *e, struct tab *t)
5032 /* we can not eat the event without throwing gtk off so defer it */
5034 /* catch middle click */
5035 if (e->type == GDK_BUTTON_RELEASE && e->button == 2) {
5036 t->ctrl_click = 1;
5037 goto done;
5040 /* catch ctrl click */
5041 if (e->type == GDK_BUTTON_RELEASE &&
5042 CLEAN(e->state) == GDK_CONTROL_MASK)
5043 t->ctrl_click = 1;
5044 else
5045 t->ctrl_click = 0;
5046 done:
5047 return (XT_CB_PASSTHROUGH);
5051 run_mimehandler(struct tab *t, char *mime_type, WebKitNetworkRequest *request)
5053 struct mime_type *m;
5054 char *sv[3];
5055 GError *gerr = NULL;
5057 m = find_mime_type(mime_type);
5058 if (m == NULL)
5059 return (1);
5060 if (m->mt_download)
5061 return (1);
5063 sv[0] = m->mt_action;
5064 sv[1] = (char *)webkit_network_request_get_uri(request);
5065 sv[2] = NULL;
5067 /* ignore donothing from example config */
5068 if (m->mt_action && !strcmp(m->mt_action, "donothing"))
5069 return (0);
5071 if (!g_spawn_async(NULL, sv, NULL, G_SPAWN_SEARCH_PATH, NULL, NULL,
5072 NULL, &gerr))
5073 show_oops(t, "%s: could not spawn process (%s)", __func__,
5074 gerr ? gerr->message : "N/A");
5075 return (0);
5078 char *
5079 get_mime_type(const char *uri)
5081 GFileInfo *fi;
5082 GFile *gf;
5083 const gchar *m;
5084 char *mime_type = NULL;
5085 char *file;
5087 if (uri == NULL) {
5088 show_oops(NULL, "%s: invalid parameters", __func__);
5089 return (NULL);
5092 if (g_str_has_prefix(uri, "file://"))
5093 file = g_filename_from_uri(uri, NULL, NULL);
5094 else
5095 file = g_strdup(uri);
5097 if (file == NULL)
5098 return (NULL);
5100 gf = g_file_new_for_path(file);
5101 fi = g_file_query_info(gf, G_FILE_ATTRIBUTE_STANDARD_CONTENT_TYPE, 0,
5102 NULL, NULL);
5103 if ((m = g_file_info_get_content_type(fi)) != NULL)
5104 mime_type = g_strdup(m);
5105 g_object_unref(fi);
5106 g_object_unref(gf);
5107 g_free(file);
5109 return (mime_type);
5113 run_download_mimehandler(char *mime_type, char *file)
5115 struct mime_type *m;
5116 char *sv[3];
5118 m = find_mime_type(mime_type);
5119 if (m == NULL)
5120 return (1);
5122 sv[0] = m->mt_action;
5123 sv[1] = file;
5124 sv[2] = NULL;
5125 if (!g_spawn_async(NULL, sv, NULL, G_SPAWN_SEARCH_PATH, NULL, NULL,
5126 NULL, NULL)) {
5127 show_oops(NULL, "%s: could not spawn process: %s %s", __func__,
5128 sv[0], sv[1]);
5129 return (1);
5131 return (0);
5134 void
5135 download_status_changed_cb(WebKitDownload *download, GParamSpec *spec,
5136 WebKitWebView *wv)
5138 WebKitDownloadStatus status;
5139 const char *uri;
5140 char *file = NULL;
5141 char *mime = NULL;
5143 if (download == NULL)
5144 return;
5145 status = webkit_download_get_status(download);
5146 if (status != WEBKIT_DOWNLOAD_STATUS_FINISHED)
5147 return;
5149 if (download_notifications)
5150 show_oops(NULL, "Download of '%s' finished",
5151 basename((char *)webkit_download_get_destination_uri(download)));
5152 uri = webkit_download_get_destination_uri(download);
5153 if (uri == NULL)
5154 return;
5155 mime = get_mime_type(uri);
5156 if (mime == NULL)
5157 return;
5159 if (g_str_has_prefix(uri, "file://"))
5160 file = g_filename_from_uri(uri, NULL, NULL);
5161 else
5162 file = g_strdup(uri);
5164 if (file == NULL)
5165 goto done;
5167 run_download_mimehandler((char *)mime, file);
5169 done:
5170 g_free(mime);
5174 webview_mimetype_cb(WebKitWebView *wv, WebKitWebFrame *frame,
5175 WebKitNetworkRequest *request, char *mime_type,
5176 WebKitWebPolicyDecision *decision, struct tab *t)
5178 if (t == NULL) {
5179 show_oops(NULL, "webview_mimetype_cb invalid parameters");
5180 return (FALSE);
5183 DNPRINTF(XT_D_DOWNLOAD, "webview_mimetype_cb: tab %d mime %s\n",
5184 t->tab_id, mime_type);
5186 if (run_mimehandler(t, mime_type, request) == 0) {
5187 webkit_web_policy_decision_ignore(decision);
5188 focus_webview(t);
5189 return (TRUE);
5192 if (webkit_web_view_can_show_mime_type(wv, mime_type) == FALSE) {
5193 webkit_web_policy_decision_download(decision);
5194 return (TRUE);
5197 return (FALSE);
5201 download_start(struct tab *t, struct download *d, int flag)
5203 WebKitNetworkRequest *req;
5204 struct stat sb;
5205 const gchar *suggested_name;
5206 gchar *filename = NULL;
5207 char *uri = NULL;
5208 char *path = NULL;
5209 int ret = TRUE;
5210 int i;
5212 if (d == NULL || t == NULL) {
5213 show_oops(NULL, "%s invalid parameters", __func__);
5214 return (FALSE);
5217 suggested_name = webkit_download_get_suggested_filename(d->download);
5218 if (suggested_name == NULL)
5219 return (FALSE); /* abort download */
5221 i = 0;
5222 do {
5223 if (filename) {
5224 g_free(filename);
5225 filename = NULL;
5227 if (i) {
5228 g_free(uri);
5229 uri = NULL;
5230 filename = g_strdup_printf("%d%s", i, suggested_name);
5232 #ifdef __MINGW32__
5233 /* XXX using urls doesn't work properly in windows? */
5234 uri = g_strdup_printf("%s\\%s", download_dir, i ?
5235 filename : suggested_name);
5236 #else
5237 path = g_strdup_printf("%s" PS "%s", download_dir, i ?
5238 filename : suggested_name);
5239 if ((uri = g_filename_to_uri(path, NULL, NULL)) == NULL)
5240 break; /* XXX */
5241 #endif
5242 i++;
5243 #ifdef __MINGW32__
5244 } while (!stat(uri, &sb));
5245 #else
5246 } while (!stat(path, &sb));
5247 #endif
5249 DNPRINTF(XT_D_DOWNLOAD, "%s: tab %d filename %s "
5250 "local %s\n", __func__, t->tab_id, filename, uri);
5252 /* if we're restarting the download, or starting
5253 * it after doing something else, we need to recreate
5254 * the download request.
5256 if (flag == XT_DL_RESTART) {
5257 req = webkit_network_request_new(webkit_download_get_uri(d->download));
5258 webkit_download_cancel(d->download);
5259 g_object_unref(d->download);
5260 d->download = webkit_download_new(req);
5263 webkit_download_set_destination_uri(d->download, uri);
5265 if (webkit_download_get_status(d->download) ==
5266 WEBKIT_DOWNLOAD_STATUS_ERROR) {
5267 show_oops(t, "%s: download failed to start", __func__);
5268 ret = FALSE;
5269 show_oops(t, "Download Failed");
5270 } else {
5271 /* connect "download first" mime handler */
5272 g_signal_connect(G_OBJECT(d->download), "notify::status",
5273 G_CALLBACK(download_status_changed_cb), NULL);
5275 /* get from history */
5276 g_object_ref(d->download);
5277 show_oops(t, "Download of '%s' started...",
5278 basename((char *)webkit_download_get_destination_uri(d->download)));
5281 if (flag != XT_DL_START)
5282 webkit_download_start(d->download);
5284 DNPRINTF(XT_D_DOWNLOAD, "download status : %d",
5285 webkit_download_get_status(d->download));
5287 /* sync other download manager tabs */
5288 update_download_tabs(NULL);
5290 if (uri)
5291 g_free(uri);
5292 if (path)
5293 g_free(path);
5294 if (filename)
5295 g_free(filename);
5297 return (ret);
5301 download_ask_cb(struct tab *t, GdkEventKey *e, gpointer data)
5303 struct download *d = data;
5305 /* unset mode */
5306 t->mode_cb = NULL;
5307 t->mode_cb_data = NULL;
5309 if (!e || !d) {
5310 e->keyval = GDK_Escape;
5311 return (XT_CB_PASSTHROUGH);
5314 DPRINTF("download_ask_cb: User pressed %c\n", e->keyval);
5315 if (e->keyval == 'y' || e->keyval == 'Y' || e->keyval == GDK_Return)
5316 /* We need to do a RESTART, because we're not calling from
5317 * webview_download_cb
5319 download_start(t, d, XT_DL_RESTART);
5321 /* for all other keyvals, we just let the download be */
5322 e->keyval = GDK_Escape;
5323 return (XT_CB_HANDLED);
5327 download_ask(struct tab *t, struct download *d)
5329 const gchar *suggested_name;
5331 suggested_name = webkit_download_get_suggested_filename(d->download);
5332 if (suggested_name == NULL)
5333 return (FALSE); /* abort download */
5335 show_oops(t, "download file %s [y/n] ?", suggested_name);
5336 t->mode_cb = download_ask_cb;
5337 t->mode_cb_data = d;
5339 return (TRUE);
5343 webview_download_cb(WebKitWebView *wv, WebKitDownload *wk_download,
5344 struct tab *t)
5346 const gchar *suggested_name;
5347 struct download *download_entry;
5348 int ret = TRUE;
5350 if (wk_download == NULL || t == NULL) {
5351 show_oops(NULL, "%s invalid parameters", __func__);
5352 return (FALSE);
5355 suggested_name = webkit_download_get_suggested_filename(wk_download);
5356 if (suggested_name == NULL)
5357 return (FALSE); /* abort download */
5359 download_entry = g_malloc(sizeof(struct download));
5360 download_entry->download = wk_download;
5361 download_entry->tab = t;
5362 download_entry->id = next_download_id++;
5363 RB_INSERT(download_list, &downloads, download_entry);
5364 t->download_requested = 1;
5366 if (download_mode == XT_DM_START)
5367 ret = download_start(t, download_entry, XT_DL_START);
5368 else if (download_mode == XT_DM_ASK)
5369 ret = download_ask(t, download_entry);
5370 else if (download_mode == XT_DM_ADD)
5371 show_oops(t, "added %s to download manager",
5372 suggested_name);
5374 /* sync other download manager tabs */
5375 update_download_tabs(NULL);
5378 * NOTE: never redirect/render the current tab before this
5379 * function returns. This will cause the download to never start.
5381 return (ret); /* start download */
5384 void
5385 webview_hover_cb(WebKitWebView *wv, gchar *title, gchar *uri, struct tab *t)
5387 DNPRINTF(XT_D_KEY, "webview_hover_cb: %s %s\n", title, uri);
5389 if (t == NULL) {
5390 show_oops(NULL, "webview_hover_cb");
5391 return;
5394 if (uri)
5395 set_status(t, "Link: %s", uri);
5396 else {
5397 if (statusbar_style == XT_STATUSBAR_URL) {
5398 const gchar *page_uri;
5400 if ((page_uri = get_uri(t)) != NULL)
5401 set_status(t, "%s", page_uri);
5402 } else
5403 set_status(t, "%s", (char *)get_title(t, FALSE));
5408 mark(struct tab *t, struct karg *arg)
5410 char mark;
5411 int index;
5412 double pos;
5414 mark = arg->s[1];
5415 if ((index = marktoindex(mark)) == -1)
5416 return (-1);
5418 if (arg->i == XT_MARK_SET)
5419 t->mark[index] = gtk_adjustment_get_value(t->adjust_v);
5420 else if (arg->i == XT_MARK_GOTO) {
5421 if (t->mark[index] == XT_INVALID_MARK) {
5422 show_oops(t, "mark '%c' does not exist", mark);
5423 return (-1);
5425 /* XXX t->mark[index] can be bigger than the maximum if ajax or
5426 something changes the document size */
5427 pos = gtk_adjustment_get_value(t->adjust_v);
5428 gtk_adjustment_set_value(t->adjust_v, t->mark[index]);
5429 t->mark[marktoindex('\'')] = pos;
5432 return (0);
5435 void
5436 marks_clear(struct tab *t)
5438 int i;
5440 for (i = 0; i < LENGTH(t->mark); i++)
5441 t->mark[i] = XT_INVALID_MARK;
5445 qmarks_load(void)
5447 char file[PATH_MAX];
5448 char *line = NULL, *p;
5449 int index, i;
5450 FILE *f;
5451 size_t linelen;
5453 snprintf(file, sizeof file, "%s" PS "%s", work_dir, XT_QMARKS_FILE);
5454 if ((f = fopen(file, "r+")) == NULL) {
5455 show_oops(NULL, "Can't open quickmarks file: %s", strerror(errno));
5456 return (1);
5459 for (i = 1; ; i++) {
5460 if ((line = fparseln(f, &linelen, NULL, NULL, 0)) == NULL)
5461 break;
5462 if (strlen(line) == 0 || line[0] == '#') {
5463 free(line);
5464 line = NULL;
5465 continue;
5468 p = strtok(line, " \t");
5470 if (p == NULL || strlen(p) != 1 ||
5471 (index = qmarktoindex(*p)) == -1) {
5472 warnx("corrupt quickmarks file, line %d", i);
5473 break;
5476 p = strtok(NULL, " \t");
5477 if (qmarks[index] != NULL)
5478 g_free(qmarks[index]);
5479 qmarks[index] = g_strdup(p);
5482 fclose(f);
5484 return (0);
5488 qmarks_save(void)
5490 char file[PATH_MAX];
5491 int i;
5492 FILE *f;
5494 snprintf(file, sizeof file, "%s" PS "%s", work_dir, XT_QMARKS_FILE);
5495 if ((f = fopen(file, "r+")) == NULL) {
5496 show_oops(NULL, "Can't open quickmarks file: %s", strerror(errno));
5497 return (1);
5500 for (i = 0; i < XT_NOQMARKS; i++)
5501 if (qmarks[i] != NULL)
5502 fprintf(f, "%c %s\n", indextoqmark(i), qmarks[i]);
5504 fclose(f);
5506 return (0);
5510 qmark(struct tab *t, struct karg *arg)
5512 char mark;
5513 int index;
5515 mark = arg->s[strlen(arg->s)-1];
5516 index = qmarktoindex(mark);
5517 if (index == -1)
5518 return (-1);
5520 switch (arg->i) {
5521 case XT_QMARK_SET:
5522 if (qmarks[index] != NULL) {
5523 g_free(qmarks[index]);
5524 qmarks[index] = NULL;
5527 qmarks_load(); /* sync if multiple instances */
5528 qmarks[index] = g_strdup(get_uri(t));
5529 qmarks_save();
5530 break;
5531 case XT_QMARK_OPEN:
5532 if (qmarks[index] != NULL)
5533 load_uri(t, qmarks[index]);
5534 else {
5535 show_oops(t, "quickmark \"%c\" does not exist",
5536 mark);
5537 return (-1);
5539 break;
5540 case XT_QMARK_TAB:
5541 if (qmarks[index] != NULL)
5542 create_new_tab(qmarks[index], NULL, 1, -1);
5543 else {
5544 show_oops(t, "quickmark \"%c\" does not exist",
5545 mark);
5546 return (-1);
5548 break;
5551 return (0);
5555 go_up(struct tab *t, struct karg *args)
5557 int levels;
5558 int lastidx;
5559 char *uri;
5560 char *tmp;
5561 char *p;
5563 if (args->i == XT_GO_UP_ROOT)
5564 levels = XT_GO_UP_ROOT;
5565 else if ((levels = atoi(args->s)) == 0)
5566 levels = 1;
5568 uri = g_strdup(get_uri(t));
5569 if (uri == NULL)
5570 return (1);
5572 if ((tmp = strstr(uri, XT_PROTO_DELIM)) == NULL)
5573 return (1);
5575 tmp += strlen(XT_PROTO_DELIM);
5577 /* it makes no sense to strip the last slash from ".../dir/", skip it */
5578 lastidx = strlen(tmp) - 1;
5579 if (lastidx > 0) {
5580 if (tmp[lastidx] == '/')
5581 tmp[lastidx] = '\0';
5584 while (levels--) {
5585 p = strrchr(tmp, '/');
5586 if (p == tmp) { /* Are we at the root of a file://-path? */
5587 p[1] = '\0';
5588 break;
5589 } else if (p != NULL)
5590 *p = '\0';
5591 else
5592 break;
5595 load_uri(t, uri);
5596 g_free(uri);
5598 return (0);
5602 gototab(struct tab *t, struct karg *args)
5604 int tab;
5605 struct karg arg = {0, NULL, -1};
5607 tab = atoi(args->s);
5609 if (args->i == 0)
5610 arg.i = XT_TAB_NEXT;
5611 else
5612 arg.i = args->i;
5614 arg.precount = tab;
5616 movetab(t, &arg);
5618 return (0);
5622 zoom_amount(struct tab *t, struct karg *arg)
5624 struct karg narg = {0, NULL, -1};
5626 narg.i = atoi(arg->s);
5627 resizetab(t, &narg);
5629 return (0);
5633 flip_colon(struct tab *t, struct karg *arg)
5635 struct karg narg = {0, NULL, -1};
5636 char *p;
5638 if (t == NULL || arg == NULL)
5639 return (1);
5641 p = strstr(arg->s, ":");
5642 if (p == NULL)
5643 return (1);
5644 *p = '\0';
5646 narg.i = ':';
5647 narg.s = arg->s;
5648 command(t, &narg);
5650 return (0);
5653 /* buffer commands receive the regex that triggered them in arg.s */
5654 char bcmd[XT_BUFCMD_SZ];
5655 struct buffercmd {
5656 char *regex;
5657 int precount;
5658 #define XT_PRE_NO (0)
5659 #define XT_PRE_YES (1)
5660 #define XT_PRE_MAYBE (2)
5661 char *cmd;
5662 int (*func)(struct tab *, struct karg *);
5663 int arg;
5664 regex_t cregex;
5665 } buffercmds[] = {
5666 { "^[0-9]*gu$", XT_PRE_MAYBE, "gu", go_up, 0 },
5667 { "^gU$", XT_PRE_NO, "gU", go_up, XT_GO_UP_ROOT },
5668 { "^gg$", XT_PRE_NO, "gg", move, XT_MOVE_TOP },
5669 { "^gG$", XT_PRE_NO, "gG", move, XT_MOVE_BOTTOM },
5670 { "^[0-9]+%$", XT_PRE_YES, "%", move, XT_MOVE_PERCENT },
5671 { "^zz$", XT_PRE_NO, "zz", move, XT_MOVE_CENTER },
5672 { "^gh$", XT_PRE_NO, "gh", go_home, 0 },
5673 { "^m[a-zA-Z0-9]$", XT_PRE_NO, "m", mark, XT_MARK_SET },
5674 { "^['][a-zA-Z0-9']$", XT_PRE_NO, "'", mark, XT_MARK_GOTO },
5675 { "^[0-9]+t$", XT_PRE_YES, "t", gototab, 0 },
5676 { "^g0$", XT_PRE_YES, "g0", movetab, XT_TAB_FIRST },
5677 { "^g[$]$", XT_PRE_YES, "g$", movetab, XT_TAB_LAST },
5678 { "^[0-9]*gt$", XT_PRE_YES, "t", movetab, XT_TAB_NEXT },
5679 { "^[0-9]*gT$", XT_PRE_YES, "T", movetab, XT_TAB_PREV },
5680 { "^M[a-zA-Z0-9]$", XT_PRE_NO, "M", qmark, XT_QMARK_SET },
5681 { "^go[a-zA-Z0-9]$", XT_PRE_NO, "go", qmark, XT_QMARK_OPEN },
5682 { "^gn[a-zA-Z0-9]$", XT_PRE_NO, "gn", qmark, XT_QMARK_TAB },
5683 { "^ZR$", XT_PRE_NO, "ZR", restart, 0 },
5684 { "^ZZ$", XT_PRE_NO, "ZZ", quit, 0 },
5685 { "^zi$", XT_PRE_NO, "zi", resizetab, XT_ZOOM_IN },
5686 { "^zo$", XT_PRE_NO, "zo", resizetab, XT_ZOOM_OUT },
5687 { "^z0$", XT_PRE_NO, "z0", resizetab, XT_ZOOM_NORMAL },
5688 { "^[0-9]+Z$", XT_PRE_YES, "Z", zoom_amount, 0 },
5689 { "^[0-9]+:$", XT_PRE_YES, ":", flip_colon, 0 },
5692 void
5693 buffercmd_init(void)
5695 int i;
5697 for (i = 0; i < LENGTH(buffercmds); i++)
5698 if (regcomp(&buffercmds[i].cregex, buffercmds[i].regex,
5699 REG_EXTENDED | REG_NOSUB))
5700 startpage_add("invalid buffercmd regex %s",
5701 buffercmds[i].regex);
5704 void
5705 buffercmd_abort(struct tab *t)
5707 int i;
5709 if (t == NULL)
5710 return;
5712 DNPRINTF(XT_D_BUFFERCMD, "%s: clearing buffer\n", __func__);
5714 for (i = 0; i < LENGTH(bcmd); i++)
5715 bcmd[i] = '\0';
5717 cmd_prefix = 0; /* clear prefix for non-buffer commands */
5718 gtk_label_set_text(GTK_LABEL(t->sbe.buffercmd), bcmd);
5721 void
5722 buffercmd_execute(struct tab *t, struct buffercmd *cmd)
5724 struct karg arg = {0, NULL, -1};
5726 arg.i = cmd->arg;
5727 arg.s = g_strdup(bcmd);
5729 DNPRINTF(XT_D_BUFFERCMD, "buffercmd_execute: buffer \"%s\" "
5730 "matches regex \"%s\", executing\n", bcmd, cmd->regex);
5731 cmd->func(t, &arg);
5733 if (arg.s)
5734 g_free(arg.s);
5736 buffercmd_abort(t);
5739 gboolean
5740 buffercmd_addkey(struct tab *t, guint keyval)
5742 int i, c, match ;
5743 char s[XT_BUFCMD_SZ];
5745 if (gtk_widget_get_visible(GTK_WIDGET(t->buffers))) {
5746 buffercmd_abort(t);
5747 return (XT_CB_PASSTHROUGH);
5750 if (keyval == GDK_Escape) {
5751 buffercmd_abort(t);
5752 return (XT_CB_HANDLED);
5755 /* key with modifier or non-ascii character */
5756 if (!isascii(keyval)) {
5758 * XXX this looks wrong but fixes some sites like
5759 * http://www.seslisozluk.com/
5760 * that eat a shift or ctrl and end putting default focus in js
5761 * instead of ignoring the keystroke
5762 * so instead of return (XT_CB_PASSTHROUGH); eat the key
5764 return (XT_CB_HANDLED);
5767 DNPRINTF(XT_D_BUFFERCMD, "buffercmd_addkey: adding key \"%c\" "
5768 "to buffer \"%s\"\n", keyval, bcmd);
5770 for (i = 0; i < LENGTH(bcmd); i++)
5771 if (bcmd[i] == '\0') {
5772 bcmd[i] = keyval;
5773 break;
5776 /* buffer full, ignore input */
5777 if (i >= LENGTH(bcmd) -1) {
5778 DNPRINTF(XT_D_BUFFERCMD, "buffercmd_addkey: buffer full\n");
5779 buffercmd_abort(t);
5780 return (XT_CB_HANDLED);
5783 gtk_label_set_text(GTK_LABEL(t->sbe.buffercmd), bcmd);
5785 /* find exact match */
5786 for (i = 0; i < LENGTH(buffercmds); i++)
5787 if (regexec(&buffercmds[i].cregex, bcmd,
5788 (size_t) 0, NULL, 0) == 0) {
5789 buffercmd_execute(t, &buffercmds[i]);
5790 goto done;
5793 /* find non exact matches to see if we need to abort ot not */
5794 for (i = 0, match = 0; i < LENGTH(buffercmds); i++) {
5795 DNPRINTF(XT_D_BUFFERCMD, "trying: %s\n", bcmd);
5796 c = -1;
5797 s[0] = '\0';
5798 if (buffercmds[i].precount == XT_PRE_MAYBE) {
5799 if (isdigit(bcmd[0])) {
5800 if (sscanf(bcmd, "%d%s", &c, s) == 0)
5801 continue;
5802 } else {
5803 c = 0;
5804 if (sscanf(bcmd, "%s", s) == 0)
5805 continue;
5807 } else if (buffercmds[i].precount == XT_PRE_YES) {
5808 if (sscanf(bcmd, "%d%s", &c, s) == 0)
5809 continue;
5810 } else {
5811 if (sscanf(bcmd, "%s", s) == 0)
5812 continue;
5814 if (c == -1 && buffercmds[i].precount)
5815 continue;
5816 if (!strncmp(s, buffercmds[i].cmd, strlen(s)))
5817 match++;
5819 DNPRINTF(XT_D_BUFFERCMD, "got[%d] %d <%s>: %d %s\n",
5820 i, match, buffercmds[i].cmd, c, s);
5822 if (match == 0) {
5823 DNPRINTF(XT_D_BUFFERCMD, "aborting: %s\n", bcmd);
5824 buffercmd_abort(t);
5827 done:
5828 return (XT_CB_HANDLED);
5832 * XXX we were seeing a bunch of focus issues with the toplevel
5833 * main_window losing its is-active and has-toplevel-focus properties.
5834 * This is the most correct and portable solution we could come up with
5835 * without relying on calling internal GTK functions (which we
5836 * couldn't link to in Linux).
5838 void
5839 fake_focus_in(GtkWidget *w)
5841 if (fevent == NULL) {
5842 fevent = gdk_event_new(GDK_FOCUS_CHANGE);
5843 fevent->focus_change.window =
5844 gtk_widget_get_window(main_window);
5845 fevent->focus_change.type = GDK_FOCUS_CHANGE;
5846 fevent->focus_change.in = TRUE;
5848 gtk_widget_send_focus_change(main_window, fevent);
5851 gboolean
5852 handle_keypress(struct tab *t, GdkEventKey *e, int entry)
5854 struct karg args;
5855 struct key_binding *k;
5858 * This sometimes gets randomly unset for whatever reason in GTK3.
5859 * If we're handling a keypress, the main window's is-active propery
5860 * *must* be true, or else many things will break.
5862 #if GTK_CHECK_VERSION(3, 0, 0)
5863 fake_focus_in(main_window);
5864 #endif
5866 /* handle keybindings if buffercmd is empty.
5867 if not empty, allow commands like C-n */
5868 if (bcmd[0] == '\0' || ((e->state & (CTRL | MOD1)) != 0))
5869 TAILQ_FOREACH(k, &kbl, entry)
5870 if (e->keyval == k->key
5871 && (entry ? k->use_in_entry : 1)) {
5872 /* when we are edditing eat ctrl/mod keys */
5873 if (edit_mode == XT_EM_VI &&
5874 t->mode == XT_MODE_INSERT &&
5875 (e->state & CTRL || e->state & MOD1))
5876 return (XT_CB_PASSTHROUGH);
5878 if (k->mask == 0) {
5879 if ((e->state & (CTRL | MOD1)) == 0)
5880 goto runcmd;
5881 } else if ((e->state & k->mask) == k->mask) {
5882 goto runcmd;
5886 if (!entry && ((e->state & (CTRL | MOD1)) == 0))
5887 return (buffercmd_addkey(t, e->keyval));
5889 return (XT_CB_PASSTHROUGH);
5891 runcmd:
5892 if (k->cmd[0] == ':') {
5893 args.i = ':';
5894 args.s = &k->cmd[1];
5895 return (command(t, &args));
5896 } else
5897 return (cmd_execute(t, k->cmd));
5901 wv_keypress_cb(GtkEntry *w, GdkEventKey *e, struct tab *t)
5903 char s[2];
5905 /* don't use w directly; use t->whatever instead */
5907 if (t == NULL) {
5908 show_oops(NULL, "wv_keypress_cb");
5909 return (XT_CB_PASSTHROUGH);
5912 hide_oops(t);
5914 if (t->mode_cb)
5915 return (t->mode_cb(t, e, t->mode_cb_data));
5917 DNPRINTF(XT_D_KEY, "wv_keypress_cb: mode %d keyval 0x%x mask "
5918 "0x%x tab %d\n", t->mode, e->keyval, e->state, t->tab_id);
5920 /* Hide buffers, if they are visible, with escape. */
5921 if (gtk_widget_get_visible(GTK_WIDGET(t->buffers)) &&
5922 CLEAN(e->state) == 0 && e->keyval == GDK_Escape) {
5923 gtk_widget_grab_focus(GTK_WIDGET(t->wv));
5924 hide_buffers(t);
5925 return (XT_CB_HANDLED);
5928 if (t->mode == XT_MODE_HINT)
5929 return (XT_CB_HANDLED);
5931 if ((CLEAN(e->state) == 0 && e->keyval == GDK_Tab) ||
5932 (CLEAN(e->state) == SHFT && e->keyval == GDK_Tab))
5933 /* something focussy is about to happen */
5934 return (XT_CB_PASSTHROUGH);
5936 /* check if we are some sort of text input thing in the dom */
5937 input_check_mode(t);
5939 if (t->mode == XT_MODE_HINT) {
5940 /* XXX make sure cmd entry is enabled */
5941 return (XT_CB_HANDLED);
5942 } else if (t->mode == XT_MODE_PASSTHROUGH) {
5943 if (CLEAN(e->state) == 0 && e->keyval == GDK_Escape)
5944 t->mode = XT_MODE_COMMAND;
5945 return (XT_CB_PASSTHROUGH);
5946 } else if (t->mode == XT_MODE_COMMAND) {
5947 /* prefix input */
5948 snprintf(s, sizeof s, "%c", e->keyval);
5949 if (CLEAN(e->state) == 0 && isdigit(s[0]))
5950 cmd_prefix = 10 * cmd_prefix + atoi(s);
5951 return (handle_keypress(t, e, 0));
5952 } else {
5953 /* insert mode */
5954 return (handle_keypress(t, e, 1));
5957 /* NOTREACHED */
5958 return (XT_CB_PASSTHROUGH);
5961 gboolean
5962 hint_continue(struct tab *t)
5964 const gchar *c = gtk_entry_get_text(GTK_ENTRY(t->cmd));
5965 char *s;
5966 const gchar *errstr = NULL;
5967 gboolean rv = TRUE;
5968 int i;
5970 if (!(c[0] == '.' || c[0] == ','))
5971 goto done;
5972 if (strlen(c) == 1) {
5973 /* XXX should not happen */
5974 rv = TRUE;
5975 goto done;
5978 if (isdigit(c[1])) {
5979 /* numeric input */
5980 i = strtonum(&c[1], 1, 4096, &errstr);
5981 if (errstr) {
5982 show_oops(t, "invalid numerical hint %s", &c[1]);
5983 goto done;
5985 s = g_strdup_printf("hints.updateHints(%d);", i);
5986 run_script(t, s);
5987 g_free(s);
5988 } else {
5989 /* alphanumeric input */
5990 s = g_strdup_printf("hints.createHints('%s', '%c');",
5991 &c[1], c[0] == '.' ? 'f' : 'F');
5992 run_script(t, s);
5993 g_free(s);
5996 rv = FALSE;
5997 done:
5998 return (rv);
6001 gboolean
6002 search_continue(struct tab *t)
6004 const gchar *c = gtk_entry_get_text(GTK_ENTRY(t->cmd));
6005 gboolean rv = FALSE;
6007 if (c[0] == ':' || c[0] == '.' || c[0] == ',')
6008 goto done;
6009 if (strlen(c) == 1) {
6010 webkit_web_view_unmark_text_matches(t->wv);
6011 goto done;
6014 if (c[0] == '/')
6015 t->search_forward = TRUE;
6016 else if (c[0] == '?')
6017 t->search_forward = FALSE;
6018 else
6019 goto done;
6021 rv = TRUE;
6022 done:
6023 return (rv);
6026 gboolean
6027 search_cb(struct tab *t)
6029 const gchar *c = gtk_entry_get_text(GTK_ENTRY(t->cmd));
6030 #if !GTK_CHECK_VERSION(3, 0, 0)
6031 GdkColor color;
6032 #endif
6034 if (search_continue(t) == FALSE)
6035 goto done;
6037 /* search */
6038 if (webkit_web_view_search_text(t->wv, &c[1], FALSE, t->search_forward,
6039 TRUE) == FALSE) {
6040 /* not found, mark red */
6041 #if GTK_CHECK_VERSION(3, 0, 0)
6042 gtk_widget_set_name(t->cmd, XT_CSS_RED);
6043 #else
6044 gdk_color_parse(XT_COLOR_RED, &color);
6045 gtk_widget_modify_base(t->cmd, GTK_STATE_NORMAL, &color);
6046 #endif
6047 /* unmark and remove selection */
6048 webkit_web_view_unmark_text_matches(t->wv);
6049 /* my kingdom for a way to unselect text in webview */
6050 } else {
6051 /* found, highlight all */
6052 webkit_web_view_unmark_text_matches(t->wv);
6053 webkit_web_view_mark_text_matches(t->wv, &c[1], FALSE, 0);
6054 webkit_web_view_set_highlight_text_matches(t->wv, TRUE);
6055 #if GTK_CHECK_VERSION(3, 0, 0)
6056 gtk_widget_set_name(t->cmd, XT_CSS_NORMAL);
6057 #else
6058 gtk_widget_modify_base(t->cmd, GTK_STATE_NORMAL,
6059 &t->default_style->base[GTK_STATE_NORMAL]);
6060 #endif
6062 done:
6063 t->search_id = 0;
6064 return (FALSE);
6068 cmd_keyrelease_cb(GtkEntry *w, GdkEventKey *e, struct tab *t)
6070 const gchar *c = gtk_entry_get_text(w);
6072 if (t == NULL) {
6073 show_oops(NULL, "cmd_keyrelease_cb invalid parameters");
6074 return (XT_CB_PASSTHROUGH);
6077 DNPRINTF(XT_D_CMD, "cmd_keyrelease_cb: keyval 0x%x mask 0x%x tab %d\n",
6078 e->keyval, e->state, t->tab_id);
6080 /* hinting */
6081 if (!(e->keyval == GDK_Tab || e->keyval == GDK_ISO_Left_Tab)) {
6082 if (hint_continue(t) == FALSE)
6083 goto done;
6086 /* search */
6087 if (search_continue(t) == FALSE)
6088 goto done;
6090 /* if search length is > 4 then no longer play timeout games */
6091 if (strlen(c) > 4) {
6092 if (t->search_id) {
6093 g_source_remove(t->search_id);
6094 t->search_id = 0;
6096 search_cb(t);
6097 goto done;
6100 /* reestablish a new timer if the user types fast */
6101 if (t->search_id)
6102 g_source_remove(t->search_id);
6103 t->search_id = g_timeout_add(250, (GSourceFunc)search_cb, (gpointer)t);
6105 done:
6106 return (XT_CB_PASSTHROUGH);
6109 gboolean
6110 match_uri(const gchar *uri, const gchar *key) {
6111 gchar *voffset;
6112 size_t len;
6113 gboolean match = FALSE;
6115 len = strlen(key);
6117 if (!strncmp(key, uri, len))
6118 match = TRUE;
6119 else {
6120 voffset = strstr(uri, "/") + 2;
6121 if (!strncmp(key, voffset, len))
6122 match = TRUE;
6123 else if (g_str_has_prefix(voffset, "www.")) {
6124 voffset = voffset + strlen("www.");
6125 if (!strncmp(key, voffset, len))
6126 match = TRUE;
6130 return (match);
6133 gboolean
6134 match_session(const gchar *name, const gchar *key) {
6135 char *sub;
6137 sub = strcasestr(name, key);
6139 return sub == name;
6142 void
6143 cmd_getlist(int id, char *key)
6145 int i, dep, c = 0;
6146 struct history *h;
6147 struct session *s;
6149 if (id >= 0) {
6150 if (cmds[id].type & XT_URLARG) {
6151 RB_FOREACH_REVERSE(h, history_list, &hl)
6152 if (match_uri(h->uri, key)) {
6153 cmd_status.list[c] = (char *)h->uri;
6154 if (++c > 255)
6155 break;
6157 cmd_status.len = c;
6158 return;
6159 } else if (cmds[id].type & XT_SESSARG) {
6160 TAILQ_FOREACH(s, &sessions, entry)
6161 if (match_session(s->name, key)) {
6162 cmd_status.list[c] = (char *)s->name;
6163 if (++c > 255)
6164 break;
6166 cmd_status.len = c;
6167 return;
6168 } else if (cmds[id].type & XT_SETARG) {
6169 for (i = 0; i < get_settings_size(); i++)
6170 if (!strncmp(key, get_setting_name(i),
6171 strlen(key)))
6172 cmd_status.list[c++] =
6173 get_setting_name(i);
6174 cmd_status.len = c;
6175 return;
6179 dep = (id == -1) ? 0 : cmds[id].level + 1;
6181 for (i = id + 1; i < LENGTH(cmds); i++) {
6182 if (cmds[i].level < dep)
6183 break;
6184 if (cmds[i].level == dep && !strncmp(key, cmds[i].cmd,
6185 strlen(key)) && !isdigit(cmds[i].cmd[0]))
6186 cmd_status.list[c++] = cmds[i].cmd;
6190 cmd_status.len = c;
6193 char *
6194 cmd_getnext(int dir)
6196 cmd_status.index += dir;
6198 if (cmd_status.index < 0)
6199 cmd_status.index = cmd_status.len - 1;
6200 else if (cmd_status.index >= cmd_status.len)
6201 cmd_status.index = 0;
6203 return cmd_status.list[cmd_status.index];
6207 cmd_tokenize(char *s, char *tokens[])
6209 int i = 0;
6210 char *tok, *last = NULL;
6211 size_t len = strlen(s);
6212 bool blank;
6214 blank = len == 0 || (len > 0 && s[len - 1] == ' ');
6215 for (tok = strtok_r(s, " ", &last); tok && i < 3;
6216 tok = strtok_r(NULL, " ", &last), i++)
6217 tokens[i] = tok;
6219 if (blank && i < 3)
6220 tokens[i++] = "";
6222 return (i);
6225 void
6226 cmd_complete(struct tab *t, char *str, int dir)
6228 GtkEntry *w = GTK_ENTRY(t->cmd);
6229 int i, j, levels, c = 0, dep = 0, parent = -1;
6230 int matchcount = 0;
6231 char *tok, *match, *s = g_strdup(str);
6232 char *tokens[3];
6233 char res[XT_MAX_URL_LENGTH + 32] = ":";
6234 char *sc = s;
6236 DNPRINTF(XT_D_CMD, "%s: complete %s\n", __func__, str);
6238 /* copy prefix*/
6239 for (i = 0; isdigit(s[i]); i++)
6240 res[i + 1] = s[i];
6242 for (; isspace(s[i]); i++)
6243 res[i + 1] = s[i];
6245 s += i;
6247 levels = cmd_tokenize(s, tokens);
6249 for (i = 0; i < levels - 1; i++) {
6250 tok = tokens[i];
6251 matchcount = 0;
6252 for (j = c; j < LENGTH(cmds); j++) {
6253 if (cmds[j].level < dep)
6254 break;
6255 if (cmds[j].level == dep && !strncmp(tok, cmds[j].cmd,
6256 strlen(tok))) {
6257 matchcount++;
6258 c = j + 1;
6259 if (strlen(tok) == strlen(cmds[j].cmd)) {
6260 matchcount = 1;
6261 break;
6266 if (matchcount == 1) {
6267 strlcat(res, tok, sizeof res);
6268 strlcat(res, " ", sizeof res);
6269 dep++;
6270 } else {
6271 g_free(sc);
6272 return;
6275 parent = c - 1;
6278 if (cmd_status.index == -1)
6279 cmd_getlist(parent, tokens[i]);
6281 if (cmd_status.len > 0) {
6282 match = cmd_getnext(dir);
6283 strlcat(res, match, sizeof res);
6284 gtk_entry_set_text(w, res);
6285 gtk_editable_set_position(GTK_EDITABLE(w), -1);
6288 g_free(sc);
6291 char *
6292 parse_prefix_and_alias(const char *str, int *prefix)
6294 struct cmd_alias *c;
6295 char *s = g_strdup(str), *sc;
6297 g_strstrip(s);
6298 sc = s;
6300 if (isdigit(s[0])) {
6301 sscanf(s, "%d", prefix);
6302 while (isdigit(s[0]) || isspace(s[0]))
6303 ++s;
6306 TAILQ_FOREACH(c, &cal, entry) {
6307 if (strncmp(s, c->alias, strlen(c->alias)))
6308 continue;
6310 if (strlen(s) == strlen(c->alias)) {
6311 g_free(sc);
6312 return (g_strdup(c->cmd));
6315 if (!isspace(s[strlen(c->alias)]))
6316 continue;
6318 s = g_strdup_printf("%s %s", c->cmd, &s[strlen(c->alias) + 1]);
6319 g_free(sc);
6320 return (s);
6322 s = g_strdup(s);
6323 g_free(sc);
6324 return (s);
6327 gboolean
6328 cmd_execute(struct tab *t, char *str)
6330 struct cmd *cmd = NULL;
6331 char *tok, *last = NULL, *s = str;
6332 int j = 0, len, c = 0, dep = 0, matchcount = 0;
6333 int prefix = -1, rv = XT_CB_PASSTHROUGH;
6334 struct karg arg = {0, NULL, -1};
6336 s = parse_prefix_and_alias(s, &prefix);
6338 for (tok = strtok_r(s, " ", &last); tok;
6339 tok = strtok_r(NULL, " ", &last)) {
6340 matchcount = 0;
6341 for (j = c; j < LENGTH(cmds); j++) {
6342 if (cmds[j].level < dep)
6343 break;
6344 len = (tok[strlen(tok) - 1] == '!') ? strlen(tok) - 1 :
6345 strlen(tok);
6346 if (cmds[j].level == dep &&
6347 !strncmp(tok, cmds[j].cmd, len)) {
6348 matchcount++;
6349 c = j + 1;
6350 cmd = &cmds[j];
6351 if (len == strlen(cmds[j].cmd)) {
6352 matchcount = 1;
6353 break;
6357 if (matchcount == 1) {
6358 if (cmd->type > 0)
6359 goto execute_cmd;
6360 dep++;
6361 } else {
6362 show_oops(t, "Invalid command: %s", str);
6363 goto done;
6366 execute_cmd:
6367 if (cmd == NULL) {
6368 show_oops(t, "Empty command");
6369 goto done;
6371 arg.i = cmd->arg;
6373 if (prefix != -1)
6374 arg.precount = prefix;
6375 else if (cmd_prefix > 0)
6376 arg.precount = cmd_prefix;
6378 if (j > 0 && !(cmd->type & XT_PREFIX) && arg.precount > -1) {
6379 show_oops(t, "No prefix allowed: %s", str);
6380 goto done;
6382 if (cmd->type > 1)
6383 arg.s = last ? g_strdup(last) : g_strdup("");
6384 if (cmd->type & XT_INTARG && last && strlen(last) > 0) {
6385 if (arg.s == NULL) {
6386 show_oops(t, "Invalid command");
6387 goto done;
6389 arg.precount = atoi(arg.s);
6390 if (arg.precount <= 0) {
6391 if (arg.s[0] == '0')
6392 show_oops(t, "Zero count");
6393 else
6394 show_oops(t, "Trailing characters");
6395 goto done;
6399 DNPRINTF(XT_D_CMD, "%s: prefix %d arg %s\n",
6400 __func__, arg.precount, arg.s);
6402 cmd->func(t, &arg);
6404 rv = XT_CB_HANDLED;
6405 done:
6406 if (j > 0)
6407 cmd_prefix = 0;
6408 g_free(s);
6409 if (arg.s)
6410 g_free(arg.s);
6412 return (rv);
6416 save_runtime_setting(const char *name, const char *val)
6418 struct stat sb;
6419 FILE *f;
6420 size_t linelen;
6421 int found = 0;
6422 char file[PATH_MAX];
6423 char delim[3] = { '\0', '\0', '\0' };
6424 char *line, *lt, *start;
6425 char *contents, *tmp;
6427 if (runtime_settings == NULL || strlen(runtime_settings) == 0)
6428 return (-1);
6430 snprintf(file, sizeof file, "%s" PS "%s", work_dir, runtime_settings);
6431 if (stat(file, &sb) || (f = fopen(file, "r+")) == NULL)
6432 return (-1);
6433 lt = g_strdup_printf("%s=%s", name, val);
6434 contents = g_strdup("");
6435 while (!feof(f)) {
6436 line = fparseln(f, &linelen, NULL, delim, 0);
6437 if (line == NULL || linelen == 0)
6438 continue;
6439 tmp = contents;
6440 start = g_strdup_printf("%s=", name);
6441 if (strstr(line, start) == NULL)
6442 contents = g_strdup_printf("%s%s\n", contents, line);
6443 else {
6444 found = 1;
6445 contents = g_strdup_printf("%s%s\n", contents, lt);
6447 g_free(tmp);
6448 g_free(start);
6449 free(line);
6450 line = NULL;
6452 if (found == 0) {
6453 tmp = contents;
6454 contents = g_strdup_printf("%s%s\n", contents, lt);
6455 g_free(tmp);
6457 if ((f = freopen(file, "w", f)) == NULL)
6458 return (-1);
6459 else {
6460 fputs(contents, f);
6461 fclose(f);
6463 g_free(lt);
6464 g_free(contents);
6466 return (0);
6470 entry_focus_cb(GtkWidget *w, GdkEvent e, struct tab *t)
6473 * This sometimes gets randomly unset for whatever reason in GTK3,
6474 * causing a GtkEntry's text cursor becomes invisible. When we focus
6475 * a GtkEntry, be sure to manually reset the main window's is-active
6476 * property so the cursor is shown correctly.
6478 #if GTK_CHECK_VERSION(3, 0, 0)
6479 fake_focus_in(main_window);
6480 #endif
6481 return (XT_CB_PASSTHROUGH);
6485 entry_key_cb(GtkEntry *w, GdkEventKey *e, struct tab *t)
6487 if (t == NULL) {
6488 show_oops(NULL, "entry_key_cb invalid parameters");
6489 return (XT_CB_PASSTHROUGH);
6492 DNPRINTF(XT_D_CMD, "entry_key_cb: keyval 0x%x mask 0x%x tab %d\n",
6493 e->keyval, e->state, t->tab_id);
6495 hide_oops(t);
6497 if (e->keyval == GDK_Escape) {
6498 /* don't use focus_webview(t) because we want to type :cmds */
6499 gtk_widget_grab_focus(GTK_WIDGET(t->wv));
6502 return (handle_keypress(t, e, 1));
6505 struct command_entry *
6506 history_prev(struct command_list *l, struct command_entry *at)
6508 if (at == NULL)
6509 at = TAILQ_LAST(l, command_list);
6510 else {
6511 at = TAILQ_PREV(at, command_list, entry);
6512 if (at == NULL)
6513 at = TAILQ_LAST(l, command_list);
6516 return (at);
6519 struct command_entry *
6520 history_next(struct command_list *l, struct command_entry *at)
6522 if (at == NULL)
6523 at = TAILQ_FIRST(l);
6524 else {
6525 at = TAILQ_NEXT(at, entry);
6526 if (at == NULL)
6527 at = TAILQ_FIRST(l);
6530 return (at);
6534 cmd_keypress_cb(GtkEntry *w, GdkEventKey *e, struct tab *t)
6536 int rv = XT_CB_HANDLED;
6537 const gchar *c = gtk_entry_get_text(w);
6538 char *s;
6540 if (t == NULL) {
6541 show_oops(NULL, "cmd_keypress_cb parameters");
6542 return (XT_CB_PASSTHROUGH);
6545 DNPRINTF(XT_D_CMD, "cmd_keypress_cb: keyval 0x%x mask 0x%x tab %d\n",
6546 e->keyval, e->state, t->tab_id);
6548 /* sanity */
6549 if (c == NULL)
6550 e->keyval = GDK_Escape;
6551 else if (!(c[0] == ':' || c[0] == '/' || c[0] == '?' ||
6552 c[0] == '.' || c[0] == ','))
6553 e->keyval = GDK_Escape;
6555 if (e->keyval != GDK_Tab && e->keyval != GDK_Shift_L &&
6556 e->keyval != GDK_ISO_Left_Tab)
6557 cmd_status.index = -1;
6559 switch (e->keyval) {
6560 case GDK_Tab:
6561 if (c[0] == ':')
6562 cmd_complete(t, (char *)&c[1], 1);
6563 else if (c[0] == '.' || c[0] == ',')
6564 run_script(t, "hints.focusNextHint();");
6565 goto done;
6566 case GDK_ISO_Left_Tab:
6567 if (c[0] == ':')
6568 cmd_complete(t, (char *)&c[1], -1);
6569 else if (c[0] == '.' || c[0] == ',')
6570 run_script(t, "hints.focusPreviousHint();");
6571 goto done;
6572 case GDK_Down:
6573 if (c[0] == '?') {
6574 if ((search_at = history_next(&shl, search_at))) {
6575 search_at->line[0] = c[0];
6576 gtk_entry_set_text(w, search_at->line);
6577 gtk_editable_set_position(GTK_EDITABLE(w), -1);
6579 } else if (c[0] == '/') {
6580 if ((search_at = history_prev(&shl, search_at))) {
6581 search_at->line[0] = c[0];
6582 gtk_entry_set_text(w, search_at->line);
6583 gtk_editable_set_position(GTK_EDITABLE(w), -1);
6585 } else if (c[0] == ':') {
6586 if ((history_at = history_prev(&chl, history_at))) {
6587 history_at->line[0] = c[0];
6588 gtk_entry_set_text(w, history_at->line);
6589 gtk_editable_set_position(GTK_EDITABLE(w), -1);
6592 goto done;
6593 case GDK_Up:
6594 if (c[0] == '/') {
6595 if ((search_at = history_next(&shl, search_at))) {
6596 search_at->line[0] = c[0];
6597 gtk_entry_set_text(w, search_at->line);
6598 gtk_editable_set_position(GTK_EDITABLE(w), -1);
6600 } else if (c[0] == '?') {
6601 if ((search_at = history_prev(&shl, search_at))) {
6602 search_at->line[0] = c[0];
6603 gtk_entry_set_text(w, search_at->line);
6604 gtk_editable_set_position(GTK_EDITABLE(w), -1);
6606 } if (c[0] == ':') {
6607 if ((history_at = history_next(&chl, history_at))) {
6608 history_at->line[0] = c[0];
6609 gtk_entry_set_text(w, history_at->line);
6610 gtk_editable_set_position(GTK_EDITABLE(w), -1);
6613 goto done;
6614 case GDK_BackSpace:
6615 if (!(!strcmp(c, ":") || !strcmp(c, "/") || !strcmp(c, "?") ||
6616 !strcmp(c, ".") || !strcmp(c, ","))) {
6617 /* see if we are doing hinting and reset it */
6618 if (c[0] == '.' || c[0] == ',') {
6619 /* recreate hints */
6620 s = g_strdup_printf("hints.createHints('', "
6621 "'%c');", c[0] == '.' ? 'f' : 'F');
6622 run_script(t, s);
6623 g_free(s);
6625 break;
6628 /* FALLTHROUGH */
6629 case GDK_Escape:
6630 hide_cmd(t);
6632 /* cancel search */
6633 if (c != NULL && (c[0] == '/' || c[0] == '?'))
6634 webkit_web_view_unmark_text_matches(t->wv);
6636 /* no need to cancel hints */
6637 goto done;
6640 rv = XT_CB_PASSTHROUGH;
6641 done:
6642 return (rv);
6645 void
6646 wv_popup_activ_cb(GtkMenuItem *menu, struct tab *t)
6648 GtkAction *a = NULL;
6649 GtkClipboard *clipboard, *primary;
6650 const gchar *name, *uri;
6652 a = gtk_activatable_get_related_action(GTK_ACTIVATABLE(menu));
6653 if (a == NULL)
6654 return;
6655 name = gtk_action_get_name(a);
6657 DNPRINTF(XT_D_CMD, "wv_popup_activ_cb: tab %d action %s\n",
6658 t->tab_id, name);
6661 * context-menu-action-3 copy link location
6662 * context-menu-action-7 copy image address
6663 * context-menu-action-2030 copy video link location
6666 /* copy actions */
6667 if ((g_strcmp0(name, "context-menu-action-3") == 0) ||
6668 (g_strcmp0(name, "context-menu-action-7") == 0) ||
6669 (g_strcmp0(name, "context-menu-action-2030") == 0)) {
6670 clipboard = gtk_clipboard_get(GDK_SELECTION_CLIPBOARD);
6671 primary = gtk_clipboard_get(GDK_SELECTION_PRIMARY);
6672 uri = gtk_clipboard_wait_for_text(clipboard);
6673 if (uri == NULL)
6674 return;
6675 gtk_clipboard_set_text(primary, uri, -1);
6679 void
6680 wv_popup_cb(WebKitWebView *wview, GtkMenu *menu, struct tab *t)
6682 GList *items, *l;
6684 DNPRINTF(XT_D_CMD, "wv_popup_cb: tab %d\n", t->tab_id);
6686 items = gtk_container_get_children(GTK_CONTAINER(menu));
6687 for (l = items; l; l = l->next)
6688 g_signal_connect(l->data, "activate",
6689 G_CALLBACK(wv_popup_activ_cb), t);
6690 g_list_free(items);
6693 void
6694 cmd_popup_cb(GtkEntry *entry, GtkMenu *menu, struct tab *t)
6696 /* popup menu enabled */
6697 t->popup = 1;
6701 cmd_focusout_cb(GtkWidget *w, GdkEventFocus *e, struct tab *t)
6703 if (t == NULL) {
6704 show_oops(NULL, "cmd_focusout_cb invalid parameters");
6705 return (XT_CB_PASSTHROUGH);
6708 DNPRINTF(XT_D_CMD, "cmd_focusout_cb: tab %d popup %d\n",
6709 t->tab_id, t->popup);
6711 /* if popup is enabled don't lose focus */
6712 if (t->popup) {
6713 t->popup = 0;
6714 return (XT_CB_PASSTHROUGH);
6717 hide_cmd(t);
6718 hide_oops(t);
6719 disable_hints(t);
6721 return (XT_CB_PASSTHROUGH);
6724 void
6725 cmd_hide_cb(GtkWidget *w, struct tab *t)
6727 if (t == NULL) {
6728 show_oops(NULL, "%s: invalid parameters", __func__);
6729 return;
6732 if (show_url == 0 || t->focus_wv)
6733 focus_webview(t);
6734 else
6735 gtk_widget_grab_focus(GTK_WIDGET(t->uri_entry));
6738 void
6739 cmd_activate_cb(GtkEntry *entry, struct tab *t)
6741 char *s;
6742 const gchar *c = gtk_entry_get_text(entry);
6744 if (t == NULL) {
6745 show_oops(NULL, "cmd_activate_cb invalid parameters");
6746 return;
6749 DNPRINTF(XT_D_CMD, "cmd_activate_cb: tab %d %s\n", t->tab_id, c);
6751 /* sanity */
6752 if (c == NULL)
6753 goto done;
6754 else if (!(c[0] == ':' || c[0] == '/' || c[0] == '?' ||
6755 c[0] == '.' || c[0] == ','))
6756 goto done;
6757 if (strlen(c) < 1)
6758 goto done;
6759 s = (char *)&c[1];
6761 if (c[0] == '/' || c[0] == '?') {
6762 /* see if there is a timer pending */
6763 if (t->search_id) {
6764 g_source_remove(t->search_id);
6765 t->search_id = 0;
6766 search_cb(t);
6769 if (t->search_text) {
6770 g_free(t->search_text);
6771 t->search_text = NULL;
6774 t->search_text = g_strdup(s);
6775 if (global_search)
6776 g_free(global_search);
6777 global_search = g_strdup(s);
6778 t->search_forward = c[0] == '/';
6780 history_add(&shl, search_file, s, &search_history_count);
6781 } else if (c[0] == '.' || c[0] == ',') {
6782 run_script(t, "hints.fire();");
6783 /* XXX history for link following? */
6784 } else if (c[0] == ':') {
6785 history_add(&chl, command_file, s, &cmd_history_count);
6786 /* can't call hide_cmd after cmd_execute */
6787 hide_cmd(t);
6788 cmd_execute(t, s);
6789 return;
6792 done:
6793 hide_cmd(t);
6796 void
6797 backward_cb(GtkWidget *w, struct tab *t)
6799 struct karg a;
6801 if (t == NULL) {
6802 show_oops(NULL, "backward_cb invalid parameters");
6803 return;
6806 DNPRINTF(XT_D_NAV, "backward_cb: tab %d\n", t->tab_id);
6808 a.i = XT_NAV_BACK;
6809 navaction(t, &a);
6812 void
6813 forward_cb(GtkWidget *w, struct tab *t)
6815 struct karg a;
6817 if (t == NULL) {
6818 show_oops(NULL, "forward_cb invalid parameters");
6819 return;
6822 DNPRINTF(XT_D_NAV, "forward_cb: tab %d\n", t->tab_id);
6824 a.i = XT_NAV_FORWARD;
6825 navaction(t, &a);
6828 void
6829 home_cb(GtkWidget *w, struct tab *t)
6831 if (t == NULL) {
6832 show_oops(NULL, "home_cb invalid parameters");
6833 return;
6836 DNPRINTF(XT_D_NAV, "home_cb: tab %d\n", t->tab_id);
6838 load_uri(t, home);
6841 void
6842 stop_cb(GtkWidget *w, struct tab *t)
6844 WebKitWebFrame *frame;
6846 if (t == NULL) {
6847 show_oops(NULL, "stop_cb invalid parameters");
6848 return;
6851 DNPRINTF(XT_D_NAV, "stop_cb: tab %d\n", t->tab_id);
6853 frame = webkit_web_view_get_main_frame(t->wv);
6854 if (frame == NULL) {
6855 show_oops(t, "stop_cb: no frame");
6856 return;
6859 webkit_web_frame_stop_loading(frame);
6860 abort_favicon_download(t);
6863 void
6864 setup_webkit(struct tab *t)
6866 if (is_g_object_setting(G_OBJECT(t->settings), "enable-dns-prefetching"))
6867 g_object_set(G_OBJECT(t->settings), "enable-dns-prefetching",
6868 FALSE, (char *)NULL);
6869 else
6870 warnx("webkit does not have \"enable-dns-prefetching\" property");
6871 g_object_set(G_OBJECT(t->settings),
6872 "user-agent", t->user_agent, (char *)NULL);
6873 g_object_set(G_OBJECT(t->settings),
6874 "enable-scripts", enable_scripts, (char *)NULL);
6875 g_object_set(G_OBJECT(t->settings),
6876 "enable-plugins", enable_plugins, (char *)NULL);
6877 g_object_set(G_OBJECT(t->settings),
6878 "javascript-can-open-windows-automatically", enable_scripts,
6879 (char *)NULL);
6880 g_object_set(G_OBJECT(t->settings),
6881 "enable-html5-database", FALSE, (char *)NULL);
6882 g_object_set(G_OBJECT(t->settings),
6883 "enable-html5-local-storage", enable_localstorage, (char *)NULL);
6884 g_object_set(G_OBJECT(t->settings),
6885 "enable_spell_checking", enable_spell_checking, (char *)NULL);
6886 g_object_set(G_OBJECT(t->settings),
6887 "spell_checking_languages", spell_check_languages, (char *)NULL);
6888 g_object_set(G_OBJECT(t->settings),
6889 "enable-developer-extras", TRUE, (char *)NULL);
6890 g_object_set(G_OBJECT(t->wv),
6891 "full-content-zoom", TRUE, (char *)NULL);
6892 g_object_set(G_OBJECT(t->settings),
6893 "auto-load-images", auto_load_images, (char *)NULL);
6894 if (is_g_object_setting(G_OBJECT(t->settings),
6895 "enable-display-of-insecure-content"))
6896 g_object_set(G_OBJECT(t->settings),
6897 "enable-display-of-insecure-content",
6898 allow_insecure_content, (char *)NULL);
6899 if (is_g_object_setting(G_OBJECT(t->settings),
6900 "enable-running-of-insecure-content"))
6901 g_object_set(G_OBJECT(t->settings),
6902 "enable-running-of-insecure-content",
6903 allow_insecure_scripts, (char *)NULL);
6905 webkit_web_view_set_settings(t->wv, t->settings);
6908 gboolean
6909 update_statusbar_position(GtkAdjustment* adjustment, gpointer data)
6911 struct tab *ti, *t = NULL;
6912 gdouble view_size, value, max;
6913 gchar *position;
6915 TAILQ_FOREACH(ti, &tabs, entry)
6916 if (ti->tab_id == gtk_notebook_get_current_page(notebook)) {
6917 t = ti;
6918 break;
6921 if (t == NULL)
6922 return FALSE;
6924 if (adjustment == NULL)
6925 adjustment = gtk_scrolled_window_get_vadjustment(
6926 GTK_SCROLLED_WINDOW(t->browser_win));
6928 view_size = gtk_adjustment_get_page_size(adjustment);
6929 value = gtk_adjustment_get_value(adjustment);
6930 max = gtk_adjustment_get_upper(adjustment) - view_size;
6932 if (max == 0)
6933 position = g_strdup("All");
6934 else if (value == max)
6935 position = g_strdup("Bot");
6936 else if (value == 0)
6937 position = g_strdup("Top");
6938 else
6939 position = g_strdup_printf("%d%%", (int) ((value / max) * 100));
6941 gtk_label_set_text(GTK_LABEL(t->sbe.position), position);
6942 g_free(position);
6944 return (TRUE);
6947 GtkWidget *
6948 create_window(const gchar *name)
6950 GtkWidget *w;
6952 w = gtk_window_new(GTK_WINDOW_TOPLEVEL);
6953 if (window_maximize)
6954 gtk_window_maximize(GTK_WINDOW(w));
6955 else
6956 gtk_window_set_default_size(GTK_WINDOW(w), window_width, window_height);
6957 gtk_widget_set_name(w, name);
6958 gtk_window_set_wmclass(GTK_WINDOW(w), name, "Xombrero");
6960 return (w);
6963 GtkWidget *
6964 create_browser(struct tab *t)
6966 GtkWidget *w;
6967 gchar *strval;
6968 GtkAdjustment *adjustment;
6970 if (t == NULL) {
6971 show_oops(NULL, "create_browser invalid parameters");
6972 return (NULL);
6975 w = gtk_scrolled_window_new(NULL, NULL);
6976 gtk_widget_set_can_focus(w, FALSE);
6977 t->adjust_h = gtk_scrolled_window_get_hadjustment(
6978 GTK_SCROLLED_WINDOW(w));
6979 t->adjust_v = gtk_scrolled_window_get_vadjustment(
6980 GTK_SCROLLED_WINDOW(w));
6981 #if !GTK_CHECK_VERSION(3, 0, 0)
6982 gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(w),
6983 GTK_POLICY_AUTOMATIC, GTK_POLICY_AUTOMATIC);
6984 #endif
6987 t->wv = WEBKIT_WEB_VIEW(webkit_web_view_new());
6988 gtk_container_add(GTK_CONTAINER(w), GTK_WIDGET(t->wv));
6990 /* set defaults */
6991 t->settings = webkit_web_settings_new();
6993 g_object_set(t->settings, "default-encoding", encoding, (char *)NULL);
6995 if (user_agent == NULL) {
6996 g_object_get(G_OBJECT(t->settings), "user-agent", &strval,
6997 (char *)NULL);
6998 t->user_agent = g_strdup_printf("%s %s+", strval, version);
6999 g_free(strval);
7000 } else
7001 t->user_agent = g_strdup(user_agent->value);
7003 t->stylesheet = g_strdup(stylesheet);
7004 t->load_images = auto_load_images;
7006 adjustment =
7007 gtk_scrolled_window_get_vadjustment(GTK_SCROLLED_WINDOW(w));
7008 g_signal_connect(G_OBJECT(adjustment), "value-changed",
7009 G_CALLBACK(update_statusbar_position), NULL);
7011 setup_webkit(t);
7012 setup_inspector(t);
7014 return (w);
7017 GtkWidget *
7018 create_kiosk_toolbar(struct tab *t)
7020 GtkWidget *toolbar = NULL, *b;
7022 #if GTK_CHECK_VERSION(3, 0, 0)
7023 b = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 0);
7024 gtk_widget_set_name(GTK_WIDGET(b), "toolbar");
7025 #else
7026 b = gtk_hbox_new(FALSE, 0);
7027 #endif
7028 toolbar = b;
7029 gtk_container_set_border_width(GTK_CONTAINER(toolbar), 0);
7031 /* backward button */
7032 t->backward = create_button("Back", GTK_STOCK_GO_BACK, 0);
7033 gtk_widget_set_sensitive(t->backward, FALSE);
7034 g_signal_connect(G_OBJECT(t->backward), "clicked",
7035 G_CALLBACK(backward_cb), t);
7036 gtk_box_pack_start(GTK_BOX(b), t->backward, TRUE, TRUE, 0);
7038 /* forward button */
7039 t->forward = create_button("Forward", GTK_STOCK_GO_FORWARD, 0);
7040 gtk_widget_set_sensitive(t->forward, FALSE);
7041 g_signal_connect(G_OBJECT(t->forward), "clicked",
7042 G_CALLBACK(forward_cb), t);
7043 gtk_box_pack_start(GTK_BOX(b), t->forward, TRUE, TRUE, 0);
7045 /* home button */
7046 t->gohome = create_button("Home", GTK_STOCK_HOME, 0);
7047 gtk_widget_set_sensitive(t->gohome, true);
7048 g_signal_connect(G_OBJECT(t->gohome), "clicked",
7049 G_CALLBACK(home_cb), t);
7050 gtk_box_pack_start(GTK_BOX(b), t->gohome, TRUE, TRUE, 0);
7052 /* create widgets but don't use them */
7053 t->uri_entry = gtk_entry_new();
7054 g_signal_connect(G_OBJECT(t->uri_entry), "focus-in-event",
7055 G_CALLBACK(entry_focus_cb), t);
7056 #if !GTK_CHECK_VERSION(3, 0, 0)
7057 t->default_style = gtk_rc_get_style(t->uri_entry);
7058 #endif
7059 t->stop = create_button("Stop", GTK_STOCK_STOP, 0);
7060 t->js_toggle = create_button("JS-Toggle", enable_scripts ?
7061 GTK_STOCK_MEDIA_PLAY : GTK_STOCK_MEDIA_PAUSE, 0);
7063 return (toolbar);
7066 GtkWidget *
7067 create_toolbar(struct tab *t)
7069 GtkWidget *toolbar = NULL, *b;
7071 #if GTK_CHECK_VERSION(3, 0, 0)
7072 b = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 0);
7073 gtk_widget_set_name(GTK_WIDGET(b), "toolbar");
7074 #else
7075 b = gtk_hbox_new(FALSE, 0);
7076 #endif
7077 toolbar = b;
7078 gtk_container_set_border_width(GTK_CONTAINER(toolbar), 0);
7080 /* backward button */
7081 t->backward = create_button("Back", GTK_STOCK_GO_BACK, 0);
7082 gtk_widget_set_sensitive(t->backward, FALSE);
7083 g_signal_connect(G_OBJECT(t->backward), "clicked",
7084 G_CALLBACK(backward_cb), t);
7085 gtk_box_pack_start(GTK_BOX(b), t->backward, FALSE, FALSE, 0);
7087 /* forward button */
7088 t->forward = create_button("Forward",GTK_STOCK_GO_FORWARD, 0);
7089 gtk_widget_set_sensitive(t->forward, FALSE);
7090 g_signal_connect(G_OBJECT(t->forward), "clicked",
7091 G_CALLBACK(forward_cb), t);
7092 gtk_box_pack_start(GTK_BOX(b), t->forward, FALSE, FALSE, 0);
7094 /* stop button */
7095 t->stop = create_button("Stop", GTK_STOCK_STOP, 0);
7096 gtk_widget_set_sensitive(t->stop, FALSE);
7097 g_signal_connect(G_OBJECT(t->stop), "clicked", G_CALLBACK(stop_cb), t);
7098 gtk_box_pack_start(GTK_BOX(b), t->stop, FALSE, FALSE, 0);
7100 /* JS button */
7101 t->js_toggle = create_button("JS-Toggle", enable_scripts ?
7102 GTK_STOCK_MEDIA_PLAY : GTK_STOCK_MEDIA_PAUSE, 0);
7103 gtk_widget_set_sensitive(t->js_toggle, TRUE);
7104 g_signal_connect(G_OBJECT(t->js_toggle), "clicked",
7105 G_CALLBACK(js_toggle_cb), t);
7106 gtk_box_pack_start(GTK_BOX(b), t->js_toggle, FALSE, FALSE, 0);
7108 t->uri_entry = gtk_entry_new();
7109 g_signal_connect(G_OBJECT(t->uri_entry), "activate",
7110 G_CALLBACK(activate_uri_entry_cb), t);
7111 g_signal_connect(G_OBJECT(t->uri_entry), "key-press-event",
7112 G_CALLBACK(entry_key_cb), t);
7113 g_signal_connect(G_OBJECT(t->uri_entry), "focus-in-event",
7114 G_CALLBACK(entry_focus_cb), t);
7115 completion_add(t);
7116 gtk_box_pack_start(GTK_BOX(b), t->uri_entry, TRUE, TRUE, 0);
7118 /* search entry */
7119 t->search_entry = gtk_entry_new();
7120 gtk_entry_set_width_chars(GTK_ENTRY(t->search_entry), 30);
7121 g_signal_connect(G_OBJECT(t->search_entry), "activate",
7122 G_CALLBACK(activate_search_entry_cb), t);
7123 g_signal_connect(G_OBJECT(t->search_entry), "key-press-event",
7124 G_CALLBACK(entry_key_cb), t);
7125 g_signal_connect(G_OBJECT(t->search_entry), "focus-in-event",
7126 G_CALLBACK(entry_focus_cb), t);
7127 gtk_box_pack_start(GTK_BOX(b), t->search_entry, FALSE, FALSE, 0);
7129 #if !GTK_CHECK_VERSION(3, 0, 0)
7130 t->default_style = gtk_rc_get_style(t->uri_entry);
7131 #endif
7133 return (toolbar);
7136 GtkWidget *
7137 create_buffers(struct tab *t)
7139 GtkCellRenderer *renderer;
7140 GtkWidget *view;
7142 view = gtk_tree_view_new();
7144 gtk_tree_view_set_headers_visible(GTK_TREE_VIEW(view), FALSE);
7146 renderer = gtk_cell_renderer_text_new();
7147 gtk_tree_view_insert_column_with_attributes
7148 (GTK_TREE_VIEW(view), -1, "Id", renderer, "text", COL_ID, (char *)NULL);
7150 renderer = gtk_cell_renderer_pixbuf_new();
7151 gtk_tree_view_insert_column_with_attributes
7152 (GTK_TREE_VIEW(view), -1, "Favicon", renderer, "pixbuf", COL_FAVICON,
7153 (char *)NULL);
7155 renderer = gtk_cell_renderer_text_new();
7156 gtk_tree_view_insert_column_with_attributes
7157 (GTK_TREE_VIEW(view), -1, "Title", renderer, "text", COL_TITLE,
7158 (char *)NULL);
7160 gtk_tree_view_set_model
7161 (GTK_TREE_VIEW(view), GTK_TREE_MODEL(buffers_store));
7163 return (view);
7166 void
7167 row_activated_cb(GtkTreeView *view, GtkTreePath *path,
7168 GtkTreeViewColumn *col, struct tab *t)
7170 GtkTreeIter iter;
7171 guint id;
7173 gtk_widget_grab_focus(GTK_WIDGET(t->wv));
7175 if (gtk_tree_model_get_iter(GTK_TREE_MODEL(buffers_store), &iter,
7176 path)) {
7177 gtk_tree_model_get
7178 (GTK_TREE_MODEL(buffers_store), &iter, COL_ID, &id, -1);
7179 set_current_tab(id - 1);
7182 hide_buffers(t);
7185 /* after tab reordering/creation/removal */
7186 void
7187 recalc_tabs(void)
7189 struct tab *t;
7191 TAILQ_FOREACH(t, &tabs, entry)
7192 t->tab_id = gtk_notebook_page_num(notebook, t->vbox);
7195 void
7196 update_statusbar_tabs(struct tab *t)
7198 int tab_id, max_tab_id;
7199 char s[16];
7201 if (t != NULL)
7202 tab_id = t->tab_id;
7203 else
7204 tab_id = gtk_notebook_get_current_page(notebook);
7206 max_tab_id = gtk_notebook_get_n_pages(notebook);
7207 snprintf(s, sizeof s, "%d/%d", tab_id + 1, max_tab_id);
7209 if (t == NULL)
7210 t = get_current_tab();
7212 if (t != NULL)
7213 gtk_label_set_text(GTK_LABEL(t->sbe.tabs), s);
7216 /* after active tab change */
7217 void
7218 recolor_compact_tabs(void)
7220 struct tab *t;
7221 int curid = 0;
7222 #if !GTK_CHECK_VERSION(3, 0, 0)
7223 GdkColor color_active, color_inactive;
7225 gdk_color_parse(XT_COLOR_CT_ACTIVE, &color_active);
7226 gdk_color_parse(XT_COLOR_CT_INACTIVE, &color_inactive);
7227 #endif
7228 curid = gtk_notebook_get_current_page(notebook);
7230 TAILQ_FOREACH(t, &tabs, entry) {
7231 #if GTK_CHECK_VERSION(3, 0, 0)
7232 if (t->tab_id == curid)
7233 gtk_widget_set_name(t->tab_elems.label, XT_CSS_ACTIVE);
7234 else
7235 gtk_widget_set_name(t->tab_elems.label, "");
7236 #else
7237 if (t->tab_id == curid)
7238 gtk_widget_modify_fg(t->tab_elems.label,
7239 GTK_STATE_NORMAL, &color_active);
7240 else
7241 gtk_widget_modify_fg(t->tab_elems.label,
7242 GTK_STATE_NORMAL, &color_inactive);
7243 #endif
7247 void
7248 set_current_tab(int page_num)
7250 buffercmd_abort(get_current_tab());
7251 gtk_notebook_set_current_page(notebook, page_num);
7252 recolor_compact_tabs();
7253 update_statusbar_tabs(NULL);
7257 undo_close_tab_save(struct tab *t)
7259 int m, n;
7260 const gchar *uri;
7261 struct undo *u1, *u2;
7262 GList *items;
7263 WebKitWebHistoryItem *item;
7265 if ((uri = get_uri(t)) == NULL)
7266 return (1);
7268 u1 = g_malloc0(sizeof(struct undo));
7269 u1->uri = g_strdup(uri);
7271 t->bfl = webkit_web_view_get_back_forward_list(t->wv);
7273 m = webkit_web_back_forward_list_get_forward_length(t->bfl);
7274 n = webkit_web_back_forward_list_get_back_length(t->bfl);
7275 u1->back = n;
7277 /* forward history */
7278 items = webkit_web_back_forward_list_get_forward_list_with_limit(t->bfl, m);
7280 while (items) {
7281 item = items->data;
7282 u1->history = g_list_prepend(u1->history,
7283 webkit_web_history_item_copy(item));
7284 items = g_list_next(items);
7287 /* current item */
7288 if (m) {
7289 item = webkit_web_back_forward_list_get_current_item(t->bfl);
7290 u1->history = g_list_prepend(u1->history,
7291 webkit_web_history_item_copy(item));
7294 /* back history */
7295 items = webkit_web_back_forward_list_get_back_list_with_limit(t->bfl, n);
7297 while (items) {
7298 item = items->data;
7299 u1->history = g_list_prepend(u1->history,
7300 webkit_web_history_item_copy(item));
7301 items = g_list_next(items);
7304 TAILQ_INSERT_HEAD(&undos, u1, entry);
7306 if (undo_count > XT_MAX_UNDO_CLOSE_TAB) {
7307 u2 = TAILQ_LAST(&undos, undo_tailq);
7308 TAILQ_REMOVE(&undos, u2, entry);
7309 g_free(u2->uri);
7310 g_list_free(u2->history);
7311 g_free(u2);
7312 } else
7313 undo_count++;
7315 return (0);
7318 void
7319 delete_tab(struct tab *t)
7321 struct karg a;
7323 DNPRINTF(XT_D_TAB, "delete_tab: %p\n", t);
7325 if (t == NULL)
7326 return;
7329 * no need to join thread here because it won't access t on completion
7332 TAILQ_REMOVE(&tabs, t, entry);
7333 buffercmd_abort(t);
7335 /* Halt all webkit activity. */
7336 abort_favicon_download(t);
7337 webkit_web_view_stop_loading(t->wv);
7339 /* Save the tab, so we can undo the close. */
7340 undo_close_tab_save(t);
7342 /* just in case */
7343 if (t->search_id)
7344 g_source_remove(t->search_id);
7346 /* session key */
7347 if (t->session_key)
7348 g_free(t->session_key);
7350 /* inspector */
7351 bzero(&a, sizeof a);
7352 a.i = XT_INS_CLOSE;
7353 inspector_cmd(t, &a);
7355 if (browser_mode == XT_BM_KIOSK) {
7356 gtk_widget_destroy(t->uri_entry);
7357 gtk_widget_destroy(t->stop);
7358 gtk_widget_destroy(t->js_toggle);
7361 g_object_unref(t->completion);
7362 if (t->item)
7363 g_object_unref(t->item);
7365 gtk_widget_destroy(t->tab_elems.eventbox);
7366 gtk_widget_destroy(t->vbox);
7368 g_free(t->user_agent);
7369 g_free(t->stylesheet);
7370 g_free(t->tmp_uri);
7371 g_free(t->status);
7372 g_free(t);
7373 t = NULL;
7375 if (TAILQ_EMPTY(&tabs)) {
7376 if (browser_mode == XT_BM_KIOSK)
7377 create_new_tab(home, NULL, 1, -1);
7378 else
7379 create_new_tab(NULL, NULL, 1, -1);
7382 /* recreate session */
7383 if (session_autosave) {
7384 bzero(&a, sizeof a);
7385 a.s = NULL;
7386 save_tabs(NULL, &a);
7389 recalc_tabs();
7390 recolor_compact_tabs();
7393 void
7394 update_statusbar_zoom(struct tab *t)
7396 gfloat zoom;
7397 char s[16] = { '\0' };
7399 g_object_get(G_OBJECT(t->wv), "zoom-level", &zoom, (char *)NULL);
7400 if ((zoom <= 0.99 || zoom >= 1.01))
7401 snprintf(s, sizeof s, "%d%%", (int)(zoom * 100));
7402 gtk_label_set_text(GTK_LABEL(t->sbe.zoom), s);
7405 void
7406 setzoom_webkit(struct tab *t, int adjust)
7408 #define XT_ZOOMPERCENT 0.04
7410 gfloat zoom;
7412 if (t == NULL) {
7413 show_oops(NULL, "setzoom_webkit invalid parameters");
7414 return;
7417 g_object_get(G_OBJECT(t->wv), "zoom-level", &zoom, (char *)NULL);
7418 if (adjust == XT_ZOOM_IN)
7419 zoom += XT_ZOOMPERCENT;
7420 else if (adjust == XT_ZOOM_OUT)
7421 zoom -= XT_ZOOMPERCENT;
7422 else if (adjust > 0)
7423 zoom = default_zoom_level + adjust / 100.0 - 1.0;
7424 else {
7425 show_oops(t, "setzoom_webkit invalid zoom value");
7426 return;
7429 if (zoom < XT_ZOOMPERCENT)
7430 zoom = XT_ZOOMPERCENT;
7431 g_object_set(G_OBJECT(t->wv), "zoom-level", zoom, (char *)NULL);
7432 update_statusbar_zoom(t);
7435 gboolean
7436 tab_clicked_cb(GtkWidget *widget, GdkEventButton *event, gpointer data)
7438 struct tab *t = (struct tab *) data;
7440 DNPRINTF(XT_D_TAB, "tab_clicked_cb: tab: %d\n", t->tab_id);
7442 switch (event->button) {
7443 case 1:
7444 set_current_tab(t->tab_id);
7445 break;
7446 case 2:
7447 delete_tab(t);
7448 break;
7451 return TRUE;
7454 void
7455 append_tab(struct tab *t)
7457 if (t == NULL)
7458 return;
7460 TAILQ_INSERT_TAIL(&tabs, t, entry);
7461 t->tab_id = gtk_notebook_append_page(notebook, t->vbox, t->tab_content);
7464 GtkWidget *
7465 create_sbe(void)
7467 GtkWidget *sbe;
7469 sbe = gtk_label_new(NULL);
7470 gtk_widget_set_can_focus(GTK_WIDGET(sbe), FALSE);
7471 gtk_widget_modify_font(GTK_WIDGET(sbe), statusbar_font);
7472 return (sbe);
7476 add_sbe(GtkWidget *box, char flag, int *used, GtkWidget *sbe)
7478 if (box == NULL || used == NULL || sbe == NULL) {
7479 DPRINTF("%s: invalid parameters", __func__);
7480 return (1);
7483 if (*used) {
7484 warnx("flag \"%c\" specified more than "
7485 "once in statusbar_elems\n", flag);
7486 return (1);
7489 gtk_box_pack_start(GTK_BOX(box), sbe, FALSE, FALSE, 0);
7490 *used = 1;
7492 return (0);
7496 statusbar_create(struct tab *t)
7498 GtkWidget *box; /* container for statusbar elems */
7499 GtkWidget *sep;
7500 char *p;
7501 int sbe_P = 0, sbe_B = 0, sbe_Z = 0, sbe_T = 0,
7502 sbe_p = 0;
7503 #if !GTK_CHECK_VERSION(3, 0, 0)
7504 GdkColor color;
7505 #endif
7507 if (t == NULL) {
7508 DPRINTF("%s: invalid parameters", __func__);
7509 return (1);
7512 #if GTK_CHECK_VERSION(3, 0, 0)
7513 t->statusbar = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 0);
7514 box = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 0);
7515 gtk_widget_set_name(GTK_WIDGET(t->statusbar), "statusbar");
7516 #else
7517 t->statusbar = gtk_hbox_new(FALSE, 0);
7518 box = gtk_hbox_new(FALSE, 0);
7519 #endif
7520 t->sbe.ebox = gtk_event_box_new();
7522 gtk_widget_set_can_focus(GTK_WIDGET(t->statusbar), FALSE);
7523 gtk_widget_set_can_focus(GTK_WIDGET(t->sbe.ebox), FALSE);
7524 gtk_widget_set_can_focus(GTK_WIDGET(box), FALSE);
7526 gtk_box_set_spacing(GTK_BOX(box), 10);
7527 gtk_box_pack_start(GTK_BOX(t->statusbar), t->sbe.ebox, TRUE, TRUE, 0);
7528 gtk_container_add(GTK_CONTAINER(t->sbe.ebox), box);
7530 /* create these widgets only if specified in statusbar_elems */
7531 t->sbe.uri = gtk_entry_new();
7532 gtk_widget_set_can_focus(GTK_WIDGET(t->sbe.uri), FALSE);
7533 gtk_widget_modify_font(GTK_WIDGET(t->sbe.uri), statusbar_font);
7534 #if !GTK_CHECK_VERSION(3, 0, 0)
7535 gtk_entry_set_inner_border(GTK_ENTRY(t->sbe.uri), NULL);
7536 gtk_entry_set_has_frame(GTK_ENTRY(t->sbe.uri), FALSE);
7537 #endif
7538 t->sbe.position = create_sbe();
7539 t->sbe.zoom = create_sbe();
7540 t->sbe.buffercmd = create_sbe();
7541 t->sbe.tabs = create_sbe();
7542 t->sbe.proxy = create_sbe();
7544 #if GTK_CHECK_VERSION(3, 0, 0)
7545 statusbar_modify_attr(t, XT_CSS_NORMAL);
7546 #else
7547 statusbar_modify_attr(t, XT_COLOR_WHITE, XT_COLOR_BLACK);
7548 #endif
7550 gtk_box_pack_start(GTK_BOX(box), t->sbe.uri, TRUE, TRUE, 0);
7553 * gtk widgets cannot be added to a box twice. The sbe_* variables
7554 * make sure of this
7556 for (p = statusbar_elems; *p != '\0'; p++) {
7557 switch (*p) {
7558 case '|':
7559 #if GTK_CHECK_VERSION(3, 0, 0)
7560 sep = gtk_separator_new(GTK_ORIENTATION_VERTICAL);
7561 #else
7562 sep = gtk_vseparator_new();
7563 gdk_color_parse(XT_COLOR_SB_SEPARATOR, &color);
7564 gtk_widget_modify_bg(sep, GTK_STATE_NORMAL, &color);
7565 #endif
7566 gtk_box_pack_start(GTK_BOX(box), sep, FALSE, FALSE, 0);
7567 break;
7568 case 'P':
7569 add_sbe(box, *p, &sbe_P, t->sbe.position);
7570 break;
7571 case 'B':
7572 add_sbe(box, *p, &sbe_B, t->sbe.buffercmd);
7573 break;
7574 case 'Z':
7575 add_sbe(box, *p, &sbe_Z, t->sbe.zoom);
7576 break;
7577 case 'T':
7578 add_sbe(box, *p, &sbe_T, t->sbe.tabs);
7579 break;
7580 case 'p':
7581 if (add_sbe(box, *p, &sbe_p, t->sbe.proxy) == 0)
7582 if (proxy_uri)
7583 gtk_entry_set_text(
7584 GTK_ENTRY(t->sbe.proxy), "proxy");
7585 break;
7586 default:
7587 warnx("illegal flag \"%c\" in statusbar_elems\n", *p);
7588 break;
7592 gtk_box_pack_end(GTK_BOX(t->vbox), t->statusbar, FALSE, FALSE, 0);
7594 return (0);
7597 struct tab *
7598 create_new_tab(char *title, struct undo *u, int focus, int position)
7600 struct tab *t;
7601 int load = 1, id;
7602 GtkWidget *b, *bb;
7603 WebKitWebHistoryItem *item;
7604 GList *items;
7605 #if !GTK_CHECK_VERSION(3, 0, 0)
7606 GdkColor color;
7607 #endif
7609 DNPRINTF(XT_D_TAB, "create_new_tab: title %s focus %d\n", title, focus);
7611 if (tabless && !TAILQ_EMPTY(&tabs)) {
7612 DNPRINTF(XT_D_TAB, "create_new_tab: new tab rejected\n");
7613 return (NULL);
7616 t = g_malloc0(sizeof *t);
7618 if (title == NULL) {
7619 title = "(untitled)";
7620 load = 0;
7623 #if GTK_CHECK_VERSION(3, 0, 0)
7624 t->vbox = gtk_box_new(GTK_ORIENTATION_VERTICAL, 0);
7625 b = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 0);
7626 gtk_widget_set_name(t->vbox, "vbox");
7627 #else
7628 t->vbox = gtk_vbox_new(FALSE, 0);
7629 b = gtk_hbox_new(FALSE, 0);
7630 #endif
7631 gtk_widget_set_can_focus(t->vbox, FALSE);
7633 /* label + button for tab */
7634 t->tab_content = b;
7635 gtk_widget_set_can_focus(t->tab_content, FALSE);
7637 t->user_agent_id = 0;
7638 t->http_accept_id = 0;
7640 #if WEBKIT_CHECK_VERSION(1, 5, 0)
7641 t->active = NULL;
7642 #endif
7644 #if GTK_CHECK_VERSION(2, 20, 0)
7645 t->spinner = gtk_spinner_new();
7646 #endif
7647 t->label = gtk_label_new(title);
7648 bb = create_button("Close", GTK_STOCK_CLOSE, 1);
7649 gtk_label_set_max_width_chars(GTK_LABEL(t->label), 20);
7650 gtk_label_set_ellipsize(GTK_LABEL(t->label), PANGO_ELLIPSIZE_END);
7651 gtk_label_set_line_wrap(GTK_LABEL(t->label), FALSE);
7652 gtk_widget_set_size_request(b, 130, 0);
7655 * this is a total hack and most likely breaks with other styles but
7656 * is necessary so the text doesn't bounce around when the spinner is
7657 * shown/hidden
7659 #if GTK_CHECK_VERSION(3, 0, 0)
7660 gtk_widget_set_size_request(t->label, 95, 0);
7661 #else
7662 gtk_widget_set_size_request(t->label, 100, 0);
7663 #endif
7665 gtk_box_pack_start(GTK_BOX(b), bb, FALSE, FALSE, 0);
7666 gtk_box_pack_start(GTK_BOX(b), t->label, FALSE, FALSE, 0);
7667 #if GTK_CHECK_VERSION(2, 20, 0)
7668 gtk_box_pack_end(GTK_BOX(b), t->spinner, FALSE, FALSE, 0);
7669 #endif
7671 /* toolbar */
7672 if (browser_mode == XT_BM_KIOSK) {
7673 t->toolbar = create_kiosk_toolbar(t);
7674 gtk_box_pack_start(GTK_BOX(t->vbox), t->toolbar, FALSE, FALSE,
7676 } else {
7677 t->toolbar = create_toolbar(t);
7678 gtk_box_pack_start(GTK_BOX(t->vbox), t->toolbar, FALSE, FALSE,
7682 /* marks */
7683 marks_clear(t);
7685 /* browser */
7686 t->browser_win = create_browser(t);
7687 set_scrollbar_visibility(t, show_scrollbars);
7688 gtk_box_pack_start(GTK_BOX(t->vbox), t->browser_win, TRUE, TRUE, 0);
7690 /* oops message for user feedback */
7691 t->oops = gtk_entry_new();
7692 gtk_entry_set_inner_border(GTK_ENTRY(t->oops), NULL);
7693 gtk_entry_set_has_frame(GTK_ENTRY(t->oops), FALSE);
7694 gtk_widget_set_can_focus(GTK_WIDGET(t->oops), FALSE);
7695 #if GTK_CHECK_VERSION(3, 0, 0)
7696 gtk_widget_set_name(t->oops, XT_CSS_RED);
7697 #else
7698 gdk_color_parse(XT_COLOR_RED, &color);
7699 gtk_widget_modify_base(t->oops, GTK_STATE_NORMAL, &color);
7700 #endif
7701 gtk_box_pack_end(GTK_BOX(t->vbox), t->oops, FALSE, FALSE, 0);
7702 gtk_widget_modify_font(GTK_WIDGET(t->oops), oops_font);
7704 /* command entry */
7705 t->cmd = gtk_entry_new();
7706 g_signal_connect(G_OBJECT(t->cmd), "focus-in-event",
7707 G_CALLBACK(entry_focus_cb), t);
7708 gtk_entry_set_inner_border(GTK_ENTRY(t->cmd), NULL);
7709 gtk_entry_set_has_frame(GTK_ENTRY(t->cmd), FALSE);
7710 gtk_box_pack_end(GTK_BOX(t->vbox), t->cmd, FALSE, FALSE, 0);
7711 gtk_widget_modify_font(GTK_WIDGET(t->cmd), cmd_font);
7713 /* status bar */
7714 statusbar_create(t);
7716 /* buffer list */
7717 t->buffers = create_buffers(t);
7718 gtk_box_pack_end(GTK_BOX(t->vbox), t->buffers, FALSE, FALSE, 0);
7720 /* xtp meaning is normal by default */
7721 set_normal_tab_meaning(t);
7723 /* set empty favicon */
7724 xt_icon_from_name(t, "text-html");
7726 /* and show it all */
7727 gtk_widget_show_all(b);
7728 gtk_widget_show_all(t->vbox);
7730 if (!fancy_bar) {
7731 gtk_widget_hide(t->backward);
7732 gtk_widget_hide(t->forward);
7733 gtk_widget_hide(t->stop);
7734 gtk_widget_hide(t->js_toggle);
7736 if (!fancy_bar || (search_string == NULL || strlen(search_string) == 0))
7737 gtk_widget_hide(t->search_entry);
7739 /* compact tab bar */
7740 t->tab_elems.label = gtk_label_new(title);
7741 t->tab_elems.favicon = gtk_image_new();
7743 t->tab_elems.eventbox = gtk_event_box_new();
7744 gtk_widget_set_name(t->tab_elems.eventbox, "compact_tab");
7745 #if GTK_CHECK_VERSION(3, 0, 0)
7746 t->tab_elems.box = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 0);
7748 gtk_label_set_ellipsize(GTK_LABEL(t->tab_elems.label),
7749 PANGO_ELLIPSIZE_END);
7750 gtk_widget_override_font(t->tab_elems.label, tabbar_font);
7751 gtk_widget_set_halign(t->tab_elems.label, GTK_ALIGN_START);
7752 gtk_widget_set_valign(t->tab_elems.label, GTK_ALIGN_START);
7753 #else
7754 t->tab_elems.box = gtk_hbox_new(FALSE, 0);
7756 gtk_label_set_width_chars(GTK_LABEL(t->tab_elems.label), 1);
7757 gtk_misc_set_alignment(GTK_MISC(t->tab_elems.label), 0.0, 0.0);
7758 gtk_misc_set_padding(GTK_MISC(t->tab_elems.label), 4.0, 4.0);
7759 gtk_widget_modify_font(GTK_WIDGET(t->tab_elems.label), tabbar_font);
7761 gdk_color_parse(XT_COLOR_CT_BACKGROUND, &color);
7762 gtk_widget_modify_bg(t->tab_elems.eventbox, GTK_STATE_NORMAL, &color);
7763 gdk_color_parse(XT_COLOR_CT_INACTIVE, &color);
7764 gtk_widget_modify_fg(t->tab_elems.label, GTK_STATE_NORMAL, &color);
7765 #endif
7767 gtk_box_pack_start(GTK_BOX(t->tab_elems.box), t->tab_elems.favicon, FALSE,
7768 FALSE, 0);
7769 gtk_box_pack_start(GTK_BOX(t->tab_elems.box), t->tab_elems.label, TRUE,
7770 TRUE, 0);
7771 gtk_container_add(GTK_CONTAINER(t->tab_elems.eventbox),
7772 t->tab_elems.box);
7774 gtk_box_pack_start(GTK_BOX(tab_bar_box), t->tab_elems.eventbox, TRUE,
7775 TRUE, 0);
7776 gtk_widget_show_all(t->tab_elems.eventbox);
7778 if (append_next == 0 || gtk_notebook_get_n_pages(notebook) == 0)
7779 append_tab(t);
7780 else {
7781 id = position >= 0 ? position :
7782 gtk_notebook_get_current_page(notebook) + 1;
7783 if (id > gtk_notebook_get_n_pages(notebook))
7784 append_tab(t);
7785 else {
7786 TAILQ_INSERT_TAIL(&tabs, t, entry);
7787 gtk_notebook_insert_page(notebook, t->vbox, b, id);
7788 gtk_box_reorder_child(GTK_BOX(tab_bar_box),
7789 t->tab_elems.eventbox, id);
7790 recalc_tabs();
7794 #if GTK_CHECK_VERSION(2, 20, 0)
7795 /* turn spinner off if we are a new tab without uri */
7796 if (!load) {
7797 gtk_spinner_stop(GTK_SPINNER(t->spinner));
7798 gtk_widget_hide(t->spinner);
7800 #endif
7801 /* make notebook tabs reorderable */
7802 gtk_notebook_set_tab_reorderable(notebook, t->vbox, TRUE);
7804 /* compact tabs clickable */
7805 g_signal_connect(G_OBJECT(t->tab_elems.eventbox),
7806 "button_press_event", G_CALLBACK(tab_clicked_cb), t);
7808 g_object_connect(G_OBJECT(t->cmd),
7809 "signal::button-release-event", G_CALLBACK(cmd_keyrelease_cb), t,
7810 "signal::key-press-event", G_CALLBACK(cmd_keypress_cb), t,
7811 "signal::key-release-event", G_CALLBACK(cmd_keyrelease_cb), t,
7812 "signal::focus-out-event", G_CALLBACK(cmd_focusout_cb), t,
7813 "signal::activate", G_CALLBACK(cmd_activate_cb), t,
7814 "signal::populate-popup", G_CALLBACK(cmd_popup_cb), t,
7815 "signal::hide", G_CALLBACK(cmd_hide_cb), t,
7816 (char *)NULL);
7818 /* reuse wv_button_cb to hide oops */
7819 g_object_connect(G_OBJECT(t->oops),
7820 "signal::button_press_event", G_CALLBACK(wv_button_cb), t,
7821 (char *)NULL);
7823 g_signal_connect(t->buffers,
7824 "row-activated", G_CALLBACK(row_activated_cb), t);
7825 g_object_connect(G_OBJECT(t->buffers),
7826 "signal::key-press-event", G_CALLBACK(wv_keypress_cb), t, (char *)NULL);
7828 g_object_connect(G_OBJECT(t->wv),
7829 "signal::key-press-event", G_CALLBACK(wv_keypress_cb), t,
7830 "signal::hovering-over-link", G_CALLBACK(webview_hover_cb), t,
7831 "signal::download-requested", G_CALLBACK(webview_download_cb), t,
7832 "signal::mime-type-policy-decision-requested", G_CALLBACK(webview_mimetype_cb), t,
7833 "signal::navigation-policy-decision-requested", G_CALLBACK(webview_npd_cb), t,
7834 "signal::new-window-policy-decision-requested", G_CALLBACK(webview_npd_cb), t,
7835 "signal::resource-request-starting", G_CALLBACK(webview_rrs_cb), t,
7836 "signal::create-web-view", G_CALLBACK(webview_cwv_cb), t,
7837 "signal::close-web-view", G_CALLBACK(webview_closewv_cb), t,
7838 "signal::event", G_CALLBACK(webview_event_cb), t,
7839 "signal::load-finished", G_CALLBACK(webview_load_finished_cb), t,
7840 "signal::load-progress-changed", G_CALLBACK(webview_progress_changed_cb), t,
7841 "signal::icon-loaded", G_CALLBACK(notify_icon_loaded_cb), t,
7842 "signal::button_press_event", G_CALLBACK(wv_button_cb), t,
7843 "signal::button_release_event", G_CALLBACK(wv_release_button_cb), t,
7844 "signal::populate-popup", G_CALLBACK(wv_popup_cb), t,
7845 (char *)NULL);
7846 g_signal_connect(t->wv,
7847 "notify::load-status", G_CALLBACK(notify_load_status_cb), t);
7848 g_signal_connect(t->wv,
7849 "notify::title", G_CALLBACK(notify_title_cb), t);
7851 /* hijack the unused keys as if we were the browser */
7852 //g_object_connect(G_OBJECT(t->toolbar),
7853 // "signal-after::key-press-event", G_CALLBACK(wv_keypress_after_cb), t,
7854 // (char *)NULL);
7856 g_signal_connect(G_OBJECT(bb), "button_press_event",
7857 G_CALLBACK(tab_close_cb), t);
7859 /* setup history */
7860 t->bfl = webkit_web_view_get_back_forward_list(t->wv);
7861 /* restore the tab's history */
7862 if (u && u->history) {
7863 items = u->history;
7864 while (items) {
7865 item = items->data;
7866 webkit_web_back_forward_list_add_item(t->bfl, item);
7867 items = g_list_next(items);
7870 item = g_list_nth_data(u->history, u->back);
7871 if (item)
7872 webkit_web_view_go_to_back_forward_item(t->wv, item);
7874 g_list_free(items);
7875 g_list_free(u->history);
7876 } else
7877 webkit_web_back_forward_list_clear(t->bfl);
7879 /* check and show url and statusbar */
7880 url_set_visibility();
7881 statusbar_set_visibility();
7883 if (focus) {
7884 set_current_tab(t->tab_id);
7885 DNPRINTF(XT_D_TAB, "create_new_tab: going to tab: %d\n",
7886 t->tab_id);
7888 if (load) {
7889 gtk_entry_set_text(GTK_ENTRY(t->uri_entry), title);
7890 load_uri(t, title);
7891 } else {
7892 if (show_url == 1)
7893 gtk_widget_grab_focus(GTK_WIDGET(t->uri_entry));
7894 else
7895 focus_webview(t);
7897 } else if (load)
7898 load_uri(t, title);
7900 if (userstyle_global)
7901 apply_style(t);
7903 recolor_compact_tabs();
7904 setzoom_webkit(t, XT_ZOOM_NORMAL);
7905 return (t);
7908 void
7909 notebook_switchpage_cb(GtkNotebook *nb, GtkWidget *nbp, guint pn,
7910 gpointer *udata)
7912 struct tab *t;
7913 const gchar *uri;
7915 DNPRINTF(XT_D_TAB, "notebook_switchpage_cb: tab: %d\n", pn);
7917 if (gtk_notebook_get_current_page(notebook) == -1)
7918 recalc_tabs();
7920 TAILQ_FOREACH(t, &tabs, entry) {
7921 if (t->tab_id == pn) {
7922 DNPRINTF(XT_D_TAB, "notebook_switchpage_cb: going to "
7923 "%d\n", pn);
7925 uri = get_title(t, TRUE);
7926 gtk_window_set_title(GTK_WINDOW(main_window), uri);
7928 hide_cmd(t);
7929 hide_oops(t);
7930 hide_buffers(t);
7932 if (t->focus_wv) {
7933 /* can't use focus_webview here */
7934 gtk_widget_grab_focus(GTK_WIDGET(t->wv));
7936 update_statusbar_tabs(t);
7937 break;
7942 void
7943 notebook_pagereordered_cb(GtkNotebook *nb, GtkWidget *nbp, guint pn,
7944 gpointer *udata)
7946 struct tab *t = NULL, *tt;
7948 recalc_tabs();
7950 TAILQ_FOREACH(tt, &tabs, entry)
7951 if (tt->tab_id == pn) {
7952 t = tt;
7953 break;
7955 if (t == NULL)
7956 return;
7957 DNPRINTF(XT_D_TAB, "page_reordered_cb: tab: %d\n", t->tab_id);
7959 gtk_box_reorder_child(GTK_BOX(tab_bar_box), t->tab_elems.eventbox,
7960 t->tab_id);
7962 update_statusbar_tabs(t);
7965 void
7966 menuitem_response(struct tab *t)
7968 gtk_notebook_set_current_page(notebook, t->tab_id);
7972 destroy_menu(GtkWidget *w, GdkEventFocus *e, void *notused)
7974 gtk_widget_destroy(w);
7975 return (XT_CB_PASSTHROUGH);
7978 gboolean
7979 arrow_cb(GtkWidget *w, GdkEventButton *event, gpointer user_data)
7981 GtkWidget *menu, *menu_items;
7982 GdkEventButton *bevent;
7983 struct tab **stabs = NULL;
7984 int i, num_tabs;
7985 const gchar *uri;
7987 if (event->type == GDK_BUTTON_PRESS) {
7988 bevent = (GdkEventButton *) event;
7989 menu = gtk_menu_new();
7991 num_tabs = sort_tabs_by_page_num(&stabs);
7992 for (i = 0; i < num_tabs; ++i) {
7993 if (stabs[i] == NULL)
7994 continue;
7995 if ((uri = get_uri(stabs[i])) == NULL)
7996 /* XXX make sure there is something to print */
7997 /* XXX add gui pages in here to look purdy */
7998 uri = "(untitled)";
7999 menu_items = gtk_menu_item_new_with_label(uri);
8000 gtk_menu_shell_append(GTK_MENU_SHELL(menu), menu_items);
8001 gtk_widget_show(menu_items);
8003 g_signal_connect_swapped((menu_items),
8004 "activate", G_CALLBACK(menuitem_response),
8005 (gpointer)stabs[i]);
8007 g_free(stabs);
8009 gtk_menu_popup(GTK_MENU(menu), NULL, NULL, NULL, NULL,
8010 bevent->button, bevent->time);
8012 g_object_connect(G_OBJECT(menu),
8013 "signal::hide", G_CALLBACK(destroy_menu), NULL,
8014 (char *)NULL);
8016 return (TRUE /* eat event */);
8019 return (FALSE /* propagate */);
8023 icon_size_map(int iconsz)
8025 if (iconsz <= GTK_ICON_SIZE_INVALID ||
8026 iconsz > GTK_ICON_SIZE_DIALOG)
8027 return (GTK_ICON_SIZE_SMALL_TOOLBAR);
8029 return (iconsz);
8032 GtkWidget *
8033 create_button(char *name, char *stockid, int size)
8035 GtkWidget *button, *image;
8036 int gtk_icon_size;
8037 #if !GTK_CHECK_VERSION(3, 0, 0)
8038 gchar *newstyle;
8039 #endif
8041 #if !GTK_CHECK_VERSION(3, 0, 0)
8042 newstyle = g_strdup_printf(
8043 "style \"%s-style\"\n"
8044 "{\n"
8045 " GtkWidget::focus-padding = 0\n"
8046 " GtkWidget::focus-line-width = 0\n"
8047 " xthickness = 0\n"
8048 " ythickness = 0\n"
8049 "}\n"
8050 "widget \"*.%s\" style \"%s-style\"", name, name, name);
8051 gtk_rc_parse_string(newstyle);
8052 g_free(newstyle);
8053 #endif
8054 button = gtk_button_new();
8055 gtk_widget_set_can_focus(button, FALSE);
8056 gtk_button_set_focus_on_click(GTK_BUTTON(button), FALSE);
8057 gtk_icon_size = icon_size_map(size ? size : icon_size);
8059 image = gtk_image_new_from_stock(stockid, gtk_icon_size);
8060 gtk_container_set_border_width(GTK_CONTAINER(button), 1);
8061 gtk_container_add(GTK_CONTAINER(button), GTK_WIDGET(image));
8062 gtk_widget_set_name(button, name);
8063 gtk_button_set_relief(GTK_BUTTON(button), GTK_RELIEF_NONE);
8065 return (button);
8068 void
8069 button_set_stockid(GtkWidget *button, char *stockid)
8071 GtkWidget *image;
8073 image = gtk_image_new_from_stock(stockid, icon_size_map(icon_size));
8074 gtk_button_set_image(GTK_BUTTON(button), image);
8077 void
8078 create_canvas(void)
8080 GtkWidget *vbox;
8081 GList *l = NULL;
8082 GdkPixbuf *pb;
8083 char file[PATH_MAX];
8084 int i;
8085 #if !GTK_CHECK_VERSION(3, 0, 0)
8086 GdkColor color;
8087 #endif
8089 #if GTK_CHECK_VERSION(3, 0, 0)
8090 vbox = gtk_box_new(GTK_ORIENTATION_VERTICAL, 0);
8091 #else
8092 vbox = gtk_vbox_new(FALSE, 0);
8093 #endif
8094 gtk_box_set_spacing(GTK_BOX(vbox), 0);
8095 gtk_widget_set_can_focus(vbox, FALSE);
8096 notebook = GTK_NOTEBOOK(gtk_notebook_new());
8097 #if !GTK_CHECK_VERSION(3, 0, 0)
8098 /* XXX seems to be needed with gtk+2 */
8099 g_object_set(G_OBJECT(notebook), "tab-border", 0, NULL);
8100 #endif
8101 gtk_notebook_set_scrollable(notebook, TRUE);
8102 gtk_notebook_set_show_border(notebook, FALSE);
8103 gtk_widget_set_can_focus(GTK_WIDGET(notebook), FALSE);
8105 abtn = gtk_button_new();
8106 gtk_widget_set_can_focus(abtn, FALSE);
8107 arrow = gtk_arrow_new(GTK_ARROW_DOWN, GTK_SHADOW_NONE);
8108 gtk_widget_set_name(abtn, "Arrow");
8109 gtk_container_add(GTK_CONTAINER(abtn), arrow);
8110 gtk_widget_set_size_request(abtn, -1, 20);
8112 #if GTK_CHECK_VERSION(2, 20, 0)
8113 gtk_notebook_set_action_widget(notebook, abtn, GTK_PACK_END);
8114 #endif
8115 /* compact tab bar */
8116 tab_bar = gtk_event_box_new();
8117 #if GTK_CHECK_VERSION(3, 0, 0)
8118 gtk_widget_set_name(tab_bar, "tab_bar");
8119 tab_bar_box = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 0);
8120 #else
8121 gdk_color_parse(XT_COLOR_CT_SEPARATOR, &color);
8122 gtk_widget_modify_bg(tab_bar, GTK_STATE_NORMAL, &color);
8123 tab_bar_box = gtk_hbox_new(TRUE, 0);
8124 #endif
8125 gtk_container_add(GTK_CONTAINER(tab_bar), tab_bar_box);
8126 gtk_box_set_homogeneous(GTK_BOX(tab_bar_box), TRUE);
8127 gtk_box_set_spacing(GTK_BOX(tab_bar_box), 2);
8129 gtk_box_pack_start(GTK_BOX(vbox), tab_bar, FALSE, FALSE, 0);
8130 gtk_box_pack_start(GTK_BOX(vbox), GTK_WIDGET(notebook), TRUE, TRUE, 0);
8132 g_object_connect(G_OBJECT(notebook),
8133 "signal::switch-page", G_CALLBACK(notebook_switchpage_cb), NULL,
8134 (char *)NULL);
8135 g_object_connect(G_OBJECT(notebook),
8136 "signal::page-reordered", G_CALLBACK(notebook_pagereordered_cb),
8137 NULL, (char *)NULL);
8138 g_signal_connect(G_OBJECT(abtn), "button_press_event",
8139 G_CALLBACK(arrow_cb), NULL);
8141 main_window = create_window("xombrero");
8142 gtk_container_add(GTK_CONTAINER(main_window), vbox);
8143 g_signal_connect(G_OBJECT(main_window), "delete_event",
8144 G_CALLBACK(gtk_main_quit), NULL);
8145 #if GTK_CHECK_VERSION(3, 0, 0)
8146 gtk_window_set_has_resize_grip(GTK_WINDOW(main_window), FALSE);
8147 #endif
8149 /* icons */
8150 for (i = 0; i < LENGTH(icons); i++) {
8151 snprintf(file, sizeof file, "%s" PS "%s", resource_dir, icons[i]);
8152 pb = gdk_pixbuf_new_from_file(file, NULL);
8153 l = g_list_append(l, pb);
8155 gtk_window_set_default_icon_list(l);
8157 gtk_widget_show_all(abtn);
8158 gtk_widget_show_all(main_window);
8159 notebook_tab_set_visibility();
8162 #ifndef XT_SOCKET_DISABLE
8164 send_cmd_to_socket(char *cmd)
8166 int s, len, rv = 1;
8167 struct sockaddr_un sa;
8169 if ((s = socket(AF_UNIX, SOCK_STREAM, 0)) == -1) {
8170 warnx("%s: socket", __func__);
8171 return (rv);
8174 sa.sun_family = AF_UNIX;
8175 snprintf(sa.sun_path, sizeof(sa.sun_path), "%s" PS "%s",
8176 work_dir, XT_SOCKET_FILE);
8177 len = SUN_LEN(&sa);
8179 if (connect(s, (struct sockaddr *)&sa, len) == -1) {
8180 warnx("%s: connect", __func__);
8181 goto done;
8184 if (send(s, cmd, strlen(cmd) + 1, 0) == -1) {
8185 warnx("%s: send", __func__);
8186 goto done;
8189 rv = 0;
8190 done:
8191 close(s);
8192 return (rv);
8195 gboolean
8196 socket_watcher(GIOChannel *source, GIOCondition condition, gpointer data)
8198 int s, n;
8199 char str[XT_MAX_URL_LENGTH];
8200 socklen_t t = sizeof(struct sockaddr_un);
8201 struct sockaddr_un sa;
8202 struct passwd *p;
8203 uid_t uid;
8204 gid_t gid;
8205 struct tab *tt;
8206 gint fd = g_io_channel_unix_get_fd(source);
8208 if ((s = accept(fd, (struct sockaddr *)&sa, &t)) == -1) {
8209 warn("accept");
8210 return (FALSE);
8213 if (getpeereid(s, &uid, &gid) == -1) {
8214 warn("getpeereid");
8215 return (FALSE);
8217 if (uid != getuid() || gid != getgid()) {
8218 warnx("unauthorized user");
8219 return (FALSE);
8222 p = getpwuid(uid);
8223 if (p == NULL) {
8224 warnx("not a valid user");
8225 return (FALSE);
8228 n = recv(s, str, sizeof(str), 0);
8229 if (n <= 0)
8230 return (TRUE);
8232 tt = get_current_tab();
8233 cmd_execute(tt, str);
8234 return (TRUE);
8238 is_running(void)
8240 int s, len, rv = 1;
8241 struct sockaddr_un sa;
8243 if ((s = socket(AF_UNIX, SOCK_STREAM, 0)) == -1) {
8244 warn("is_running: socket");
8245 return (-1);
8248 sa.sun_family = AF_UNIX;
8249 snprintf(sa.sun_path, sizeof(sa.sun_path), "%s" PS "%s",
8250 work_dir, XT_SOCKET_FILE);
8251 len = SUN_LEN(&sa);
8253 /* connect to see if there is a listener */
8254 if (connect(s, (struct sockaddr *)&sa, len) == -1)
8255 rv = 0; /* not running */
8256 else
8257 rv = 1; /* already running */
8259 close(s);
8261 return (rv);
8265 build_socket(void)
8267 int s, len;
8268 struct sockaddr_un sa;
8270 if ((s = socket(AF_UNIX, SOCK_STREAM, 0)) == -1) {
8271 warn("build_socket: socket");
8272 return (-1);
8275 sa.sun_family = AF_UNIX;
8276 snprintf(sa.sun_path, sizeof(sa.sun_path), "%s" PS "%s",
8277 work_dir, XT_SOCKET_FILE);
8278 len = SUN_LEN(&sa);
8280 /* connect to see if there is a listener */
8281 if (connect(s, (struct sockaddr *)&sa, len) == -1) {
8282 /* no listener so we will */
8283 unlink(sa.sun_path);
8285 if (bind(s, (struct sockaddr *)&sa, len) == -1) {
8286 warn("build_socket: bind");
8287 goto done;
8290 if (listen(s, 1) == -1) {
8291 warn("build_socket: listen");
8292 goto done;
8295 return (s);
8298 done:
8299 close(s);
8300 return (-1);
8302 #endif
8304 void
8305 xxx_dir(char *dir)
8307 struct stat sb;
8309 if (stat(dir, &sb)) {
8310 #if defined __MINGW32__
8311 if (mkdir(dir) == -1)
8312 #else
8313 if (mkdir(dir, S_IRWXU) == -1)
8314 #endif
8315 err(1, "mkdir %s", dir);
8316 if (stat(dir, &sb))
8317 err(1, "stat %s", dir);
8319 if (S_ISDIR(sb.st_mode) == 0)
8320 errx(1, "%s not a dir", dir);
8321 #if !defined __MINGW32__
8322 if (((sb.st_mode & (S_IRWXU | S_IRWXG | S_IRWXO))) != S_IRWXU) {
8323 warnx("fixing invalid permissions on %s", dir);
8324 if (chmod(dir, S_IRWXU) == -1)
8325 err(1, "chmod %s", dir);
8327 #endif
8330 void
8331 usage(void)
8333 fprintf(stderr,
8334 "%s [-nSTVt][-f file][-s session] url ...\n", __progname);
8335 exit(0);
8338 GStaticRecMutex my_gdk_mtx = G_STATIC_REC_MUTEX_INIT;
8339 volatile int mtx_depth;
8340 int mtx_complain;
8343 * The linux flash plugin violates the gdk locking mechanism.
8344 * Work around the issue by using a recursive mutex with some match applied
8345 * to see if we hit a buggy condition.
8347 * The following code is painful so just don't read it. It really doesn't
8348 * make much sense but seems to work.
8350 void
8351 mtx_lock(void)
8353 #ifdef XT_DEBUG
8354 char *s = NULL;
8355 #endif
8357 g_static_rec_mutex_lock(&my_gdk_mtx);
8358 if (my_gdk_mtx.depth <= 0) {
8359 #ifdef XT_DEBUG
8360 s = "lock <= 0";
8361 #endif
8362 g_static_rec_mutex_lock(&my_gdk_mtx);
8363 goto complain;
8364 } else if (my_gdk_mtx.depth != 1) {
8365 #ifdef XT_DEBUG
8366 s = "lock != 1";
8367 #endif
8368 do {
8369 g_static_rec_mutex_unlock(&my_gdk_mtx);
8370 } while (my_gdk_mtx.depth > 1);
8371 goto complain;
8373 return;
8375 complain:
8376 if (mtx_complain == 0) {
8377 DNPRINTF(XT_D_MTX, "buggy mutex implementation detected(%s), "
8378 "work around implemented", s);
8379 mtx_complain = 1;
8383 void
8384 mtx_unlock(void)
8386 #ifdef XT_DEBUG
8387 char *s = NULL;
8388 #endif
8390 if (my_gdk_mtx.depth <= 0) {
8391 #ifdef XT_DEBUG
8392 s = "unlock <= 0";
8393 #endif
8394 goto complain;
8395 } else if (my_gdk_mtx.depth != 1) {
8396 #ifdef XT_DEBUG
8397 s = "unlock != 1";
8398 #endif
8399 g_static_rec_mutex_unlock_full(&my_gdk_mtx);
8400 goto complain;
8402 g_static_rec_mutex_unlock(&my_gdk_mtx);
8403 return;
8405 complain:
8406 if (mtx_complain == 0) {
8407 DNPRINTF(XT_D_MTX, "buggy mutex implementation detected(%s), "
8408 "work around implemented", s);
8409 mtx_complain = 1;
8413 #if GTK_CHECK_VERSION(3, 0, 0)
8414 void
8415 setup_css(void)
8417 GtkCssProvider *provider;
8418 GdkDisplay *display;
8419 GdkScreen *screen;
8420 GFile *file;
8421 char path[PATH_MAX];
8422 #if defined __MINGW32__
8423 GtkCssProvider *windows_hacks;
8424 #endif
8426 provider = gtk_css_provider_new();
8427 display = gdk_display_get_default();
8428 screen = gdk_display_get_default_screen(display);
8429 snprintf(path, sizeof path, "%s" PS "%s", resource_dir, XT_CSS_FILE);
8430 file = g_file_new_for_path(path);
8431 gtk_css_provider_load_from_file(provider, file, NULL);
8432 gtk_style_context_add_provider_for_screen(screen,
8433 GTK_STYLE_PROVIDER(provider),
8434 GTK_STYLE_PROVIDER_PRIORITY_APPLICATION);
8435 #if defined __MINGW32__
8436 windows_hacks = gtk_css_provider_new();
8437 gtk_css_provider_load_from_data(windows_hacks,
8438 ".notebook tab {\n"
8439 " border-width: 0px;\n"
8440 "}", -1, NULL);
8441 gtk_style_context_add_provider_for_screen(screen,
8442 GTK_STYLE_PROVIDER(windows_hacks),
8443 GTK_STYLE_PROVIDER_PRIORITY_APPLICATION);
8444 #endif
8445 g_object_unref(file);
8447 #endif
8449 void
8450 welcome(void)
8452 startpage_add("<b>Welcome to xombrero %s!</b><p>", version);
8453 startpage_add("Details at "
8454 "<a href=https://opensource.conformal.com/wiki/xombrero>xombrero "
8455 "wiki page</a><p>");
8459 main(int argc, char **argv)
8461 struct stat sb;
8462 int c, optn = 0, opte = 0, focus = 1;
8463 char conf[PATH_MAX] = { '\0' };
8464 char file[PATH_MAX];
8465 char sodversion[32];
8466 char *env_proxy = NULL;
8467 char *path;
8468 FILE *f = NULL;
8469 struct karg a;
8471 start_argv = (char * const *)argv;
8473 if (os_init)
8474 os_init();
8476 /* prepare gtk */
8477 #ifdef USE_THREADS
8478 #if !defined __MINGW32__
8479 /* http://web.archiveorange.com/archive/v/UsPjxkX5PsaXBIoOjqxf */
8480 XInitThreads();
8481 #endif
8482 /* http://developer.gnome.org/gdk/stable/gdk-Threads.html */
8483 g_thread_init(NULL);
8484 gdk_threads_set_lock_functions(mtx_lock, mtx_unlock);
8485 gdk_threads_init();
8486 gdk_threads_enter();
8488 /* http://www.gnupg.org/documentation/manuals/gcrypt/Multi_002dThreading.html */
8489 gcry_control (GCRYCTL_SET_THREAD_CBS, &gcry_threads_pthread);
8490 #endif
8491 gtk_init(&argc, &argv);
8493 gnutls_global_init();
8495 strlcpy(named_session, XT_SAVED_TABS_FILE, sizeof named_session);
8497 RB_INIT(&hl);
8498 RB_INIT(&js_wl);
8499 RB_INIT(&pl_wl);
8500 RB_INIT(&force_https);
8501 RB_INIT(&downloads);
8502 RB_INIT(&st_tree);
8503 RB_INIT(&svl);
8504 RB_INIT(&svil);
8505 RB_INIT(&ua_list);
8507 TAILQ_INIT(&sessions);
8508 TAILQ_INIT(&tabs);
8509 TAILQ_INIT(&mtl);
8510 TAILQ_INIT(&aliases);
8511 TAILQ_INIT(&undos);
8512 TAILQ_INIT(&kbl);
8513 TAILQ_INIT(&spl);
8514 TAILQ_INIT(&chl);
8515 TAILQ_INIT(&shl);
8516 TAILQ_INIT(&cul);
8517 TAILQ_INIT(&srl);
8519 #ifndef XT_RESOURCE_LIMITS_DISABLE
8520 struct rlimit rlp;
8521 char *cmd = NULL;
8522 int s;
8523 GIOChannel *channel;
8525 /* fiddle with ulimits */
8526 if (getrlimit(RLIMIT_NOFILE, &rlp) == -1)
8527 warn("getrlimit");
8528 else {
8529 /* just use them all */
8530 rlp.rlim_cur = rlp.rlim_max;
8531 if (setrlimit(RLIMIT_NOFILE, &rlp) == -1)
8532 warn("setrlimit");
8533 if (getrlimit(RLIMIT_NOFILE, &rlp) == -1)
8534 warn("getrlimit");
8535 else if (rlp.rlim_cur < 1024)
8536 startpage_add("%s requires at least 1024 "
8537 "(2048 recommended) file " "descriptors, "
8538 "currently it has up to %d available",
8539 __progname, rlp.rlim_cur);
8541 #endif
8543 while ((c = getopt(argc, argv, "STVf:s:tne")) != -1) {
8544 switch (c) {
8545 case 'S':
8546 show_url = 0;
8547 break;
8548 case 'T':
8549 show_tabs = 0;
8550 break;
8551 case 'V':
8552 #ifdef XOMBRERO_BUILDSTR
8553 errx(0 , "Version: %s Build: %s",
8554 version, XOMBRERO_BUILDSTR);
8555 #else
8556 errx(0 , "Version: %s", version);
8557 #endif
8558 break;
8559 case 'f':
8560 strlcpy(conf, optarg, sizeof(conf));
8561 break;
8562 case 's':
8563 strlcpy(named_session, optarg, sizeof(named_session));
8564 break;
8565 case 't':
8566 tabless = 1;
8567 break;
8568 case 'n':
8569 optn = 1;
8570 break;
8571 case 'e':
8572 opte = 1;
8573 break;
8574 default:
8575 usage();
8576 /* NOTREACHED */
8579 argc -= optind;
8580 argv += optind;
8582 init_keybindings();
8584 pwd = getpwuid(getuid());
8585 if (pwd == NULL)
8586 errx(1, "invalid user %d", getuid());
8588 /* set download dir */
8589 if (strlen(download_dir) == 0)
8590 strlcpy(download_dir, pwd->pw_dir, sizeof download_dir);
8592 /* compile buffer command regexes */
8593 buffercmd_init();
8595 /* set default dynamic string settings */
8596 home = g_strdup(XT_DS_HOME);
8597 search_string = g_strdup(XT_DS_SEARCH_STRING);
8598 strlcpy(runtime_settings, "runtime", sizeof runtime_settings);
8599 cmd_font_name = g_strdup(XT_DS_CMD_FONT_NAME);
8600 oops_font_name = g_strdup(XT_DS_OOPS_FONT_NAME);
8601 statusbar_font_name = g_strdup(XT_DS_STATUSBAR_FONT_NAME);
8602 tabbar_font_name = g_strdup(XT_DS_TABBAR_FONT_NAME);
8603 statusbar_elems = g_strdup("BP");
8604 spell_check_languages = g_strdup(XT_DS_SPELL_CHECK_LANGUAGES);
8605 encoding = g_strdup(XT_DS_ENCODING);
8606 spell_check_languages = g_strdup(XT_DS_SPELL_CHECK_LANGUAGES);
8607 path = g_strdup_printf("%s" PS "style.css", resource_dir);
8608 userstyle = g_filename_to_uri(path, NULL, NULL);
8609 g_free(path);
8610 stylesheet = g_strdup(userstyle);
8612 /* set statically allocated (struct special) settings */
8613 if (strlen(default_script) == 0)
8614 expand_tilde(default_script, sizeof default_script,
8615 XT_DS_DEFAULT_SCRIPT);
8616 if (strlen(ssl_ca_file) == 0)
8617 expand_tilde(ssl_ca_file, sizeof ssl_ca_file,
8618 XT_DS_SSL_CA_FILE);
8620 /* soup session */
8621 session = webkit_get_default_session();
8623 /* read config file */
8624 if (strlen(conf) == 0)
8625 snprintf(conf, sizeof conf, "%s" PS ".%s",
8626 pwd->pw_dir, XT_CONF_FILE);
8627 config_parse(conf, 0);
8629 /* read preloaded HSTS list */
8630 if (preload_strict_transport) {
8631 snprintf(conf, sizeof conf, "%s" PS "%s",
8632 resource_dir, XT_HSTS_PRELOAD_FILE);
8633 config_parse(conf, 0);
8636 /* init fonts */
8637 cmd_font = pango_font_description_from_string(cmd_font_name);
8638 oops_font = pango_font_description_from_string(oops_font_name);
8639 statusbar_font = pango_font_description_from_string(statusbar_font_name);
8640 tabbar_font = pango_font_description_from_string(tabbar_font_name);
8642 /* working directory */
8643 if (strlen(work_dir) == 0)
8644 snprintf(work_dir, sizeof work_dir, "%s" PS "%s",
8645 pwd->pw_dir, XT_DIR);
8646 xxx_dir(work_dir);
8648 /* icon cache dir */
8649 snprintf(cache_dir, sizeof cache_dir, "%s" PS "%s", work_dir, XT_CACHE_DIR);
8650 xxx_dir(cache_dir);
8652 /* certs dir */
8653 snprintf(certs_dir, sizeof certs_dir, "%s" PS "%s", work_dir, XT_CERT_DIR);
8654 xxx_dir(certs_dir);
8656 /* cert changes dir */
8657 snprintf(certs_cache_dir, sizeof certs_cache_dir, "%s" PS "%s",
8658 work_dir, XT_CERT_CACHE_DIR);
8659 xxx_dir(certs_cache_dir);
8661 /* sessions dir */
8662 snprintf(sessions_dir, sizeof sessions_dir, "%s" PS "%s",
8663 work_dir, XT_SESSIONS_DIR);
8664 xxx_dir(sessions_dir);
8666 /* js dir */
8667 snprintf(js_dir, sizeof js_dir, "%s" PS "%s", work_dir, XT_JS_DIR);
8668 xxx_dir(js_dir);
8670 /* temp dir */
8671 snprintf(temp_dir, sizeof temp_dir, "%s" PS "%s", work_dir, XT_TEMP_DIR);
8672 xxx_dir(temp_dir);
8674 /* runtime settings that can override config file */
8675 if (runtime_settings[0] != '\0')
8676 config_parse(runtime_settings, 1);
8678 /* download dir */
8679 if (!strcmp(download_dir, pwd->pw_dir))
8680 strlcat(download_dir, PS "downloads", sizeof download_dir);
8681 xxx_dir(download_dir);
8683 /* first start file */
8684 snprintf(file, sizeof file, "%s" PS "%s", work_dir, XT_SOD_FILE);
8685 if (stat(file, &sb)) {
8686 warnx("start of day file doesn't exist, creating it");
8687 if ((f = fopen(file, "w")) == NULL)
8688 err(1, "startofday");
8689 if (fputs(version, f) == EOF)
8690 err(1, "fputs");
8691 fclose(f);
8693 /* welcome user */
8694 welcome();
8695 } else {
8696 if ((f = fopen(file, "r+")) == NULL)
8697 err(1, "startofday");
8698 if (fgets(sodversion, sizeof sodversion, f) == NULL)
8699 err(1, "fgets");
8700 sodversion[strcspn(sodversion, "\n")] = '\0';
8701 if (strcmp(version, sodversion)) {
8702 if ((f = freopen(file, "w", f)) == NULL)
8703 err(1, "startofday");
8704 if (fputs(version, f) == EOF)
8705 err(1, "fputs");
8707 /* upgrade, say something smart */
8708 welcome();
8710 fclose(f);
8713 /* favorites file */
8714 snprintf(file, sizeof file, "%s" PS "%s", work_dir, XT_FAVS_FILE);
8715 if (stat(file, &sb)) {
8716 warnx("favorites file doesn't exist, creating it");
8717 if ((f = fopen(file, "w")) == NULL)
8718 err(1, "favorites");
8719 fclose(f);
8722 /* quickmarks file */
8723 snprintf(file, sizeof file, "%s" PS "%s", work_dir, XT_QMARKS_FILE);
8724 if (stat(file, &sb)) {
8725 warnx("quickmarks file doesn't exist, creating it");
8726 if ((f = fopen(file, "w")) == NULL)
8727 err(1, "quickmarks");
8728 fclose(f);
8731 /* search history */
8732 if (history_autosave) {
8733 snprintf(search_file, sizeof search_file, "%s" PS "%s",
8734 work_dir, XT_SEARCH_FILE);
8735 if (stat(search_file, &sb)) {
8736 warnx("search history file doesn't exist, creating it");
8737 if ((f = fopen(search_file, "w")) == NULL)
8738 err(1, "search_history");
8739 fclose(f);
8741 history_read(&shl, search_file, &search_history_count);
8744 /* command history */
8745 if (history_autosave) {
8746 snprintf(command_file, sizeof command_file, "%s" PS "%s",
8747 work_dir, XT_COMMAND_FILE);
8748 if (stat(command_file, &sb)) {
8749 warnx("command history file doesn't exist, creating it");
8750 if ((f = fopen(command_file, "w")) == NULL)
8751 err(1, "command_history");
8752 fclose(f);
8754 history_read(&chl, command_file, &cmd_history_count);
8757 /* cookies */
8758 setup_cookies();
8760 /* guess_search regex */
8761 if (url_regex == NULL)
8762 url_regex = g_strdup(XT_URL_REGEX);
8763 if (url_regex)
8764 if (regcomp(&url_re, url_regex, REG_EXTENDED | REG_NOSUB))
8765 startpage_add("invalid url regex %s", url_regex);
8767 /* proxy */
8768 env_proxy = getenv("http_proxy");
8769 if (env_proxy)
8770 setup_proxy(env_proxy);
8771 else {
8772 env_proxy = getenv("HTTP_PROXY");
8773 if (env_proxy)
8774 setup_proxy(env_proxy);
8775 else
8776 setup_proxy(http_proxy);
8779 /* the user can optionally have the proxy disabled at startup */
8780 if ((http_proxy_starts_enabled == 0) && (http_proxy != NULL)) {
8781 http_proxy_save = g_strdup(http_proxy);
8782 setup_proxy(NULL);
8785 #ifndef XT_SOCKET_DISABLE
8786 if (opte) {
8787 send_cmd_to_socket(argv[0]);
8788 exit(0);
8790 #else
8791 opte = opte; /* shut mingw up */
8792 #endif
8793 /* set some connection parameters */
8794 g_object_set(session, "max-conns", max_connections, (char *)NULL);
8795 g_object_set(session, "max-conns-per-host", max_host_connections,
8796 (char *)NULL);
8797 g_object_set(session, SOUP_SESSION_SSL_STRICT, ssl_strict_certs,
8798 (char *)NULL);
8800 g_signal_connect(session, "request-queued", G_CALLBACK(session_rq_cb),
8801 NULL);
8803 #ifndef XT_SOCKET_DISABLE
8804 /* see if there is already a xombrero running */
8805 if (single_instance && is_running()) {
8806 optn = 1;
8807 warnx("already running");
8810 if (optn) {
8811 while (argc) {
8812 cmd = g_strdup_printf("%s %s", "tabnew", argv[0]);
8813 send_cmd_to_socket(cmd);
8814 if (cmd)
8815 g_free(cmd);
8817 argc--;
8818 argv++;
8820 exit(0);
8822 #else
8823 optn = optn; /* shut mingw up */
8824 #endif
8825 /* tld list */
8826 tld_tree_init();
8828 if (enable_strict_transport)
8829 strict_transport_init();
8831 /* uri completion */
8832 completion_model = gtk_list_store_new(1, G_TYPE_STRING);
8834 /* buffers */
8835 buffers_store = gtk_list_store_new
8836 (NUM_COLS, G_TYPE_UINT, GDK_TYPE_PIXBUF, G_TYPE_STRING);
8838 qmarks_load();
8840 /* go graphical */
8841 create_canvas();
8842 notebook_tab_set_visibility();
8844 if (save_global_history)
8845 restore_global_history();
8847 /* restore session list */
8848 restore_sessions_list();
8850 if (!strcmp(named_session, XT_SAVED_TABS_FILE))
8851 restore_saved_tabs();
8852 else {
8853 a.s = named_session;
8854 a.i = XT_SES_DONOTHING;
8855 open_tabs(NULL, &a);
8858 /* see if we have an exception */
8859 if (!TAILQ_EMPTY(&spl)) {
8860 create_new_tab("about:startpage", NULL, focus, -1);
8861 focus = 0;
8864 while (argc) {
8865 create_new_tab(argv[0], NULL, focus, -1);
8866 focus = 0;
8868 argc--;
8869 argv++;
8872 if (TAILQ_EMPTY(&tabs))
8873 create_new_tab(home, NULL, 1, -1);
8874 #ifndef XT_SOCKET_DISABLE
8875 if (enable_socket)
8876 if ((s = build_socket()) != -1) {
8877 channel = g_io_channel_unix_new(s);
8878 g_io_add_watch(channel, G_IO_IN, socket_watcher, NULL);
8880 #endif
8882 #if GTK_CHECK_VERSION(3, 0, 0)
8883 setup_css();
8884 #endif
8886 gtk_main();
8888 #ifdef USE_THREADS
8889 GDK_FLUSH();
8890 gdk_threads_leave();
8891 g_static_rec_mutex_unlock_full(&my_gdk_mtx); /* just in case */
8892 #endif
8894 gnutls_global_deinit();
8896 if (url_regex)
8897 regfree(&url_re);
8899 return (0);