/* X-Chat * Copyright (C) 1998 Peter Zelezny. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA */ #include #include #include #include #include #include #include #include #ifdef WIN32 #include #else #include #include #endif #include "hexchat.h" #include #include "cfgfiles.h" #include "chanopt.h" #include "plugin.h" #include "fe.h" #include "server.h" #include "util.h" #include "outbound.h" #include "hexchatc.h" #include "text.h" #ifdef WIN32 #include #endif struct pevt_stage1 { int len; char *data; struct pevt_stage1 *next; }; static void mkdir_p (char *dir); static char *log_create_filename (char *channame); static char * scrollback_get_filename (session *sess, char *buf, int max) { char *net, *chan; net = server_get_network (sess->server, FALSE); if (!net) return NULL; snprintf (buf, max, "%s/scrollback/%s/%s.txt", get_xdir_fs (), net, ""); mkdir_p (buf); chan = log_create_filename (sess->channel); snprintf (buf, max, "%s/scrollback/%s/%s.txt", get_xdir_fs (), net, chan); free (chan); return buf; } #if 0 static void scrollback_unlock (session *sess) { char buf[1024]; if (scrollback_get_filename (sess, buf, sizeof (buf) - 6) == NULL) return; strcat (buf, ".lock"); unlink (buf); } static gboolean scrollback_lock (session *sess) { char buf[1024]; int fh; if (scrollback_get_filename (sess, buf, sizeof (buf) - 6) == NULL) return FALSE; strcat (buf, ".lock"); if (access (buf, F_OK) == 0) return FALSE; /* can't get lock */ fh = open (buf, O_CREAT | O_TRUNC | O_APPEND | O_WRONLY, 0644); if (fh == -1) return FALSE; return TRUE; } #endif void scrollback_close (session *sess) { if (sess->scrollfd != -1) { close (sess->scrollfd); sess->scrollfd = -1; } } static char * file_to_buffer (char *file, int *len) { int fh; char *buf; struct stat st; fh = open (file, O_RDONLY | OFLAGS); if (fh == -1) return NULL; fstat (fh, &st); buf = malloc (st.st_size); if (!buf) { close (fh); return NULL; } if (read (fh, buf, st.st_size) != st.st_size) { free (buf); close (fh); return NULL; } *len = st.st_size; close (fh); return buf; } /* shrink the file to roughly prefs.hex_text_max_lines */ static void scrollback_shrink (session *sess) { char file[1024]; char *buf; int fh; int lines; int line; int len; char *p; scrollback_close (sess); sess->scrollwritten = 0; lines = 0; if (scrollback_get_filename (sess, file, sizeof (file)) == NULL) return; buf = file_to_buffer (file, &len); if (!buf) return; /* count all lines */ p = buf; while (p != buf + len) { if (*p == '\n') lines++; p++; } fh = open (file, O_CREAT | O_TRUNC | O_APPEND | O_WRONLY, 0644); if (fh == -1) { free (buf); return; } line = 0; p = buf; while (p != buf + len) { if (*p == '\n') { line++; if (line >= lines - prefs.hex_text_max_lines && p + 1 != buf + len) { p++; write (fh, p, len - (p - buf)); break; } } p++; } close (fh); free (buf); } static void scrollback_save (session *sess, char *text) { char buf[512 * 4]; time_t stamp; int len; if (sess->type == SESS_SERVER) return; if (sess->text_scrollback == SET_DEFAULT) { if (!prefs.hex_text_replay) return; } else { if (sess->text_scrollback != SET_ON) return; } if (sess->scrollfd == -1) { if (scrollback_get_filename (sess, buf, sizeof (buf)) == NULL) return; sess->scrollfd = open (buf, O_CREAT | O_APPEND | O_WRONLY, 0644); if (sess->scrollfd == -1) return; } stamp = time (0); if (sizeof (stamp) == 4) /* gcc will optimize one of these out */ write (sess->scrollfd, buf, snprintf (buf, sizeof (buf), "T %d ", (int)stamp)); else write (sess->scrollfd, buf, snprintf (buf, sizeof (buf), "T %"G_GINT64_FORMAT" ", (gint64)stamp)); len = strlen (text); write (sess->scrollfd, text, len); if (len && text[len - 1] != '\n') write (sess->scrollfd, "\n", 1); sess->scrollwritten++; if ((sess->scrollwritten * 2 > prefs.hex_text_max_lines && prefs.hex_text_max_lines > 0) || sess->scrollwritten > 32000) scrollback_shrink (sess); } void scrollback_load (session *sess) { int fh; char buf[512 * 4]; char *text; time_t stamp; int lines; #ifdef WIN32 #if 0 char *cleaned_text; int cleaned_len; #endif #else char *map, *end_map; struct stat statbuf; const char *begin, *eol; #endif if (sess->text_scrollback == SET_DEFAULT) { if (!prefs.hex_text_replay) return; } else { if (sess->text_scrollback != SET_ON) return; } if (scrollback_get_filename (sess, buf, sizeof (buf)) == NULL) return; fh = open (buf, O_RDONLY | OFLAGS); if (fh == -1) return; #ifndef WIN32 if (fstat (fh, &statbuf) < 0) return; map = mmap (NULL, statbuf.st_size, PROT_READ, MAP_PRIVATE, fh, 0); if (map == MAP_FAILED) return; end_map = map + statbuf.st_size; lines = 0; begin = map; while (begin < end_map) { int n_bytes; eol = memchr (begin, '\n', end_map - begin); if (!eol) eol = end_map; n_bytes = MIN (eol - begin, sizeof (buf) - 1); strncpy (buf, begin, n_bytes); buf[n_bytes] = 0; if (buf[0] == 'T') { if (sizeof (time_t) == 4) stamp = strtoul (buf + 2, NULL, 10); else stamp = strtoull (buf + 2, NULL, 10); /* just incase time_t is 64 bits */ text = strchr (buf + 3, ' '); if (text) { if (prefs.hex_text_stripcolor_replay) { text = strip_color (text + 1, -1, STRIP_COLOR); } fe_print_text (sess, text, stamp); if (prefs.hex_text_stripcolor_replay) { g_free (text); } } lines++; } begin = eol + 1; } sess->scrollwritten = lines; if (lines) { text = ctime (&stamp); text[24] = 0; /* get rid of the \n */ snprintf (buf, sizeof (buf), "\n*\t%s %s\n\n", _("Loaded log from"), text); fe_print_text (sess, buf, 0); /*EMIT_SIGNAL (XP_TE_GENMSG, sess, "*", buf, NULL, NULL, NULL, 0);*/ } munmap (map, statbuf.st_size); #else lines = 0; while (waitline (fh, buf, sizeof buf, FALSE) != -1) { if (buf[0] == 'T') { if (sizeof (time_t) == 4) stamp = strtoul (buf + 2, NULL, 10); else stamp = strtoull (buf + 2, NULL, 10); /* just incase time_t is 64 bits */ text = strchr (buf + 3, ' '); if (text) { if (prefs.hex_text_stripcolor_replay) { text = strip_color (text + 1, -1, STRIP_COLOR); } #if 0 cleaned_text = text_replace_non_bmp (text, -1, &cleaned_len); if (cleaned_text != NULL) { if (prefs.hex_text_stripcolor_replay) { g_free (text); } text = cleaned_text; } #endif text_replace_non_bmp2 (text); fe_print_text (sess, text, stamp); if (prefs.hex_text_stripcolor_replay) { g_free (text); } } lines++; } } sess->scrollwritten = lines; if (lines) { text = ctime (&stamp); text[24] = 0; /* get rid of the \n */ snprintf (buf, sizeof (buf), "\n*\t%s %s\n\n", _("Loaded log from"), text); fe_print_text (sess, buf, 0); /*EMIT_SIGNAL (XP_TE_GENMSG, sess, "*", buf, NULL, NULL, NULL, 0);*/ } #endif close (fh); } void log_close (session *sess) { char obuf[512]; time_t currenttime; if (sess->logfd != -1) { currenttime = time (NULL); write (sess->logfd, obuf, snprintf (obuf, sizeof (obuf) - 1, _("**** ENDING LOGGING AT %s\n"), ctime (¤ttime))); close (sess->logfd); sess->logfd = -1; } } static void mkdir_p (char *dir) /* like "mkdir -p" from a shell, FS encoding */ { char *start = dir; /* the whole thing already exists? */ if (access (dir, F_OK) == 0) return; while (*dir) { #ifdef WIN32 if (dir != start && (*dir == '/' || *dir == '\\')) #else if (dir != start && *dir == '/') #endif { *dir = 0; #ifdef WIN32 mkdir (start); #else mkdir (start, S_IRUSR | S_IWUSR | S_IXUSR); #endif *dir = '/'; } dir++; } } static char * log_create_filename (char *channame) { char *tmp, *ret; int mbl; ret = tmp = strdup (channame); while (*tmp) { mbl = g_utf8_skip[((unsigned char *)tmp)[0]]; if (mbl == 1) { #ifndef WIN32 *tmp = rfc_tolower (*tmp); if (*tmp == '/') #else /* win32 can't handle filenames with \|/><:"*? characters */ if (*tmp == '\\' || *tmp == '|' || *tmp == '/' || *tmp == '>' || *tmp == '<' || *tmp == ':' || *tmp == '\"' || *tmp == '*' || *tmp == '?') #endif *tmp = '_'; } tmp += mbl; } return ret; } /* like strcpy, but % turns into %% */ static char * log_escape_strcpy (char *dest, char *src, char *end) { while (*src) { *dest = *src; if (dest + 1 == end) break; dest++; src++; if (*src == '%') { if (dest + 1 == end) break; dest[0] = '%'; dest++; } } dest[0] = 0; return dest - 1; } /* substitutes %c %n %s into buffer */ static void log_insert_vars (char *buf, int bufsize, char *fmt, char *c, char *n, char *s) { char *end = buf + bufsize; while (1) { switch (fmt[0]) { case 0: buf[0] = 0; return; case '%': fmt++; switch (fmt[0]) { case 'c': buf = log_escape_strcpy (buf, c, end); break; case 'n': buf = log_escape_strcpy (buf, n, end); break; case 's': buf = log_escape_strcpy (buf, s, end); break; default: buf[0] = '%'; buf++; buf[0] = fmt[0]; break; } break; default: buf[0] = fmt[0]; } fmt++; buf++; /* doesn't fit? */ if (buf == end) { buf[-1] = 0; return; } } } static int logmask_is_fullpath () { /* Check if final path/filename is absolute or relative. * If one uses log mask variables, such as "%c/...", %c will be empty upon * connecting since there's no channel name yet, so we have to make sure * we won't try to write to the FS root. On Windows we can be sure it's * full path if the 2nd character is a colon since Windows doesn't allow * colons in filenames. */ #ifdef WIN32 /* Treat it as full path if it * - starts with '\' which denotes the root directory of the current drive letter * - starts with a drive letter and followed by ':' */ if (prefs.hex_irc_logmask[0] == '\\' || (((prefs.hex_irc_logmask[0] >= 'A' && prefs.hex_irc_logmask[0] <= 'Z') || (prefs.hex_irc_logmask[0] >= 'a' && prefs.hex_irc_logmask[0] <= 'z')) && prefs.hex_irc_logmask[1] == ':')) #else if (prefs.hex_irc_logmask[0] == '/') #endif { return 1; } else { return 0; } } static char * log_create_pathname (char *servname, char *channame, char *netname) { char fname[384]; char fnametime[384]; char *fs; struct tm *tm; time_t now; if (!netname) { netname = "NETWORK"; } /* first, everything is in UTF-8 */ if (!rfc_casecmp (channame, servname)) { channame = strdup ("server"); } else { channame = log_create_filename (channame); } log_insert_vars (fname, sizeof (fname), prefs.hex_irc_logmask, channame, netname, servname); free (channame); /* insert time/date */ now = time (NULL); tm = localtime (&now); strftime (fnametime, sizeof (fnametime), fname, tm); /* create final path/filename */ if (logmask_is_fullpath ()) { snprintf (fname, sizeof (fname), "%s", fnametime); } else /* relative path */ { snprintf (fname, sizeof (fname), "%s/logs/%s", get_xdir_utf8 (), fnametime); } /* now we need it in FileSystem encoding */ fs = xchat_filename_from_utf8 (fname, -1, 0, 0, 0); /* create all the subdirectories */ if (fs) { mkdir_p (fs); } return fs; } static int log_open_file (char *servname, char *channame, char *netname) { char buf[512]; int fd; char *file; time_t currenttime; file = log_create_pathname (servname, channame, netname); if (!file) return -1; #ifdef WIN32 fd = open (file, O_CREAT | O_APPEND | O_WRONLY, S_IREAD|S_IWRITE); #else fd = open (file, O_CREAT | O_APPEND | O_WRONLY, 0644); #endif g_free (file); if (fd == -1) return -1; currenttime = time (NULL); write (fd, buf, snprintf (buf, sizeof (buf), _("**** BEGIN LOGGING AT %s\n"), ctime (¤ttime))); return fd; } static void log_open (session *sess) { static gboolean log_error = FALSE; log_close (sess); sess->logfd = log_open_file (sess->server->servername, sess->channel, server_get_network (sess->server, FALSE)); if (!log_error && sess->logfd == -1) { char message[512]; snprintf (message, sizeof (message), _("* Can't open log file(s) for writing. Check the\npermissions on %s"), log_create_pathname (sess->server->servername, sess->channel, server_get_network (sess->server, FALSE))); fe_message (message, FE_MSG_WAIT | FE_MSG_ERROR); log_error = TRUE; } } void log_open_or_close (session *sess) { if (sess->text_logging == SET_DEFAULT) { if (prefs.hex_irc_logging) log_open (sess); else log_close (sess); } else { if (sess->text_logging) log_open (sess); else log_close (sess); } } int get_stamp_str (char *fmt, time_t tim, char **ret) { char *loc = NULL; char dest[128]; gsize len; /* strftime wants the format string in LOCALE! */ if (!prefs.utf8_locale) { const gchar *charset; g_get_charset (&charset); loc = g_convert_with_fallback (fmt, -1, charset, "UTF-8", "?", 0, 0, 0); if (loc) fmt = loc; } len = strftime (dest, sizeof (dest), fmt, localtime (&tim)); #ifdef WIN32 if (!len) { /* use failsafe format until a correct one is specified */ len = strftime (dest, sizeof (dest), "[%H:%M:%S]", localtime (&tim)); } #endif if (len) { if (prefs.utf8_locale) *ret = g_strdup (dest); else *ret = g_locale_to_utf8 (dest, len, 0, &len, 0); } if (loc) g_free (loc); return len; } static void log_write (session *sess, char *text) { char *temp; char *stamp; char *file; int len; if (sess->text_logging == SET_DEFAULT) { if (!prefs.hex_irc_logging) return; } else { if (sess->text_logging != SET_ON) return; } if (sess->logfd == -1) log_open (sess); /* change to a different log file? */ file = log_create_pathname (sess->server->servername, sess->channel, server_get_network (sess->server, FALSE)); if (file) { if (access (file, F_OK) != 0) { close (sess->logfd); sess->logfd = log_open_file (sess->server->servername, sess->channel, server_get_network (sess->server, FALSE)); } g_free (file); } if (prefs.hex_stamp_log) { len = get_stamp_str (prefs.hex_stamp_log_format, time (0), &stamp); if (len) { write (sess->logfd, stamp, len); g_free (stamp); } } temp = strip_color (text, -1, STRIP_ALL); len = strlen (temp); write (sess->logfd, temp, len); /* lots of scripts/plugins print without a \n at the end */ if (temp[len - 1] != '\n') write (sess->logfd, "\n", 1); /* emulate what xtext would display */ g_free (temp); } /* converts a CP1252/ISO-8859-1(5) hybrid to UTF-8 */ /* Features: 1. It never fails, all 00-FF chars are converted to valid UTF-8 */ /* 2. Uses CP1252 in the range 80-9f because ISO doesn't have any- */ /* thing useful in this range and it helps us receive from mIRC */ /* 3. The five undefined chars in CP1252 80-9f are replaced with */ /* ISO-8859-15 control codes. */ /* 4. Handles 0xa4 as a Euro symbol ala ISO-8859-15. */ /* 5. Uses ISO-8859-1 (which matches CP1252) for everything else. */ /* 6. This routine measured 3x faster than g_convert :) */ static unsigned char * iso_8859_1_to_utf8 (unsigned char *text, int len, gsize *bytes_written) { unsigned int idx; unsigned char *res, *output; static const unsigned short lowtable[] = /* 74 byte table for 80-a4 */ { /* compressed utf-8 table: if the first byte's 0x20 bit is set, it indicates a 2-byte utf-8 sequence, otherwise prepend a 0xe2. */ 0x82ac, /* 80 Euro. CP1252 from here on... */ 0xe281, /* 81 NA */ 0x809a, /* 82 */ 0xe692, /* 83 */ 0x809e, /* 84 */ 0x80a6, /* 85 */ 0x80a0, /* 86 */ 0x80a1, /* 87 */ 0xeb86, /* 88 */ 0x80b0, /* 89 */ 0xe5a0, /* 8a */ 0x80b9, /* 8b */ 0xe592, /* 8c */ 0xe28d, /* 8d NA */ 0xe5bd, /* 8e */ 0xe28f, /* 8f NA */ 0xe290, /* 90 NA */ 0x8098, /* 91 */ 0x8099, /* 92 */ 0x809c, /* 93 */ 0x809d, /* 94 */ 0x80a2, /* 95 */ 0x8093, /* 96 */ 0x8094, /* 97 */ 0xeb9c, /* 98 */ 0x84a2, /* 99 */ 0xe5a1, /* 9a */ 0x80ba, /* 9b */ 0xe593, /* 9c */ 0xe29d, /* 9d NA */ 0xe5be, /* 9e */ 0xe5b8, /* 9f */ 0xe2a0, /* a0 */ 0xe2a1, /* a1 */ 0xe2a2, /* a2 */ 0xe2a3, /* a3 */ 0x82ac /* a4 ISO-8859-15 Euro. */ }; if (len == -1) len = strlen (text); /* worst case scenario: every byte turns into 3 bytes */ res = output = g_malloc ((len * 3) + 1); if (!output) return NULL; while (len) { if (G_LIKELY (*text < 0x80)) { *output = *text; /* ascii maps directly */ } else if (*text <= 0xa4) /* 80-a4 use a lookup table */ { idx = *text - 0x80; if (lowtable[idx] & 0x2000) { *output++ = (lowtable[idx] >> 8) & 0xdf; /* 2 byte utf-8 */ *output = lowtable[idx] & 0xff; } else { *output++ = 0xe2; /* 3 byte utf-8 */ *output++ = (lowtable[idx] >> 8) & 0xff; *output = lowtable[idx] & 0xff; } } else if (*text < 0xc0) { *output++ = 0xc2; *output = *text; } else { *output++ = 0xc3; *output = *text - 0x40; } output++; text++; len--; } *output = 0; /* terminate */ *bytes_written = output - res; return res; } #ifdef WIN32 /* replace characters outside of the Basic Multilingual Plane with * replacement characters (0xFFFD) */ #if 0 char * text_replace_non_bmp (char *utf8_input, int input_length, glong *output_length) { gunichar *ucs4_text; gunichar suspect; gchar *utf8_text; glong ucs4_length; glong index; ucs4_text = g_utf8_to_ucs4_fast (utf8_input, input_length, &ucs4_length); /* replace anything not in the Basic Multilingual Plane * (code points above 0xFFFF) with the replacement * character */ for (index = 0; index < ucs4_length; index++) { suspect = ucs4_text[index]; if ((suspect >= 0x1D173 && suspect <= 0x1D17A) || (suspect >= 0xE0001 && suspect <= 0xE007F)) { ucs4_text[index] = 0xFFFD; /* replacement character */ } } utf8_text = g_ucs4_to_utf8 ( ucs4_text, ucs4_length, NULL, output_length, NULL ); g_free (ucs4_text); return utf8_text; } #endif void text_replace_non_bmp2 (char *utf8_input) { char *tmp = utf8_input, *next; gunichar suspect; while (tmp != NULL && *tmp) { next = g_utf8_next_char(tmp); suspect = g_utf8_get_char_validated(tmp, next - tmp); if ((suspect >= 0x1D173 && suspect <= 0x1D17A) || (suspect >= 0xE0001 && suspect <= 0xE007F)) { /* 0xFFFD - replacement character */ *tmp = 0xEF; *(++tmp) = 0xBF; *(++tmp) = 0xBD; *(++tmp) = 0x1A; /* ASCII Sub to fill the 4th non-BMP byte */ } tmp = next; } } #endif char * text_validate (char **text, int *len) { char *utf; gsize utf_len; /* valid utf8? */ if (g_utf8_validate (*text, *len, 0)) return NULL; #ifdef WIN32 if (GetACP () == 1252) /* our routine is better than iconv's 1252 */ #else if (prefs.utf8_locale) #endif /* fallback to iso-8859-1 */ utf = iso_8859_1_to_utf8 (*text, *len, &utf_len); else { /* fallback to locale */ utf = g_locale_to_utf8 (*text, *len, 0, &utf_len, NULL); if (!utf) utf = iso_8859_1_to_utf8 (*text, *len, &utf_len); } if (!utf) { *text = g_strdup ("%INVALID%"); *len = 9; } else { *text = utf; *len = utf_len; } return utf; } void PrintText (session *sess, char *text) { char *conv; if (!sess) { if (!sess_list) return; sess = (session *) sess_list->data; } /* make sure it's valid utf8 */ if (text[0] == 0) { text = "\n"; conv = NULL; } else { int len = -1; conv = text_validate ((char **)&text, &len); } log_write (sess, text); scrollback_save (sess, text); fe_print_text (sess, text, 0); if (conv) g_free (conv); } void PrintTextf (session *sess, char *format, ...) { va_list args; char *buf; va_start (args, format); buf = g_strdup_vprintf (format, args); va_end (args); PrintText (sess, buf); g_free (buf); } /* Print Events stuff here --AGL */ /* Consider the following a NOTES file: The main upshot of this is: * Plugins and Perl scripts (when I get round to signaling perl.c) can intercept text events and do what they like * The default text engine can be config'ed By default it should appear *exactly* the same (I'm working hard not to change the default style) but if you go into Settings->Edit Event Texts you can change the text's. The format is thus: The normal %Cx (color) and %B (bold) etc work $x is replaced with the data in var x (e.g. $1 is often the nick) $axxx is replace with a single byte of value xxx (in base 10) AGL (990507) */ /* These lists are thus: pntevts_text[] are the strings the user sees (WITH %x etc) pntevts[] are the data strings with \000 etc */ /* To add a new event: Think up a name (like "Join") Make up a pevt_name_help struct Add an entry to textevents.in Type: make textevents */ /* Internals: On startup ~/.xchat/printevents.conf is loaded if it doesn't exist the defaults are loaded. Any missing events are filled from defaults. Each event is parsed by pevt_build_string and a binary output is produced which looks like: (byte) value: 0 = { (int) numbers of bytes (char []) that number of byte to be memcpy'ed into the buffer } 1 = (byte) number of varable to insert 2 = end of buffer Each XP_TE_* signal is hard coded to call text_emit which calls display_event which decodes the data This means that this system *should be faster* than snprintf because it always 'knows' that format of the string (basically is preparses much of the work) --AGL */ char *pntevts_text[NUM_XP]; char *pntevts[NUM_XP]; #define pevt_generic_none_help NULL static char * const pevt_genmsg_help[] = { N_("Left message"), N_("Rig
/*
 *  Copyright (C) 2005 Nathan Fredrickson
 *  Borrowed from Galeon, renamed, and simplified to only use iso-codes with no
 *  fallback method.
 *
 *  Copyright (C) 2004 Christian Persch
 *  Copyright (C) 2004 Crispin Flowerday
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the
 * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
 */

#ifdef WIN32
#include "../../config-win32.h"
#else
#include "../../config.h"
#endif

#include "sexy-iso-codes.h"

#include <glib/gi18n.h>

#include <string.h>

#include <libxml/xmlreader.h>

static GHashTable *iso_639_table = NULL;
static GHashTable *iso_3166_table = NULL;

#define ISO_639_DOMAIN	"iso_639"
#define ISO_3166_DOMAIN	"iso_3166"

#ifdef HAVE_ISO_CODES

#define ISOCODESLOCALEDIR "/share/locale"

static void
read_iso_639_entry (xmlTextReaderPtr reader,
		    GHashTable *table)
{
	xmlChar *code, *name;

	code = xmlTextReaderGetAttribute (reader, (const xmlChar *) "iso_639_1_code");
	name = xmlTextReaderGetAttribute (reader, (const xmlChar *) "name");

	/* Get iso-639-2 code */
	if (code == NULL || code[0] == '\0')
	{
		xmlFree (code);
		/* FIXME: use the 2T or 2B code? */
		code = xmlTextReaderGetAttribute (reader, (const xmlChar *) "iso_639_2T_code");
	}

	if (code != NULL && code[0] != '\0' && name != NULL && name[0] != '\0')
	{
		g_hash_table_insert (table, code, name);
	}
	else
	{
		xmlFree (code);
		xmlFree (name);
	}
}

static void
read_iso_3166_entry (xmlTextReaderPtr reader,
		     GHashTable *table)
{
	xmlChar *code, *name;

	code = xmlTextReaderGetAttribute (reader, (const xmlChar *) "alpha_2_code");
	name = xmlTextReaderGetAttribute (reader, (const xmlChar *) "name");

	if (code != NULL && code[0] != '\0' && name != NULL && name[0] != '\0')
	{
		char *lcode;

		lcode = g_ascii_strdown ((char *) code, -1);
		xmlFree (code);

		g_hash_table_insert (table, lcode, name);
	}
	else
	{
		xmlFree (code);
		xmlFree (name);
	}

}

typedef enum
{
	STATE_START,
	STATE_STOP,
	STATE_ENTRIES,
} ParserState;

static gboolean
load_iso_entries (int iso,
		  GFunc read_entry_func,
		  gpointer user_data)
{
	xmlTextReaderPtr reader;
	ParserState state = STATE_START;
	xmlChar iso_entries[32], iso_entry[32];
	char *filename;
	int ret = -1;

#ifdef WIN32
	filename = g_strdup_printf (".\\share\\xml\\iso-codes\\iso_%d.xml", iso);
#else
	filename = g_strdup_printf ("/usr/share/xml/iso-codes/iso_%d.xml", iso);
#endif
	reader = xmlNewTextReaderFilename (filename);
	if (reader == NULL) goto out;

	xmlStrPrintf (iso_entries, sizeof (iso_entries),
				  (xmlChar *)"iso_%d_entries", iso);
	xmlStrPrintf (iso_entry, sizeof (iso_entry),
				  (xmlChar *)"iso_%d_entry", iso);

	ret = xmlTextReaderRead (reader);

	while (ret == 1)
	{
		const xmlChar *tag;
		xmlReaderTypes type;

		tag = xmlTextReaderConstName (reader);
		type = xmlTextReaderNodeType (reader);

		if (state == STATE_ENTRIES &&
		    type == XML_READER_TYPE_ELEMENT &&
		    xmlStrEqual (tag, iso_entry))
		{
			read_entry_func (reader, user_data);
		}
		else if (state == STATE_START &&
			 type == XML_READER_TYPE_ELEMENT &&
			 xmlStrEqual (tag, iso_entries))
		{
			state = STATE_ENTRIES;
		}
		else if (state == STATE_ENTRIES &&
			 type == XML_READER_TYPE_END_ELEMENT &&
			 xmlStrEqual (tag, iso_entries))
		{
			state = STATE_STOP