Initialize some variables to remove warnings.
[xombrero.git] / xombrero.c
blob85daf52fa3822bb3189de5652dcfbbd322e62e42
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 /* autorun some js if enabled */
4268 js_autorun(t);
4270 input_autofocus(t);
4272 if (!strncmp(uri, "http://", strlen("http://")) ||
4273 !strncmp(uri, "https://", strlen("https://")) ||
4274 !strncmp(uri, "file://", strlen("file://"))) {
4275 find.uri = (gchar *)uri;
4276 h = RB_FIND(history_list, &hl, &find);
4277 if (!h)
4278 insert_history_item(uri,
4279 get_title(t, FALSE), time(NULL));
4280 else
4281 h->time = time(NULL);
4284 if (statusbar_style == XT_STATUSBAR_URL)
4285 set_status(t, "%s", (char *)uri);
4286 else
4287 set_status(t, "%s", (char *)get_title(t, FALSE));
4288 gtk_widget_set_sensitive(GTK_WIDGET(t->stop), FALSE);
4289 #if GTK_CHECK_VERSION(2, 20, 0)
4290 gtk_spinner_stop(GTK_SPINNER(t->spinner));
4291 gtk_widget_hide(t->spinner);
4292 #endif
4293 break;
4295 #if WEBKIT_CHECK_VERSION(1, 1, 18)
4296 case WEBKIT_LOAD_FAILED:
4297 /* 4 */
4298 if (!t->download_requested) {
4299 gtk_label_set_text(GTK_LABEL(t->label),
4300 get_title(t, FALSE));
4301 gtk_label_set_text(GTK_LABEL(t->tab_elems.label),
4302 get_title(t, FALSE));
4303 set_status(t, "%s", (char *)get_title(t, FALSE));
4304 gtk_window_set_title(GTK_WINDOW(main_window),
4305 get_title(t, TRUE));
4306 } else {
4309 #endif
4310 default:
4311 #if GTK_CHECK_VERSION(2, 20, 0)
4312 gtk_spinner_stop(GTK_SPINNER(t->spinner));
4313 gtk_widget_hide(t->spinner);
4314 #endif
4315 gtk_widget_set_sensitive(GTK_WIDGET(t->stop), FALSE);
4316 break;
4319 gtk_widget_set_sensitive(GTK_WIDGET(t->backward),
4320 t->item || webkit_web_view_can_go_back(t->wv));
4322 gtk_widget_set_sensitive(GTK_WIDGET(t->forward),
4323 webkit_web_view_can_go_forward(t->wv));
4326 void
4327 notify_title_cb(WebKitWebView* wview, GParamSpec* pspec, struct tab *t)
4329 const gchar *title = NULL, *win_title = NULL;
4331 title = get_title(t, FALSE);
4332 win_title = get_title(t, TRUE);
4333 if (title) {
4334 gtk_label_set_text(GTK_LABEL(t->label), title);
4335 gtk_label_set_text(GTK_LABEL(t->tab_elems.label), title);
4338 if (win_title && t->tab_id == gtk_notebook_get_current_page(notebook))
4339 gtk_window_set_title(GTK_WINDOW(main_window), win_title);
4342 char *
4343 get_domain(const gchar *host)
4345 size_t x;
4346 char *p;
4348 /* handle silly domains like .co.uk */
4350 if ((x = strlen(host)) <= 6)
4351 return (g_strdup(host));
4353 if (host[x - 3] == '.' && host[x - 6] == '.') {
4354 x = x - 7;
4355 while (x > 0)
4356 if (host[x] != '.')
4357 x--;
4358 else
4359 return (g_strdup(&host[x + 1]));
4362 /* find first . */
4363 p = g_strrstr(host, ".");
4364 if (p == NULL)
4365 return (g_strdup(""));
4366 p--;
4367 while (p > host)
4368 if (*p != '.')
4369 p--;
4370 else
4371 return (g_strdup(p + 1));
4373 return (g_strdup(host));
4376 void
4377 js_autorun(struct tab *t)
4379 SoupURI *su = NULL;
4380 const gchar *uri;
4381 size_t got_default = 0, got_host = 0;
4382 struct stat sb;
4383 char deff[PATH_MAX], hostf[PATH_MAX];
4384 char *js = NULL, *jsat, *domain = NULL;
4385 FILE *deffile = NULL, *hostfile = NULL;
4387 if (enable_js_autorun == 0)
4388 return;
4390 uri = get_uri(t);
4391 if (uri &&
4392 !(g_str_has_prefix(uri, "http://") ||
4393 g_str_has_prefix(uri, "https://")))
4394 goto done;
4396 su = soup_uri_new(uri);
4397 if (su == NULL)
4398 goto done;
4399 if (!SOUP_URI_VALID_FOR_HTTP(su))
4400 goto done;
4402 DNPRINTF(XT_D_JS, "%s: host: %s domain: %s\n", __func__,
4403 su->host, domain);
4404 domain = get_domain(su->host);
4406 snprintf(deff, sizeof deff, "%s" PS "default.js", js_dir);
4407 if ((deffile = fopen(deff, "r")) != NULL) {
4408 if (fstat(fileno(deffile), &sb) == -1) {
4409 show_oops(t, "can't stat default JS file");
4410 goto done;
4412 got_default = sb.st_size;
4415 /* try host first followed by domain */
4416 snprintf(hostf, sizeof hostf, "%s" PS "%s.js", js_dir, su->host);
4417 DNPRINTF(XT_D_JS, "trying file: %s\n", hostf);
4418 if ((hostfile = fopen(hostf, "r")) == NULL) {
4419 snprintf(hostf, sizeof hostf, "%s" PS "%s.js", js_dir, domain);
4420 DNPRINTF(XT_D_JS, "trying file: %s\n", hostf);
4421 if ((hostfile = fopen(hostf, "r")) == NULL)
4422 goto nofile;
4424 DNPRINTF(XT_D_JS, "file: %s\n", hostf);
4425 if (fstat(fileno(hostfile), &sb) == -1) {
4426 show_oops(t, "can't stat %s JS file", hostf);
4427 goto done;
4429 got_host = sb.st_size;
4431 nofile:
4432 if (got_default + got_host == 0)
4433 goto done;
4435 js = g_malloc0(got_default + got_host + 1);
4436 jsat = js;
4438 if (got_default) {
4439 if (fread(js, got_default, 1, deffile) != 1) {
4440 show_oops(t, "default file read error");
4441 goto done;
4443 jsat = js + got_default;
4446 if (got_host) {
4447 if (fread(jsat, got_host, 1, hostfile) != 1) {
4448 show_oops(t, "host file read error");
4449 goto done;
4453 DNPRINTF(XT_D_JS, "%s: about to run script\n", __func__);
4454 run_script_locked(t, js);
4456 done:
4457 if (su)
4458 soup_uri_free(su);
4459 if (js)
4460 g_free(js);
4461 if (deffile)
4462 fclose(deffile);
4463 if (hostfile)
4464 fclose(hostfile);
4465 if (domain)
4466 g_free(domain);
4469 void
4470 webview_progress_changed_cb(WebKitWebView *wv, GParamSpec *pspec, struct tab *t)
4472 gdouble progress;
4474 progress = webkit_web_view_get_progress(wv);
4475 gtk_entry_set_progress_fraction(GTK_ENTRY(t->sbe.uri),
4476 progress == 1.0 ? 0 : progress);
4477 gtk_entry_set_progress_fraction(GTK_ENTRY(t->uri_entry),
4478 progress == 1.0 ? 0 : progress);
4480 update_statusbar_position(NULL, NULL);
4484 strict_transport_rb_cmp(struct strict_transport *a, struct strict_transport *b)
4486 char *p1, *p2;
4487 int l1, l2;
4489 /* compare strings from the end */
4490 l1 = strlen(a->host);
4491 l2 = strlen(b->host);
4493 p1 = a->host + l1;
4494 p2 = b->host + l2;
4495 for (; *p1 == *p2 && p1 > a->host && p2 > b->host;
4496 p1--, p2--)
4500 * Check if we need to do pattern expansion,
4501 * or if we're just keeping the tree in order
4503 if (a->flags & XT_STS_FLAGS_EXPAND &&
4504 b->flags & XT_STS_FLAGS_INCLUDE_SUBDOMAINS) {
4505 /* Check if we're matching the
4506 * 'host.xyz' part in '*.host.xyz'
4508 if (p2 == b->host && (p1 == a->host || *(p1-1) == '.')) {
4509 return (0);
4513 if (p1 == a->host && p2 == b->host)
4514 return (0);
4515 if (p1 == a->host)
4516 return (1);
4517 if (p2 == b->host)
4518 return (-1);
4520 if (*p1 < *p2)
4521 return (-1);
4522 if (*p1 > *p2)
4523 return (1);
4525 return (0);
4527 RB_GENERATE(strict_transport_tree, strict_transport, entry,
4528 strict_transport_rb_cmp);
4531 strict_transport_add(const char *domain, time_t timeout, int subdomains)
4533 struct strict_transport *d, find;
4534 time_t now;
4535 FILE *f;
4537 if (enable_strict_transport == FALSE)
4538 return (0);
4540 DPRINTF("strict_transport_add(%s,%" PRIi64 ",%d)\n", domain,
4541 (uint64_t)timeout, subdomains);
4543 now = time(NULL);
4544 if (timeout < now)
4545 return (0);
4547 find.host = (char *)domain;
4548 find.flags = 0;
4549 d = RB_FIND(strict_transport_tree, &st_tree, &find);
4551 /* update flags */
4552 if (d) {
4553 /* check if update is needed */
4554 if (d->timeout == timeout &&
4555 (d->flags & XT_STS_FLAGS_INCLUDE_SUBDOMAINS) == subdomains)
4556 return (0);
4558 d->timeout = timeout;
4559 if (subdomains)
4560 d->flags |= XT_STS_FLAGS_INCLUDE_SUBDOMAINS;
4562 /* We're still initializing */
4563 if (strict_transport_file == NULL)
4564 return (0);
4566 if ((f = fopen(strict_transport_file, "w")) == NULL) {
4567 show_oops(NULL,
4568 "can't open strict-transport rules file");
4569 return (1);
4572 fprintf(f, "# Generated file - do not update unless you know "
4573 "what you're doing\n");
4574 RB_FOREACH(d, strict_transport_tree, &st_tree) {
4575 if (d->timeout < now)
4576 continue;
4577 fprintf(f, "%s\t%" PRIi64 "\t%d\n", d->host,
4578 (uint64_t)d->timeout,
4579 d->flags & XT_STS_FLAGS_INCLUDE_SUBDOMAINS);
4581 fclose(f);
4582 } else {
4583 d = g_malloc(sizeof *d);
4584 d->host= g_strdup(domain);
4585 d->timeout = timeout;
4586 if (subdomains)
4587 d->flags = XT_STS_FLAGS_INCLUDE_SUBDOMAINS;
4588 else
4589 d->flags = 0;
4590 RB_INSERT(strict_transport_tree, &st_tree, d);
4592 /* We're still initializing */
4593 if (strict_transport_file == NULL)
4594 return (0);
4596 if ((f = fopen(strict_transport_file, "a+")) == NULL) {
4597 show_oops(NULL,
4598 "can't open strict-transport rules file");
4599 return (1);
4602 fseek(f, 0, SEEK_END);
4603 fprintf(f,"%s\t%" PRIi64 "\t%d\n", d->host, (uint64_t)timeout,
4604 subdomains);
4605 fclose(f);
4607 return (0);
4611 strict_transport_check(const char *host)
4613 static struct strict_transport *d = NULL;
4614 struct strict_transport find;
4616 if (enable_strict_transport == FALSE)
4617 return (0);
4619 find.host = (char *)host;
4621 /* match for domains that include subdomains */
4622 find.flags = XT_STS_FLAGS_EXPAND;
4624 /* First, check if we're already at the right node */
4625 if (d != NULL && strict_transport_rb_cmp(&find, d) == 0) {
4626 return (1);
4629 d = RB_FIND(strict_transport_tree, &st_tree, &find);
4630 if (d != NULL)
4631 return (1);
4633 return (0);
4637 strict_transport_init()
4639 char file[PATH_MAX];
4640 char delim[3];
4641 char *rule;
4642 char *ptr;
4643 FILE *f;
4644 size_t len;
4645 time_t timeout, now;
4646 int subdomains;
4648 snprintf(file, sizeof file, "%s" PS "%s", work_dir, XT_STS_FILE);
4649 if ((f = fopen(file, "r")) == NULL) {
4650 strict_transport_file = g_strdup(file);
4651 return (0);
4654 delim[0] = '\\';
4655 delim[1] = '\\';
4656 delim[2] = '#';
4657 rule = NULL;
4658 now = time(NULL);
4660 for (;;) {
4661 if ((rule = fparseln(f, &len, NULL, delim, 0)) == NULL) {
4662 if (!feof(f) || ferror(f))
4663 goto corrupt_file;
4664 else
4665 break;
4668 /* get second entry */
4669 if ((ptr = strpbrk(rule, " \t")) == NULL)
4670 goto corrupt_file;
4672 *ptr++ = '\0';
4673 timeout = atoi(ptr);
4675 /* get third entry */
4676 if ((ptr = strpbrk(ptr, " \t")) == NULL)
4677 goto corrupt_file;
4679 ptr ++;
4680 subdomains = atoi(ptr);
4682 if (timeout > now)
4683 strict_transport_add(rule, timeout, subdomains);
4684 free(rule);
4687 fclose(f);
4688 strict_transport_file = g_strdup(file);
4689 return (0);
4691 corrupt_file:
4692 startpage_add("strict-transport rules file ('%s') is corrupt", file);
4693 if (rule)
4694 free(rule);
4695 fclose(f);
4696 return (1);
4700 force_https_check(const char *uri)
4702 struct domain *d = NULL;
4704 if (uri == NULL)
4705 return (0);
4707 if ((d = wl_find_uri(uri, &force_https)) == NULL)
4708 return (0);
4709 else
4710 return (1);
4713 void
4714 strict_transport_security_cb(SoupMessage *msg, gpointer data)
4716 SoupURI *uri;
4717 const char *sts;
4718 char *ptr;
4719 time_t timeout = 0;
4720 int subdomains = FALSE;
4722 if (msg == NULL)
4723 return;
4725 sts = soup_message_headers_get_one(msg->response_headers,
4726 "Strict-Transport-Security");
4727 uri = soup_message_get_uri(msg);
4729 if (sts == NULL || uri == NULL)
4730 return;
4732 if ((ptr = strcasestr(sts, "max-age="))) {
4733 ptr += strlen("max-age=");
4734 timeout = atoll(ptr);
4735 } else
4736 return; /* malformed header - max-age must be included */
4738 if ((ptr = strcasestr(sts, "includeSubDomains")))
4739 subdomains = TRUE;
4741 strict_transport_add(uri->host, timeout + time(NULL), subdomains);
4744 void
4745 session_rq_cb(SoupSession *s, SoupMessage *msg, SoupSocket *socket,
4746 gpointer data)
4748 SoupURI *dest;
4749 SoupURI *ref_uri;
4750 const char *ref;
4752 char *ref_suffix;
4753 char *dest_suffix;
4755 if (s == NULL || msg == NULL)
4756 return;
4758 if (enable_strict_transport) {
4759 soup_message_add_header_handler(msg, "finished",
4760 "Strict-Transport-Security",
4761 G_CALLBACK(strict_transport_security_cb), NULL);
4764 if (referer_mode == XT_REFERER_ALWAYS)
4765 return;
4767 /* Check if referer is set - and what the user requested for referers */
4768 ref = soup_message_headers_get_one(msg->request_headers, "Referer");
4769 if (ref) {
4770 DNPRINTF(XT_D_NAV, "session_rq_cb: Referer: %s\n", ref);
4771 switch (referer_mode) {
4772 case XT_REFERER_NEVER:
4773 DNPRINTF(XT_D_NAV, "session_rq_cb: removing referer\n");
4774 soup_message_headers_remove(msg->request_headers,
4775 "Referer");
4776 break;
4777 case XT_REFERER_SAME_DOMAIN:
4778 ref_uri = soup_uri_new(ref);
4779 dest = soup_message_get_uri(msg);
4781 ref_suffix = tld_get_suffix(ref_uri->host);
4782 dest_suffix = tld_get_suffix(dest->host);
4784 if (dest && ref_suffix && dest_suffix &&
4785 strcmp(ref_suffix, dest_suffix) != 0) {
4786 soup_message_headers_remove(msg->request_headers,
4787 "Referer");
4788 DNPRINTF(XT_D_NAV, "session_rq_cb: removing "
4789 "referer (not same domain) (suffixes: %s - %s)\n",
4790 ref_suffix, dest_suffix);
4792 soup_uri_free(ref_uri);
4793 break;
4794 case XT_REFERER_SAME_FQDN:
4795 ref_uri = soup_uri_new(ref);
4796 dest = soup_message_get_uri(msg);
4797 if (dest && strcmp(ref_uri->host, dest->host) != 0) {
4798 soup_message_headers_remove(msg->request_headers,
4799 "Referer");
4800 DNPRINTF(XT_D_NAV, "session_rq_cb: removing "
4801 "referer (not same fqdn) (should be %s)\n",
4802 dest->host);
4804 soup_uri_free(ref_uri);
4805 break;
4806 case XT_REFERER_CUSTOM:
4807 DNPRINTF(XT_D_NAV, "session_rq_cb: setting referer "
4808 "to %s\n", referer_custom);
4809 soup_message_headers_replace(msg->request_headers,
4810 "Referer", referer_custom);
4811 break;
4817 webview_npd_cb(WebKitWebView *wv, WebKitWebFrame *wf,
4818 WebKitNetworkRequest *request, WebKitWebNavigationAction *na,
4819 WebKitWebPolicyDecision *pd, struct tab *t)
4821 WebKitWebNavigationReason reason;
4822 struct user_agent ua_find, *ua;
4823 char *uri;
4825 if (t == NULL) {
4826 show_oops(NULL, "webview_npd_cb invalid parameters");
4827 return (FALSE);
4830 DNPRINTF(XT_D_NAV, "webview_npd_cb: ctrl_click %d %s\n",
4831 t->ctrl_click,
4832 webkit_network_request_get_uri(request));
4834 uri = (char *)webkit_network_request_get_uri(request);
4836 if (valid_url_type(uri)) {
4837 show_oops(t, "Stopping attempt to load an invalid URI (possible"
4838 " bait and switch attack)");
4839 return (TRUE);
4842 /* clear t->item, except if we're switching to an about: page */
4843 if (t->item && !g_str_has_prefix(uri, "xxxt://")) {
4844 g_object_unref(t->item);
4845 t->item = NULL;
4848 if (!auto_load_images && t->load_images) {
4850 /* Disable autoloading of images, now that we're done loading
4851 * them. */
4852 g_object_set(G_OBJECT(t->settings),
4853 "auto-load-images", FALSE, (char *)NULL);
4854 webkit_web_view_set_settings(t->wv, t->settings);
4856 t->load_images = FALSE;
4859 /* If this is an xtp url, we don't load anything else. */
4860 if (parse_xtp_url(t, uri))
4861 return (TRUE);
4863 if (parse_custom_uri(t, uri))
4864 return (TRUE);
4866 if ((t->mode == XT_MODE_HINT && t->new_tab) || t->ctrl_click) {
4867 t->ctrl_click = 0;
4868 create_new_tab(uri, NULL, ctrl_click_focus, -1);
4869 webkit_web_policy_decision_ignore(pd);
4870 return (TRUE); /* we made the decission */
4873 /* Change user agent if more than one has been given. */
4874 if (!RB_EMPTY(&ua_list)) {
4875 ua_find.id = t->user_agent_id;
4877 if ((ua = RB_FIND(user_agent_list, &ua_list, &ua_find)) == NULL) {
4878 ua_find.id = 0;
4879 t->user_agent_id = 1;
4880 user_agent = RB_FIND(user_agent_list, &ua_list, &ua_find);
4881 } else {
4882 ++t->user_agent_id;
4883 user_agent = ua;
4886 g_free(t->user_agent);
4887 t->user_agent = g_strdup(user_agent->value);
4889 DNPRINTF(XT_D_NAV, "user-agent: %s\n", t->user_agent);
4891 g_object_set(G_OBJECT(t->settings),
4892 "user-agent", t->user_agent, (char *)NULL);
4894 webkit_web_view_set_settings(wv, t->settings);
4898 * This is a little hairy but it comes down to this:
4899 * when we run in whitelist mode we have to assist the browser in
4900 * opening the URL that it would have opened in a new tab.
4902 reason = webkit_web_navigation_action_get_reason(na);
4903 if (reason == WEBKIT_WEB_NAVIGATION_REASON_LINK_CLICKED) {
4904 set_normal_tab_meaning(t);
4905 if (enable_scripts == 0 && enable_cookie_whitelist == 1)
4906 load_uri(t, uri);
4907 webkit_web_policy_decision_use(pd);
4908 return (TRUE); /* we made the decision */
4911 return (FALSE);
4914 void
4915 webview_rrs_cb(WebKitWebView *wv, WebKitWebFrame *wf, WebKitWebResource *res,
4916 WebKitNetworkRequest *request, WebKitNetworkResponse *response,
4917 struct tab *t)
4919 SoupMessage *msg = NULL;
4920 SoupURI *uri = NULL;
4921 struct http_accept ha_find, *ha = NULL;
4922 const char *accept = NULL;
4923 char *uri_s = NULL;
4925 msg = webkit_network_request_get_message(request);
4926 if (!msg) return;
4928 uri = soup_message_get_uri(msg);
4929 if (!uri)
4930 return;
4931 uri_s = soup_uri_to_string(uri, FALSE);
4933 if (strcmp(uri->scheme, SOUP_URI_SCHEME_HTTP) == 0) {
4934 if (strict_transport_check(uri->host) ||
4935 force_https_check(uri_s)) {
4936 DNPRINTF(XT_D_NAV, "webview_rrs_cb: force https for %s\n",
4937 uri->host);
4938 soup_uri_set_scheme(uri, SOUP_URI_SCHEME_HTTPS);
4942 if (do_not_track)
4943 soup_message_headers_append(msg->request_headers, "DNT", "1");
4945 /* Round-robin through HTTP Accept headers if any have been set */
4946 if (!RB_EMPTY(&ha_list)) {
4947 accept = soup_message_headers_get_list(msg->request_headers,
4948 "Accept");
4949 if (accept == NULL ||
4950 strncmp(accept, "text/html", strlen("text/html")))
4951 goto done;
4953 ha_find.id = t->http_accept_id;
4954 ha = RB_FIND(http_accept_list, &ha_list, &ha_find);
4955 if (ha == NULL) {
4956 ha_find.id = 0;
4957 t->http_accept_id = 1;
4958 http_accept = RB_FIND(http_accept_list, &ha_list,
4959 &ha_find);
4960 } else {
4961 ++t->http_accept_id;
4962 http_accept = ha;
4965 soup_message_headers_replace(msg->request_headers, "Accept",
4966 http_accept->value);
4968 done:
4969 if (uri_s)
4970 g_free(uri_s);
4973 WebKitWebView *
4974 webview_cwv_cb(WebKitWebView *wv, WebKitWebFrame *wf, struct tab *t)
4976 struct tab *tt;
4977 struct domain *d = NULL;
4978 const gchar *uri;
4979 WebKitWebView *webview = NULL;
4980 int x = 1;
4982 DNPRINTF(XT_D_NAV, "webview_cwv_cb: %s\n",
4983 webkit_web_view_get_uri(wv));
4985 if (tabless) {
4986 /* open in current tab */
4987 webview = t->wv;
4988 } else if (enable_scripts == 0 && enable_js_whitelist == 1) {
4989 uri = webkit_web_view_get_uri(wv);
4990 if (uri && (d = wl_find_uri(uri, &js_wl)) == NULL)
4991 return (NULL);
4993 if (t->ctrl_click) {
4994 x = ctrl_click_focus;
4995 t->ctrl_click = 0;
4997 tt = create_new_tab(NULL, NULL, x, -1);
4998 webview = tt->wv;
4999 } else if (enable_scripts == 1) {
5000 if (t->ctrl_click) {
5001 x = ctrl_click_focus;
5002 t->ctrl_click = 0;
5004 tt = create_new_tab(NULL, NULL, x, -1);
5005 webview = tt->wv;
5008 return (webview);
5011 gboolean
5012 webview_closewv_cb(WebKitWebView *wv, struct tab *t)
5014 const gchar *uri;
5015 struct domain *d = NULL;
5017 DNPRINTF(XT_D_NAV, "webview_close_cb: %d\n", t->tab_id);
5019 if (enable_scripts == 0 && enable_cookie_whitelist == 1) {
5020 uri = webkit_web_view_get_uri(wv);
5021 if (uri && (d = wl_find_uri(uri, &js_wl)) == NULL)
5022 return (FALSE);
5024 delete_tab(t);
5025 } else if (enable_scripts == 1)
5026 delete_tab(t);
5028 return (TRUE);
5032 webview_event_cb(GtkWidget *w, GdkEventButton *e, struct tab *t)
5034 /* we can not eat the event without throwing gtk off so defer it */
5036 /* catch middle click */
5037 if (e->type == GDK_BUTTON_RELEASE && e->button == 2) {
5038 t->ctrl_click = 1;
5039 goto done;
5042 /* catch ctrl click */
5043 if (e->type == GDK_BUTTON_RELEASE &&
5044 CLEAN(e->state) == GDK_CONTROL_MASK)
5045 t->ctrl_click = 1;
5046 else
5047 t->ctrl_click = 0;
5048 done:
5049 return (XT_CB_PASSTHROUGH);
5053 run_mimehandler(struct tab *t, char *mime_type, WebKitNetworkRequest *request)
5055 struct mime_type *m;
5056 char *sv[3];
5057 GError *gerr = NULL;
5059 m = find_mime_type(mime_type);
5060 if (m == NULL)
5061 return (1);
5062 if (m->mt_download)
5063 return (1);
5065 sv[0] = m->mt_action;
5066 sv[1] = (char *)webkit_network_request_get_uri(request);
5067 sv[2] = NULL;
5069 /* ignore donothing from example config */
5070 if (m->mt_action && !strcmp(m->mt_action, "donothing"))
5071 return (0);
5073 if (!g_spawn_async(NULL, sv, NULL, G_SPAWN_SEARCH_PATH, NULL, NULL,
5074 NULL, &gerr))
5075 show_oops(t, "%s: could not spawn process (%s)", __func__,
5076 gerr ? gerr->message : "N/A");
5077 return (0);
5080 char *
5081 get_mime_type(const char *uri)
5083 GFileInfo *fi;
5084 GFile *gf;
5085 const gchar *m;
5086 char *mime_type = NULL;
5087 char *file;
5089 if (uri == NULL) {
5090 show_oops(NULL, "%s: invalid parameters", __func__);
5091 return (NULL);
5094 if (g_str_has_prefix(uri, "file://"))
5095 file = g_filename_from_uri(uri, NULL, NULL);
5096 else
5097 file = g_strdup(uri);
5099 if (file == NULL)
5100 return (NULL);
5102 gf = g_file_new_for_path(file);
5103 fi = g_file_query_info(gf, G_FILE_ATTRIBUTE_STANDARD_CONTENT_TYPE, 0,
5104 NULL, NULL);
5105 if ((m = g_file_info_get_content_type(fi)) != NULL)
5106 mime_type = g_strdup(m);
5107 g_object_unref(fi);
5108 g_object_unref(gf);
5109 g_free(file);
5111 return (mime_type);
5115 run_download_mimehandler(char *mime_type, char *file)
5117 struct mime_type *m;
5118 char *sv[3];
5120 m = find_mime_type(mime_type);
5121 if (m == NULL)
5122 return (1);
5124 sv[0] = m->mt_action;
5125 sv[1] = file;
5126 sv[2] = NULL;
5127 if (!g_spawn_async(NULL, sv, NULL, G_SPAWN_SEARCH_PATH, NULL, NULL,
5128 NULL, NULL)) {
5129 show_oops(NULL, "%s: could not spawn process: %s %s", __func__,
5130 sv[0], sv[1]);
5131 return (1);
5133 return (0);
5136 void
5137 download_status_changed_cb(WebKitDownload *download, GParamSpec *spec,
5138 WebKitWebView *wv)
5140 WebKitDownloadStatus status;
5141 const char *uri;
5142 char *file = NULL;
5143 char *mime = NULL;
5145 if (download == NULL)
5146 return;
5147 status = webkit_download_get_status(download);
5148 if (status != WEBKIT_DOWNLOAD_STATUS_FINISHED)
5149 return;
5151 if (download_notifications)
5152 show_oops(NULL, "Download of '%s' finished",
5153 basename((char *)webkit_download_get_destination_uri(download)));
5154 uri = webkit_download_get_destination_uri(download);
5155 if (uri == NULL)
5156 return;
5157 mime = get_mime_type(uri);
5158 if (mime == NULL)
5159 return;
5161 if (g_str_has_prefix(uri, "file://"))
5162 file = g_filename_from_uri(uri, NULL, NULL);
5163 else
5164 file = g_strdup(uri);
5166 if (file == NULL)
5167 goto done;
5169 run_download_mimehandler((char *)mime, file);
5171 done:
5172 g_free(mime);
5176 webview_mimetype_cb(WebKitWebView *wv, WebKitWebFrame *frame,
5177 WebKitNetworkRequest *request, char *mime_type,
5178 WebKitWebPolicyDecision *decision, struct tab *t)
5180 if (t == NULL) {
5181 show_oops(NULL, "webview_mimetype_cb invalid parameters");
5182 return (FALSE);
5185 DNPRINTF(XT_D_DOWNLOAD, "webview_mimetype_cb: tab %d mime %s\n",
5186 t->tab_id, mime_type);
5188 if (run_mimehandler(t, mime_type, request) == 0) {
5189 webkit_web_policy_decision_ignore(decision);
5190 focus_webview(t);
5191 return (TRUE);
5194 if (webkit_web_view_can_show_mime_type(wv, mime_type) == FALSE) {
5195 webkit_web_policy_decision_download(decision);
5196 return (TRUE);
5199 return (FALSE);
5203 download_start(struct tab *t, struct download *d, int flag)
5205 WebKitNetworkRequest *req;
5206 struct stat sb;
5207 const gchar *suggested_name;
5208 gchar *filename = NULL;
5209 char *uri = NULL;
5210 char *path = NULL;
5211 int ret = TRUE;
5212 int i;
5214 if (d == NULL || t == NULL) {
5215 show_oops(NULL, "%s invalid parameters", __func__);
5216 return (FALSE);
5219 suggested_name = webkit_download_get_suggested_filename(d->download);
5220 if (suggested_name == NULL)
5221 return (FALSE); /* abort download */
5223 i = 0;
5224 do {
5225 if (filename) {
5226 g_free(filename);
5227 filename = NULL;
5229 if (i) {
5230 g_free(uri);
5231 uri = NULL;
5232 filename = g_strdup_printf("%d%s", i, suggested_name);
5234 #ifdef __MINGW32__
5235 /* XXX using urls doesn't work properly in windows? */
5236 uri = g_strdup_printf("%s\\%s", download_dir, i ?
5237 filename : suggested_name);
5238 #else
5239 path = g_strdup_printf("%s" PS "%s", download_dir, i ?
5240 filename : suggested_name);
5241 if ((uri = g_filename_to_uri(path, NULL, NULL)) == NULL)
5242 break; /* XXX */
5243 #endif
5244 i++;
5245 #ifdef __MINGW32__
5246 } while (!stat(uri, &sb));
5247 #else
5248 } while (!stat(path, &sb));
5249 #endif
5251 DNPRINTF(XT_D_DOWNLOAD, "%s: tab %d filename %s "
5252 "local %s\n", __func__, t->tab_id, filename, uri);
5254 /* if we're restarting the download, or starting
5255 * it after doing something else, we need to recreate
5256 * the download request.
5258 if (flag == XT_DL_RESTART) {
5259 req = webkit_network_request_new(webkit_download_get_uri(d->download));
5260 webkit_download_cancel(d->download);
5261 g_object_unref(d->download);
5262 d->download = webkit_download_new(req);
5265 webkit_download_set_destination_uri(d->download, uri);
5267 if (webkit_download_get_status(d->download) ==
5268 WEBKIT_DOWNLOAD_STATUS_ERROR) {
5269 show_oops(t, "%s: download failed to start", __func__);
5270 ret = FALSE;
5271 show_oops(t, "Download Failed");
5272 } else {
5273 /* connect "download first" mime handler */
5274 g_signal_connect(G_OBJECT(d->download), "notify::status",
5275 G_CALLBACK(download_status_changed_cb), NULL);
5277 /* get from history */
5278 g_object_ref(d->download);
5279 show_oops(t, "Download of '%s' started...",
5280 basename((char *)webkit_download_get_destination_uri(d->download)));
5283 if (flag != XT_DL_START)
5284 webkit_download_start(d->download);
5286 DNPRINTF(XT_D_DOWNLOAD, "download status : %d",
5287 webkit_download_get_status(d->download));
5289 /* sync other download manager tabs */
5290 update_download_tabs(NULL);
5292 if (uri)
5293 g_free(uri);
5294 if (path)
5295 g_free(path);
5296 if (filename)
5297 g_free(filename);
5299 return (ret);
5303 download_ask_cb(struct tab *t, GdkEventKey *e, gpointer data)
5305 struct download *d = data;
5307 /* unset mode */
5308 t->mode_cb = NULL;
5309 t->mode_cb_data = NULL;
5311 if (!e || !d) {
5312 e->keyval = GDK_Escape;
5313 return (XT_CB_PASSTHROUGH);
5316 DPRINTF("download_ask_cb: User pressed %c\n", e->keyval);
5317 if (e->keyval == 'y' || e->keyval == 'Y' || e->keyval == GDK_Return)
5318 /* We need to do a RESTART, because we're not calling from
5319 * webview_download_cb
5321 download_start(t, d, XT_DL_RESTART);
5323 /* for all other keyvals, we just let the download be */
5324 e->keyval = GDK_Escape;
5325 return (XT_CB_HANDLED);
5329 download_ask(struct tab *t, struct download *d)
5331 const gchar *suggested_name;
5333 suggested_name = webkit_download_get_suggested_filename(d->download);
5334 if (suggested_name == NULL)
5335 return (FALSE); /* abort download */
5337 show_oops(t, "download file %s [y/n] ?", suggested_name);
5338 t->mode_cb = download_ask_cb;
5339 t->mode_cb_data = d;
5341 return (TRUE);
5345 webview_download_cb(WebKitWebView *wv, WebKitDownload *wk_download,
5346 struct tab *t)
5348 const gchar *suggested_name;
5349 struct download *download_entry;
5350 int ret = TRUE;
5352 if (wk_download == NULL || t == NULL) {
5353 show_oops(NULL, "%s invalid parameters", __func__);
5354 return (FALSE);
5357 suggested_name = webkit_download_get_suggested_filename(wk_download);
5358 if (suggested_name == NULL)
5359 return (FALSE); /* abort download */
5361 download_entry = g_malloc(sizeof(struct download));
5362 download_entry->download = wk_download;
5363 download_entry->tab = t;
5364 download_entry->id = next_download_id++;
5365 RB_INSERT(download_list, &downloads, download_entry);
5366 t->download_requested = 1;
5368 if (download_mode == XT_DM_START)
5369 ret = download_start(t, download_entry, XT_DL_START);
5370 else if (download_mode == XT_DM_ASK)
5371 ret = download_ask(t, download_entry);
5372 else if (download_mode == XT_DM_ADD)
5373 show_oops(t, "added %s to download manager",
5374 suggested_name);
5376 /* sync other download manager tabs */
5377 update_download_tabs(NULL);
5380 * NOTE: never redirect/render the current tab before this
5381 * function returns. This will cause the download to never start.
5383 return (ret); /* start download */
5386 void
5387 webview_hover_cb(WebKitWebView *wv, gchar *title, gchar *uri, struct tab *t)
5389 DNPRINTF(XT_D_KEY, "webview_hover_cb: %s %s\n", title, uri);
5391 if (t == NULL) {
5392 show_oops(NULL, "webview_hover_cb");
5393 return;
5396 if (uri)
5397 set_status(t, "Link: %s", uri);
5398 else {
5399 if (statusbar_style == XT_STATUSBAR_URL) {
5400 const gchar *page_uri;
5402 if ((page_uri = get_uri(t)) != NULL)
5403 set_status(t, "%s", page_uri);
5404 } else
5405 set_status(t, "%s", (char *)get_title(t, FALSE));
5410 mark(struct tab *t, struct karg *arg)
5412 char mark;
5413 int index;
5414 double pos;
5416 mark = arg->s[1];
5417 if ((index = marktoindex(mark)) == -1)
5418 return (-1);
5420 if (arg->i == XT_MARK_SET)
5421 t->mark[index] = gtk_adjustment_get_value(t->adjust_v);
5422 else if (arg->i == XT_MARK_GOTO) {
5423 if (t->mark[index] == XT_INVALID_MARK) {
5424 show_oops(t, "mark '%c' does not exist", mark);
5425 return (-1);
5427 /* XXX t->mark[index] can be bigger than the maximum if ajax or
5428 something changes the document size */
5429 pos = gtk_adjustment_get_value(t->adjust_v);
5430 gtk_adjustment_set_value(t->adjust_v, t->mark[index]);
5431 t->mark[marktoindex('\'')] = pos;
5434 return (0);
5437 void
5438 marks_clear(struct tab *t)
5440 int i;
5442 for (i = 0; i < LENGTH(t->mark); i++)
5443 t->mark[i] = XT_INVALID_MARK;
5447 qmarks_load(void)
5449 char file[PATH_MAX];
5450 char *line = NULL, *p;
5451 int index, i;
5452 FILE *f;
5453 size_t linelen;
5455 snprintf(file, sizeof file, "%s" PS "%s", work_dir, XT_QMARKS_FILE);
5456 if ((f = fopen(file, "r+")) == NULL) {
5457 show_oops(NULL, "Can't open quickmarks file: %s", strerror(errno));
5458 return (1);
5461 for (i = 1; ; i++) {
5462 if ((line = fparseln(f, &linelen, NULL, NULL, 0)) == NULL)
5463 break;
5464 if (strlen(line) == 0 || line[0] == '#') {
5465 free(line);
5466 line = NULL;
5467 continue;
5470 p = strtok(line, " \t");
5472 if (p == NULL || strlen(p) != 1 ||
5473 (index = qmarktoindex(*p)) == -1) {
5474 warnx("corrupt quickmarks file, line %d", i);
5475 break;
5478 p = strtok(NULL, " \t");
5479 if (qmarks[index] != NULL)
5480 g_free(qmarks[index]);
5481 qmarks[index] = g_strdup(p);
5484 fclose(f);
5486 return (0);
5490 qmarks_save(void)
5492 char file[PATH_MAX];
5493 int i;
5494 FILE *f;
5496 snprintf(file, sizeof file, "%s" PS "%s", work_dir, XT_QMARKS_FILE);
5497 if ((f = fopen(file, "r+")) == NULL) {
5498 show_oops(NULL, "Can't open quickmarks file: %s", strerror(errno));
5499 return (1);
5502 for (i = 0; i < XT_NOQMARKS; i++)
5503 if (qmarks[i] != NULL)
5504 fprintf(f, "%c %s\n", indextoqmark(i), qmarks[i]);
5506 fclose(f);
5508 return (0);
5512 qmark(struct tab *t, struct karg *arg)
5514 char mark;
5515 int index;
5517 mark = arg->s[strlen(arg->s)-1];
5518 index = qmarktoindex(mark);
5519 if (index == -1)
5520 return (-1);
5522 switch (arg->i) {
5523 case XT_QMARK_SET:
5524 if (qmarks[index] != NULL) {
5525 g_free(qmarks[index]);
5526 qmarks[index] = NULL;
5529 qmarks_load(); /* sync if multiple instances */
5530 qmarks[index] = g_strdup(get_uri(t));
5531 qmarks_save();
5532 break;
5533 case XT_QMARK_OPEN:
5534 if (qmarks[index] != NULL)
5535 load_uri(t, qmarks[index]);
5536 else {
5537 show_oops(t, "quickmark \"%c\" does not exist",
5538 mark);
5539 return (-1);
5541 break;
5542 case XT_QMARK_TAB:
5543 if (qmarks[index] != NULL)
5544 create_new_tab(qmarks[index], NULL, 1, -1);
5545 else {
5546 show_oops(t, "quickmark \"%c\" does not exist",
5547 mark);
5548 return (-1);
5550 break;
5553 return (0);
5557 go_up(struct tab *t, struct karg *args)
5559 int levels;
5560 int lastidx;
5561 char *uri;
5562 char *tmp;
5563 char *p;
5565 if (args->i == XT_GO_UP_ROOT)
5566 levels = XT_GO_UP_ROOT;
5567 else if ((levels = atoi(args->s)) == 0)
5568 levels = 1;
5570 uri = g_strdup(get_uri(t));
5571 if (uri == NULL)
5572 return (1);
5574 if ((tmp = strstr(uri, XT_PROTO_DELIM)) == NULL)
5575 return (1);
5577 tmp += strlen(XT_PROTO_DELIM);
5579 /* it makes no sense to strip the last slash from ".../dir/", skip it */
5580 lastidx = strlen(tmp) - 1;
5581 if (lastidx > 0) {
5582 if (tmp[lastidx] == '/')
5583 tmp[lastidx] = '\0';
5586 while (levels--) {
5587 p = strrchr(tmp, '/');
5588 if (p == tmp) { /* Are we at the root of a file://-path? */
5589 p[1] = '\0';
5590 break;
5591 } else if (p != NULL)
5592 *p = '\0';
5593 else
5594 break;
5597 load_uri(t, uri);
5598 g_free(uri);
5600 return (0);
5604 gototab(struct tab *t, struct karg *args)
5606 int tab;
5607 struct karg arg = {0, NULL, -1};
5609 tab = atoi(args->s);
5611 if (args->i == 0)
5612 arg.i = XT_TAB_NEXT;
5613 else
5614 arg.i = args->i;
5616 arg.precount = tab;
5618 movetab(t, &arg);
5620 return (0);
5624 zoom_amount(struct tab *t, struct karg *arg)
5626 struct karg narg = {0, NULL, -1};
5628 narg.i = atoi(arg->s);
5629 resizetab(t, &narg);
5631 return (0);
5635 flip_colon(struct tab *t, struct karg *arg)
5637 struct karg narg = {0, NULL, -1};
5638 char *p;
5640 if (t == NULL || arg == NULL)
5641 return (1);
5643 p = strstr(arg->s, ":");
5644 if (p == NULL)
5645 return (1);
5646 *p = '\0';
5648 narg.i = ':';
5649 narg.s = arg->s;
5650 command(t, &narg);
5652 return (0);
5655 /* buffer commands receive the regex that triggered them in arg.s */
5656 char bcmd[XT_BUFCMD_SZ];
5657 struct buffercmd {
5658 char *regex;
5659 int precount;
5660 #define XT_PRE_NO (0)
5661 #define XT_PRE_YES (1)
5662 #define XT_PRE_MAYBE (2)
5663 char *cmd;
5664 int (*func)(struct tab *, struct karg *);
5665 int arg;
5666 regex_t cregex;
5667 } buffercmds[] = {
5668 { "^[0-9]*gu$", XT_PRE_MAYBE, "gu", go_up, 0 },
5669 { "^gU$", XT_PRE_NO, "gU", go_up, XT_GO_UP_ROOT },
5670 { "^gg$", XT_PRE_NO, "gg", move, XT_MOVE_TOP },
5671 { "^gG$", XT_PRE_NO, "gG", move, XT_MOVE_BOTTOM },
5672 { "^[0-9]+%$", XT_PRE_YES, "%", move, XT_MOVE_PERCENT },
5673 { "^zz$", XT_PRE_NO, "zz", move, XT_MOVE_CENTER },
5674 { "^gh$", XT_PRE_NO, "gh", go_home, 0 },
5675 { "^m[a-zA-Z0-9]$", XT_PRE_NO, "m", mark, XT_MARK_SET },
5676 { "^['][a-zA-Z0-9']$", XT_PRE_NO, "'", mark, XT_MARK_GOTO },
5677 { "^[0-9]+t$", XT_PRE_YES, "t", gototab, 0 },
5678 { "^g0$", XT_PRE_YES, "g0", movetab, XT_TAB_FIRST },
5679 { "^g[$]$", XT_PRE_YES, "g$", movetab, XT_TAB_LAST },
5680 { "^[0-9]*gt$", XT_PRE_YES, "t", movetab, XT_TAB_NEXT },
5681 { "^[0-9]*gT$", XT_PRE_YES, "T", movetab, XT_TAB_PREV },
5682 { "^M[a-zA-Z0-9]$", XT_PRE_NO, "M", qmark, XT_QMARK_SET },
5683 { "^go[a-zA-Z0-9]$", XT_PRE_NO, "go", qmark, XT_QMARK_OPEN },
5684 { "^gn[a-zA-Z0-9]$", XT_PRE_NO, "gn", qmark, XT_QMARK_TAB },
5685 { "^ZR$", XT_PRE_NO, "ZR", restart, 0 },
5686 { "^ZZ$", XT_PRE_NO, "ZZ", quit, 0 },
5687 { "^zi$", XT_PRE_NO, "zi", resizetab, XT_ZOOM_IN },
5688 { "^zo$", XT_PRE_NO, "zo", resizetab, XT_ZOOM_OUT },
5689 { "^z0$", XT_PRE_NO, "z0", resizetab, XT_ZOOM_NORMAL },
5690 { "^[0-9]+Z$", XT_PRE_YES, "Z", zoom_amount, 0 },
5691 { "^[0-9]+:$", XT_PRE_YES, ":", flip_colon, 0 },
5694 void
5695 buffercmd_init(void)
5697 int i;
5699 for (i = 0; i < LENGTH(buffercmds); i++)
5700 if (regcomp(&buffercmds[i].cregex, buffercmds[i].regex,
5701 REG_EXTENDED | REG_NOSUB))
5702 startpage_add("invalid buffercmd regex %s",
5703 buffercmds[i].regex);
5706 void
5707 buffercmd_abort(struct tab *t)
5709 int i;
5711 if (t == NULL)
5712 return;
5714 DNPRINTF(XT_D_BUFFERCMD, "%s: clearing buffer\n", __func__);
5716 for (i = 0; i < LENGTH(bcmd); i++)
5717 bcmd[i] = '\0';
5719 cmd_prefix = 0; /* clear prefix for non-buffer commands */
5720 gtk_label_set_text(GTK_LABEL(t->sbe.buffercmd), bcmd);
5723 void
5724 buffercmd_execute(struct tab *t, struct buffercmd *cmd)
5726 struct karg arg = {0, NULL, -1};
5728 arg.i = cmd->arg;
5729 arg.s = g_strdup(bcmd);
5731 DNPRINTF(XT_D_BUFFERCMD, "buffercmd_execute: buffer \"%s\" "
5732 "matches regex \"%s\", executing\n", bcmd, cmd->regex);
5733 cmd->func(t, &arg);
5735 if (arg.s)
5736 g_free(arg.s);
5738 buffercmd_abort(t);
5741 gboolean
5742 buffercmd_addkey(struct tab *t, guint keyval)
5744 int i, c, match ;
5745 char s[XT_BUFCMD_SZ];
5747 if (gtk_widget_get_visible(GTK_WIDGET(t->buffers))) {
5748 buffercmd_abort(t);
5749 return (XT_CB_PASSTHROUGH);
5752 if (keyval == GDK_Escape) {
5753 buffercmd_abort(t);
5754 return (XT_CB_HANDLED);
5757 /* key with modifier or non-ascii character */
5758 if (!isascii(keyval)) {
5760 * XXX this looks wrong but fixes some sites like
5761 * http://www.seslisozluk.com/
5762 * that eat a shift or ctrl and end putting default focus in js
5763 * instead of ignoring the keystroke
5764 * so instead of return (XT_CB_PASSTHROUGH); eat the key
5766 return (XT_CB_HANDLED);
5769 DNPRINTF(XT_D_BUFFERCMD, "buffercmd_addkey: adding key \"%c\" "
5770 "to buffer \"%s\"\n", keyval, bcmd);
5772 for (i = 0; i < LENGTH(bcmd); i++)
5773 if (bcmd[i] == '\0') {
5774 bcmd[i] = keyval;
5775 break;
5778 /* buffer full, ignore input */
5779 if (i >= LENGTH(bcmd) -1) {
5780 DNPRINTF(XT_D_BUFFERCMD, "buffercmd_addkey: buffer full\n");
5781 buffercmd_abort(t);
5782 return (XT_CB_HANDLED);
5785 gtk_label_set_text(GTK_LABEL(t->sbe.buffercmd), bcmd);
5787 /* find exact match */
5788 for (i = 0; i < LENGTH(buffercmds); i++)
5789 if (regexec(&buffercmds[i].cregex, bcmd,
5790 (size_t) 0, NULL, 0) == 0) {
5791 buffercmd_execute(t, &buffercmds[i]);
5792 goto done;
5795 /* find non exact matches to see if we need to abort ot not */
5796 for (i = 0, match = 0; i < LENGTH(buffercmds); i++) {
5797 DNPRINTF(XT_D_BUFFERCMD, "trying: %s\n", bcmd);
5798 c = -1;
5799 s[0] = '\0';
5800 if (buffercmds[i].precount == XT_PRE_MAYBE) {
5801 if (isdigit(bcmd[0])) {
5802 if (sscanf(bcmd, "%d%s", &c, s) == 0)
5803 continue;
5804 } else {
5805 c = 0;
5806 if (sscanf(bcmd, "%s", s) == 0)
5807 continue;
5809 } else if (buffercmds[i].precount == XT_PRE_YES) {
5810 if (sscanf(bcmd, "%d%s", &c, s) == 0)
5811 continue;
5812 } else {
5813 if (sscanf(bcmd, "%s", s) == 0)
5814 continue;
5816 if (c == -1 && buffercmds[i].precount)
5817 continue;
5818 if (!strncmp(s, buffercmds[i].cmd, strlen(s)))
5819 match++;
5821 DNPRINTF(XT_D_BUFFERCMD, "got[%d] %d <%s>: %d %s\n",
5822 i, match, buffercmds[i].cmd, c, s);
5824 if (match == 0) {
5825 DNPRINTF(XT_D_BUFFERCMD, "aborting: %s\n", bcmd);
5826 buffercmd_abort(t);
5829 done:
5830 return (XT_CB_HANDLED);
5834 * XXX we were seeing a bunch of focus issues with the toplevel
5835 * main_window losing its is-active and has-toplevel-focus properties.
5836 * This is the most correct and portable solution we could come up with
5837 * without relying on calling internal GTK functions (which we
5838 * couldn't link to in Linux).
5840 void
5841 fake_focus_in(GtkWidget *w)
5843 if (fevent == NULL) {
5844 fevent = gdk_event_new(GDK_FOCUS_CHANGE);
5845 fevent->focus_change.window =
5846 gtk_widget_get_window(main_window);
5847 fevent->focus_change.type = GDK_FOCUS_CHANGE;
5848 fevent->focus_change.in = TRUE;
5850 gtk_widget_send_focus_change(main_window, fevent);
5853 gboolean
5854 handle_keypress(struct tab *t, GdkEventKey *e, int entry)
5856 struct karg args;
5857 struct key_binding *k;
5860 * This sometimes gets randomly unset for whatever reason in GTK3.
5861 * If we're handling a keypress, the main window's is-active propery
5862 * *must* be true, or else many things will break.
5864 #if GTK_CHECK_VERSION(3, 0, 0)
5865 fake_focus_in(main_window);
5866 #endif
5868 /* handle keybindings if buffercmd is empty.
5869 if not empty, allow commands like C-n */
5870 if (bcmd[0] == '\0' || ((e->state & (CTRL | MOD1)) != 0))
5871 TAILQ_FOREACH(k, &kbl, entry)
5872 if (e->keyval == k->key
5873 && (entry ? k->use_in_entry : 1)) {
5874 /* when we are edditing eat ctrl/mod keys */
5875 if (edit_mode == XT_EM_VI &&
5876 t->mode == XT_MODE_INSERT &&
5877 (e->state & CTRL || e->state & MOD1))
5878 return (XT_CB_PASSTHROUGH);
5880 if (k->mask == 0) {
5881 if ((e->state & (CTRL | MOD1)) == 0)
5882 goto runcmd;
5883 } else if ((e->state & k->mask) == k->mask) {
5884 goto runcmd;
5888 if (!entry && ((e->state & (CTRL | MOD1)) == 0))
5889 return (buffercmd_addkey(t, e->keyval));
5891 return (XT_CB_PASSTHROUGH);
5893 runcmd:
5894 if (k->cmd[0] == ':') {
5895 args.i = ':';
5896 args.s = &k->cmd[1];
5897 return (command(t, &args));
5898 } else
5899 return (cmd_execute(t, k->cmd));
5903 wv_keypress_cb(GtkEntry *w, GdkEventKey *e, struct tab *t)
5905 char s[2];
5907 /* don't use w directly; use t->whatever instead */
5909 if (t == NULL) {
5910 show_oops(NULL, "wv_keypress_cb");
5911 return (XT_CB_PASSTHROUGH);
5914 hide_oops(t);
5916 if (t->mode_cb)
5917 return (t->mode_cb(t, e, t->mode_cb_data));
5919 DNPRINTF(XT_D_KEY, "wv_keypress_cb: mode %d keyval 0x%x mask "
5920 "0x%x tab %d\n", t->mode, e->keyval, e->state, t->tab_id);
5922 /* Hide buffers, if they are visible, with escape. */
5923 if (gtk_widget_get_visible(GTK_WIDGET(t->buffers)) &&
5924 CLEAN(e->state) == 0 && e->keyval == GDK_Escape) {
5925 gtk_widget_grab_focus(GTK_WIDGET(t->wv));
5926 hide_buffers(t);
5927 return (XT_CB_HANDLED);
5930 if (t->mode == XT_MODE_HINT)
5931 return (XT_CB_HANDLED);
5933 if ((CLEAN(e->state) == 0 && e->keyval == GDK_Tab) ||
5934 (CLEAN(e->state) == SHFT && e->keyval == GDK_Tab))
5935 /* something focussy is about to happen */
5936 return (XT_CB_PASSTHROUGH);
5938 /* check if we are some sort of text input thing in the dom */
5939 input_check_mode(t);
5941 if (t->mode == XT_MODE_HINT) {
5942 /* XXX make sure cmd entry is enabled */
5943 return (XT_CB_HANDLED);
5944 } else if (t->mode == XT_MODE_PASSTHROUGH) {
5945 if (CLEAN(e->state) == 0 && e->keyval == GDK_Escape)
5946 t->mode = XT_MODE_COMMAND;
5947 return (XT_CB_PASSTHROUGH);
5948 } else if (t->mode == XT_MODE_COMMAND) {
5949 /* prefix input */
5950 snprintf(s, sizeof s, "%c", e->keyval);
5951 if (CLEAN(e->state) == 0 && isdigit(s[0]))
5952 cmd_prefix = 10 * cmd_prefix + atoi(s);
5953 return (handle_keypress(t, e, 0));
5954 } else {
5955 /* insert mode */
5956 return (handle_keypress(t, e, 1));
5959 /* NOTREACHED */
5960 return (XT_CB_PASSTHROUGH);
5963 gboolean
5964 hint_continue(struct tab *t)
5966 const gchar *c = gtk_entry_get_text(GTK_ENTRY(t->cmd));
5967 char *s;
5968 const gchar *errstr = NULL;
5969 gboolean rv = TRUE;
5970 int i;
5972 if (!(c[0] == '.' || c[0] == ','))
5973 goto done;
5974 if (strlen(c) == 1) {
5975 /* XXX should not happen */
5976 rv = TRUE;
5977 goto done;
5980 if (isdigit(c[1])) {
5981 /* numeric input */
5982 i = strtonum(&c[1], 1, 4096, &errstr);
5983 if (errstr) {
5984 show_oops(t, "invalid numerical hint %s", &c[1]);
5985 goto done;
5987 s = g_strdup_printf("hints.updateHints(%d);", i);
5988 run_script(t, s);
5989 g_free(s);
5990 } else {
5991 /* alphanumeric input */
5992 s = g_strdup_printf("hints.createHints('%s', '%c');",
5993 &c[1], c[0] == '.' ? 'f' : 'F');
5994 run_script(t, s);
5995 g_free(s);
5998 rv = FALSE;
5999 done:
6000 return (rv);
6003 gboolean
6004 search_continue(struct tab *t)
6006 const gchar *c = gtk_entry_get_text(GTK_ENTRY(t->cmd));
6007 gboolean rv = FALSE;
6009 if (c[0] == ':' || c[0] == '.' || c[0] == ',')
6010 goto done;
6011 if (strlen(c) == 1) {
6012 webkit_web_view_unmark_text_matches(t->wv);
6013 goto done;
6016 if (c[0] == '/')
6017 t->search_forward = TRUE;
6018 else if (c[0] == '?')
6019 t->search_forward = FALSE;
6020 else
6021 goto done;
6023 rv = TRUE;
6024 done:
6025 return (rv);
6028 gboolean
6029 search_cb(struct tab *t)
6031 const gchar *c = gtk_entry_get_text(GTK_ENTRY(t->cmd));
6032 #if !GTK_CHECK_VERSION(3, 0, 0)
6033 GdkColor color;
6034 #endif
6036 if (search_continue(t) == FALSE)
6037 goto done;
6039 /* search */
6040 if (webkit_web_view_search_text(t->wv, &c[1], FALSE, t->search_forward,
6041 TRUE) == FALSE) {
6042 /* not found, mark red */
6043 #if GTK_CHECK_VERSION(3, 0, 0)
6044 gtk_widget_set_name(t->cmd, XT_CSS_RED);
6045 #else
6046 gdk_color_parse(XT_COLOR_RED, &color);
6047 gtk_widget_modify_base(t->cmd, GTK_STATE_NORMAL, &color);
6048 #endif
6049 /* unmark and remove selection */
6050 webkit_web_view_unmark_text_matches(t->wv);
6051 /* my kingdom for a way to unselect text in webview */
6052 } else {
6053 /* found, highlight all */
6054 webkit_web_view_unmark_text_matches(t->wv);
6055 webkit_web_view_mark_text_matches(t->wv, &c[1], FALSE, 0);
6056 webkit_web_view_set_highlight_text_matches(t->wv, TRUE);
6057 #if GTK_CHECK_VERSION(3, 0, 0)
6058 gtk_widget_set_name(t->cmd, XT_CSS_NORMAL);
6059 #else
6060 gtk_widget_modify_base(t->cmd, GTK_STATE_NORMAL,
6061 &t->default_style->base[GTK_STATE_NORMAL]);
6062 #endif
6064 done:
6065 t->search_id = 0;
6066 return (FALSE);
6070 cmd_keyrelease_cb(GtkEntry *w, GdkEventKey *e, struct tab *t)
6072 const gchar *c = gtk_entry_get_text(w);
6074 if (t == NULL) {
6075 show_oops(NULL, "cmd_keyrelease_cb invalid parameters");
6076 return (XT_CB_PASSTHROUGH);
6079 DNPRINTF(XT_D_CMD, "cmd_keyrelease_cb: keyval 0x%x mask 0x%x tab %d\n",
6080 e->keyval, e->state, t->tab_id);
6082 /* hinting */
6083 if (!(e->keyval == GDK_Tab || e->keyval == GDK_ISO_Left_Tab)) {
6084 if (hint_continue(t) == FALSE)
6085 goto done;
6088 /* search */
6089 if (search_continue(t) == FALSE)
6090 goto done;
6092 /* if search length is > 4 then no longer play timeout games */
6093 if (strlen(c) > 4) {
6094 if (t->search_id) {
6095 g_source_remove(t->search_id);
6096 t->search_id = 0;
6098 search_cb(t);
6099 goto done;
6102 /* reestablish a new timer if the user types fast */
6103 if (t->search_id)
6104 g_source_remove(t->search_id);
6105 t->search_id = g_timeout_add(250, (GSourceFunc)search_cb, (gpointer)t);
6107 done:
6108 return (XT_CB_PASSTHROUGH);
6111 gboolean
6112 match_uri(const gchar *uri, const gchar *key) {
6113 gchar *voffset;
6114 size_t len;
6115 gboolean match = FALSE;
6117 len = strlen(key);
6119 if (!strncmp(key, uri, len))
6120 match = TRUE;
6121 else {
6122 voffset = strstr(uri, "/") + 2;
6123 if (!strncmp(key, voffset, len))
6124 match = TRUE;
6125 else if (g_str_has_prefix(voffset, "www.")) {
6126 voffset = voffset + strlen("www.");
6127 if (!strncmp(key, voffset, len))
6128 match = TRUE;
6132 return (match);
6135 gboolean
6136 match_session(const gchar *name, const gchar *key) {
6137 char *sub;
6139 sub = strcasestr(name, key);
6141 return sub == name;
6144 void
6145 cmd_getlist(int id, char *key)
6147 int i, dep, c = 0;
6148 struct history *h;
6149 struct session *s;
6151 if (id >= 0) {
6152 if (cmds[id].type & XT_URLARG) {
6153 RB_FOREACH_REVERSE(h, history_list, &hl)
6154 if (match_uri(h->uri, key)) {
6155 cmd_status.list[c] = (char *)h->uri;
6156 if (++c > 255)
6157 break;
6159 cmd_status.len = c;
6160 return;
6161 } else if (cmds[id].type & XT_SESSARG) {
6162 TAILQ_FOREACH(s, &sessions, entry)
6163 if (match_session(s->name, key)) {
6164 cmd_status.list[c] = (char *)s->name;
6165 if (++c > 255)
6166 break;
6168 cmd_status.len = c;
6169 return;
6170 } else if (cmds[id].type & XT_SETARG) {
6171 for (i = 0; i < get_settings_size(); i++)
6172 if (!strncmp(key, get_setting_name(i),
6173 strlen(key)))
6174 cmd_status.list[c++] =
6175 get_setting_name(i);
6176 cmd_status.len = c;
6177 return;
6181 dep = (id == -1) ? 0 : cmds[id].level + 1;
6183 for (i = id + 1; i < LENGTH(cmds); i++) {
6184 if (cmds[i].level < dep)
6185 break;
6186 if (cmds[i].level == dep && !strncmp(key, cmds[i].cmd,
6187 strlen(key)) && !isdigit(cmds[i].cmd[0]))
6188 cmd_status.list[c++] = cmds[i].cmd;
6192 cmd_status.len = c;
6195 char *
6196 cmd_getnext(int dir)
6198 cmd_status.index += dir;
6200 if (cmd_status.index < 0)
6201 cmd_status.index = cmd_status.len - 1;
6202 else if (cmd_status.index >= cmd_status.len)
6203 cmd_status.index = 0;
6205 return cmd_status.list[cmd_status.index];
6209 cmd_tokenize(char *s, char *tokens[])
6211 int i = 0;
6212 char *tok, *last = NULL;
6213 size_t len = strlen(s);
6214 bool blank;
6216 blank = len == 0 || (len > 0 && s[len - 1] == ' ');
6217 for (tok = strtok_r(s, " ", &last); tok && i < 3;
6218 tok = strtok_r(NULL, " ", &last), i++)
6219 tokens[i] = tok;
6221 if (blank && i < 3)
6222 tokens[i++] = "";
6224 return (i);
6227 void
6228 cmd_complete(struct tab *t, char *str, int dir)
6230 GtkEntry *w = GTK_ENTRY(t->cmd);
6231 int i, j, levels, c = 0, dep = 0, parent = -1;
6232 int matchcount = 0;
6233 char *tok, *match, *s = g_strdup(str);
6234 char *tokens[3];
6235 char res[XT_MAX_URL_LENGTH + 32] = ":";
6236 char *sc = s;
6238 DNPRINTF(XT_D_CMD, "%s: complete %s\n", __func__, str);
6240 /* copy prefix*/
6241 for (i = 0; isdigit(s[i]); i++)
6242 res[i + 1] = s[i];
6244 for (; isspace(s[i]); i++)
6245 res[i + 1] = s[i];
6247 s += i;
6249 levels = cmd_tokenize(s, tokens);
6251 for (i = 0; i < levels - 1; i++) {
6252 tok = tokens[i];
6253 matchcount = 0;
6254 for (j = c; j < LENGTH(cmds); j++) {
6255 if (cmds[j].level < dep)
6256 break;
6257 if (cmds[j].level == dep && !strncmp(tok, cmds[j].cmd,
6258 strlen(tok))) {
6259 matchcount++;
6260 c = j + 1;
6261 if (strlen(tok) == strlen(cmds[j].cmd)) {
6262 matchcount = 1;
6263 break;
6268 if (matchcount == 1) {
6269 strlcat(res, tok, sizeof res);
6270 strlcat(res, " ", sizeof res);
6271 dep++;
6272 } else {
6273 g_free(sc);
6274 return;
6277 parent = c - 1;
6280 if (cmd_status.index == -1)
6281 cmd_getlist(parent, tokens[i]);
6283 if (cmd_status.len > 0) {
6284 match = cmd_getnext(dir);
6285 strlcat(res, match, sizeof res);
6286 gtk_entry_set_text(w, res);
6287 gtk_editable_set_position(GTK_EDITABLE(w), -1);
6290 g_free(sc);
6293 char *
6294 parse_prefix_and_alias(const char *str, int *prefix)
6296 struct cmd_alias *c;
6297 char *s = g_strdup(str), *sc;
6299 g_strstrip(s);
6300 sc = s;
6302 if (isdigit(s[0])) {
6303 sscanf(s, "%d", prefix);
6304 while (isdigit(s[0]) || isspace(s[0]))
6305 ++s;
6308 TAILQ_FOREACH(c, &cal, entry) {
6309 if (strncmp(s, c->alias, strlen(c->alias)))
6310 continue;
6312 if (strlen(s) == strlen(c->alias)) {
6313 g_free(sc);
6314 return (g_strdup(c->cmd));
6317 if (!isspace(s[strlen(c->alias)]))
6318 continue;
6320 s = g_strdup_printf("%s %s", c->cmd, &s[strlen(c->alias) + 1]);
6321 g_free(sc);
6322 return (s);
6324 s = g_strdup(s);
6325 g_free(sc);
6326 return (s);
6329 gboolean
6330 cmd_execute(struct tab *t, char *str)
6332 struct cmd *cmd = NULL;
6333 char *tok, *last = NULL, *s = str;
6334 int j = 0, len, c = 0, dep = 0, matchcount = 0;
6335 int prefix = -1, rv = XT_CB_PASSTHROUGH;
6336 struct karg arg = {0, NULL, -1};
6338 s = parse_prefix_and_alias(s, &prefix);
6340 for (tok = strtok_r(s, " ", &last); tok;
6341 tok = strtok_r(NULL, " ", &last)) {
6342 matchcount = 0;
6343 for (j = c; j < LENGTH(cmds); j++) {
6344 if (cmds[j].level < dep)
6345 break;
6346 len = (tok[strlen(tok) - 1] == '!') ? strlen(tok) - 1 :
6347 strlen(tok);
6348 if (cmds[j].level == dep &&
6349 !strncmp(tok, cmds[j].cmd, len)) {
6350 matchcount++;
6351 c = j + 1;
6352 cmd = &cmds[j];
6353 if (len == strlen(cmds[j].cmd)) {
6354 matchcount = 1;
6355 break;
6359 if (matchcount == 1) {
6360 if (cmd->type > 0)
6361 goto execute_cmd;
6362 dep++;
6363 } else {
6364 show_oops(t, "Invalid command: %s", str);
6365 goto done;
6368 execute_cmd:
6369 if (cmd == NULL) {
6370 show_oops(t, "Empty command");
6371 goto done;
6373 arg.i = cmd->arg;
6375 if (prefix != -1)
6376 arg.precount = prefix;
6377 else if (cmd_prefix > 0)
6378 arg.precount = cmd_prefix;
6380 if (j > 0 && !(cmd->type & XT_PREFIX) && arg.precount > -1) {
6381 show_oops(t, "No prefix allowed: %s", str);
6382 goto done;
6384 if (cmd->type > 1)
6385 arg.s = last ? g_strdup(last) : g_strdup("");
6386 if (cmd->type & XT_INTARG && last && strlen(last) > 0) {
6387 if (arg.s == NULL) {
6388 show_oops(t, "Invalid command");
6389 goto done;
6391 arg.precount = atoi(arg.s);
6392 if (arg.precount <= 0) {
6393 if (arg.s[0] == '0')
6394 show_oops(t, "Zero count");
6395 else
6396 show_oops(t, "Trailing characters");
6397 goto done;
6401 DNPRINTF(XT_D_CMD, "%s: prefix %d arg %s\n",
6402 __func__, arg.precount, arg.s);
6404 cmd->func(t, &arg);
6406 rv = XT_CB_HANDLED;
6407 done:
6408 if (j > 0)
6409 cmd_prefix = 0;
6410 g_free(s);
6411 if (arg.s)
6412 g_free(arg.s);
6414 return (rv);
6418 save_runtime_setting(const char *name, const char *val)
6420 struct stat sb;
6421 FILE *f;
6422 size_t linelen;
6423 int found = 0;
6424 char file[PATH_MAX];
6425 char delim[3] = { '\0', '\0', '\0' };
6426 char *line, *lt, *start;
6427 char *contents, *tmp;
6429 if (runtime_settings == NULL || strlen(runtime_settings) == 0)
6430 return (-1);
6432 snprintf(file, sizeof file, "%s" PS "%s", work_dir, runtime_settings);
6433 if (stat(file, &sb) || (f = fopen(file, "r+")) == NULL)
6434 return (-1);
6435 lt = g_strdup_printf("%s=%s", name, val);
6436 contents = g_strdup("");
6437 while (!feof(f)) {
6438 line = fparseln(f, &linelen, NULL, delim, 0);
6439 if (line == NULL || linelen == 0)
6440 continue;
6441 tmp = contents;
6442 start = g_strdup_printf("%s=", name);
6443 if (strstr(line, start) == NULL)
6444 contents = g_strdup_printf("%s%s\n", contents, line);
6445 else {
6446 found = 1;
6447 contents = g_strdup_printf("%s%s\n", contents, lt);
6449 g_free(tmp);
6450 g_free(start);
6451 free(line);
6452 line = NULL;
6454 if (found == 0) {
6455 tmp = contents;
6456 contents = g_strdup_printf("%s%s\n", contents, lt);
6457 g_free(tmp);
6459 if ((f = freopen(file, "w", f)) == NULL)
6460 return (-1);
6461 else {
6462 fputs(contents, f);
6463 fclose(f);
6465 g_free(lt);
6466 g_free(contents);
6468 return (0);
6472 entry_focus_cb(GtkWidget *w, GdkEvent e, struct tab *t)
6475 * This sometimes gets randomly unset for whatever reason in GTK3,
6476 * causing a GtkEntry's text cursor becomes invisible. When we focus
6477 * a GtkEntry, be sure to manually reset the main window's is-active
6478 * property so the cursor is shown correctly.
6480 #if GTK_CHECK_VERSION(3, 0, 0)
6481 fake_focus_in(main_window);
6482 #endif
6483 return (XT_CB_PASSTHROUGH);
6487 entry_key_cb(GtkEntry *w, GdkEventKey *e, struct tab *t)
6489 if (t == NULL) {
6490 show_oops(NULL, "entry_key_cb invalid parameters");
6491 return (XT_CB_PASSTHROUGH);
6494 DNPRINTF(XT_D_CMD, "entry_key_cb: keyval 0x%x mask 0x%x tab %d\n",
6495 e->keyval, e->state, t->tab_id);
6497 hide_oops(t);
6499 if (e->keyval == GDK_Escape) {
6500 /* don't use focus_webview(t) because we want to type :cmds */
6501 gtk_widget_grab_focus(GTK_WIDGET(t->wv));
6504 return (handle_keypress(t, e, 1));
6507 struct command_entry *
6508 history_prev(struct command_list *l, struct command_entry *at)
6510 if (at == NULL)
6511 at = TAILQ_LAST(l, command_list);
6512 else {
6513 at = TAILQ_PREV(at, command_list, entry);
6514 if (at == NULL)
6515 at = TAILQ_LAST(l, command_list);
6518 return (at);
6521 struct command_entry *
6522 history_next(struct command_list *l, struct command_entry *at)
6524 if (at == NULL)
6525 at = TAILQ_FIRST(l);
6526 else {
6527 at = TAILQ_NEXT(at, entry);
6528 if (at == NULL)
6529 at = TAILQ_FIRST(l);
6532 return (at);
6536 cmd_keypress_cb(GtkEntry *w, GdkEventKey *e, struct tab *t)
6538 int rv = XT_CB_HANDLED;
6539 const gchar *c = gtk_entry_get_text(w);
6540 char *s;
6542 if (t == NULL) {
6543 show_oops(NULL, "cmd_keypress_cb parameters");
6544 return (XT_CB_PASSTHROUGH);
6547 DNPRINTF(XT_D_CMD, "cmd_keypress_cb: keyval 0x%x mask 0x%x tab %d\n",
6548 e->keyval, e->state, t->tab_id);
6550 /* sanity */
6551 if (c == NULL)
6552 e->keyval = GDK_Escape;
6553 else if (!(c[0] == ':' || c[0] == '/' || c[0] == '?' ||
6554 c[0] == '.' || c[0] == ','))
6555 e->keyval = GDK_Escape;
6557 if (e->keyval != GDK_Tab && e->keyval != GDK_Shift_L &&
6558 e->keyval != GDK_ISO_Left_Tab)
6559 cmd_status.index = -1;
6561 switch (e->keyval) {
6562 case GDK_Tab:
6563 if (c[0] == ':')
6564 cmd_complete(t, (char *)&c[1], 1);
6565 else if (c[0] == '.' || c[0] == ',')
6566 run_script(t, "hints.focusNextHint();");
6567 goto done;
6568 case GDK_ISO_Left_Tab:
6569 if (c[0] == ':')
6570 cmd_complete(t, (char *)&c[1], -1);
6571 else if (c[0] == '.' || c[0] == ',')
6572 run_script(t, "hints.focusPreviousHint();");
6573 goto done;
6574 case GDK_Down:
6575 if (c[0] == '?') {
6576 if ((search_at = history_next(&shl, search_at))) {
6577 search_at->line[0] = c[0];
6578 gtk_entry_set_text(w, search_at->line);
6579 gtk_editable_set_position(GTK_EDITABLE(w), -1);
6581 } else if (c[0] == '/') {
6582 if ((search_at = history_prev(&shl, search_at))) {
6583 search_at->line[0] = c[0];
6584 gtk_entry_set_text(w, search_at->line);
6585 gtk_editable_set_position(GTK_EDITABLE(w), -1);
6587 } else if (c[0] == ':') {
6588 if ((history_at = history_prev(&chl, history_at))) {
6589 history_at->line[0] = c[0];
6590 gtk_entry_set_text(w, history_at->line);
6591 gtk_editable_set_position(GTK_EDITABLE(w), -1);
6594 goto done;
6595 case GDK_Up:
6596 if (c[0] == '/') {
6597 if ((search_at = history_next(&shl, search_at))) {
6598 search_at->line[0] = c[0];
6599 gtk_entry_set_text(w, search_at->line);
6600 gtk_editable_set_position(GTK_EDITABLE(w), -1);
6602 } else if (c[0] == '?') {
6603 if ((search_at = history_prev(&shl, search_at))) {
6604 search_at->line[0] = c[0];
6605 gtk_entry_set_text(w, search_at->line);
6606 gtk_editable_set_position(GTK_EDITABLE(w), -1);
6608 } if (c[0] == ':') {
6609 if ((history_at = history_next(&chl, history_at))) {
6610 history_at->line[0] = c[0];
6611 gtk_entry_set_text(w, history_at->line);
6612 gtk_editable_set_position(GTK_EDITABLE(w), -1);
6615 goto done;
6616 case GDK_BackSpace:
6617 if (!(!strcmp(c, ":") || !strcmp(c, "/") || !strcmp(c, "?") ||
6618 !strcmp(c, ".") || !strcmp(c, ","))) {
6619 /* see if we are doing hinting and reset it */
6620 if (c[0] == '.' || c[0] == ',') {
6621 /* recreate hints */
6622 s = g_strdup_printf("hints.createHints('', "
6623 "'%c');", c[0] == '.' ? 'f' : 'F');
6624 run_script(t, s);
6625 g_free(s);
6627 break;
6630 /* FALLTHROUGH */
6631 case GDK_Escape:
6632 hide_cmd(t);
6634 /* cancel search */
6635 if (c != NULL && (c[0] == '/' || c[0] == '?'))
6636 webkit_web_view_unmark_text_matches(t->wv);
6638 /* no need to cancel hints */
6639 goto done;
6642 rv = XT_CB_PASSTHROUGH;
6643 done:
6644 return (rv);
6647 void
6648 wv_popup_activ_cb(GtkMenuItem *menu, struct tab *t)
6650 GtkAction *a = NULL;
6651 GtkClipboard *clipboard, *primary;
6652 const gchar *name, *uri;
6654 a = gtk_activatable_get_related_action(GTK_ACTIVATABLE(menu));
6655 if (a == NULL)
6656 return;
6657 name = gtk_action_get_name(a);
6659 DNPRINTF(XT_D_CMD, "wv_popup_activ_cb: tab %d action %s\n",
6660 t->tab_id, name);
6663 * context-menu-action-3 copy link location
6664 * context-menu-action-7 copy image address
6665 * context-menu-action-2030 copy video link location
6668 /* copy actions */
6669 if ((g_strcmp0(name, "context-menu-action-3") == 0) ||
6670 (g_strcmp0(name, "context-menu-action-7") == 0) ||
6671 (g_strcmp0(name, "context-menu-action-2030") == 0)) {
6672 clipboard = gtk_clipboard_get(GDK_SELECTION_CLIPBOARD);
6673 primary = gtk_clipboard_get(GDK_SELECTION_PRIMARY);
6674 uri = gtk_clipboard_wait_for_text(clipboard);
6675 if (uri == NULL)
6676 return;
6677 gtk_clipboard_set_text(primary, uri, -1);
6681 void
6682 wv_popup_cb(WebKitWebView *wview, GtkMenu *menu, struct tab *t)
6684 GList *items, *l;
6686 DNPRINTF(XT_D_CMD, "wv_popup_cb: tab %d\n", t->tab_id);
6688 items = gtk_container_get_children(GTK_CONTAINER(menu));
6689 for (l = items; l; l = l->next)
6690 g_signal_connect(l->data, "activate",
6691 G_CALLBACK(wv_popup_activ_cb), t);
6692 g_list_free(items);
6695 void
6696 cmd_popup_cb(GtkEntry *entry, GtkMenu *menu, struct tab *t)
6698 /* popup menu enabled */
6699 t->popup = 1;
6703 cmd_focusout_cb(GtkWidget *w, GdkEventFocus *e, struct tab *t)
6705 if (t == NULL) {
6706 show_oops(NULL, "cmd_focusout_cb invalid parameters");
6707 return (XT_CB_PASSTHROUGH);
6710 DNPRINTF(XT_D_CMD, "cmd_focusout_cb: tab %d popup %d\n",
6711 t->tab_id, t->popup);
6713 /* if popup is enabled don't lose focus */
6714 if (t->popup) {
6715 t->popup = 0;
6716 return (XT_CB_PASSTHROUGH);
6719 hide_cmd(t);
6720 hide_oops(t);
6721 disable_hints(t);
6723 return (XT_CB_PASSTHROUGH);
6726 void
6727 cmd_hide_cb(GtkWidget *w, struct tab *t)
6729 if (t == NULL) {
6730 show_oops(NULL, "%s: invalid parameters", __func__);
6731 return;
6734 if (show_url == 0 || t->focus_wv)
6735 focus_webview(t);
6736 else
6737 gtk_widget_grab_focus(GTK_WIDGET(t->uri_entry));
6740 void
6741 cmd_activate_cb(GtkEntry *entry, struct tab *t)
6743 char *s;
6744 const gchar *c = gtk_entry_get_text(entry);
6746 if (t == NULL) {
6747 show_oops(NULL, "cmd_activate_cb invalid parameters");
6748 return;
6751 DNPRINTF(XT_D_CMD, "cmd_activate_cb: tab %d %s\n", t->tab_id, c);
6753 /* sanity */
6754 if (c == NULL)
6755 goto done;
6756 else if (!(c[0] == ':' || c[0] == '/' || c[0] == '?' ||
6757 c[0] == '.' || c[0] == ','))
6758 goto done;
6759 if (strlen(c) < 1)
6760 goto done;
6761 s = (char *)&c[1];
6763 if (c[0] == '/' || c[0] == '?') {
6764 /* see if there is a timer pending */
6765 if (t->search_id) {
6766 g_source_remove(t->search_id);
6767 t->search_id = 0;
6768 search_cb(t);
6771 if (t->search_text) {
6772 g_free(t->search_text);
6773 t->search_text = NULL;
6776 t->search_text = g_strdup(s);
6777 if (global_search)
6778 g_free(global_search);
6779 global_search = g_strdup(s);
6780 t->search_forward = c[0] == '/';
6782 history_add(&shl, search_file, s, &search_history_count);
6783 } else if (c[0] == '.' || c[0] == ',') {
6784 run_script(t, "hints.fire();");
6785 /* XXX history for link following? */
6786 } else if (c[0] == ':') {
6787 history_add(&chl, command_file, s, &cmd_history_count);
6788 /* can't call hide_cmd after cmd_execute */
6789 hide_cmd(t);
6790 cmd_execute(t, s);
6791 return;
6794 done:
6795 hide_cmd(t);
6798 void
6799 backward_cb(GtkWidget *w, struct tab *t)
6801 struct karg a;
6803 if (t == NULL) {
6804 show_oops(NULL, "backward_cb invalid parameters");
6805 return;
6808 DNPRINTF(XT_D_NAV, "backward_cb: tab %d\n", t->tab_id);
6810 a.i = XT_NAV_BACK;
6811 navaction(t, &a);
6814 void
6815 forward_cb(GtkWidget *w, struct tab *t)
6817 struct karg a;
6819 if (t == NULL) {
6820 show_oops(NULL, "forward_cb invalid parameters");
6821 return;
6824 DNPRINTF(XT_D_NAV, "forward_cb: tab %d\n", t->tab_id);
6826 a.i = XT_NAV_FORWARD;
6827 navaction(t, &a);
6830 void
6831 home_cb(GtkWidget *w, struct tab *t)
6833 if (t == NULL) {
6834 show_oops(NULL, "home_cb invalid parameters");
6835 return;
6838 DNPRINTF(XT_D_NAV, "home_cb: tab %d\n", t->tab_id);
6840 load_uri(t, home);
6843 void
6844 stop_cb(GtkWidget *w, struct tab *t)
6846 WebKitWebFrame *frame;
6848 if (t == NULL) {
6849 show_oops(NULL, "stop_cb invalid parameters");
6850 return;
6853 DNPRINTF(XT_D_NAV, "stop_cb: tab %d\n", t->tab_id);
6855 frame = webkit_web_view_get_main_frame(t->wv);
6856 if (frame == NULL) {
6857 show_oops(t, "stop_cb: no frame");
6858 return;
6861 webkit_web_frame_stop_loading(frame);
6862 abort_favicon_download(t);
6865 void
6866 setup_webkit(struct tab *t)
6868 if (is_g_object_setting(G_OBJECT(t->settings), "enable-dns-prefetching"))
6869 g_object_set(G_OBJECT(t->settings), "enable-dns-prefetching",
6870 FALSE, (char *)NULL);
6871 else
6872 warnx("webkit does not have \"enable-dns-prefetching\" property");
6873 g_object_set(G_OBJECT(t->settings),
6874 "user-agent", t->user_agent, (char *)NULL);
6875 g_object_set(G_OBJECT(t->settings),
6876 "enable-scripts", enable_scripts, (char *)NULL);
6877 g_object_set(G_OBJECT(t->settings),
6878 "enable-plugins", enable_plugins, (char *)NULL);
6879 g_object_set(G_OBJECT(t->settings),
6880 "javascript-can-open-windows-automatically", enable_scripts,
6881 (char *)NULL);
6882 g_object_set(G_OBJECT(t->settings),
6883 "enable-html5-database", FALSE, (char *)NULL);
6884 g_object_set(G_OBJECT(t->settings),
6885 "enable-html5-local-storage", enable_localstorage, (char *)NULL);
6886 g_object_set(G_OBJECT(t->settings),
6887 "enable_spell_checking", enable_spell_checking, (char *)NULL);
6888 g_object_set(G_OBJECT(t->settings),
6889 "spell_checking_languages", spell_check_languages, (char *)NULL);
6890 g_object_set(G_OBJECT(t->settings),
6891 "enable-developer-extras", TRUE, (char *)NULL);
6892 g_object_set(G_OBJECT(t->wv),
6893 "full-content-zoom", TRUE, (char *)NULL);
6894 g_object_set(G_OBJECT(t->settings),
6895 "auto-load-images", auto_load_images, (char *)NULL);
6896 if (is_g_object_setting(G_OBJECT(t->settings),
6897 "enable-display-of-insecure-content"))
6898 g_object_set(G_OBJECT(t->settings),
6899 "enable-display-of-insecure-content",
6900 allow_insecure_content, (char *)NULL);
6901 if (is_g_object_setting(G_OBJECT(t->settings),
6902 "enable-running-of-insecure-content"))
6903 g_object_set(G_OBJECT(t->settings),
6904 "enable-running-of-insecure-content",
6905 allow_insecure_scripts, (char *)NULL);
6907 webkit_web_view_set_settings(t->wv, t->settings);
6910 gboolean
6911 update_statusbar_position(GtkAdjustment* adjustment, gpointer data)
6913 struct tab *ti, *t = NULL;
6914 gdouble view_size, value, max;
6915 gchar *position;
6917 TAILQ_FOREACH(ti, &tabs, entry)
6918 if (ti->tab_id == gtk_notebook_get_current_page(notebook)) {
6919 t = ti;
6920 break;
6923 if (t == NULL)
6924 return FALSE;
6926 if (adjustment == NULL)
6927 adjustment = gtk_scrolled_window_get_vadjustment(
6928 GTK_SCROLLED_WINDOW(t->browser_win));
6930 view_size = gtk_adjustment_get_page_size(adjustment);
6931 value = gtk_adjustment_get_value(adjustment);
6932 max = gtk_adjustment_get_upper(adjustment) - view_size;
6934 if (max == 0)
6935 position = g_strdup("All");
6936 else if (value == max)
6937 position = g_strdup("Bot");
6938 else if (value == 0)
6939 position = g_strdup("Top");
6940 else
6941 position = g_strdup_printf("%d%%", (int) ((value / max) * 100));
6943 gtk_label_set_text(GTK_LABEL(t->sbe.position), position);
6944 g_free(position);
6946 return (TRUE);
6949 GtkWidget *
6950 create_window(const gchar *name)
6952 GtkWidget *w;
6954 w = gtk_window_new(GTK_WINDOW_TOPLEVEL);
6955 if (window_maximize)
6956 gtk_window_maximize(GTK_WINDOW(w));
6957 else
6958 gtk_window_set_default_size(GTK_WINDOW(w), window_width, window_height);
6959 gtk_widget_set_name(w, name);
6960 gtk_window_set_wmclass(GTK_WINDOW(w), name, "Xombrero");
6962 return (w);
6965 GtkWidget *
6966 create_browser(struct tab *t)
6968 GtkWidget *w;
6969 gchar *strval;
6970 GtkAdjustment *adjustment;
6972 if (t == NULL) {
6973 show_oops(NULL, "create_browser invalid parameters");
6974 return (NULL);
6977 w = gtk_scrolled_window_new(NULL, NULL);
6978 gtk_widget_set_can_focus(w, FALSE);
6979 t->adjust_h = gtk_scrolled_window_get_hadjustment(
6980 GTK_SCROLLED_WINDOW(w));
6981 t->adjust_v = gtk_scrolled_window_get_vadjustment(
6982 GTK_SCROLLED_WINDOW(w));
6983 #if !GTK_CHECK_VERSION(3, 0, 0)
6984 gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(w),
6985 GTK_POLICY_AUTOMATIC, GTK_POLICY_AUTOMATIC);
6986 #endif
6989 t->wv = WEBKIT_WEB_VIEW(webkit_web_view_new());
6990 gtk_container_add(GTK_CONTAINER(w), GTK_WIDGET(t->wv));
6992 /* set defaults */
6993 t->settings = webkit_web_settings_new();
6995 g_object_set(t->settings, "default-encoding", encoding, (char *)NULL);
6997 if (user_agent == NULL) {
6998 g_object_get(G_OBJECT(t->settings), "user-agent", &strval,
6999 (char *)NULL);
7000 t->user_agent = g_strdup_printf("%s %s+", strval, version);
7001 g_free(strval);
7002 } else
7003 t->user_agent = g_strdup(user_agent->value);
7005 t->stylesheet = g_strdup(stylesheet);
7006 t->load_images = auto_load_images;
7008 adjustment =
7009 gtk_scrolled_window_get_vadjustment(GTK_SCROLLED_WINDOW(w));
7010 g_signal_connect(G_OBJECT(adjustment), "value-changed",
7011 G_CALLBACK(update_statusbar_position), NULL);
7013 setup_webkit(t);
7014 setup_inspector(t);
7016 return (w);
7019 GtkWidget *
7020 create_kiosk_toolbar(struct tab *t)
7022 GtkWidget *toolbar = NULL, *b;
7024 #if GTK_CHECK_VERSION(3, 0, 0)
7025 b = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 0);
7026 gtk_widget_set_name(GTK_WIDGET(b), "toolbar");
7027 #else
7028 b = gtk_hbox_new(FALSE, 0);
7029 #endif
7030 toolbar = b;
7031 gtk_container_set_border_width(GTK_CONTAINER(toolbar), 0);
7033 /* backward button */
7034 t->backward = create_button("Back", GTK_STOCK_GO_BACK, 0);
7035 gtk_widget_set_sensitive(t->backward, FALSE);
7036 g_signal_connect(G_OBJECT(t->backward), "clicked",
7037 G_CALLBACK(backward_cb), t);
7038 gtk_box_pack_start(GTK_BOX(b), t->backward, TRUE, TRUE, 0);
7040 /* forward button */
7041 t->forward = create_button("Forward", GTK_STOCK_GO_FORWARD, 0);
7042 gtk_widget_set_sensitive(t->forward, FALSE);
7043 g_signal_connect(G_OBJECT(t->forward), "clicked",
7044 G_CALLBACK(forward_cb), t);
7045 gtk_box_pack_start(GTK_BOX(b), t->forward, TRUE, TRUE, 0);
7047 /* home button */
7048 t->gohome = create_button("Home", GTK_STOCK_HOME, 0);
7049 gtk_widget_set_sensitive(t->gohome, true);
7050 g_signal_connect(G_OBJECT(t->gohome), "clicked",
7051 G_CALLBACK(home_cb), t);
7052 gtk_box_pack_start(GTK_BOX(b), t->gohome, TRUE, TRUE, 0);
7054 /* create widgets but don't use them */
7055 t->uri_entry = gtk_entry_new();
7056 g_signal_connect(G_OBJECT(t->uri_entry), "focus-in-event",
7057 G_CALLBACK(entry_focus_cb), t);
7058 #if !GTK_CHECK_VERSION(3, 0, 0)
7059 t->default_style = gtk_rc_get_style(t->uri_entry);
7060 #endif
7061 t->stop = create_button("Stop", GTK_STOCK_STOP, 0);
7062 t->js_toggle = create_button("JS-Toggle", enable_scripts ?
7063 GTK_STOCK_MEDIA_PLAY : GTK_STOCK_MEDIA_PAUSE, 0);
7065 return (toolbar);
7068 GtkWidget *
7069 create_toolbar(struct tab *t)
7071 GtkWidget *toolbar = NULL, *b;
7073 #if GTK_CHECK_VERSION(3, 0, 0)
7074 b = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 0);
7075 gtk_widget_set_name(GTK_WIDGET(b), "toolbar");
7076 #else
7077 b = gtk_hbox_new(FALSE, 0);
7078 #endif
7079 toolbar = b;
7080 gtk_container_set_border_width(GTK_CONTAINER(toolbar), 0);
7082 /* backward button */
7083 t->backward = create_button("Back", GTK_STOCK_GO_BACK, 0);
7084 gtk_widget_set_sensitive(t->backward, FALSE);
7085 g_signal_connect(G_OBJECT(t->backward), "clicked",
7086 G_CALLBACK(backward_cb), t);
7087 gtk_box_pack_start(GTK_BOX(b), t->backward, FALSE, FALSE, 0);
7089 /* forward button */
7090 t->forward = create_button("Forward",GTK_STOCK_GO_FORWARD, 0);
7091 gtk_widget_set_sensitive(t->forward, FALSE);
7092 g_signal_connect(G_OBJECT(t->forward), "clicked",
7093 G_CALLBACK(forward_cb), t);
7094 gtk_box_pack_start(GTK_BOX(b), t->forward, FALSE, FALSE, 0);
7096 /* stop button */
7097 t->stop = create_button("Stop", GTK_STOCK_STOP, 0);
7098 gtk_widget_set_sensitive(t->stop, FALSE);
7099 g_signal_connect(G_OBJECT(t->stop), "clicked", G_CALLBACK(stop_cb), t);
7100 gtk_box_pack_start(GTK_BOX(b), t->stop, FALSE, FALSE, 0);
7102 /* JS button */
7103 t->js_toggle = create_button("JS-Toggle", enable_scripts ?
7104 GTK_STOCK_MEDIA_PLAY : GTK_STOCK_MEDIA_PAUSE, 0);
7105 gtk_widget_set_sensitive(t->js_toggle, TRUE);
7106 g_signal_connect(G_OBJECT(t->js_toggle), "clicked",
7107 G_CALLBACK(js_toggle_cb), t);
7108 gtk_box_pack_start(GTK_BOX(b), t->js_toggle, FALSE, FALSE, 0);
7110 t->uri_entry = gtk_entry_new();
7111 g_signal_connect(G_OBJECT(t->uri_entry), "activate",
7112 G_CALLBACK(activate_uri_entry_cb), t);
7113 g_signal_connect(G_OBJECT(t->uri_entry), "key-press-event",
7114 G_CALLBACK(entry_key_cb), t);
7115 g_signal_connect(G_OBJECT(t->uri_entry), "focus-in-event",
7116 G_CALLBACK(entry_focus_cb), t);
7117 completion_add(t);
7118 gtk_box_pack_start(GTK_BOX(b), t->uri_entry, TRUE, TRUE, 0);
7120 /* search entry */
7121 t->search_entry = gtk_entry_new();
7122 gtk_entry_set_width_chars(GTK_ENTRY(t->search_entry), 30);
7123 g_signal_connect(G_OBJECT(t->search_entry), "activate",
7124 G_CALLBACK(activate_search_entry_cb), t);
7125 g_signal_connect(G_OBJECT(t->search_entry), "key-press-event",
7126 G_CALLBACK(entry_key_cb), t);
7127 g_signal_connect(G_OBJECT(t->search_entry), "focus-in-event",
7128 G_CALLBACK(entry_focus_cb), t);
7129 gtk_box_pack_start(GTK_BOX(b), t->search_entry, FALSE, FALSE, 0);
7131 #if !GTK_CHECK_VERSION(3, 0, 0)
7132 t->default_style = gtk_rc_get_style(t->uri_entry);
7133 #endif
7135 return (toolbar);
7138 GtkWidget *
7139 create_buffers(struct tab *t)
7141 GtkCellRenderer *renderer;
7142 GtkWidget *view;
7144 view = gtk_tree_view_new();
7146 gtk_tree_view_set_headers_visible(GTK_TREE_VIEW(view), FALSE);
7148 renderer = gtk_cell_renderer_text_new();
7149 gtk_tree_view_insert_column_with_attributes
7150 (GTK_TREE_VIEW(view), -1, "Id", renderer, "text", COL_ID, (char *)NULL);
7152 renderer = gtk_cell_renderer_pixbuf_new();
7153 gtk_tree_view_insert_column_with_attributes
7154 (GTK_TREE_VIEW(view), -1, "Favicon", renderer, "pixbuf", COL_FAVICON,
7155 (char *)NULL);
7157 renderer = gtk_cell_renderer_text_new();
7158 gtk_tree_view_insert_column_with_attributes
7159 (GTK_TREE_VIEW(view), -1, "Title", renderer, "text", COL_TITLE,
7160 (char *)NULL);
7162 gtk_tree_view_set_model
7163 (GTK_TREE_VIEW(view), GTK_TREE_MODEL(buffers_store));
7165 return (view);
7168 void
7169 row_activated_cb(GtkTreeView *view, GtkTreePath *path,
7170 GtkTreeViewColumn *col, struct tab *t)
7172 GtkTreeIter iter;
7173 guint id;
7175 gtk_widget_grab_focus(GTK_WIDGET(t->wv));
7177 if (gtk_tree_model_get_iter(GTK_TREE_MODEL(buffers_store), &iter,
7178 path)) {
7179 gtk_tree_model_get
7180 (GTK_TREE_MODEL(buffers_store), &iter, COL_ID, &id, -1);
7181 set_current_tab(id - 1);
7184 hide_buffers(t);
7187 /* after tab reordering/creation/removal */
7188 void
7189 recalc_tabs(void)
7191 struct tab *t;
7193 TAILQ_FOREACH(t, &tabs, entry)
7194 t->tab_id = gtk_notebook_page_num(notebook, t->vbox);
7197 void
7198 update_statusbar_tabs(struct tab *t)
7200 int tab_id, max_tab_id;
7201 char s[16];
7203 if (t != NULL)
7204 tab_id = t->tab_id;
7205 else
7206 tab_id = gtk_notebook_get_current_page(notebook);
7208 max_tab_id = gtk_notebook_get_n_pages(notebook);
7209 snprintf(s, sizeof s, "%d/%d", tab_id + 1, max_tab_id);
7211 if (t == NULL)
7212 t = get_current_tab();
7214 if (t != NULL)
7215 gtk_label_set_text(GTK_LABEL(t->sbe.tabs), s);
7218 /* after active tab change */
7219 void
7220 recolor_compact_tabs(void)
7222 struct tab *t;
7223 int curid = 0;
7224 #if !GTK_CHECK_VERSION(3, 0, 0)
7225 GdkColor color_active, color_inactive;
7227 gdk_color_parse(XT_COLOR_CT_ACTIVE, &color_active);
7228 gdk_color_parse(XT_COLOR_CT_INACTIVE, &color_inactive);
7229 #endif
7230 curid = gtk_notebook_get_current_page(notebook);
7232 TAILQ_FOREACH(t, &tabs, entry) {
7233 #if GTK_CHECK_VERSION(3, 0, 0)
7234 if (t->tab_id == curid)
7235 gtk_widget_set_name(t->tab_elems.label, XT_CSS_ACTIVE);
7236 else
7237 gtk_widget_set_name(t->tab_elems.label, "");
7238 #else
7239 if (t->tab_id == curid)
7240 gtk_widget_modify_fg(t->tab_elems.label,
7241 GTK_STATE_NORMAL, &color_active);
7242 else
7243 gtk_widget_modify_fg(t->tab_elems.label,
7244 GTK_STATE_NORMAL, &color_inactive);
7245 #endif
7249 void
7250 set_current_tab(int page_num)
7252 buffercmd_abort(get_current_tab());
7253 gtk_notebook_set_current_page(notebook, page_num);
7254 recolor_compact_tabs();
7255 update_statusbar_tabs(NULL);
7259 undo_close_tab_save(struct tab *t)
7261 int m, n;
7262 const gchar *uri;
7263 struct undo *u1, *u2;
7264 GList *items;
7265 WebKitWebHistoryItem *item;
7267 if ((uri = get_uri(t)) == NULL)
7268 return (1);
7270 u1 = g_malloc0(sizeof(struct undo));
7271 u1->uri = g_strdup(uri);
7273 t->bfl = webkit_web_view_get_back_forward_list(t->wv);
7275 m = webkit_web_back_forward_list_get_forward_length(t->bfl);
7276 n = webkit_web_back_forward_list_get_back_length(t->bfl);
7277 u1->back = n;
7279 /* forward history */
7280 items = webkit_web_back_forward_list_get_forward_list_with_limit(t->bfl, m);
7282 while (items) {
7283 item = items->data;
7284 u1->history = g_list_prepend(u1->history,
7285 webkit_web_history_item_copy(item));
7286 items = g_list_next(items);
7289 /* current item */
7290 if (m) {
7291 item = webkit_web_back_forward_list_get_current_item(t->bfl);
7292 u1->history = g_list_prepend(u1->history,
7293 webkit_web_history_item_copy(item));
7296 /* back history */
7297 items = webkit_web_back_forward_list_get_back_list_with_limit(t->bfl, n);
7299 while (items) {
7300 item = items->data;
7301 u1->history = g_list_prepend(u1->history,
7302 webkit_web_history_item_copy(item));
7303 items = g_list_next(items);
7306 TAILQ_INSERT_HEAD(&undos, u1, entry);
7308 if (undo_count > XT_MAX_UNDO_CLOSE_TAB) {
7309 u2 = TAILQ_LAST(&undos, undo_tailq);
7310 TAILQ_REMOVE(&undos, u2, entry);
7311 g_free(u2->uri);
7312 g_list_free(u2->history);
7313 g_free(u2);
7314 } else
7315 undo_count++;
7317 return (0);
7320 void
7321 delete_tab(struct tab *t)
7323 struct karg a;
7325 DNPRINTF(XT_D_TAB, "delete_tab: %p\n", t);
7327 if (t == NULL)
7328 return;
7331 * no need to join thread here because it won't access t on completion
7334 TAILQ_REMOVE(&tabs, t, entry);
7335 buffercmd_abort(t);
7337 /* Halt all webkit activity. */
7338 abort_favicon_download(t);
7339 webkit_web_view_stop_loading(t->wv);
7341 /* Save the tab, so we can undo the close. */
7342 undo_close_tab_save(t);
7344 /* just in case */
7345 if (t->search_id)
7346 g_source_remove(t->search_id);
7348 /* session key */
7349 if (t->session_key)
7350 g_free(t->session_key);
7352 /* inspector */
7353 bzero(&a, sizeof a);
7354 a.i = XT_INS_CLOSE;
7355 inspector_cmd(t, &a);
7357 if (browser_mode == XT_BM_KIOSK) {
7358 gtk_widget_destroy(t->uri_entry);
7359 gtk_widget_destroy(t->stop);
7360 gtk_widget_destroy(t->js_toggle);
7363 g_object_unref(t->completion);
7364 if (t->item)
7365 g_object_unref(t->item);
7367 gtk_widget_destroy(t->tab_elems.eventbox);
7368 gtk_widget_destroy(t->vbox);
7370 g_free(t->user_agent);
7371 g_free(t->stylesheet);
7372 g_free(t->tmp_uri);
7373 g_free(t->status);
7374 g_free(t);
7375 t = NULL;
7377 if (TAILQ_EMPTY(&tabs)) {
7378 if (browser_mode == XT_BM_KIOSK)
7379 create_new_tab(home, NULL, 1, -1);
7380 else
7381 create_new_tab(NULL, NULL, 1, -1);
7384 /* recreate session */
7385 if (session_autosave) {
7386 bzero(&a, sizeof a);
7387 a.s = NULL;
7388 save_tabs(NULL, &a);
7391 recalc_tabs();
7392 recolor_compact_tabs();
7395 void
7396 update_statusbar_zoom(struct tab *t)
7398 gfloat zoom;
7399 char s[16] = { '\0' };
7401 g_object_get(G_OBJECT(t->wv), "zoom-level", &zoom, (char *)NULL);
7402 if ((zoom <= 0.99 || zoom >= 1.01))
7403 snprintf(s, sizeof s, "%d%%", (int)(zoom * 100));
7404 gtk_label_set_text(GTK_LABEL(t->sbe.zoom), s);
7407 void
7408 setzoom_webkit(struct tab *t, int adjust)
7410 #define XT_ZOOMPERCENT 0.04
7412 gfloat zoom;
7414 if (t == NULL) {
7415 show_oops(NULL, "setzoom_webkit invalid parameters");
7416 return;
7419 g_object_get(G_OBJECT(t->wv), "zoom-level", &zoom, (char *)NULL);
7420 if (adjust == XT_ZOOM_IN)
7421 zoom += XT_ZOOMPERCENT;
7422 else if (adjust == XT_ZOOM_OUT)
7423 zoom -= XT_ZOOMPERCENT;
7424 else if (adjust > 0)
7425 zoom = default_zoom_level + adjust / 100.0 - 1.0;
7426 else {
7427 show_oops(t, "setzoom_webkit invalid zoom value");
7428 return;
7431 if (zoom < XT_ZOOMPERCENT)
7432 zoom = XT_ZOOMPERCENT;
7433 g_object_set(G_OBJECT(t->wv), "zoom-level", zoom, (char *)NULL);
7434 update_statusbar_zoom(t);
7437 gboolean
7438 tab_clicked_cb(GtkWidget *widget, GdkEventButton *event, gpointer data)
7440 struct tab *t = (struct tab *) data;
7442 DNPRINTF(XT_D_TAB, "tab_clicked_cb: tab: %d\n", t->tab_id);
7444 switch (event->button) {
7445 case 1:
7446 set_current_tab(t->tab_id);
7447 break;
7448 case 2:
7449 delete_tab(t);
7450 break;
7453 return TRUE;
7456 void
7457 append_tab(struct tab *t)
7459 if (t == NULL)
7460 return;
7462 TAILQ_INSERT_TAIL(&tabs, t, entry);
7463 t->tab_id = gtk_notebook_append_page(notebook, t->vbox, t->tab_content);
7466 GtkWidget *
7467 create_sbe(void)
7469 GtkWidget *sbe;
7471 sbe = gtk_label_new(NULL);
7472 gtk_widget_set_can_focus(GTK_WIDGET(sbe), FALSE);
7473 gtk_widget_modify_font(GTK_WIDGET(sbe), statusbar_font);
7474 return (sbe);
7478 add_sbe(GtkWidget *box, char flag, int *used, GtkWidget *sbe)
7480 if (box == NULL || used == NULL || sbe == NULL) {
7481 DPRINTF("%s: invalid parameters", __func__);
7482 return (1);
7485 if (*used) {
7486 warnx("flag \"%c\" specified more than "
7487 "once in statusbar_elems\n", flag);
7488 return (1);
7491 gtk_box_pack_start(GTK_BOX(box), sbe, FALSE, FALSE, 0);
7492 *used = 1;
7494 return (0);
7498 statusbar_create(struct tab *t)
7500 GtkWidget *box; /* container for statusbar elems */
7501 GtkWidget *sep;
7502 char *p;
7503 int sbe_P = 0, sbe_B = 0, sbe_Z = 0, sbe_T = 0,
7504 sbe_p = 0;
7505 #if !GTK_CHECK_VERSION(3, 0, 0)
7506 GdkColor color;
7507 #endif
7509 if (t == NULL) {
7510 DPRINTF("%s: invalid parameters", __func__);
7511 return (1);
7514 #if GTK_CHECK_VERSION(3, 0, 0)
7515 t->statusbar = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 0);
7516 box = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 0);
7517 gtk_widget_set_name(GTK_WIDGET(t->statusbar), "statusbar");
7518 #else
7519 t->statusbar = gtk_hbox_new(FALSE, 0);
7520 box = gtk_hbox_new(FALSE, 0);
7521 #endif
7522 t->sbe.ebox = gtk_event_box_new();
7524 gtk_widget_set_can_focus(GTK_WIDGET(t->statusbar), FALSE);
7525 gtk_widget_set_can_focus(GTK_WIDGET(t->sbe.ebox), FALSE);
7526 gtk_widget_set_can_focus(GTK_WIDGET(box), FALSE);
7528 gtk_box_set_spacing(GTK_BOX(box), 10);
7529 gtk_box_pack_start(GTK_BOX(t->statusbar), t->sbe.ebox, TRUE, TRUE, 0);
7530 gtk_container_add(GTK_CONTAINER(t->sbe.ebox), box);
7532 /* create these widgets only if specified in statusbar_elems */
7533 t->sbe.uri = gtk_entry_new();
7534 gtk_widget_set_can_focus(GTK_WIDGET(t->sbe.uri), FALSE);
7535 gtk_widget_modify_font(GTK_WIDGET(t->sbe.uri), statusbar_font);
7536 #if !GTK_CHECK_VERSION(3, 0, 0)
7537 gtk_entry_set_inner_border(GTK_ENTRY(t->sbe.uri), NULL);
7538 gtk_entry_set_has_frame(GTK_ENTRY(t->sbe.uri), FALSE);
7539 #endif
7540 t->sbe.position = create_sbe();
7541 t->sbe.zoom = create_sbe();
7542 t->sbe.buffercmd = create_sbe();
7543 t->sbe.tabs = create_sbe();
7544 t->sbe.proxy = create_sbe();
7546 #if GTK_CHECK_VERSION(3, 0, 0)
7547 statusbar_modify_attr(t, XT_CSS_NORMAL);
7548 #else
7549 statusbar_modify_attr(t, XT_COLOR_WHITE, XT_COLOR_BLACK);
7550 #endif
7552 gtk_box_pack_start(GTK_BOX(box), t->sbe.uri, TRUE, TRUE, 0);
7555 * gtk widgets cannot be added to a box twice. The sbe_* variables
7556 * make sure of this
7558 for (p = statusbar_elems; *p != '\0'; p++) {
7559 switch (*p) {
7560 case '|':
7561 #if GTK_CHECK_VERSION(3, 0, 0)
7562 sep = gtk_separator_new(GTK_ORIENTATION_VERTICAL);
7563 #else
7564 sep = gtk_vseparator_new();
7565 gdk_color_parse(XT_COLOR_SB_SEPARATOR, &color);
7566 gtk_widget_modify_bg(sep, GTK_STATE_NORMAL, &color);
7567 #endif
7568 gtk_box_pack_start(GTK_BOX(box), sep, FALSE, FALSE, 0);
7569 break;
7570 case 'P':
7571 add_sbe(box, *p, &sbe_P, t->sbe.position);
7572 break;
7573 case 'B':
7574 add_sbe(box, *p, &sbe_B, t->sbe.buffercmd);
7575 break;
7576 case 'Z':
7577 add_sbe(box, *p, &sbe_Z, t->sbe.zoom);
7578 break;
7579 case 'T':
7580 add_sbe(box, *p, &sbe_T, t->sbe.tabs);
7581 break;
7582 case 'p':
7583 if (add_sbe(box, *p, &sbe_p, t->sbe.proxy) == 0)
7584 if (proxy_uri)
7585 gtk_entry_set_text(
7586 GTK_ENTRY(t->sbe.proxy), "proxy");
7587 break;
7588 default:
7589 warnx("illegal flag \"%c\" in statusbar_elems\n", *p);
7590 break;
7594 gtk_box_pack_end(GTK_BOX(t->vbox), t->statusbar, FALSE, FALSE, 0);
7596 return (0);
7599 struct tab *
7600 create_new_tab(char *title, struct undo *u, int focus, int position)
7602 struct tab *t;
7603 int load = 1, id;
7604 GtkWidget *b, *bb;
7605 WebKitWebHistoryItem *item;
7606 GList *items;
7607 #if !GTK_CHECK_VERSION(3, 0, 0)
7608 GdkColor color;
7609 #endif
7611 DNPRINTF(XT_D_TAB, "create_new_tab: title %s focus %d\n", title, focus);
7613 if (tabless && !TAILQ_EMPTY(&tabs)) {
7614 DNPRINTF(XT_D_TAB, "create_new_tab: new tab rejected\n");
7615 return (NULL);
7618 t = g_malloc0(sizeof *t);
7620 if (title == NULL) {
7621 title = "(untitled)";
7622 load = 0;
7625 #if GTK_CHECK_VERSION(3, 0, 0)
7626 t->vbox = gtk_box_new(GTK_ORIENTATION_VERTICAL, 0);
7627 b = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 0);
7628 gtk_widget_set_name(t->vbox, "vbox");
7629 #else
7630 t->vbox = gtk_vbox_new(FALSE, 0);
7631 b = gtk_hbox_new(FALSE, 0);
7632 #endif
7633 gtk_widget_set_can_focus(t->vbox, FALSE);
7635 /* label + button for tab */
7636 t->tab_content = b;
7637 gtk_widget_set_can_focus(t->tab_content, FALSE);
7639 t->user_agent_id = 0;
7640 t->http_accept_id = 0;
7642 #if WEBKIT_CHECK_VERSION(1, 5, 0)
7643 t->active = NULL;
7644 #endif
7646 #if GTK_CHECK_VERSION(2, 20, 0)
7647 t->spinner = gtk_spinner_new();
7648 #endif
7649 t->label = gtk_label_new(title);
7650 bb = create_button("Close", GTK_STOCK_CLOSE, 1);
7651 gtk_label_set_max_width_chars(GTK_LABEL(t->label), 20);
7652 gtk_label_set_ellipsize(GTK_LABEL(t->label), PANGO_ELLIPSIZE_END);
7653 gtk_label_set_line_wrap(GTK_LABEL(t->label), FALSE);
7654 gtk_widget_set_size_request(b, 130, 0);
7657 * this is a total hack and most likely breaks with other styles but
7658 * is necessary so the text doesn't bounce around when the spinner is
7659 * shown/hidden
7661 #if GTK_CHECK_VERSION(3, 0, 0)
7662 gtk_widget_set_size_request(t->label, 95, 0);
7663 #else
7664 gtk_widget_set_size_request(t->label, 100, 0);
7665 #endif
7667 gtk_box_pack_start(GTK_BOX(b), bb, FALSE, FALSE, 0);
7668 gtk_box_pack_start(GTK_BOX(b), t->label, FALSE, FALSE, 0);
7669 #if GTK_CHECK_VERSION(2, 20, 0)
7670 gtk_box_pack_end(GTK_BOX(b), t->spinner, FALSE, FALSE, 0);
7671 #endif
7673 /* toolbar */
7674 if (browser_mode == XT_BM_KIOSK) {
7675 t->toolbar = create_kiosk_toolbar(t);
7676 gtk_box_pack_start(GTK_BOX(t->vbox), t->toolbar, FALSE, FALSE,
7678 } else {
7679 t->toolbar = create_toolbar(t);
7680 gtk_box_pack_start(GTK_BOX(t->vbox), t->toolbar, FALSE, FALSE,
7684 /* marks */
7685 marks_clear(t);
7687 /* browser */
7688 t->browser_win = create_browser(t);
7689 set_scrollbar_visibility(t, show_scrollbars);
7690 gtk_box_pack_start(GTK_BOX(t->vbox), t->browser_win, TRUE, TRUE, 0);
7692 /* oops message for user feedback */
7693 t->oops = gtk_entry_new();
7694 gtk_entry_set_inner_border(GTK_ENTRY(t->oops), NULL);
7695 gtk_entry_set_has_frame(GTK_ENTRY(t->oops), FALSE);
7696 gtk_widget_set_can_focus(GTK_WIDGET(t->oops), FALSE);
7697 #if GTK_CHECK_VERSION(3, 0, 0)
7698 gtk_widget_set_name(t->oops, XT_CSS_RED);
7699 #else
7700 gdk_color_parse(XT_COLOR_RED, &color);
7701 gtk_widget_modify_base(t->oops, GTK_STATE_NORMAL, &color);
7702 #endif
7703 gtk_box_pack_end(GTK_BOX(t->vbox), t->oops, FALSE, FALSE, 0);
7704 gtk_widget_modify_font(GTK_WIDGET(t->oops), oops_font);
7706 /* command entry */
7707 t->cmd = gtk_entry_new();
7708 g_signal_connect(G_OBJECT(t->cmd), "focus-in-event",
7709 G_CALLBACK(entry_focus_cb), t);
7710 gtk_entry_set_inner_border(GTK_ENTRY(t->cmd), NULL);
7711 gtk_entry_set_has_frame(GTK_ENTRY(t->cmd), FALSE);
7712 gtk_box_pack_end(GTK_BOX(t->vbox), t->cmd, FALSE, FALSE, 0);
7713 gtk_widget_modify_font(GTK_WIDGET(t->cmd), cmd_font);
7715 /* status bar */
7716 statusbar_create(t);
7718 /* buffer list */
7719 t->buffers = create_buffers(t);
7720 gtk_box_pack_end(GTK_BOX(t->vbox), t->buffers, FALSE, FALSE, 0);
7722 /* xtp meaning is normal by default */
7723 set_normal_tab_meaning(t);
7725 /* set empty favicon */
7726 xt_icon_from_name(t, "text-html");
7728 /* and show it all */
7729 gtk_widget_show_all(b);
7730 gtk_widget_show_all(t->vbox);
7732 if (!fancy_bar) {
7733 gtk_widget_hide(t->backward);
7734 gtk_widget_hide(t->forward);
7735 gtk_widget_hide(t->stop);
7736 gtk_widget_hide(t->js_toggle);
7738 if (!fancy_bar || (search_string == NULL || strlen(search_string) == 0))
7739 gtk_widget_hide(t->search_entry);
7741 /* compact tab bar */
7742 t->tab_elems.label = gtk_label_new(title);
7743 t->tab_elems.favicon = gtk_image_new();
7745 t->tab_elems.eventbox = gtk_event_box_new();
7746 gtk_widget_set_name(t->tab_elems.eventbox, "compact_tab");
7747 #if GTK_CHECK_VERSION(3, 0, 0)
7748 t->tab_elems.box = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 0);
7750 gtk_label_set_ellipsize(GTK_LABEL(t->tab_elems.label),
7751 PANGO_ELLIPSIZE_END);
7752 gtk_widget_override_font(t->tab_elems.label, tabbar_font);
7753 gtk_widget_set_halign(t->tab_elems.label, GTK_ALIGN_START);
7754 gtk_widget_set_valign(t->tab_elems.label, GTK_ALIGN_START);
7755 #else
7756 t->tab_elems.box = gtk_hbox_new(FALSE, 0);
7758 gtk_label_set_width_chars(GTK_LABEL(t->tab_elems.label), 1);
7759 gtk_misc_set_alignment(GTK_MISC(t->tab_elems.label), 0.0, 0.0);
7760 gtk_misc_set_padding(GTK_MISC(t->tab_elems.label), 4.0, 4.0);
7761 gtk_widget_modify_font(GTK_WIDGET(t->tab_elems.label), tabbar_font);
7763 gdk_color_parse(XT_COLOR_CT_BACKGROUND, &color);
7764 gtk_widget_modify_bg(t->tab_elems.eventbox, GTK_STATE_NORMAL, &color);
7765 gdk_color_parse(XT_COLOR_CT_INACTIVE, &color);
7766 gtk_widget_modify_fg(t->tab_elems.label, GTK_STATE_NORMAL, &color);
7767 #endif
7769 gtk_box_pack_start(GTK_BOX(t->tab_elems.box), t->tab_elems.favicon, FALSE,
7770 FALSE, 0);
7771 gtk_box_pack_start(GTK_BOX(t->tab_elems.box), t->tab_elems.label, TRUE,
7772 TRUE, 0);
7773 gtk_container_add(GTK_CONTAINER(t->tab_elems.eventbox),
7774 t->tab_elems.box);
7776 gtk_box_pack_start(GTK_BOX(tab_bar_box), t->tab_elems.eventbox, TRUE,
7777 TRUE, 0);
7778 gtk_widget_show_all(t->tab_elems.eventbox);
7780 if (append_next == 0 || gtk_notebook_get_n_pages(notebook) == 0)
7781 append_tab(t);
7782 else {
7783 id = position >= 0 ? position :
7784 gtk_notebook_get_current_page(notebook) + 1;
7785 if (id > gtk_notebook_get_n_pages(notebook))
7786 append_tab(t);
7787 else {
7788 TAILQ_INSERT_TAIL(&tabs, t, entry);
7789 gtk_notebook_insert_page(notebook, t->vbox, b, id);
7790 gtk_box_reorder_child(GTK_BOX(tab_bar_box),
7791 t->tab_elems.eventbox, id);
7792 recalc_tabs();
7796 #if GTK_CHECK_VERSION(2, 20, 0)
7797 /* turn spinner off if we are a new tab without uri */
7798 if (!load) {
7799 gtk_spinner_stop(GTK_SPINNER(t->spinner));
7800 gtk_widget_hide(t->spinner);
7802 #endif
7803 /* make notebook tabs reorderable */
7804 gtk_notebook_set_tab_reorderable(notebook, t->vbox, TRUE);
7806 /* compact tabs clickable */
7807 g_signal_connect(G_OBJECT(t->tab_elems.eventbox),
7808 "button_press_event", G_CALLBACK(tab_clicked_cb), t);
7810 g_object_connect(G_OBJECT(t->cmd),
7811 "signal::button-release-event", G_CALLBACK(cmd_keyrelease_cb), t,
7812 "signal::key-press-event", G_CALLBACK(cmd_keypress_cb), t,
7813 "signal::key-release-event", G_CALLBACK(cmd_keyrelease_cb), t,
7814 "signal::focus-out-event", G_CALLBACK(cmd_focusout_cb), t,
7815 "signal::activate", G_CALLBACK(cmd_activate_cb), t,
7816 "signal::populate-popup", G_CALLBACK(cmd_popup_cb), t,
7817 "signal::hide", G_CALLBACK(cmd_hide_cb), t,
7818 (char *)NULL);
7820 /* reuse wv_button_cb to hide oops */
7821 g_object_connect(G_OBJECT(t->oops),
7822 "signal::button_press_event", G_CALLBACK(wv_button_cb), t,
7823 (char *)NULL);
7825 g_signal_connect(t->buffers,
7826 "row-activated", G_CALLBACK(row_activated_cb), t);
7827 g_object_connect(G_OBJECT(t->buffers),
7828 "signal::key-press-event", G_CALLBACK(wv_keypress_cb), t, (char *)NULL);
7830 g_object_connect(G_OBJECT(t->wv),
7831 "signal::key-press-event", G_CALLBACK(wv_keypress_cb), t,
7832 "signal::hovering-over-link", G_CALLBACK(webview_hover_cb), t,
7833 "signal::download-requested", G_CALLBACK(webview_download_cb), t,
7834 "signal::mime-type-policy-decision-requested", G_CALLBACK(webview_mimetype_cb), t,
7835 "signal::navigation-policy-decision-requested", G_CALLBACK(webview_npd_cb), t,
7836 "signal::new-window-policy-decision-requested", G_CALLBACK(webview_npd_cb), t,
7837 "signal::resource-request-starting", G_CALLBACK(webview_rrs_cb), t,
7838 "signal::create-web-view", G_CALLBACK(webview_cwv_cb), t,
7839 "signal::close-web-view", G_CALLBACK(webview_closewv_cb), t,
7840 "signal::event", G_CALLBACK(webview_event_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);
7850 t->progress_handle = g_signal_connect(t->wv,
7851 "notify::progress", G_CALLBACK(webview_progress_changed_cb), t);
7853 /* hijack the unused keys as if we were the browser */
7854 //g_object_connect(G_OBJECT(t->toolbar),
7855 // "signal-after::key-press-event", G_CALLBACK(wv_keypress_after_cb), t,
7856 // (char *)NULL);
7858 g_signal_connect(G_OBJECT(bb), "button_press_event",
7859 G_CALLBACK(tab_close_cb), t);
7861 /* setup history */
7862 t->bfl = webkit_web_view_get_back_forward_list(t->wv);
7863 /* restore the tab's history */
7864 if (u && u->history) {
7865 items = u->history;
7866 while (items) {
7867 item = items->data;
7868 webkit_web_back_forward_list_add_item(t->bfl, item);
7869 items = g_list_next(items);
7872 item = g_list_nth_data(u->history, u->back);
7873 if (item)
7874 webkit_web_view_go_to_back_forward_item(t->wv, item);
7876 g_list_free(items);
7877 g_list_free(u->history);
7878 } else
7879 webkit_web_back_forward_list_clear(t->bfl);
7881 /* check and show url and statusbar */
7882 url_set_visibility();
7883 statusbar_set_visibility();
7885 if (focus) {
7886 set_current_tab(t->tab_id);
7887 DNPRINTF(XT_D_TAB, "create_new_tab: going to tab: %d\n",
7888 t->tab_id);
7890 if (load) {
7891 gtk_entry_set_text(GTK_ENTRY(t->uri_entry), title);
7892 load_uri(t, title);
7893 } else {
7894 if (show_url == 1)
7895 gtk_widget_grab_focus(GTK_WIDGET(t->uri_entry));
7896 else
7897 focus_webview(t);
7899 } else if (load)
7900 load_uri(t, title);
7902 if (userstyle_global)
7903 apply_style(t);
7905 recolor_compact_tabs();
7906 setzoom_webkit(t, XT_ZOOM_NORMAL);
7907 return (t);
7910 void
7911 notebook_switchpage_cb(GtkNotebook *nb, GtkWidget *nbp, guint pn,
7912 gpointer *udata)
7914 struct tab *t;
7915 const gchar *uri;
7917 DNPRINTF(XT_D_TAB, "notebook_switchpage_cb: tab: %d\n", pn);
7919 if (gtk_notebook_get_current_page(notebook) == -1)
7920 recalc_tabs();
7922 TAILQ_FOREACH(t, &tabs, entry) {
7923 if (t->tab_id == pn) {
7924 DNPRINTF(XT_D_TAB, "notebook_switchpage_cb: going to "
7925 "%d\n", pn);
7927 uri = get_title(t, TRUE);
7928 gtk_window_set_title(GTK_WINDOW(main_window), uri);
7930 hide_cmd(t);
7931 hide_oops(t);
7932 hide_buffers(t);
7934 if (t->focus_wv) {
7935 /* can't use focus_webview here */
7936 gtk_widget_grab_focus(GTK_WIDGET(t->wv));
7938 update_statusbar_tabs(t);
7939 break;
7944 void
7945 notebook_pagereordered_cb(GtkNotebook *nb, GtkWidget *nbp, guint pn,
7946 gpointer *udata)
7948 struct tab *t = NULL, *tt;
7950 recalc_tabs();
7952 TAILQ_FOREACH(tt, &tabs, entry)
7953 if (tt->tab_id == pn) {
7954 t = tt;
7955 break;
7957 if (t == NULL)
7958 return;
7959 DNPRINTF(XT_D_TAB, "page_reordered_cb: tab: %d\n", t->tab_id);
7961 gtk_box_reorder_child(GTK_BOX(tab_bar_box), t->tab_elems.eventbox,
7962 t->tab_id);
7964 update_statusbar_tabs(t);
7967 void
7968 menuitem_response(struct tab *t)
7970 gtk_notebook_set_current_page(notebook, t->tab_id);
7974 destroy_menu(GtkWidget *w, GdkEventFocus *e, void *notused)
7976 gtk_widget_destroy(w);
7977 return (XT_CB_PASSTHROUGH);
7980 gboolean
7981 arrow_cb(GtkWidget *w, GdkEventButton *event, gpointer user_data)
7983 GtkWidget *menu, *menu_items;
7984 GdkEventButton *bevent;
7985 struct tab **stabs = NULL;
7986 int i, num_tabs;
7987 const gchar *uri;
7989 if (event->type == GDK_BUTTON_PRESS) {
7990 bevent = (GdkEventButton *) event;
7991 menu = gtk_menu_new();
7993 num_tabs = sort_tabs_by_page_num(&stabs);
7994 for (i = 0; i < num_tabs; ++i) {
7995 if (stabs[i] == NULL)
7996 continue;
7997 if ((uri = get_uri(stabs[i])) == NULL)
7998 /* XXX make sure there is something to print */
7999 /* XXX add gui pages in here to look purdy */
8000 uri = "(untitled)";
8001 menu_items = gtk_menu_item_new_with_label(uri);
8002 gtk_menu_shell_append(GTK_MENU_SHELL(menu), menu_items);
8003 gtk_widget_show(menu_items);
8005 g_signal_connect_swapped((menu_items),
8006 "activate", G_CALLBACK(menuitem_response),
8007 (gpointer)stabs[i]);
8009 g_free(stabs);
8011 gtk_menu_popup(GTK_MENU(menu), NULL, NULL, NULL, NULL,
8012 bevent->button, bevent->time);
8014 g_object_connect(G_OBJECT(menu),
8015 "signal::hide", G_CALLBACK(destroy_menu), NULL,
8016 (char *)NULL);
8018 return (TRUE /* eat event */);
8021 return (FALSE /* propagate */);
8025 icon_size_map(int iconsz)
8027 if (iconsz <= GTK_ICON_SIZE_INVALID ||
8028 iconsz > GTK_ICON_SIZE_DIALOG)
8029 return (GTK_ICON_SIZE_SMALL_TOOLBAR);
8031 return (iconsz);
8034 GtkWidget *
8035 create_button(char *name, char *stockid, int size)
8037 GtkWidget *button, *image;
8038 int gtk_icon_size;
8039 #if !GTK_CHECK_VERSION(3, 0, 0)
8040 gchar *newstyle;
8041 #endif
8043 #if !GTK_CHECK_VERSION(3, 0, 0)
8044 newstyle = g_strdup_printf(
8045 "style \"%s-style\"\n"
8046 "{\n"
8047 " GtkWidget::focus-padding = 0\n"
8048 " GtkWidget::focus-line-width = 0\n"
8049 " xthickness = 0\n"
8050 " ythickness = 0\n"
8051 "}\n"
8052 "widget \"*.%s\" style \"%s-style\"", name, name, name);
8053 gtk_rc_parse_string(newstyle);
8054 g_free(newstyle);
8055 #endif
8056 button = gtk_button_new();
8057 gtk_widget_set_can_focus(button, FALSE);
8058 gtk_button_set_focus_on_click(GTK_BUTTON(button), FALSE);
8059 gtk_icon_size = icon_size_map(size ? size : icon_size);
8061 image = gtk_image_new_from_stock(stockid, gtk_icon_size);
8062 gtk_container_set_border_width(GTK_CONTAINER(button), 1);
8063 gtk_container_add(GTK_CONTAINER(button), GTK_WIDGET(image));
8064 gtk_widget_set_name(button, name);
8065 gtk_button_set_relief(GTK_BUTTON(button), GTK_RELIEF_NONE);
8067 return (button);
8070 void
8071 button_set_stockid(GtkWidget *button, char *stockid)
8073 GtkWidget *image;
8075 image = gtk_image_new_from_stock(stockid, icon_size_map(icon_size));
8076 gtk_button_set_image(GTK_BUTTON(button), image);
8079 void
8080 create_canvas(void)
8082 GtkWidget *vbox;
8083 GList *l = NULL;
8084 GdkPixbuf *pb;
8085 char file[PATH_MAX];
8086 int i;
8087 #if !GTK_CHECK_VERSION(3, 0, 0)
8088 GdkColor color;
8089 #endif
8091 #if GTK_CHECK_VERSION(3, 0, 0)
8092 vbox = gtk_box_new(GTK_ORIENTATION_VERTICAL, 0);
8093 #else
8094 vbox = gtk_vbox_new(FALSE, 0);
8095 #endif
8096 gtk_box_set_spacing(GTK_BOX(vbox), 0);
8097 gtk_widget_set_can_focus(vbox, FALSE);
8098 notebook = GTK_NOTEBOOK(gtk_notebook_new());
8099 #if !GTK_CHECK_VERSION(3, 0, 0)
8100 /* XXX seems to be needed with gtk+2 */
8101 g_object_set(G_OBJECT(notebook), "tab-border", 0, NULL);
8102 #endif
8103 gtk_notebook_set_scrollable(notebook, TRUE);
8104 gtk_notebook_set_show_border(notebook, FALSE);
8105 gtk_widget_set_can_focus(GTK_WIDGET(notebook), FALSE);
8107 abtn = gtk_button_new();
8108 gtk_widget_set_can_focus(abtn, FALSE);
8109 arrow = gtk_arrow_new(GTK_ARROW_DOWN, GTK_SHADOW_NONE);
8110 gtk_widget_set_name(abtn, "Arrow");
8111 gtk_container_add(GTK_CONTAINER(abtn), arrow);
8112 gtk_widget_set_size_request(abtn, -1, 20);
8114 #if GTK_CHECK_VERSION(2, 20, 0)
8115 gtk_notebook_set_action_widget(notebook, abtn, GTK_PACK_END);
8116 #endif
8117 /* compact tab bar */
8118 tab_bar = gtk_event_box_new();
8119 #if GTK_CHECK_VERSION(3, 0, 0)
8120 gtk_widget_set_name(tab_bar, "tab_bar");
8121 tab_bar_box = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 0);
8122 #else
8123 gdk_color_parse(XT_COLOR_CT_SEPARATOR, &color);
8124 gtk_widget_modify_bg(tab_bar, GTK_STATE_NORMAL, &color);
8125 tab_bar_box = gtk_hbox_new(TRUE, 0);
8126 #endif
8127 gtk_container_add(GTK_CONTAINER(tab_bar), tab_bar_box);
8128 gtk_box_set_homogeneous(GTK_BOX(tab_bar_box), TRUE);
8129 gtk_box_set_spacing(GTK_BOX(tab_bar_box), 2);
8131 gtk_box_pack_start(GTK_BOX(vbox), tab_bar, FALSE, FALSE, 0);
8132 gtk_box_pack_start(GTK_BOX(vbox), GTK_WIDGET(notebook), TRUE, TRUE, 0);
8134 g_object_connect(G_OBJECT(notebook),
8135 "signal::switch-page", G_CALLBACK(notebook_switchpage_cb), NULL,
8136 (char *)NULL);
8137 g_object_connect(G_OBJECT(notebook),
8138 "signal::page-reordered", G_CALLBACK(notebook_pagereordered_cb),
8139 NULL, (char *)NULL);
8140 g_signal_connect(G_OBJECT(abtn), "button_press_event",
8141 G_CALLBACK(arrow_cb), NULL);
8143 main_window = create_window("xombrero");
8144 gtk_container_add(GTK_CONTAINER(main_window), vbox);
8145 g_signal_connect(G_OBJECT(main_window), "delete_event",
8146 G_CALLBACK(gtk_main_quit), NULL);
8147 #if GTK_CHECK_VERSION(3, 0, 0)
8148 gtk_window_set_has_resize_grip(GTK_WINDOW(main_window), FALSE);
8149 #endif
8151 /* icons */
8152 for (i = 0; i < LENGTH(icons); i++) {
8153 snprintf(file, sizeof file, "%s" PS "%s", resource_dir, icons[i]);
8154 pb = gdk_pixbuf_new_from_file(file, NULL);
8155 l = g_list_append(l, pb);
8157 gtk_window_set_default_icon_list(l);
8159 gtk_widget_show_all(abtn);
8160 gtk_widget_show_all(main_window);
8161 notebook_tab_set_visibility();
8164 #ifndef XT_SOCKET_DISABLE
8166 send_cmd_to_socket(char *cmd)
8168 int s, len, rv = 1;
8169 struct sockaddr_un sa;
8171 if ((s = socket(AF_UNIX, SOCK_STREAM, 0)) == -1) {
8172 warnx("%s: socket", __func__);
8173 return (rv);
8176 sa.sun_family = AF_UNIX;
8177 snprintf(sa.sun_path, sizeof(sa.sun_path), "%s" PS "%s",
8178 work_dir, XT_SOCKET_FILE);
8179 len = SUN_LEN(&sa);
8181 if (connect(s, (struct sockaddr *)&sa, len) == -1) {
8182 warnx("%s: connect", __func__);
8183 goto done;
8186 if (send(s, cmd, strlen(cmd) + 1, 0) == -1) {
8187 warnx("%s: send", __func__);
8188 goto done;
8191 rv = 0;
8192 done:
8193 close(s);
8194 return (rv);
8197 gboolean
8198 socket_watcher(GIOChannel *source, GIOCondition condition, gpointer data)
8200 int s, n;
8201 char str[XT_MAX_URL_LENGTH];
8202 socklen_t t = sizeof(struct sockaddr_un);
8203 struct sockaddr_un sa;
8204 struct passwd *p;
8205 uid_t uid;
8206 gid_t gid;
8207 struct tab *tt;
8208 gint fd = g_io_channel_unix_get_fd(source);
8210 if ((s = accept(fd, (struct sockaddr *)&sa, &t)) == -1) {
8211 warn("accept");
8212 return (FALSE);
8215 if (getpeereid(s, &uid, &gid) == -1) {
8216 warn("getpeereid");
8217 return (FALSE);
8219 if (uid != getuid() || gid != getgid()) {
8220 warnx("unauthorized user");
8221 return (FALSE);
8224 p = getpwuid(uid);
8225 if (p == NULL) {
8226 warnx("not a valid user");
8227 return (FALSE);
8230 n = recv(s, str, sizeof(str), 0);
8231 if (n <= 0)
8232 return (TRUE);
8234 tt = get_current_tab();
8235 cmd_execute(tt, str);
8236 return (TRUE);
8240 is_running(void)
8242 int s, len, rv = 1;
8243 struct sockaddr_un sa;
8245 if ((s = socket(AF_UNIX, SOCK_STREAM, 0)) == -1) {
8246 warn("is_running: socket");
8247 return (-1);
8250 sa.sun_family = AF_UNIX;
8251 snprintf(sa.sun_path, sizeof(sa.sun_path), "%s" PS "%s",
8252 work_dir, XT_SOCKET_FILE);
8253 len = SUN_LEN(&sa);
8255 /* connect to see if there is a listener */
8256 if (connect(s, (struct sockaddr *)&sa, len) == -1)
8257 rv = 0; /* not running */
8258 else
8259 rv = 1; /* already running */
8261 close(s);
8263 return (rv);
8267 build_socket(void)
8269 int s, len;
8270 struct sockaddr_un sa;
8272 if ((s = socket(AF_UNIX, SOCK_STREAM, 0)) == -1) {
8273 warn("build_socket: socket");
8274 return (-1);
8277 sa.sun_family = AF_UNIX;
8278 snprintf(sa.sun_path, sizeof(sa.sun_path), "%s" PS "%s",
8279 work_dir, XT_SOCKET_FILE);
8280 len = SUN_LEN(&sa);
8282 /* connect to see if there is a listener */
8283 if (connect(s, (struct sockaddr *)&sa, len) == -1) {
8284 /* no listener so we will */
8285 unlink(sa.sun_path);
8287 if (bind(s, (struct sockaddr *)&sa, len) == -1) {
8288 warn("build_socket: bind");
8289 goto done;
8292 if (listen(s, 1) == -1) {
8293 warn("build_socket: listen");
8294 goto done;
8297 return (s);
8300 done:
8301 close(s);
8302 return (-1);
8304 #endif
8306 void
8307 xxx_dir(char *dir)
8309 struct stat sb;
8311 if (stat(dir, &sb)) {
8312 #if defined __MINGW32__
8313 if (mkdir(dir) == -1)
8314 #else
8315 if (mkdir(dir, S_IRWXU) == -1)
8316 #endif
8317 err(1, "mkdir %s", dir);
8318 if (stat(dir, &sb))
8319 err(1, "stat %s", dir);
8321 if (S_ISDIR(sb.st_mode) == 0)
8322 errx(1, "%s not a dir", dir);
8323 #if !defined __MINGW32__
8324 if (((sb.st_mode & (S_IRWXU | S_IRWXG | S_IRWXO))) != S_IRWXU) {
8325 warnx("fixing invalid permissions on %s", dir);
8326 if (chmod(dir, S_IRWXU) == -1)
8327 err(1, "chmod %s", dir);
8329 #endif
8332 void
8333 usage(void)
8335 fprintf(stderr,
8336 "%s [-nSTVt][-f file][-s session] url ...\n", __progname);
8337 exit(0);
8340 GStaticRecMutex my_gdk_mtx = G_STATIC_REC_MUTEX_INIT;
8341 volatile int mtx_depth;
8342 int mtx_complain;
8345 * The linux flash plugin violates the gdk locking mechanism.
8346 * Work around the issue by using a recursive mutex with some match applied
8347 * to see if we hit a buggy condition.
8349 * The following code is painful so just don't read it. It really doesn't
8350 * make much sense but seems to work.
8352 void
8353 mtx_lock(void)
8355 #ifdef XT_DEBUG
8356 char *s = NULL;
8357 #endif
8359 g_static_rec_mutex_lock(&my_gdk_mtx);
8360 if (my_gdk_mtx.depth <= 0) {
8361 #ifdef XT_DEBUG
8362 s = "lock <= 0";
8363 #endif
8364 g_static_rec_mutex_lock(&my_gdk_mtx);
8365 goto complain;
8366 } else if (my_gdk_mtx.depth != 1) {
8367 #ifdef XT_DEBUG
8368 s = "lock != 1";
8369 #endif
8370 do {
8371 g_static_rec_mutex_unlock(&my_gdk_mtx);
8372 } while (my_gdk_mtx.depth > 1);
8373 goto complain;
8375 return;
8377 complain:
8378 if (mtx_complain == 0) {
8379 DNPRINTF(XT_D_MTX, "buggy mutex implementation detected(%s), "
8380 "work around implemented", s);
8381 mtx_complain = 1;
8385 void
8386 mtx_unlock(void)
8388 #ifdef XT_DEBUG
8389 char *s = NULL;
8390 #endif
8392 if (my_gdk_mtx.depth <= 0) {
8393 #ifdef XT_DEBUG
8394 s = "unlock <= 0";
8395 #endif
8396 goto complain;
8397 } else if (my_gdk_mtx.depth != 1) {
8398 #ifdef XT_DEBUG
8399 s = "unlock != 1";
8400 #endif
8401 g_static_rec_mutex_unlock_full(&my_gdk_mtx);
8402 goto complain;
8404 g_static_rec_mutex_unlock(&my_gdk_mtx);
8405 return;
8407 complain:
8408 if (mtx_complain == 0) {
8409 DNPRINTF(XT_D_MTX, "buggy mutex implementation detected(%s), "
8410 "work around implemented", s);
8411 mtx_complain = 1;
8415 #if GTK_CHECK_VERSION(3, 0, 0)
8416 void
8417 setup_css(void)
8419 GtkCssProvider *provider;
8420 GdkDisplay *display;
8421 GdkScreen *screen;
8422 GFile *file;
8423 char path[PATH_MAX];
8424 #if defined __MINGW32__
8425 GtkCssProvider *windows_hacks;
8426 #endif
8428 provider = gtk_css_provider_new();
8429 display = gdk_display_get_default();
8430 screen = gdk_display_get_default_screen(display);
8431 snprintf(path, sizeof path, "%s" PS "%s", resource_dir, XT_CSS_FILE);
8432 file = g_file_new_for_path(path);
8433 gtk_css_provider_load_from_file(provider, file, NULL);
8434 gtk_style_context_add_provider_for_screen(screen,
8435 GTK_STYLE_PROVIDER(provider),
8436 GTK_STYLE_PROVIDER_PRIORITY_APPLICATION);
8437 #if defined __MINGW32__
8438 windows_hacks = gtk_css_provider_new();
8439 gtk_css_provider_load_from_data(windows_hacks,
8440 ".notebook tab {\n"
8441 " border-width: 0px;\n"
8442 "}", -1, NULL);
8443 gtk_style_context_add_provider_for_screen(screen,
8444 GTK_STYLE_PROVIDER(windows_hacks),
8445 GTK_STYLE_PROVIDER_PRIORITY_APPLICATION);
8446 #endif
8447 g_object_unref(file);
8449 #endif
8451 void
8452 welcome(void)
8454 startpage_add("<b>Welcome to xombrero %s!</b><p>", version);
8455 startpage_add("Details at "
8456 "<a href=https://opensource.conformal.com/wiki/xombrero>xombrero "
8457 "wiki page</a><p>");
8461 main(int argc, char **argv)
8463 struct stat sb;
8464 int c, optn = 0, opte = 0, focus = 1;
8465 char conf[PATH_MAX] = { '\0' };
8466 char file[PATH_MAX];
8467 char sodversion[32];
8468 char *env_proxy = NULL;
8469 char *path;
8470 FILE *f = NULL;
8471 struct karg a;
8473 start_argv = (char * const *)argv;
8475 if (os_init)
8476 os_init();
8478 /* prepare gtk */
8479 #ifdef USE_THREADS
8480 #if !defined __MINGW32__
8481 /* http://web.archiveorange.com/archive/v/UsPjxkX5PsaXBIoOjqxf */
8482 XInitThreads();
8483 #endif
8484 /* http://developer.gnome.org/gdk/stable/gdk-Threads.html */
8485 g_thread_init(NULL);
8486 gdk_threads_set_lock_functions(mtx_lock, mtx_unlock);
8487 gdk_threads_init();
8488 gdk_threads_enter();
8490 /* http://www.gnupg.org/documentation/manuals/gcrypt/Multi_002dThreading.html */
8491 gcry_control (GCRYCTL_SET_THREAD_CBS, &gcry_threads_pthread);
8492 #endif
8493 gtk_init(&argc, &argv);
8495 gnutls_global_init();
8497 strlcpy(named_session, XT_SAVED_TABS_FILE, sizeof named_session);
8499 RB_INIT(&hl);
8500 RB_INIT(&js_wl);
8501 RB_INIT(&pl_wl);
8502 RB_INIT(&force_https);
8503 RB_INIT(&downloads);
8504 RB_INIT(&st_tree);
8505 RB_INIT(&svl);
8506 RB_INIT(&svil);
8507 RB_INIT(&ua_list);
8509 TAILQ_INIT(&sessions);
8510 TAILQ_INIT(&tabs);
8511 TAILQ_INIT(&mtl);
8512 TAILQ_INIT(&aliases);
8513 TAILQ_INIT(&undos);
8514 TAILQ_INIT(&kbl);
8515 TAILQ_INIT(&spl);
8516 TAILQ_INIT(&chl);
8517 TAILQ_INIT(&shl);
8518 TAILQ_INIT(&cul);
8519 TAILQ_INIT(&srl);
8521 #ifndef XT_RESOURCE_LIMITS_DISABLE
8522 struct rlimit rlp;
8523 char *cmd = NULL;
8524 int s;
8525 GIOChannel *channel;
8527 /* fiddle with ulimits */
8528 if (getrlimit(RLIMIT_NOFILE, &rlp) == -1)
8529 warn("getrlimit");
8530 else {
8531 /* just use them all */
8532 rlp.rlim_cur = rlp.rlim_max;
8533 if (setrlimit(RLIMIT_NOFILE, &rlp) == -1)
8534 warn("setrlimit");
8535 if (getrlimit(RLIMIT_NOFILE, &rlp) == -1)
8536 warn("getrlimit");
8537 else if (rlp.rlim_cur < 1024)
8538 startpage_add("%s requires at least 1024 "
8539 "(2048 recommended) file " "descriptors, "
8540 "currently it has up to %d available",
8541 __progname, rlp.rlim_cur);
8543 #endif
8545 while ((c = getopt(argc, argv, "STVf:s:tne")) != -1) {
8546 switch (c) {
8547 case 'S':
8548 show_url = 0;
8549 break;
8550 case 'T':
8551 show_tabs = 0;
8552 break;
8553 case 'V':
8554 #ifdef XOMBRERO_BUILDSTR
8555 errx(0 , "Version: %s Build: %s",
8556 version, XOMBRERO_BUILDSTR);
8557 #else
8558 errx(0 , "Version: %s", version);
8559 #endif
8560 break;
8561 case 'f':
8562 strlcpy(conf, optarg, sizeof(conf));
8563 break;
8564 case 's':
8565 strlcpy(named_session, optarg, sizeof(named_session));
8566 break;
8567 case 't':
8568 tabless = 1;
8569 break;
8570 case 'n':
8571 optn = 1;
8572 break;
8573 case 'e':
8574 opte = 1;
8575 break;
8576 default:
8577 usage();
8578 /* NOTREACHED */
8581 argc -= optind;
8582 argv += optind;
8584 init_keybindings();
8586 pwd = getpwuid(getuid());
8587 if (pwd == NULL)
8588 errx(1, "invalid user %d", getuid());
8590 /* set download dir */
8591 if (strlen(download_dir) == 0)
8592 strlcpy(download_dir, pwd->pw_dir, sizeof download_dir);
8594 /* compile buffer command regexes */
8595 buffercmd_init();
8597 /* set default dynamic string settings */
8598 home = g_strdup(XT_DS_HOME);
8599 search_string = g_strdup(XT_DS_SEARCH_STRING);
8600 strlcpy(runtime_settings, "runtime", sizeof runtime_settings);
8601 cmd_font_name = g_strdup(XT_DS_CMD_FONT_NAME);
8602 oops_font_name = g_strdup(XT_DS_OOPS_FONT_NAME);
8603 statusbar_font_name = g_strdup(XT_DS_STATUSBAR_FONT_NAME);
8604 tabbar_font_name = g_strdup(XT_DS_TABBAR_FONT_NAME);
8605 statusbar_elems = g_strdup("BP");
8606 spell_check_languages = g_strdup(XT_DS_SPELL_CHECK_LANGUAGES);
8607 encoding = g_strdup(XT_DS_ENCODING);
8608 spell_check_languages = g_strdup(XT_DS_SPELL_CHECK_LANGUAGES);
8609 path = g_strdup_printf("%s" PS "style.css", resource_dir);
8610 userstyle = g_filename_to_uri(path, NULL, NULL);
8611 g_free(path);
8612 stylesheet = g_strdup(userstyle);
8614 /* set statically allocated (struct special) settings */
8615 if (strlen(default_script) == 0)
8616 expand_tilde(default_script, sizeof default_script,
8617 XT_DS_DEFAULT_SCRIPT);
8618 if (strlen(ssl_ca_file) == 0)
8619 expand_tilde(ssl_ca_file, sizeof ssl_ca_file,
8620 XT_DS_SSL_CA_FILE);
8622 /* soup session */
8623 session = webkit_get_default_session();
8625 /* read config file */
8626 if (strlen(conf) == 0)
8627 snprintf(conf, sizeof conf, "%s" PS ".%s",
8628 pwd->pw_dir, XT_CONF_FILE);
8629 config_parse(conf, 0);
8631 /* read preloaded HSTS list */
8632 if (preload_strict_transport) {
8633 snprintf(conf, sizeof conf, "%s" PS "%s",
8634 resource_dir, XT_HSTS_PRELOAD_FILE);
8635 config_parse(conf, 0);
8638 /* init fonts */
8639 cmd_font = pango_font_description_from_string(cmd_font_name);
8640 oops_font = pango_font_description_from_string(oops_font_name);
8641 statusbar_font = pango_font_description_from_string(statusbar_font_name);
8642 tabbar_font = pango_font_description_from_string(tabbar_font_name);
8644 /* working directory */
8645 if (strlen(work_dir) == 0)
8646 snprintf(work_dir, sizeof work_dir, "%s" PS "%s",
8647 pwd->pw_dir, XT_DIR);
8648 xxx_dir(work_dir);
8650 /* icon cache dir */
8651 snprintf(cache_dir, sizeof cache_dir, "%s" PS "%s", work_dir, XT_CACHE_DIR);
8652 xxx_dir(cache_dir);
8654 /* certs dir */
8655 snprintf(certs_dir, sizeof certs_dir, "%s" PS "%s", work_dir, XT_CERT_DIR);
8656 xxx_dir(certs_dir);
8658 /* cert changes dir */
8659 snprintf(certs_cache_dir, sizeof certs_cache_dir, "%s" PS "%s",
8660 work_dir, XT_CERT_CACHE_DIR);
8661 xxx_dir(certs_cache_dir);
8663 /* sessions dir */
8664 snprintf(sessions_dir, sizeof sessions_dir, "%s" PS "%s",
8665 work_dir, XT_SESSIONS_DIR);
8666 xxx_dir(sessions_dir);
8668 /* js dir */
8669 snprintf(js_dir, sizeof js_dir, "%s" PS "%s", work_dir, XT_JS_DIR);
8670 xxx_dir(js_dir);
8672 /* temp dir */
8673 snprintf(temp_dir, sizeof temp_dir, "%s" PS "%s", work_dir, XT_TEMP_DIR);
8674 xxx_dir(temp_dir);
8676 /* runtime settings that can override config file */
8677 if (runtime_settings[0] != '\0')
8678 config_parse(runtime_settings, 1);
8680 /* download dir */
8681 if (!strcmp(download_dir, pwd->pw_dir))
8682 strlcat(download_dir, PS "downloads", sizeof download_dir);
8683 xxx_dir(download_dir);
8685 /* first start file */
8686 snprintf(file, sizeof file, "%s" PS "%s", work_dir, XT_SOD_FILE);
8687 if (stat(file, &sb)) {
8688 warnx("start of day file doesn't exist, creating it");
8689 if ((f = fopen(file, "w")) == NULL)
8690 err(1, "startofday");
8691 if (fputs(version, f) == EOF)
8692 err(1, "fputs");
8693 fclose(f);
8695 /* welcome user */
8696 welcome();
8697 } else {
8698 if ((f = fopen(file, "r+")) == NULL)
8699 err(1, "startofday");
8700 if (fgets(sodversion, sizeof sodversion, f) == NULL)
8701 err(1, "fgets");
8702 sodversion[strcspn(sodversion, "\n")] = '\0';
8703 if (strcmp(version, sodversion)) {
8704 if ((f = freopen(file, "w", f)) == NULL)
8705 err(1, "startofday");
8706 if (fputs(version, f) == EOF)
8707 err(1, "fputs");
8709 /* upgrade, say something smart */
8710 welcome();
8712 fclose(f);
8715 /* favorites file */
8716 snprintf(file, sizeof file, "%s" PS "%s", work_dir, XT_FAVS_FILE);
8717 if (stat(file, &sb)) {
8718 warnx("favorites file doesn't exist, creating it");
8719 if ((f = fopen(file, "w")) == NULL)
8720 err(1, "favorites");
8721 fclose(f);
8724 /* quickmarks file */
8725 snprintf(file, sizeof file, "%s" PS "%s", work_dir, XT_QMARKS_FILE);
8726 if (stat(file, &sb)) {
8727 warnx("quickmarks file doesn't exist, creating it");
8728 if ((f = fopen(file, "w")) == NULL)
8729 err(1, "quickmarks");
8730 fclose(f);
8733 /* search history */
8734 if (history_autosave) {
8735 snprintf(search_file, sizeof search_file, "%s" PS "%s",
8736 work_dir, XT_SEARCH_FILE);
8737 if (stat(search_file, &sb)) {
8738 warnx("search history file doesn't exist, creating it");
8739 if ((f = fopen(search_file, "w")) == NULL)
8740 err(1, "search_history");
8741 fclose(f);
8743 history_read(&shl, search_file, &search_history_count);
8746 /* command history */
8747 if (history_autosave) {
8748 snprintf(command_file, sizeof command_file, "%s" PS "%s",
8749 work_dir, XT_COMMAND_FILE);
8750 if (stat(command_file, &sb)) {
8751 warnx("command history file doesn't exist, creating it");
8752 if ((f = fopen(command_file, "w")) == NULL)
8753 err(1, "command_history");
8754 fclose(f);
8756 history_read(&chl, command_file, &cmd_history_count);
8759 /* cookies */
8760 setup_cookies();
8762 /* guess_search regex */
8763 if (url_regex == NULL)
8764 url_regex = g_strdup(XT_URL_REGEX);
8765 if (url_regex)
8766 if (regcomp(&url_re, url_regex, REG_EXTENDED | REG_NOSUB))
8767 startpage_add("invalid url regex %s", url_regex);
8769 /* proxy */
8770 env_proxy = getenv("http_proxy");
8771 if (env_proxy)
8772 setup_proxy(env_proxy);
8773 else {
8774 env_proxy = getenv("HTTP_PROXY");
8775 if (env_proxy)
8776 setup_proxy(env_proxy);
8777 else
8778 setup_proxy(http_proxy);
8781 /* the user can optionally have the proxy disabled at startup */
8782 if ((http_proxy_starts_enabled == 0) && (http_proxy != NULL)) {
8783 http_proxy_save = g_strdup(http_proxy);
8784 setup_proxy(NULL);
8787 #ifndef XT_SOCKET_DISABLE
8788 if (opte) {
8789 send_cmd_to_socket(argv[0]);
8790 exit(0);
8792 #else
8793 opte = opte; /* shut mingw up */
8794 #endif
8795 /* set some connection parameters */
8796 g_object_set(session, "max-conns", max_connections, (char *)NULL);
8797 g_object_set(session, "max-conns-per-host", max_host_connections,
8798 (char *)NULL);
8799 g_object_set(session, SOUP_SESSION_SSL_STRICT, ssl_strict_certs,
8800 (char *)NULL);
8802 g_signal_connect(session, "request-queued", G_CALLBACK(session_rq_cb),
8803 NULL);
8805 #ifndef XT_SOCKET_DISABLE
8806 /* see if there is already a xombrero running */
8807 if (single_instance && is_running()) {
8808 optn = 1;
8809 warnx("already running");
8812 if (optn) {
8813 while (argc) {
8814 cmd = g_strdup_printf("%s %s", "tabnew", argv[0]);
8815 send_cmd_to_socket(cmd);
8816 if (cmd)
8817 g_free(cmd);
8819 argc--;
8820 argv++;
8822 exit(0);
8824 #else
8825 optn = optn; /* shut mingw up */
8826 #endif
8827 /* tld list */
8828 tld_tree_init();
8830 if (enable_strict_transport)
8831 strict_transport_init();
8833 /* uri completion */
8834 completion_model = gtk_list_store_new(1, G_TYPE_STRING);
8836 /* buffers */
8837 buffers_store = gtk_list_store_new
8838 (NUM_COLS, G_TYPE_UINT, GDK_TYPE_PIXBUF, G_TYPE_STRING);
8840 qmarks_load();
8842 /* go graphical */
8843 create_canvas();
8844 notebook_tab_set_visibility();
8846 if (save_global_history)
8847 restore_global_history();
8849 /* restore session list */
8850 restore_sessions_list();
8852 if (!strcmp(named_session, XT_SAVED_TABS_FILE))
8853 restore_saved_tabs();
8854 else {
8855 a.s = named_session;
8856 a.i = XT_SES_DONOTHING;
8857 open_tabs(NULL, &a);
8860 /* see if we have an exception */
8861 if (!TAILQ_EMPTY(&spl)) {
8862 create_new_tab("about:startpage", NULL, focus, -1);
8863 focus = 0;
8866 while (argc) {
8867 create_new_tab(argv[0], NULL, focus, -1);
8868 focus = 0;
8870 argc--;
8871 argv++;
8874 if (TAILQ_EMPTY(&tabs))
8875 create_new_tab(home, NULL, 1, -1);
8876 #ifndef XT_SOCKET_DISABLE
8877 if (enable_socket)
8878 if ((s = build_socket()) != -1) {
8879 channel = g_io_channel_unix_new(s);
8880 g_io_add_watch(channel, G_IO_IN, socket_watcher, NULL);
8882 #endif
8884 #if GTK_CHECK_VERSION(3, 0, 0)
8885 setup_css();
8886 #endif
8888 gtk_main();
8890 #ifdef USE_THREADS
8891 GDK_FLUSH();
8892 gdk_threads_leave();
8893 g_static_rec_mutex_unlock_full(&my_gdk_mtx); /* just in case */
8894 #endif
8896 gnutls_global_deinit();
8898 if (url_regex)
8899 regfree(&url_re);
8901 return (0);