Esempio n. 1
0
/* Handle raw profiles by Imagemagick (at least). Hex encoded with
 * line-changes and other (undocumented/unofficial) twists.
 */
static gchar *
raw_profile_new (const gchar *input,
                 const guint  input_length,
                 guint       *output_length)
{
	static const gchar* const lut = "0123456789abcdef";
	gchar *output;
	const gchar *ptr;
	const gchar *length_ptr;
	gsize size;
	gchar *length_str;
	guint length;

	size_t len;
	size_t i;
	size_t o;
	char *p;
	char *q;

	ptr = input;

	if (*ptr != '\n') {
		return NULL;
	}

	ptr++;

	if (!g_ascii_isalpha (*ptr)) {
		return NULL;
	}

	/* Skip the type string */
	do {
		ptr++;
	} while (g_ascii_isalpha (*ptr));

	if (*ptr != '\n') {
		return NULL;
	}

	/* Hop over whitespaces */
	do {
		ptr++;
	} while (*ptr == ' ');

	if (!g_ascii_isdigit (*ptr)) {
		return NULL;
	}

	/* Get the length string */
	length_ptr = ptr;
	size = 1;

	do {
		ptr++;
		size++;
	} while (g_ascii_isdigit (*ptr));

	length_str = g_strndup (length_ptr, size - 1);

	if (*ptr != '\n') {
		return NULL;
	}

	ptr++;

	length = atoi (length_str);
	g_free (length_str);

	len = length;
	i = 0;
	o = 0;

	output = malloc (length + 1); /* A bit less with non-valid */

	o = 0;
	while (o < len) {
		do {
			gchar a = ptr[i];
			p = strchr (lut, a);
			i++;
		} while (p == 0);

		do {
			gchar b = ptr[i];
			q = strchr (lut, b);
			i++;
		} while (q == 0);

		output[o] = (((p - lut) << 4) | (q - lut));
		o++;
	}

	output[o] = '\0';
	*output_length = o;

	return output;
}
Esempio n. 2
0
static CoglBool
is_symbol_char (const char c)
{
  return (g_ascii_isalpha (c) || c == '_') ? TRUE : FALSE;
}
Esempio n. 3
0
static gint pop3_session_recv_msg(Session *session, const gchar *msg)
{
	Pop3Session *pop3_session = POP3_SESSION(session);
	Pop3ErrorValue val = PS_SUCCESS;
	const gchar *body;

	body = msg;
	if (pop3_session->state != POP3_GETRANGE_UIDL_RECV &&
	    pop3_session->state != POP3_GETSIZE_LIST_RECV) {
		val = pop3_ok(pop3_session, msg);
		if (val != PS_SUCCESS) {
			if (val != PS_NOTSUPPORTED) {
				pop3_session->state = POP3_ERROR;
				return -1;
			}
		}

		if (*body == '+' || *body == '-')
			body++;
		while (g_ascii_isalpha(*body))
			body++;
		while (g_ascii_isspace(*body))
			body++;
	}

	switch (pop3_session->state) {
	case POP3_READY:
	case POP3_GREETING:
		pop3_greeting_recv(pop3_session, body);
#ifdef USE_GNUTLS
		if (pop3_session->ac_prefs->ssl_pop == SSL_STARTTLS)
			val = pop3_stls_send(pop3_session);
		else
#endif
		if (pop3_session->ac_prefs->use_apop_auth)
			val = pop3_getauth_apop_send(pop3_session);
		else
			val = pop3_getauth_user_send(pop3_session);
		break;
#ifdef USE_GNUTLS
	case POP3_STLS:
		if (pop3_stls_recv(pop3_session) != PS_SUCCESS)
			return -1;
		if (pop3_session->ac_prefs->use_apop_auth)
			val = pop3_getauth_apop_send(pop3_session);
		else
			val = pop3_getauth_user_send(pop3_session);
		break;
#endif
	case POP3_GETAUTH_USER:
		val = pop3_getauth_pass_send(pop3_session);
		break;
	case POP3_GETAUTH_PASS:
	case POP3_GETAUTH_APOP:
		if (!pop3_session->pop_before_smtp)
			val = pop3_getrange_stat_send(pop3_session);
		else
			val = pop3_logout_send(pop3_session);
		break;
	case POP3_GETRANGE_STAT:
		if (pop3_getrange_stat_recv(pop3_session, body) < 0)
			return -1;
		if (pop3_session->count > 0)
			val = pop3_getrange_uidl_send(pop3_session);
		else
			val = pop3_logout_send(pop3_session);
		break;
	case POP3_GETRANGE_LAST:
		if (val == PS_NOTSUPPORTED)
			pop3_session->error_val = PS_SUCCESS;
		else if (pop3_getrange_last_recv(pop3_session, body) < 0)
			return -1;
		if (pop3_session->cur_msg > 0)
			val = pop3_getsize_list_send(pop3_session);
		else
			val = pop3_logout_send(pop3_session);
		break;
	case POP3_GETRANGE_UIDL:
		if (val == PS_NOTSUPPORTED) {
			pop3_session->error_val = PS_SUCCESS;
			val = pop3_getrange_last_send(pop3_session);
		} else {
			pop3_session->state = POP3_GETRANGE_UIDL_RECV;
			session_recv_data(session, 0, ".\r\n");
		}
		break;
	case POP3_GETSIZE_LIST:
		pop3_session->state = POP3_GETSIZE_LIST_RECV;
		session_recv_data(session, 0, ".\r\n");
		break;
	case POP3_RETR:
		pop3_session->state = POP3_RETR_RECV;
		session_recv_data(session, 0, ".\r\n");
		break;
	case POP3_TOP:
		if (val == PS_NOTSUPPORTED) {
			pop3_session->error_val = PS_SUCCESS;
		} else {
			pop3_session->state = POP3_TOP_RECV;
			session_recv_data(session, 0, ".\r\n");
		}
		break;
	case POP3_DELETE:
		pop3_delete_recv(pop3_session);
		if (pop3_session->cur_msg == pop3_session->count)
			val = pop3_logout_send(pop3_session);
		else {
			pop3_session->cur_msg++;
			if (pop3_lookup_next(pop3_session) == POP3_ERROR)
				return -1;
		}
		break;
	case POP3_LOGOUT:
		pop3_session->state = POP3_DONE;
		session_disconnect(session);
		break;
	case POP3_ERROR:
	default:
		return -1;
	}

	return val == PS_SUCCESS?0:-1;
}
Esempio n. 4
0
/**
 * soup_uri_new_with_base:
 * @base: a base URI
 * @uri_string: the URI
 *
 * Parses @uri_string relative to @base.
 *
 * Return value: a parsed #SoupURI.
 **/
SoupURI *
soup_uri_new_with_base (SoupURI *base, const char *uri_string)
{
    SoupURI *uri, fixed_base;
    const char *end, *hash, *colon, *at, *path, *question;
    const char *p, *hostend;
    gboolean remove_dot_segments = TRUE;
    int len;

    g_return_val_if_fail (uri_string != NULL, NULL);

    /* Allow a %NULL path in @base, for compatibility */
    if (base && base->scheme && !base->path) {
        g_warn_if_fail (SOUP_URI_IS_VALID (base));

        memcpy (&fixed_base, base, sizeof (SoupURI));
        fixed_base.path = "";
        base = &fixed_base;
    }

    g_return_val_if_fail (base == NULL || SOUP_URI_IS_VALID (base), NULL);

    /* First some cleanup steps (which are supposed to all be no-ops,
     * but...). Skip initial whitespace, strip out internal tabs and
     * line breaks, and ignore trailing whitespace.
     */
    while (g_ascii_isspace (*uri_string))
        uri_string++;

    len = strcspn (uri_string, "\t\n\r");
    if (uri_string[len]) {
        char *clean = g_malloc (strlen (uri_string) + 1), *d;
        const char *s;

        for (s = uri_string, d = clean; *s; s++) {
            if (*s != '\t' && *s != '\n' && *s != '\r')
                *d++ = *s;
        }
        *d = '\0';

        uri = soup_uri_new_with_base (base, clean);
        g_free (clean);
        return uri;
    }
    end = uri_string + len;
    while (end > uri_string && g_ascii_isspace (end[-1]))
        end--;

    uri = g_slice_new0 (SoupURI);

    /* Find fragment. */
    hash = strchr (uri_string, '#');
    if (hash) {
        uri->fragment = uri_normalized_copy (hash + 1, end - hash + 1,
                                             NULL);
        end = hash;
    }

    /* Find scheme */
    p = uri_string;
    while (p < end && (g_ascii_isalpha (*p) ||
                       (p > uri_string && (g_ascii_isdigit (*p) ||
                                           *p == '.' ||
                                           *p == '+' ||
                                           *p == '-'))))
        p++;

    if (p > uri_string && *p == ':') {
        uri->scheme = soup_uri_parse_scheme (uri_string, p - uri_string);
        uri_string = p + 1;
    }

    if (uri_string == end && !base && !uri->fragment) {
        uri->path = g_strdup ("");
        return uri;
    }

    /* Check for authority */
    if (strncmp (uri_string, "//", 2) == 0) {
        uri_string += 2;

        path = uri_string + strcspn (uri_string, "/?#");
        if (path > end)
            path = end;
        at = strchr (uri_string, '@');
        if (at && at < path) {
            colon = strchr (uri_string, ':');
            if (colon && colon < at) {
                uri->password = soup_uri_decoded_copy (colon + 1,
                                                       at - colon - 1, NULL);
            } else {
                uri->password = NULL;
                colon = at;
            }

            uri->user = soup_uri_decoded_copy (uri_string,
                                               colon - uri_string, NULL);
            uri_string = at + 1;
        } else
            uri->user = uri->password = NULL;

        /* Find host and port. */
        if (*uri_string == '[') {
            const char *pct;

            uri_string++;
            hostend = strchr (uri_string, ']');
            if (!hostend || hostend > path) {
                soup_uri_free (uri);
                return NULL;
            }
            if (*(hostend + 1) == ':')
                colon = hostend + 1;
            else
                colon = NULL;

            pct = memchr (uri_string, '%', hostend - uri_string);
            if (!pct || (pct[1] == '2' && pct[2] == '5')) {
                uri->host = soup_uri_decoded_copy (uri_string,
                                                   hostend - uri_string, NULL);
            } else
                uri->host = g_strndup (uri_string, hostend - uri_string);
        } else {
            colon = memchr (uri_string, ':', path - uri_string);
            hostend = colon ? colon : path;
            uri->host = soup_uri_decoded_copy (uri_string,
                                               hostend - uri_string, NULL);
        }

        if (colon && colon != path - 1) {
            char *portend;
            uri->port = strtoul (colon + 1, &portend, 10);
            if (portend != (char *)path) {
                soup_uri_free (uri);
                return NULL;
            }
        }

        uri_string = path;
    }

    /* Find query */
    question = memchr (uri_string, '?', end - uri_string);
    if (question) {
        uri->query = uri_normalized_copy (question + 1,
                                          end - (question + 1),
                                          NULL);
        end = question;
    }

    if (end != uri_string) {
        uri->path = uri_normalized_copy (uri_string, end - uri_string,
                                         NULL);
    }

    /* Apply base URI. This is spelled out in RFC 3986. */
    if (base && !uri->scheme && uri->host)
        uri->scheme = base->scheme;
    else if (base && !uri->scheme) {
        uri->scheme = base->scheme;
        uri->user = g_strdup (base->user);
        uri->password = g_strdup (base->password);
        uri->host = g_strdup (base->host);
        uri->port = base->port;

        if (!uri->path) {
            uri->path = g_strdup (base->path);
            if (!uri->query)
                uri->query = g_strdup (base->query);
            remove_dot_segments = FALSE;
        } else if (*uri->path != '/') {
            char *newpath, *last;

            last = strrchr (base->path, '/');
            if (last) {
                newpath = g_strdup_printf ("%.*s%s",
                                           (int)(last + 1 - base->path),
                                           base->path,
                                           uri->path);
            } else
                newpath = g_strdup_printf ("/%s", uri->path);

            g_free (uri->path);
            uri->path = newpath;
        }
    }

    if (remove_dot_segments && uri->path && *uri->path) {
        char *p, *q;

        /* Remove "./" where "." is a complete segment. */
        for (p = uri->path + 1; *p; ) {
            if (*(p - 1) == '/' &&
                    *p == '.' && *(p + 1) == '/')
                memmove (p, p + 2, strlen (p + 2) + 1);
            else
                p++;
        }
        /* Remove "." at end. */
        if (p > uri->path + 2 &&
                *(p - 1) == '.' && *(p - 2) == '/')
            *(p - 1) = '\0';

        /* Remove "<segment>/../" where <segment> != ".." */
        for (p = uri->path + 1; *p; ) {
            if (!strncmp (p, "../", 3)) {
                p += 3;
                continue;
            }
            q = strchr (p + 1, '/');
            if (!q)
                break;
            if (strncmp (q, "/../", 4) != 0) {
                p = q + 1;
                continue;
            }
            memmove (p, q + 4, strlen (q + 4) + 1);
            p = uri->path + 1;
        }
        /* Remove "<segment>/.." at end where <segment> != ".." */
        q = strrchr (uri->path, '/');
        if (q && !strcmp (q, "/..")) {
            p = q - 1;
            while (p > uri->path && *p != '/')
                p--;
            if (strncmp (p, "/../", 4) != 0)
                *(p + 1) = 0;
        }

        /* Remove extraneous initial "/.."s */
        while (!strncmp (uri->path, "/../", 4))
            memmove (uri->path, uri->path + 3, strlen (uri->path) - 2);
        if (!strcmp (uri->path, "/.."))
            uri->path[1] = '\0';
    }

    /* HTTP-specific stuff */
    if (uri->scheme == SOUP_URI_SCHEME_HTTP ||
            uri->scheme == SOUP_URI_SCHEME_HTTPS) {
        if (!uri->path)
            uri->path = g_strdup ("/");
        if (!SOUP_URI_VALID_FOR_HTTP (uri)) {
            soup_uri_free (uri);
            return NULL;
        }
    }

    if (uri->scheme == SOUP_URI_SCHEME_FTP) {
        if (!uri->host) {
            soup_uri_free (uri);
            return NULL;
        }
    }

    if (!uri->port)
        uri->port = soup_scheme_default_port (uri->scheme);
    if (!uri->path)
        uri->path = g_strdup ("");

    return uri;
}
IdolPlParserResult
idol_pl_parser_add_m3u (IdolPlParser *parser,
			 GFile *file,
			 GFile *base_file,
			 IdolPlParseData *parse_data,
			 gpointer data)
{
	IdolPlParserResult retval = IDOL_PL_PARSER_RESULT_UNHANDLED;
	char *contents, **lines;
	gsize size;
	guint i, num_lines;
	gboolean dos_mode = FALSE;
	const char *extinfo;

	if (g_file_load_contents (file, NULL, &contents, &size, NULL, NULL) == FALSE)
		return IDOL_PL_PARSER_RESULT_ERROR;

	/* .pls files with a .m3u extension, the nasties */
	if (g_str_has_prefix (contents, "[playlist]") != FALSE
			|| g_str_has_prefix (contents, "[Playlist]") != FALSE
			|| g_str_has_prefix (contents, "[PLAYLIST]") != FALSE) {
		retval = idol_pl_parser_add_pls_with_contents (parser, file, base_file, contents, parse_data);
		g_free (contents);
		return retval;
	}

	/* Try to use ISO-8859-1 if we don't have valid UTF-8,
	 * try to parse anyway if it's not ISO-8859-1 */
	if (g_utf8_validate (contents, -1, NULL) == FALSE) {
		char *fixed;
		fixed = g_convert (contents, -1, "UTF-8", "ISO8859-1", NULL, NULL, NULL);
		if (fixed != NULL) {
			g_free (contents);
			contents = fixed;
		}
	}

	/* is non-NULL if there's an EXTINF on a preceding line */
	extinfo = NULL;

	/* figure out whether we're a unix m3u or dos m3u */
	if (strstr(contents, "\x0d")) {
		dos_mode = TRUE;
	}

	lines = g_strsplit_set (contents, "\r\n", 0);
	g_free (contents);
	num_lines = g_strv_length (lines);
	/* We don't count the terminating NULL */
	num_lines--;

	for (i = 0; lines[i] != NULL; i++) {
		const char *line;

		line = lines[i];

		if (line[0] == '\0')
			continue;

		retval = IDOL_PL_PARSER_RESULT_SUCCESS;

		/* Ignore leading spaces */
		for (; g_ascii_isspace (line[0]); line++)
			;

		/* Ignore comments, but mark it if we have extra info */
		if (line[0] == '#') {
			if (extinfo == NULL && g_str_has_prefix (line, EXTINF) != FALSE)
				extinfo = line;
			continue;
		}

		/* Either it's a URI, or it has a proper path ... */
		if (strstr(line, "://") != NULL
				|| line[0] == G_DIR_SEPARATOR) {
			GFile *uri;

			uri = g_file_new_for_commandline_arg (line);
			if (idol_pl_parser_parse_internal (parser, uri, NULL, parse_data) != IDOL_PL_PARSER_RESULT_SUCCESS) {
				idol_pl_parser_add_one_uri (parser, line,
						idol_pl_parser_get_extinfo_title (extinfo));
			}
			g_object_unref (uri);
			extinfo = NULL;
		} else if (g_ascii_isalpha (line[0]) != FALSE
			   && g_str_has_prefix (line + 1, ":\\")) {
			/* Path relative to a drive on Windows, we need to use
			 * the base that was passed to us */
			GFile *uri;

			lines[i] = g_strdelimit (lines[i], "\\", '/');
			/* + 2, skip drive letter */
			uri = g_file_get_child (base_file, line + 2);
			idol_pl_parser_add_one_file (parser, uri,
						     idol_pl_parser_get_extinfo_title (extinfo));
			g_object_unref (uri);
			extinfo = NULL;
		} else if (line[0] == '\\' && line[1] == '\\') {
			/* ... Or it's in the windows smb form
			 * (\\machine\share\filename), Note drive names
			 * (C:\ D:\ etc) are unhandled (unknown base for
			 * drive letters) */
		        char *tmpuri;

			lines[i] = g_strdelimit (lines[i], "\\", '/');
			tmpuri = g_strjoin (NULL, "smb:", line, NULL);

			idol_pl_parser_add_one_uri (parser, line,
					idol_pl_parser_get_extinfo_title (extinfo));
			extinfo = NULL;

			g_free (tmpuri);
		} else {
			/* Try with a base */
			GFile *uri, *_base_file;
			char sep;

			_base_file = g_file_get_parent (file);
			sep = (dos_mode ? '\\' : '/');
			if (sep == '\\')
				lines[i] = g_strdelimit (lines[i], "\\", '/');
			uri = g_file_get_child (_base_file, line);
			g_object_unref (_base_file);
			idol_pl_parser_add_one_file (parser, uri,
						     idol_pl_parser_get_extinfo_title (extinfo));
			g_object_unref (uri);
			extinfo = NULL;
		}
	}

	g_strfreev (lines);

	return retval;
}
Esempio n. 6
0
gboolean
mbus_symbol_is_valid_char( gchar c )
{
  return ( g_ascii_isalpha( c ) || g_ascii_isdigit( c ) ||
      c == '-' || c == '_' || c == '.' );
}
Esempio n. 7
0
static gboolean
gwy_si_unit_parse(GwySIUnit *siunit,
                  const gchar *string)
{
    GwySimpleUnit unit;
    gdouble q;
    const gchar *end;
    gchar *p, *e;
    gint n, i, pfpower;
    GString *buf;
    gboolean dividing = FALSE;

    g_array_set_size(siunit->units, 0);
    siunit->power10 = 0;

    if (!string || !*string)
        return TRUE;

    /* give up when it looks too wild */
    end = strpbrk(string,
                  "\177\001\002\003\004\005\006\007"
                  "\010\011\012\013\014\015\016\017"
                  "\020\021\022\023\024\025\026\027"
                  "\030\031\032\033\034\035\036\037"
                  "!#$&()*,:;=?@\\[]_`|{}");
    if (end) {
        g_warning("Invalid character 0x%02x", *end);
        return FALSE;
    }

    /* may start with a multiplier, but it must be a power of 10 */
    q = g_ascii_strtod(string, (gchar**)&end);
    if (end != string) {
        string = end;
        siunit->power10 = ROUND(log10(q));
        if (q <= 0 || fabs(log(q/pow10(siunit->power10))) > 1e-14) {
            g_warning("Bad multiplier %g", q);
            siunit->power10 = 0;
        }
        else if (g_str_has_prefix(string, "<sup>")) {
            string += strlen("<sup>");
            n = strtol(string, (gchar**)&end, 10);
            if (end == string)
                g_warning("Bad exponent %s", string);
            else if (!g_str_has_prefix(end, "</sup>"))
                g_warning("Expected </sup> after exponent");
            else
                siunit->power10 *= n;
            string = end;
        }
        else if (string[0] == '^') {
            string++;
            n = strtol(string, (gchar**)&end, 10);
            if (end == string)
                g_warning("Bad exponent %s", string);
            else
                siunit->power10 *= n;
            string = end;
        }
    }
    while (g_ascii_isspace(*string))
        string++;

    buf = g_string_new("");

    /* the rest are units */
    while (*string) {
        /* units are separated with whitespace and maybe a division sign */
        end = string;
        do {
            end = strpbrk(end, " /");
            if (!end || end == string || *end != '/' || *(end-1) != '<')
                break;
            end++;
        } while (TRUE);
        if (!end)
            end = string + strlen(string);

        g_string_set_size(buf, 0);
        g_string_append_len(buf, string, end - string);

        /* fix sloppy notations */
        if (buf->str[0] == '\272') {
            if (!buf->str[1])
                g_string_assign(buf, "deg");
            else {
                g_string_erase(buf, 0, 1);
                g_string_prepend(buf, "°");
            }
        }
        else if (gwy_strequal(buf->str, "°"))
            g_string_assign(buf, "deg");
        else if (buf->str[0] == '\305' && !buf->str[1])
            g_string_assign(buf, "Å");
        else if (gwy_strequal(buf->str, "Å"))
            g_string_assign(buf, "Å");
        else if (gwy_strequal(buf->str, "AA"))
            g_string_assign(buf, "Å");

        /* get prefix, but be careful not to split mol to mili-ol */
        pfpower = 0;
        for (i = 0; i < G_N_ELEMENTS(known_units); i++) {
            if (g_str_has_prefix(buf->str, known_units[i])
                && !g_ascii_isalpha(buf->str[strlen(known_units[i])]))
                break;
        }
        if (i == G_N_ELEMENTS(known_units) && strlen(buf->str) > 1) {
            for (i = 0; i < G_N_ELEMENTS(SI_prefixes); i++) {
                const gchar *pfx = SI_prefixes[i].prefix;

                if (g_str_has_prefix(buf->str, pfx)
                    && g_ascii_isalpha(buf->str[strlen(pfx)])) {
                    pfpower = SI_prefixes[i].power10;
                    g_string_erase(buf, 0, strlen(pfx));
                    break;
                }
            }
        }

        /* get unit power */
        unit.power = 1;
        if ((p = strstr(buf->str + 1, "<sup>"))) {
            unit.power = strtol(p + strlen("<sup>"), &e, 10);
            if (e == p + strlen("<sup>")
                || !g_str_has_prefix(e, "</sup>")) {
                g_warning("Bad power %s", p);
                unit.power = 1;
            }
            else if (!unit.power || abs(unit.power) > 12) {
                g_warning("Bad power %d", unit.power);
                unit.power = 1;
            }
            g_string_truncate(buf, p - buf->str);
        }
        else if ((p = strchr(buf->str + 1, '^'))) {
            unit.power = strtol(p + 1, &e, 10);
            if (e == p + 1 || *e) {
                g_warning("Bad power %s", p);
                unit.power = 1;
            }
            else if (!unit.power || abs(unit.power) > 12) {
                g_warning("Bad power %d", unit.power);
                unit.power = 1;
            }
            g_string_truncate(buf, p - buf->str);
        }
        else if (buf->len) {
            /* Are we really desperate?  Yes, we are! */
            i = buf->len;
            while (i && (g_ascii_isdigit(buf->str[i-1])
                         || buf->str[i-1] == '-'))
                i--;
            if (i != buf->len) {
                unit.power = strtol(buf->str + i, NULL, 10);
                if (!unit.power || abs(unit.power) > 12) {
                    g_warning("Bad power %d", unit.power);
                    unit.power = 1;
                }
                g_string_truncate(buf, i);
            }
        }

        /* handle some ugly, but quite common units */
        if (gwy_strequal(buf->str, "Å")) {
            pfpower -= 10;
            g_string_assign(buf, "m");
        }
        else if (gwy_strequal(buf->str, "%")) {
            pfpower -= 2;
            g_string_assign(buf, "");
        }

        /* elementary sanity */
        if (!g_utf8_validate(buf->str, -1, (const gchar**)&p)) {
            g_warning("Unit string is not valid UTF-8");
            g_string_truncate(buf, p - buf->str);
        }
        if (!buf->len) {
            /* maybe it's just percentage.  cross fingers and proceed. */
            if (dividing)
                unit.power = -unit.power;
            siunit->power10 += unit.power * pfpower;
        }
        else if (!g_ascii_isalpha(buf->str[0]) && (guchar)buf->str[0] < 128)
            g_warning("Invalid base unit: %s", buf->str);
        else {
            /* append it */
            unit.unit = g_quark_from_string(buf->str);
            if (dividing)
                unit.power = -unit.power;
            gwy_debug("<%s:%u> %d\n", buf->str, unit.unit, unit.power);
            siunit->power10 += unit.power * pfpower;
            g_array_append_val(siunit->units, unit);
        }

        /* TODO: scan known obscure units */
        unit.traits = 0;

        /* get to the next token, looking for division */
        while (g_ascii_isspace(*end))
            end++;
        if (*end == '/') {
            if (dividing)
                g_warning("Cannot group multiple divisions");
            dividing = TRUE;
            end++;
            while (g_ascii_isspace(*end))
                end++;
        }
        string = end;
    }

    gwy_si_unit_canonicalize(siunit);

    return TRUE;
}
Esempio n. 8
0
double _parse(gchar *args, struct global_vars *gvars)
{
	gdouble minus_one = -1.0;
	gdouble null = 0;
	gint args_len = strlen(args);
	
	struct stack *arguments = stack_init(sizeof(gdouble));
	struct stack *operators = stack_init(sizeof(gchar));

	gint i = 0;
	gint j = 0;
	gint local_nest_level = 0;

	gint8 last_p = 0;  /** priority of last parsed operator */
	gboolean coef_flag = FALSE;  /** set if value might preceed a bracket and thus become a coefficient */
	gboolean func_flag = FALSE;  /** set if result of next bracket is to be passed as an argument to function <symbol> */
	gboolean nest_flag = FALSE;  /** indicates characters are being collected and not parsed */
	gboolean nest_init_flag = FALSE;  /** necessary to skip first character '(' during string collection */
	gboolean value_flag = FALSE; /** indicates previously parsed value as opposed to an operator */
	gboolean frac_flag = FALSE;
	
	gboolean no_input_flag = FALSE;
	if (strlen(args) == 0) {no_input_flag = TRUE;}
	
	GString *nested_term = g_string_new("\0"); /** collector string for contents of nested term */
	GString *symbol = g_string_new("\0"); /** collector string for symbol name */

	if (!no_input_flag) {
		for (i=0; i < args_len; i++)
		{
	
			if (nest_init_flag) {nest_init_flag = FALSE;}
	
			/** lock computing by raising nest level, substitute '*' if coefficient exists */
			if (args[i] == '(')
			{
				if (!nest_flag) /** nested interpreting is just about to be initialized */
				{
					if (coef_flag) {stack_push(operators, "*"); last_p = priority('*');}
					coef_flag = TRUE;
					nest_flag = TRUE;
					nest_init_flag = TRUE;
					gvars->nest_level += 1;
					nested_term = g_string_new("\0");
				}
				else  /** nested interpreting is in progress */
				{
					local_nest_level += 1;
				}
			}
	
			else if (args[i] == ')')
			{
				if (nest_flag && local_nest_level == 0) /** nesting has reached end */
				{
					nest_flag = FALSE; value_flag = TRUE;
					gdouble nested_term_result = _parse(nested_term->str, gvars);
					gvars->nest_level -= 1;
					g_string_free(nested_term, TRUE);
					nested_term = g_string_new("\0");
					if (func_flag)
					{
						gdouble compute_function_results =
							compute_function(symbol->str, nested_term_result, gvars);
						stack_push(arguments, &compute_function_results);
						func_flag = FALSE;
						g_string_free(symbol, TRUE);
						symbol = g_string_new("\0");
					}
					else {stack_push(arguments, &nested_term_result);}
				}
				else  /** nested interpreting is in progress, passing by uninterpreted ')' */
				{
					local_nest_level -= 1;
				}
			}
	
	
			if (!nest_flag)
			{
	
				if (args[i] == '.' || args[i] == ',')
				{
					if (g_ascii_isdigit(char_at(args,i+1))) {frac_flag = TRUE;}
					else {gvars->error_type = 3; return 0;}
				}
	
				else if (g_ascii_isdigit(args[i]))  /** parse number */
				{
					if (gvars->debug)
						{for (j=0;j<gvars->nest_level;j++) {g_printf("   ");} g_printf("args[%d] is digit\n", i);}
	
					gint8 dig = to_d(args[i]);
					stack_push(gvars->digits, &dig);
					if (frac_flag) {gvars->frac_point -= 1;}
					/** check if there is more than one digit or fractal part */
					if (!(g_ascii_isdigit(char_at(args, i+1)) || char_at(args, i+1) == '.' || char_at(args, i+1) == ','))
					{
						if (coef_flag) {stack_push(operators, "*"); last_p = priority('*');}
						gdouble joined_dig =  join_digits(gvars->digits, gvars->frac_point);
						stack_push(arguments, &joined_dig);
						coef_flag = TRUE; frac_flag = FALSE; value_flag = TRUE; gvars->frac_point = 0;
					}
				}
	
				else if (isoperator(args[i]))  /** parse operators */
				{
					if (gvars->debug)
						{for (j=0;j<gvars->nest_level;j++) {g_printf("   ");} g_printf("args[%d] is operator\n", i);}
	
					if (args[i] == '-')  /** check if preceeding minus changes sign of next symbol */
					{
						if (value_flag)
						{
							compute(arguments, operators, gvars);
							stack_push(operators, "+");
						}
						stack_push(arguments, &minus_one);
						stack_push(operators, "*"); last_p = priority('*');
						
						coef_flag = FALSE;
					}
					else
					{
						if (stack_length(arguments) <= stack_length(operators)) {gvars->error_type = 4; break;}
						/** check beforehand if lower priority operator is encountered */
						if (priority(args[i]) < last_p) {compute(arguments, operators, gvars);}
						last_p = priority(args[i]);
						stack_push(operators, &args[i]);
						if (args[i] == '!') {stack_push(arguments, &null);}  // dummy zero to avoid complications due to missing second args for faculty
						coef_flag = FALSE;
						value_flag = FALSE;
					}
				}
	
				else if (g_ascii_isalpha(args[i])) /** parse letters */
				{
					if (gvars->debug)
						{for (j=0;j<gvars->nest_level;j++) {g_printf("   ");} printf("args[%d] is letter\n", i);}
	
					if (coef_flag) {coef_flag = FALSE; stack_push(operators, "*"); last_p = priority('*');}
					g_string_append_c(symbol, args[i]);
					if (char_at(args,i+1) == '(')
					{
						compute_function(symbol->str, 0, gvars);
						if (gvars->error_type != 0)
						{
							gvars->error_type = 0;
							gdouble looked_up_c = lookup_constant(symbol->str, gvars);
							stack_push(arguments, &looked_up_c);
							g_string_free(symbol, TRUE);
							symbol = g_string_new("\0");
							coef_flag = TRUE;
							value_flag = TRUE;
						}
						else {func_flag = TRUE;}
					}
					else if (!g_ascii_isalpha(char_at(args,i+1)))
					{
						gdouble looked_up_c = lookup_constant(symbol->str, gvars);
						stack_push(arguments, &looked_up_c);
						g_string_free(symbol, TRUE);
						symbol = g_string_new("\0");
						coef_flag = TRUE;
						value_flag = TRUE;
					}
				}
	
			}
	
			else if (!nest_init_flag) /** this collector block needs to be skipped once so the first '(' isn't collected */
			{
				g_string_append_c(nested_term, args[i]);
			}

			if (args[i] == ' ') {coef_flag = FALSE;}

			if (char_at(args,i) == '#') {break;}  /** failsafe, in case array bounds are left */
		}
	}
	if (gvars->debug)
		{printf("<args>\n");stack_dump(arguments, 'd');printf("<ops>\n");stack_dump(operators, 'c');printf("<>\n");
		printf("errors so far: %d\n", gvars->error_type);}

	if (local_nest_level != 0 && gvars->error_type == 0) {gvars->error_type = 1;}
	if (!no_input_flag && gvars->error_type == 0) {compute(arguments, operators, gvars);}
	if (stack_length(arguments) > 1 && gvars->error_type == 0) {gvars->error_type = 4;}

	gdouble return_value = 0;
	if (gvars->error_type == 0 && !no_input_flag) {stack_pop(arguments, &return_value);}
	stack_destroy(arguments);
	stack_destroy(operators);

	return return_value;
}
Esempio n. 9
0
static void
deserialize_exif_gps_coordinate (GstTagList * taglist, const gchar * gst_tag,
    const gchar * str, gchar pos, gchar neg)
{
  gdouble value = 0;
  gint d = 0, m = 0, s = 0;
  gdouble m2 = 0;
  gchar c = 0;
  const gchar *current;

  /* get the degrees */
  if (sscanf (str, "%d", &d) != 1)
    goto error;

  /* find the beginning of the minutes */
  current = strchr (str, ',');
  if (current == NULL)
    goto end;
  current += 1;

  /* check if it uses ,SS or .mm */
  if (strchr (current, ',') != NULL) {
    sscanf (current, "%d,%d%c", &m, &s, &c);
  } else {
    gchar *copy = g_strdup (current);
    gint len = strlen (copy);
    gint i;

    /* check the last letter */
    for (i = len - 1; len >= 0; len--) {
      if (g_ascii_isspace (copy[i]))
        continue;

      if (g_ascii_isalpha (copy[i])) {
        /* found it */
        c = copy[i];
        copy[i] = '\0';
        break;

      } else {
        /* something is wrong */
        g_free (copy);
        goto error;
      }
    }

    /* use a copy so we can change the last letter as E can cause
     * problems here */
    m2 = g_ascii_strtod (copy, NULL);
    g_free (copy);
  }

end:
  /* we can add them all as those that aren't parsed are 0 */
  value = d + (m / 60.0) + (s / (60.0 * 60.0)) + (m2 / 60.0);

  if (c == pos) {
    //NOP
  } else if (c == neg) {
    value *= -1;
  } else {
    goto error;
  }

  gst_tag_list_add (taglist, GST_TAG_MERGE_REPLACE, gst_tag, value, NULL);
  return;

error:
  GST_WARNING ("Failed to deserialize gps coordinate: %s", str);
}
Esempio n. 10
0
static gboolean
is_escalpha (gunichar c)
{
  return c > 0x7F || g_ascii_isalpha (c);
}
Esempio n. 11
0
/**
 * g_filename_from_uri:
 * @uri: a uri describing a filename (escaped, encoded in UTF-8).
 * @hostname: Location to store hostname for the URI, or %NULL.
 *            If there is no hostname in the URI, %NULL will be
 *            stored in this location.
 * @error: location to store the error occuring, or %NULL to ignore
 *         errors. Any of the errors in #GConvertError may occur.
 *
 * Converts an escaped UTF-8 encoded URI to a local filename in the
 * encoding used for filenames.
 *
 * Return value: a newly-allocated string holding the resulting
 *               filename, or %NULL on an error.
 **/
gchar *
filename_from_uri (const char *uri,
		   char      **hostname,
		   GError    **error)
{
  const char *path_part;
  const char *host_part;
  char *unescaped_hostname;
  char *result;
  char *filename;
  int offs;
#ifdef G_OS_WIN32
  char *p, *slash;
#endif

  if (hostname)
    *hostname = NULL;

  if (!has_case_prefix (uri, "file:/"))
    {
      g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_BAD_URI,
		   _("The URI '%s' is not an absolute URI using the file scheme"),
		   uri);
      return NULL;
    }

  path_part = uri + strlen ("file:");

  if (strchr (path_part, '#') != NULL)
    {
      g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_BAD_URI,
		   _("The local file URI '%s' may not include a '#'"),
		   uri);
      return NULL;
    }

  if (has_case_prefix (path_part, "///"))
    path_part += 2;
  else if (has_case_prefix (path_part, "//"))
    {
      path_part += 2;
      host_part = path_part;

      path_part = strchr (path_part, '/');

      if (path_part == NULL)
	{
	  g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_BAD_URI,
		       _("The URI '%s' is invalid"),
		       uri);
	  return NULL;
	}

      unescaped_hostname = g_unescape_uri_string (host_part, path_part - host_part, "", TRUE);

      if (unescaped_hostname == NULL ||
	  !hostname_validate (unescaped_hostname))
	{
	  g_free (unescaped_hostname);
	  g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_BAD_URI,
		       _("The hostname of the URI '%s' is invalid"),
		       uri);
	  return NULL;
	}

      if (hostname)
	*hostname = unescaped_hostname;
      else
	g_free (unescaped_hostname);
    }

  filename = g_unescape_uri_string (path_part, -1, "/", FALSE);

  if (filename == NULL)
    {
      g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_BAD_URI,
		   _("The URI '%s' contains invalidly escaped characters"),
		   uri);
      return NULL;
    }

  offs = 0;
#ifdef G_OS_WIN32
  /* Drop localhost */
  if (hostname && *hostname != NULL &&
      g_ascii_strcasecmp (*hostname, "localhost") == 0)
    {
      g_free (*hostname);
      *hostname = NULL;
    }

  /* Turn slashes into backslashes, because that's the canonical spelling */
  p = filename;
  while ((slash = strchr (p, '/')) != NULL)
    {
      *slash = '\\';
      p = slash + 1;
    }

  /* Windows URIs with a drive letter can be like "file://host/c:/foo"
   * or "file://host/c|/foo" (some Netscape versions). In those cases, start
   * the filename from the drive letter.
   */
  if (g_ascii_isalpha (filename[1]))
    {
      if (filename[2] == ':')
	offs = 1;
      else if (filename[2] == '|')
	{
	  filename[2] = ':';
	  offs = 1;
	}
    }
#endif

  /* This is where we differ from glib2.0.6: we use
     gtkpod's charset_from_utf8() instead of glib's
     g_filename_from_utf8() */
  result = charset_from_utf8 (filename + offs);
  g_free (filename);

  return result;
}
Esempio n. 12
0
static gboolean
push_chunk (GArray      *ar,
            const gchar *str)
{
  g_autofree gchar *attr = NULL;
  g_autofree gchar *post = NULL;
  g_autofree gchar *return_type = NULL;
  g_autofree gchar *ident = NULL;
  const gchar *pos;
  Chunk chunk = {0};

  g_assert (ar);
  g_assert (str);

  if ((attr = read_attr (str, &pos)))
    {
      chunk.pre = g_strstrip (g_steal_pointer (&attr));
      str = pos;
    }

  if (!(return_type = read_return_type (str, &pos)))
    goto failure;
  str = pos;

  chunk.return_type = g_strstrip (g_steal_pointer (&return_type));

  if (!(ident = getword (str, &pos)))
    goto failure;
  if (*ident != '_' && !g_ascii_isalpha (*ident))
    goto failure;
  str = pos;
  chunk.identifier = g_strstrip (g_steal_pointer (&ident));

  if (!read_char (str, '(', &pos))
    goto failure;
  str = pos;

  /* get params */
  if (!(pos = strchr (str, ')')))
    goto failure;

  {
    g_autofree gchar *inner = g_strndup (str, pos - str);
    chunk.params = parse_parameters (inner);
    str = pos;
  }

  if (!read_char (str, ')', &pos))
    goto failure;
  str = pos;

  chunk.post = g_strstrip (g_strdup (str));
  if (chunk.post[0] == 0)
    g_clear_pointer (&chunk.post, g_free);

  g_array_append_val (ar, chunk);

  return TRUE;

failure:

  clear_chunk (&chunk);

  return FALSE;
}
Esempio n. 13
0
static void
gnm_glpk_read_solution (GnmGlpk *lp)
{
	GnmSubSolver *subsol = lp->parent;
	GnmSolver *sol = GNM_SOLVER (subsol);
	GsfInput *input;
	GsfInputTextline *tl = NULL;
	const char *line;
	GnmSolverResult *result = NULL;
	GnmSolverSensitivity *sensitivity = NULL;
	enum { SEC_UNKNOWN, SEC_ROWS, SEC_COLUMNS } state;
	gboolean has_integer;
	GSList *l;

	input = gsf_input_stdio_new (lp->result_filename, NULL);
	if (!input)
		goto fail;
	tl = GSF_INPUT_TEXTLINE (gsf_input_textline_new (input));
	g_object_unref (input);

	result = g_object_new (GNM_SOLVER_RESULT_TYPE, NULL);
	result->solution = g_new0 (gnm_float, sol->input_cells->len);

	sensitivity = gnm_solver_sensitivity_new (sol);

	/*
	 * glpsol's output format is different if there are any integer
	 * constraint.  Go figure.
	 */
	has_integer = sol->params->options.assume_discrete;
	for (l = sol->params->constraints; !has_integer && l; l = l->next) {
		GnmSolverConstraint *c = l->data;
		has_integer = (c->type == GNM_SOLVER_INTEGER ||
			       c->type == GNM_SOLVER_BOOLEAN);
	}

	switch (gnm_glpk_detect_version (lp, tl)) {
	case GLPK_457:
		if (gnm_glpk_read_solution_457 (lp, tl, result, sensitivity,
						has_integer))
			goto fail;
		break;
	case GLPK_458:
		if (gnm_glpk_read_solution_458 (lp, tl, result, sensitivity,
						has_integer))
			goto fail;
		break;
	default:
		goto fail;
	}

	g_object_unref (tl);
	tl = NULL;

	// ----------------------------------------

	if (!lp->ranges_filename)
		goto done;

	input = gsf_input_stdio_new (lp->ranges_filename, NULL);
	if (!input)
		goto fail;
	tl = GSF_INPUT_TEXTLINE (gsf_input_textline_new (input));
	g_object_unref (input);

	state = SEC_UNKNOWN;
	// We are reading a file intended for human consumption.
	// That is unfortunately because it implies rounding, for example.
	// The information does not appear to be available elsewhere.

	while ((line = gsf_input_textline_utf8_gets (tl)) != NULL) {
		gchar **items, **items2 = NULL;
		int len, len2 = 0;

		if (g_str_has_prefix (line, "   No. Row name")) {
			state = SEC_ROWS;
			continue;
		} else if (g_str_has_prefix (line, "   No. Column name")) {
			state = SEC_COLUMNS;
			continue;
		} else if (g_ascii_isalpha (line[0])) {
			state = SEC_UNKNOWN;
			continue;
		}

		if (state == SEC_UNKNOWN)
			continue;

		items = my_strsplit (line);
		len = g_strv_length (items);

		if (len == 10 && g_ascii_isdigit (items[0][0])) {
			line = gsf_input_textline_utf8_gets (tl);
			if (line) {
				items2 = my_strsplit (line);
				len2 = g_strv_length (items2);
			}
		}

		if (len == 10 && len2 == 6 && state == SEC_COLUMNS) {
			gnm_float low = parse_number (items[7]);
			gnm_float high = parse_number (items2[3]);
			GnmCell const *cell = gnm_sub_solver_find_cell (lp->parent, items[1]);
			int idx = gnm_solver_cell_index (sol, cell);
			if (idx >= 0) {
				sensitivity->vars[idx].low = low;
				sensitivity->vars[idx].high = high;
			}
		}

		if (len == 10 && len2 == 6 && state == SEC_ROWS) {
			gnm_float low = parse_number (items[6]);
			gnm_float high = parse_number (items2[2]);
			int cidx = gnm_sub_solver_find_constraint (lp->parent, items[1]);
			if (cidx >= 0) {
				sensitivity->constraints[cidx].low = low;
				sensitivity->constraints[cidx].high = high;
			}
		}
		
		g_strfreev (items);
		g_strfreev (items2);

	}

	g_object_unref (tl);

	// ----------------------------------------
done:
	gnm_solver_set_status (sol, GNM_SOLVER_STATUS_DONE);
	g_object_set (subsol, "result", result, NULL);
	g_object_unref (result);
	g_object_set (subsol, "sensitivity", sensitivity, NULL);
	g_object_unref (sensitivity);

	return;

fail:
	if (tl)
		g_object_unref (tl);
	if (result)
		g_object_unref (result);
	if (sensitivity)
		g_object_unref (sensitivity);
	gnm_solver_set_status (sol, GNM_SOLVER_STATUS_ERROR);
}
Esempio n. 14
0
static gboolean
ibus_keymap_parse_line (gchar  *str,
                        KEYMAP  keymap)
{
    gchar *p1, *p2;
    gint i;
    guint keycode;
    guint keysym;

    const struct {
        const gchar *prefix;
        const gint len;
    } prefix [] = {
        { "keycode ", sizeof ("keycode ") - 1 },
        { "shift keycode ", sizeof ("shift keycode ") - 1 },
        { "capslock keycode ", sizeof ("capslock keycode ") - 1 },
        { "shift capslock keycode ", sizeof ("shift capslock keycode ") - 1 },
        { "altgr keycode ", sizeof ("altgr keycode ") - 1},
        { "shift altgr keycode ", sizeof ("shift altgr keycode ") - 1},
        { "numlock keycode ", sizeof ("numlock keycode ") - 1},
    };

    p1 = str;

    SKIP_SPACE(p1);

    if (*p1 == '#')
        return TRUE;

    if (strncmp (p1, "include ", sizeof ("include ") - 1) == 0) {
        p1 += sizeof ("include ") - 1;
        for (p2 = p1; *p2 != '\n'; p2++);
        *p2 = '\0';
        return ibus_keymap_load (p1, keymap);
    }

    for (i = 0; i < sizeof (prefix) / sizeof (prefix[0]); i++) {
        if (strncmp (p1, prefix[i].prefix, prefix[i].len) == 0) {
            p1 += prefix[i].len;
            break;
        }
    }

    if (i >= sizeof (prefix) / sizeof (prefix[0]))
        return FALSE;

    keycode = (guint) strtoul (p1, &p2, 10);

    if (keycode == 0 && p1 == p2)
        return FALSE;

    if (keycode < 0 || keycode > 255)
        return FALSE;

    p1 = p2;

    if (*p1++ != ' ')
        return FALSE;
    if (*p1++ != '=')
        return FALSE;
    if (*p1++ != ' ')
        return FALSE;

    for (p2 = p1; *p2 != '\n' && *p2 != ' '; p2++);
    *p2 = '\0'; p2++;

    keysym = ibus_keyval_from_name (p1);

    if (keysym == IBUS_VoidSymbol)
        return FALSE;

    if (i == 0 &&
        strncmp (p2, "addupper", sizeof ("addupper") - 1) == 0 &&
        g_ascii_isalpha (*p1)) {
        gchar buf[] = "a";
        buf[0] = g_ascii_toupper(*p1);
        keymap[keycode][0] = keymap[keycode][3] = keysym;
        keymap[keycode][1] = keymap[keycode][2] = ibus_keyval_from_name (buf);

    }
    else {
        keymap[keycode][i] = keysym;
    }

    return TRUE;
}
Esempio n. 15
0
bool
AsxTokenizer::is_name_char (char c)
{
	return g_ascii_isalpha (c);
}
Esempio n. 16
0
static gboolean
parse_comment_frame (ID3TagsWorking * work)
{
  guint dummy;
  guint8 encoding;
  gchar language[4];
  GArray *fields = NULL;
  gchar *description, *text;

  if (work->parse_size < 6)
    return FALSE;

  encoding = work->parse_data[0];
  language[0] = g_ascii_tolower (work->parse_data[1]);
  language[1] = g_ascii_tolower (work->parse_data[2]);
  language[2] = g_ascii_tolower (work->parse_data[3]);
  language[3] = '\0';

  parse_split_strings (encoding, (gchar *) work->parse_data + 4,
      work->parse_size - 4, &fields);

  if (fields == NULL || fields->len < 2) {
    GST_WARNING ("Failed to decode comment frame");
    goto fail;
  }
  description = g_array_index (fields, gchar *, 0);
  text = g_array_index (fields, gchar *, 1);

  if (!g_utf8_validate (text, -1, NULL)) {
    GST_WARNING ("Converted string is not valid utf-8");
    goto fail;
  }

  /* skip our own dummy descriptions (from id3v2mux) */
  if (strlen (description) > 0 && g_utf8_validate (description, -1, NULL) &&
      sscanf (description, "c%u", &dummy) != 1) {
    gchar *s;

    /* must be either an ISO-639-1 or ISO-639-2 language code */
    if (language[0] != '\0' &&
        g_ascii_isalpha (language[0]) &&
        g_ascii_isalpha (language[1]) &&
        (g_ascii_isalpha (language[2]) || language[2] == '\0')) {
      const gchar *lang_code;

      /* prefer two-letter ISO 639-1 code if we have a mapping */
      lang_code = gst_tag_get_language_code (language);
      s = g_strdup_printf ("%s[%s]=%s", description,
          (lang_code) ? lang_code : language, text);
    } else {
      s = g_strdup_printf ("%s=%s", description, text);
    }
    gst_tag_list_add (work->tags, GST_TAG_MERGE_APPEND,
        GST_TAG_EXTENDED_COMMENT, s, NULL);
    g_free (s);
  } else if (text != NULL && *text != '\0') {
    gst_tag_list_add (work->tags, GST_TAG_MERGE_APPEND,
        GST_TAG_COMMENT, text, NULL);
  } else {
    goto fail;
  }

  free_tag_strings (fields);
  return TRUE;

fail:
  {
    GST_WARNING ("failed to parse COMM frame");
    free_tag_strings (fields);
    return FALSE;
  }
}
Esempio n. 17
0
static gboolean
omicron_read_header(gchar *buffer,
                    OmicronFile *ofile,
                    GError **error)
{
    gchar *line, *val, *comment;

    ofile->meta = g_hash_table_new(g_str_hash, g_str_equal);

    while ((line = gwy_str_next_line(&buffer))) {
        /* FIXME: This strips 2nd and following lines from possibly multiline
         * fields like Comment. */
        if (!line[0] || line[0] == ';' || g_ascii_isspace(line[0]))
            continue;

        val = strchr(line, ':');
        if (!val) {
            g_set_error(error, GWY_MODULE_FILE_ERROR,
                        GWY_MODULE_FILE_ERROR_DATA,
                        _("Missing colon in header line."));
            return FALSE;
        }
        if (val == line) {
            g_set_error(error, GWY_MODULE_FILE_ERROR,
                        GWY_MODULE_FILE_ERROR_DATA,
                        _("Header line starts with a colon."));
            return FALSE;
        }
        *val = '\0';
        val++;
        g_strstrip(line);
        comment = strchr(val, ';');
        if (comment) {
            /* If the coment has the form ;[units], move the [units] part after
             * the number. */
            if (comment[1] == '[' && (g_ascii_isalpha(comment[2])
                                      || comment[2] == '%')) {
                gchar *c, *s = comment-1;

                while (g_ascii_isspace(*s))
                    s--;
                s++;

                c = comment + 1;
                *c = ' ';
                while (*c && *c != ']')
                    *(s++) = *(c++);
                *s = '\0';
            }
            else
                *comment = '\0';
            comment++;
            g_strstrip(comment);
        }
        g_strstrip(val);

        if (gwy_strequal(line, "Topographic Channel")) {
            OmicronTopoChannel *channel;

            gwy_debug("Topographic Channel found (type %c)", val[0]);
            channel = g_new0(OmicronTopoChannel, 1);
            channel->type = val[0];
            if (!omicron_read_topo_header(&buffer, channel, error)) {
                g_free(channel);
                return FALSE;
            }
            if (!ofile->topo_channels)
                ofile->topo_channels = g_ptr_array_new();
            g_ptr_array_add(ofile->topo_channels, channel);
        }
        else if (gwy_strequal(line, "Spectroscopy Channel")) {
            OmicronSpectroChannel *channel;

            gwy_debug("Spectroscopic Channel found (chan %s)", val);

            channel = g_new0(OmicronSpectroChannel, 1);
            channel->chan = val;
            if (!omicron_read_spectro_header(&buffer, channel, error)) {
                g_free(channel);
                return FALSE;
            }
            if (!ofile->spectro_channels)
                ofile->spectro_channels = g_ptr_array_new();
            g_ptr_array_add(ofile->spectro_channels, channel);

        }
        else {
            gwy_debug("<%s> = <%s>", line, val);
            g_hash_table_insert(ofile->meta, line, val);
        }
    }

    GET_FIELD(ofile->meta, val, "Image Size in X", error);
    ofile->xres = abs(atoi(val));
    GET_FIELD(ofile->meta, val, "Image Size in Y", error);
    ofile->yres = abs(atoi(val));
    if (err_DIMENSION(error, ofile->xres)
        || err_DIMENSION(error, ofile->yres))
        return FALSE;

    GET_FIELD(ofile->meta, val, "Field X Size in nm", error);
    ofile->xreal = g_ascii_strtod(val, NULL);
    GET_FIELD(ofile->meta, val, "Field Y Size in nm", error);
    ofile->yreal = g_ascii_strtod(val, NULL);
    /* Use negated positive conditions to catch NaNs */
    if (!((ofile->xreal = fabs(ofile->xreal)) > 0)) {
        g_warning("Real x size is 0.0, fixing to 1.0");
        ofile->xreal = 1.0;
    }
    if (!((ofile->yreal = fabs(ofile->yreal)) > 0)) {
        g_warning("Real y size is 0.0, fixing to 1.0");
        ofile->yreal = 1.0;
    }
    ofile->xreal *= Nanometer;
    ofile->yreal *= Nanometer;

    return TRUE;
}
Esempio n. 18
0
static void
rspamd_html_parse_tag_content (rspamd_mempool_t *pool,
		struct html_content *hc, struct html_tag *tag, const guchar *in,
		gint *statep, guchar const **savep)
{
	enum {
		parse_start = 0,
		parse_name,
		parse_attr_name,
		parse_equal,
		parse_start_dquote,
		parse_dqvalue,
		parse_end_dquote,
		parse_start_squote,
		parse_sqvalue,
		parse_end_squote,
		parse_value,
		spaces_after_name,
		spaces_before_eq,
		spaces_after_eq,
		spaces_after_param,
		ignore_bad_tag
	} state;
	struct html_tag_def *found;
	gboolean store = FALSE;
	struct html_tag_component *comp;

	state = *statep;

	switch (state) {
	case parse_start:
		if (!g_ascii_isalpha (*in) && !g_ascii_isspace (*in)) {
			hc->flags |= RSPAMD_HTML_FLAG_BAD_ELEMENTS;
			state = ignore_bad_tag;
		}
		else if (g_ascii_isalpha (*in)) {
			state = parse_name;
			tag->name.start = in;
		}
		break;

	case parse_name:
		if (g_ascii_isspace (*in) || *in == '>' || *in == '/') {
			g_assert (in >= tag->name.start);

			if (*in == '/') {
				tag->flags |= FL_CLOSED;
			}

			tag->name.len = in - tag->name.start;

			if (tag->name.len == 0) {
				hc->flags |= RSPAMD_HTML_FLAG_BAD_ELEMENTS;
				tag->flags |= FL_BROKEN;
				state = ignore_bad_tag;
			}
			else {
				/* We can safely modify tag's name here, as it is already parsed */
				tag->name.len = rspamd_html_decode_entitles_inplace (
						(gchar *)tag->name.start,
						tag->name.len);

				found = bsearch (tag, tag_defs, G_N_ELEMENTS (tag_defs),
					sizeof (tag_defs[0]), tag_find);
				if (found == NULL) {
					hc->flags |= RSPAMD_HTML_FLAG_UNKNOWN_ELEMENTS;
					tag->id = -1;
				}
				else {
					tag->id = found->id;
					tag->flags = found->flags;
				}
				state = spaces_after_name;
			}
		}
		break;

	case parse_attr_name:
		if (*savep == NULL) {
			state = ignore_bad_tag;
		}
		else {
			if (*in == '=') {
				state = parse_equal;
			}
			else if (g_ascii_isspace (*in)) {
				state = spaces_before_eq;
			}
			else if (*in == '/') {
				tag->flags |= FL_CLOSED;
			}
			else {
				return;
			}

			if (!rspamd_html_parse_tag_component (pool, *savep, in, tag)) {
				/* Ignore unknown params */
				*savep = NULL;
			}
		}

		break;

	case spaces_after_name:
		if (!g_ascii_isspace (*in)) {
			*savep = in;
			if (*in == '/') {
				tag->flags |= FL_CLOSED;
			}
			else if (*in != '>') {
				state = parse_attr_name;
			}
		}
		break;

	case spaces_before_eq:
		if (*in == '=') {
			state = parse_equal;
		}
		else if (!g_ascii_isspace (*in)) {
			hc->flags |= RSPAMD_HTML_FLAG_BAD_ELEMENTS;
			tag->flags |= FL_BROKEN;
			state = ignore_bad_tag;
		}
		break;

	case spaces_after_eq:
		if (*in == '"') {
			state = parse_start_dquote;
		}
		else if (*in == '\'') {
			state = parse_start_squote;
		}
		else if (!g_ascii_isspace (*in)) {
			if (*savep != NULL) {
				/* We need to save this param */
				*savep = in;
			}
			state = parse_value;
		}
		break;

	case parse_equal:
		if (g_ascii_isspace (*in)) {
			state = spaces_after_eq;
		}
		else if (*in == '"') {
			state = parse_start_dquote;
		}
		else if (*in == '\'') {
			state = parse_start_squote;
		}
		else {
			if (*savep != NULL) {
				/* We need to save this param */
				*savep = in;
			}
			state = parse_value;
		}
		break;

	case parse_start_dquote:
		if (*in == '"') {
			if (*savep != NULL) {
				/* We have an empty attribute value */
				savep = NULL;
			}
			state = spaces_after_param;
		}
		else {
			if (*savep != NULL) {
				/* We need to save this param */
				*savep = in;
			}
			state = parse_dqvalue;
		}
		break;

	case parse_start_squote:
		if (*in == '\'') {
			if (*savep != NULL) {
				/* We have an empty attribute value */
				savep = NULL;
			}
			state = spaces_after_param;
		}
		else {
			if (*savep != NULL) {
				/* We need to save this param */
				*savep = in;
			}
			state = parse_sqvalue;
		}
		break;

	case parse_dqvalue:
		if (*in == '"') {
			store = TRUE;
			state = parse_end_dquote;
		}
		if (store) {
			if (*savep != NULL) {
				g_assert (tag->params != NULL);
				comp = g_queue_peek_tail (tag->params);
				g_assert (comp != NULL);
				comp->len = in - *savep;
				comp->start = *savep;
				comp->len = rspamd_html_decode_entitles_inplace ((gchar *)*savep,
						comp->len);
				*savep = NULL;
			}
		}
		break;

	case parse_sqvalue:
		if (*in == '\'') {
			store = TRUE;
			state = parse_end_squote;
		}
		if (store) {
			if (*savep != NULL) {
				g_assert (tag->params != NULL);
				comp = g_queue_peek_tail (tag->params);
				g_assert (comp != NULL);
				comp->len = in - *savep;
				comp->start = *savep;
				comp->len = rspamd_html_decode_entitles_inplace ((gchar *)*savep,
						comp->len);
				*savep = NULL;
			}
		}
		break;

	case parse_value:
		if (*in == '/' && *(in + 1) == '>') {
			tag->flags |= FL_CLOSED;
			store = TRUE;
		}
		else if (g_ascii_isspace (*in) || *in == '>') {
			store = TRUE;
			state = spaces_after_param;
		}

		if (store) {
			if (*savep != NULL) {
				g_assert (tag->params != NULL);
				comp = g_queue_peek_tail (tag->params);
				g_assert (comp != NULL);
				comp->len = in - *savep;
				comp->start = *savep;
				comp->len = rspamd_html_decode_entitles_inplace ((gchar *)*savep,
						comp->len);
				*savep = NULL;
			}
		}
		break;

	case parse_end_dquote:
	case parse_end_squote:
		if (g_ascii_isspace (*in)) {
			state = spaces_after_param;
		}
		break;

	case spaces_after_param:
		if (!g_ascii_isspace (*in)) {
			state = parse_attr_name;
			*savep = in;
		}
		break;

	case ignore_bad_tag:
		break;
	}

	*statep = state;
}
Esempio n. 19
0
gint
mbus_list_read( MObject * mlist, const guchar * buf )
{
  MList *	list;
  gint		len = 0;

  M_OBJECT_ASSERT( mlist, MLIST );
  list = M_LIST( mlist );
  len += __first_non_whitespace( ( gchar * ) buf );
  /* beginning of list */

  if ( buf[ len++ ] == '(' ) {
    const guchar *	start = &( buf[ len - 1 ] );
    guchar *		pos = ( guchar * ) ( start + 1 );
    guchar *		end = NULL;
    MObject *		obj = NULL;

    while ( *pos != '\0' && *pos != ')' ) {
      pos += __first_non_whitespace( ( gchar * ) pos );
      if ( *pos == '\0' || *pos == ')' ) break;
      if ( *pos == '"' ) {
	/* string */
	end = mbus_util_find_char( ++pos, '"' );
	if ( end ) {
	  *end = '\0';
	  obj = mbus_string_new( ( gchar * ) pos );
	} else
	  goto failed;
      } else if ( *pos == '<' ) {
	/* data */
	end = mbus_util_find_char( ++pos, '>' );
	if ( end ) {
	  *end = '\0';
	  obj = mbus_data_new( pos, ( gint ) ( end - pos ), TRUE );
	} else
	  goto failed;
      } else if ( *pos == '(' ) {
	/* list */
	gint len;

	obj = mbus_list_new();
	len = mbus_list_read( obj, pos );
        end = pos + len - 1;
      } else if ( g_ascii_isdigit( *pos ) || *pos == '-' ) {
	/* number */
	end = pos + 1;
	while ( *end != ' ' && *end != '\n' && *end != '\0' ) ++end;
	*end = '\0';
        if ( mbus_util_find_char( pos + 1, '.' ) ) {
          gdouble d = g_ascii_strtod( ( gchar * ) pos, NULL );
          obj = mbus_float_new( d );
        } else {
          gint64 i = ( gint64 ) g_ascii_strtoull( ( gchar * ) pos,
						  ( char ** ) NULL, 10 );
          obj = mbus_integer_new( i );
        }
      } else if ( g_ascii_isalpha( *pos ) && g_ascii_isupper( *pos ) ) {
	end = mbus_util_find_char( pos, ' ' );
	if ( end ) {
	  *end = '\0';
	  obj = mbus_symbol_new( ( gchar * ) pos );
          if ( !obj ) goto failed;
	} else
	  goto failed;
      }

      pos = ++end;

      list->list = g_slist_append( list->list, obj );
    }
    mlist->ok = TRUE;
    return ( pos - start + 1 );
  }

 failed:
  mlist->ok = FALSE;
  return -1;
}
Esempio n. 20
0
static cb_ret_t
dlg_try_hotkey (WDialog * h, int d_key)
{
    GList *hot_cur;
    Widget *current;
    cb_ret_t handled;
    int c;

    if (h->widgets == NULL)
        return MSG_NOT_HANDLED;

    if (h->current == NULL)
        h->current = h->widgets;

    /*
     * Explanation: we don't send letter hotkeys to other widgets if
     * the currently selected widget is an input line
     */

    current = WIDGET (h->current->data);

    if (widget_get_state (current, WST_DISABLED))
        return MSG_NOT_HANDLED;

    if (widget_get_options (current, WOP_IS_INPUT))
    {
        /* skip ascii control characters, anything else can valid character in
         * some encoding */
        if (d_key >= 32 && d_key < 256)
            return MSG_NOT_HANDLED;
    }

    /* If it's an alt key, send the message */
    c = d_key & ~ALT (0);
    if (d_key & ALT (0) && g_ascii_isalpha (c))
        d_key = g_ascii_tolower (c);

    handled = MSG_NOT_HANDLED;
    if (widget_get_options (current, WOP_WANT_HOTKEY))
        handled = send_message (current, NULL, MSG_HOTKEY, d_key, NULL);

    /* If not used, send hotkey to other widgets */
    if (handled == MSG_HANDLED)
        return MSG_HANDLED;

    hot_cur = dlg_get_widget_next_of (h->current);

    /* send it to all widgets */
    while (h->current != hot_cur && handled == MSG_NOT_HANDLED)
    {
        current = WIDGET (hot_cur->data);

        if (widget_get_options (current, WOP_WANT_HOTKEY)
            && !widget_get_state (current, WST_DISABLED))
            handled = send_message (current, NULL, MSG_HOTKEY, d_key, NULL);

        if (handled == MSG_NOT_HANDLED)
            hot_cur = dlg_get_widget_next_of (hot_cur);
    }

    if (handled == MSG_HANDLED)
        widget_select (WIDGET (hot_cur->data));

    return handled;
}
Esempio n. 21
0
static gboolean
check_part (struct rspamd_mime_text_part *part, gboolean raw_mode)
{
	guchar *p, *p1;
	gunichar c, t;
	GUnicodeScript scc, sct;
	guint32 mark = 0, total = 0, max = 0, i;
	guint32 remain = part->content->len;
	guint32 scripts[G_UNICODE_SCRIPT_NKO];
	GUnicodeScript sel = 0;

	p = part->content->data;

	if (IS_PART_UTF (part) || raw_mode) {
		while (remain > 1) {
			if ((g_ascii_isalpha (*p) &&
				(*(p + 1) & 0x80)) ||
				((*p & 0x80) && g_ascii_isalpha (*(p + 1)))) {
				mark++;
				total++;
			}
			/* Current and next symbols are of one class */
			else if (((*p & 0x80) &&
				(*(p + 1) & 0x80)) ||
				(g_ascii_isalpha (*p) && g_ascii_isalpha (*(p + 1)))) {
				total++;
			}
			p++;
			remain--;
		}
	}
	else {
		memset (&scripts, 0, sizeof (scripts));
		while (remain > 0) {
			c = g_utf8_get_char_validated (p, remain);
			if (c == (gunichar) - 2 || c == (gunichar) - 1) {
				/* Invalid characters detected, stop processing */
				return FALSE;
			}

			scc = g_unichar_get_script (c);
			if (scc < (gint)G_N_ELEMENTS (scripts)) {
				scripts[scc]++;
			}
			p1 = g_utf8_next_char (p);
			remain -= p1 - p;
			p = p1;

			if (remain > 0) {
				t = g_utf8_get_char_validated (p, remain);
				if (t == (gunichar) - 2 || t == (gunichar) - 1) {
					/* Invalid characters detected, stop processing */
					return FALSE;
				}
				sct = g_unichar_get_script (t);
				if (g_unichar_isalpha (c) && g_unichar_isalpha (t)) {
					/* We have two unicode alphanumeric characters, so we can check its script */
					if (sct != scc) {
						mark++;
					}
					total++;
				}
				p1 = g_utf8_next_char (p);
				remain -= p1 - p;
				p = p1;
			}
		}
		/* Detect the mostly charset of this part */
		for (i = 0; i < G_N_ELEMENTS (scripts); i++) {
			if (scripts[i] > max) {
				max = scripts[i];
				sel = i;
			}
		}
		part->script = sel;
	}

	if (total == 0) {
		return 0;
	}

	return ((double)mark / (double)total) > chartable_module_ctx->threshold;
}
TotemPlParserResult
totem_pl_parser_add_m3u (TotemPlParser *parser,
			 GFile *file,
			 GFile *base_file,
			 TotemPlParseData *parse_data,
			 gpointer data)
{
	TotemPlParserResult retval = TOTEM_PL_PARSER_RESULT_UNHANDLED;
	char *contents, **lines;
	gsize size;
	guint i, num_lines;
	gboolean dos_mode = FALSE;
	const char *extinfo, *extvlcopt_audiotrack;
	char *pl_uri;

	if (g_file_load_contents (file, NULL, &contents, &size, NULL, NULL) == FALSE) {
		DEBUG (file, g_print ("Failed to load '%s'\n", uri));
		return TOTEM_PL_PARSER_RESULT_ERROR;
	}

	/* .pls files with a .m3u extension, the nasties */
	if (g_str_has_prefix (contents, "[playlist]") != FALSE
			|| g_str_has_prefix (contents, "[Playlist]") != FALSE
			|| g_str_has_prefix (contents, "[PLAYLIST]") != FALSE) {
		DEBUG (file, g_print ("Parsing '%s' playlist as PLS\n", uri));
		retval = totem_pl_parser_add_pls_with_contents (parser, file, base_file, contents, parse_data);
		g_free (contents);
		return retval;
	}

	if (strstr (contents, EXTINF_HLS) ||
	    strstr (contents, EXTINF_HLS2)) {
		DEBUG (file, g_print ("Unhandled HLS playlist '%s', should be passed to player\n", uri));
		g_free (contents);
		return retval;
	}

	/* Try to use ISO-8859-1 if we don't have valid UTF-8,
	 * try to parse anyway if it's not ISO-8859-1 */
	if (g_utf8_validate (contents, -1, NULL) == FALSE) {
		char *fixed;
		fixed = g_convert (contents, -1, "UTF-8", "ISO8859-1", NULL, NULL, NULL);
		if (fixed != NULL) {
			g_free (contents);
			contents = fixed;
		}
	}

	/* is non-NULL if there's an EXTINF on a preceding line */
	extinfo = NULL;
	extvlcopt_audiotrack = NULL;

	/* figure out whether we're a unix m3u or dos m3u */
	if (strstr(contents, "\x0d")) {
		dos_mode = TRUE;
	}

	lines = g_strsplit_set (contents, "\r\n", 0);
	g_free (contents);
	num_lines = g_strv_length (lines);
	/* We don't count the terminating NULL */
	num_lines--;

	/* Send out the playlist start and get crackin' */
	pl_uri = g_file_get_uri (file);
	totem_pl_parser_add_uri (parser,
				 TOTEM_PL_PARSER_FIELD_IS_PLAYLIST, TRUE,
				 TOTEM_PL_PARSER_FIELD_URI, pl_uri,
				 TOTEM_PL_PARSER_FIELD_CONTENT_TYPE, "audio/x-mpegurl",
				 NULL);

	for (i = 0; lines[i] != NULL; i++) {
		const char *line;
		char *length;
		gint64 length_num = 0;
		char *audio_track;

		line = lines[i];

		if (line[0] == '\0')
			continue;

		retval = TOTEM_PL_PARSER_RESULT_SUCCESS;

		/* Ignore leading spaces */
		for (; g_ascii_isspace (line[0]); line++)
			;

		/* Ignore comments, but mark it if we have extra info */
		if (line[0] == '#') {
			if (extinfo == NULL && g_str_has_prefix (line, EXTINF) != FALSE)
				extinfo = line;
			if (extvlcopt_audiotrack == NULL && g_str_has_prefix (line, EXTVLCOPT_AUDIOTRACK) != FALSE)
				extvlcopt_audiotrack = line;
			continue;
		}

		length = totem_pl_parser_get_extinfo_length (extinfo);
		if (length != NULL)
			length_num = totem_pl_parser_parse_duration (length, totem_pl_parser_is_debugging_enabled (parser));
		g_free (length);

		audio_track = totem_pl_parser_get_extvlcopt_audio_track (extvlcopt_audiotrack);

		/* Either it's a URI, or it has a proper path ... */
		if (strstr(line, "://") != NULL
				|| line[0] == G_DIR_SEPARATOR) {
			GFile *uri;

			uri = g_file_new_for_commandline_arg (line);
			if (length_num < 0 ||
			    totem_pl_parser_parse_internal (parser, uri, NULL, parse_data) != TOTEM_PL_PARSER_RESULT_SUCCESS) {
				totem_pl_parser_add_uri (parser,
							 TOTEM_PL_PARSER_FIELD_URI, line,
							 TOTEM_PL_PARSER_FIELD_TITLE, totem_pl_parser_get_extinfo_title (extinfo),
							 TOTEM_PL_PARSER_FIELD_AUDIO_TRACK, audio_track,
							 NULL);
			}
			g_object_unref (uri);
		} else if (g_ascii_isalpha (line[0]) != FALSE
			   && g_str_has_prefix (line + 1, ":\\")) {
			/* Path relative to a drive on Windows, we need to use
			 * the base that was passed to us */
			GFile *uri;

			lines[i] = g_strdelimit (lines[i], "\\", '/');
			/* + 2, skip drive letter */
			uri = g_file_get_child (base_file, line + 2);
			totem_pl_parser_add_uri (parser,
						 TOTEM_PL_PARSER_FIELD_FILE, uri,
						 TOTEM_PL_PARSER_FIELD_TITLE, totem_pl_parser_get_extinfo_title (extinfo),
						 TOTEM_PL_PARSER_FIELD_AUDIO_TRACK, audio_track,
						 NULL);
			g_object_unref (uri);
		} else if (line[0] == '\\' && line[1] == '\\') {
			/* ... Or it's in the windows smb form
			 * (\\machine\share\filename), Note drive names
			 * (C:\ D:\ etc) are unhandled (unknown base for
			 * drive letters) */
		        char *tmpuri;

			lines[i] = g_strdelimit (lines[i], "\\", '/');
			tmpuri = g_strjoin (NULL, "smb:", line, NULL);

			totem_pl_parser_add_uri (parser,
						 TOTEM_PL_PARSER_FIELD_URI, tmpuri,
						 TOTEM_PL_PARSER_FIELD_TITLE, totem_pl_parser_get_extinfo_title (extinfo),
						 TOTEM_PL_PARSER_FIELD_AUDIO_TRACK, audio_track,
						 NULL);

			g_free (tmpuri);
		} else {
			/* Try with a base */
			GFile *uri, *_base_file;
			char sep;

			_base_file = g_file_get_parent (file);
			sep = (dos_mode ? '\\' : '/');
			if (sep == '\\')
				lines[i] = g_strdelimit (lines[i], "\\", '/');
			uri = g_file_get_child (_base_file, line);
			g_object_unref (_base_file);
			totem_pl_parser_add_uri (parser,
						 TOTEM_PL_PARSER_FIELD_FILE, uri,
						 TOTEM_PL_PARSER_FIELD_TITLE, totem_pl_parser_get_extinfo_title (extinfo),
						 TOTEM_PL_PARSER_FIELD_AUDIO_TRACK, audio_track,
						 NULL);
			g_object_unref (uri);
		}
		extinfo = NULL;
		extvlcopt_audiotrack = NULL;

		g_free (audio_track);
	}

	g_strfreev (lines);

	totem_pl_parser_playlist_end (parser, pl_uri);
	g_free (pl_uri);

	return retval;
}
Esempio n. 23
0
File: dialog.c Progetto: ryanlee/mc
static cb_ret_t
dlg_try_hotkey (Dlg_head * h, int d_key)
{
    GList *hot_cur;
    Widget *current;
    cb_ret_t handled;
    int c;

    if (h->widgets == NULL)
        return MSG_NOT_HANDLED;

    if (h->current == NULL)
        h->current = h->widgets;

    /*
     * Explanation: we don't send letter hotkeys to other widgets if
     * the currently selected widget is an input line
     */

    current = (Widget *) h->current->data;

    if ((current->options & W_DISABLED) != 0)
        return MSG_NOT_HANDLED;

    if (current->options & W_IS_INPUT)
    {
        /* skip ascii control characters, anything else can valid character in
         * some encoding */
        if (d_key >= 32 && d_key < 256)
            return MSG_NOT_HANDLED;
    }

    /* If it's an alt key, send the message */
    c = d_key & ~ALT (0);
    if (d_key & ALT (0) && g_ascii_isalpha (c))
        d_key = g_ascii_tolower (c);

    handled = MSG_NOT_HANDLED;
    if ((current->options & W_WANT_HOTKEY) != 0)
        handled = send_message (current, WIDGET_HOTKEY, d_key);

    /* If not used, send hotkey to other widgets */
    if (handled == MSG_HANDLED)
        return MSG_HANDLED;

    hot_cur = dlg_widget_next (h, h->current);

    /* send it to all widgets */
    while (h->current != hot_cur && handled == MSG_NOT_HANDLED)
    {
        current = (Widget *) hot_cur->data;

        if ((current->options & W_WANT_HOTKEY) != 0 && (current->options & W_DISABLED) == 0)
            handled = send_message (current, WIDGET_HOTKEY, d_key);

        if (handled == MSG_NOT_HANDLED)
            hot_cur = dlg_widget_next (h, hot_cur);
    }

    if (handled == MSG_HANDLED)
        do_select_widget (h, hot_cur, SELECT_EXACT);

    return handled;
}
static gboolean
parse_variable (const gchar  *line,
                glong        *n,
                gchar       **inner,
                const gchar **endptr,
                gchar       **name)
{
  gboolean has_inner = FALSE;
  char *end = NULL;
  gint brackets;
  gint i;

  *n = -1;
  *inner = NULL;
  *endptr = NULL;
  *name = NULL;

  g_assert (*line == '$');

  line++;

  *endptr = line;

  if (!*line)
    {
      *endptr = NULL;
      return FALSE;
    }

  if (*line == '{')
    {
      has_inner = TRUE;
      line++;
    }

  if (g_ascii_isdigit (*line))
    {
      errno = 0;
      *n = strtol (line, &end, 10);
      if (((*n == LONG_MIN) || (*n == LONG_MAX)) && errno == ERANGE)
        return FALSE;
      else if (*n < 0)
        return FALSE;
      line = end;
    }
  else if (g_ascii_isalpha (*line))
    {
      const gchar *cur;

      for (cur = line; *cur; cur++)
        {
          if (g_ascii_isalnum (*cur))
            continue;
          break;
        }
      *endptr = cur;
      *name = g_strndup (line, cur - line);
      *n = -2;
      return TRUE;
    }

  if (has_inner)
    {
      if (*line == ':')
        line++;

      brackets = 1;

      for (i = 0; line[i]; i++)
        {
          switch (line[i])
            {
            case '{':
              brackets++;
              break;

            case '}':
              brackets--;
              break;

            default:
              break;
            }

          if (!brackets)
            {
              *inner = g_strndup (line, i);
              *endptr = &line[i + 1];
              return TRUE;
            }
        }

      return FALSE;
    }

  *endptr = line;

  return TRUE;
}
Esempio n. 25
0
DejaDupDecodedUri *
deja_dup_decoded_uri_decode_uri (const char *uri)
{
  DejaDupDecodedUri *decoded;
  const char *p, *in, *hier_part_start, *hier_part_end, *query_start, *fragment_start;
  char *out;
  char c;

  /* From RFC 3986 Decodes:
   * URI         = scheme ":" hier-part [ "?" query ] [ "#" fragment ]
   */ 

  p = uri;
  
  /* Decode scheme:
     scheme      = ALPHA *( ALPHA / DIGIT / "+" / "-" / "." )
  */

  if (!g_ascii_isalpha (*p))
    return NULL;

  while (1)
    {
      c = *p++;

      if (c == ':')
        break;
      
      if (!(g_ascii_isalnum(c) ||
            c == '+' ||
            c == '-' ||
            c == '.'))
        return NULL;
    }

  decoded = deja_dup_decoded_uri_new ();
  
  decoded->scheme = g_malloc (p - uri);
  out = decoded->scheme;
  for (in = uri; in < p - 1; in++)
    *out++ = g_ascii_tolower (*in);
  *out = 0;

  hier_part_start = p;

  query_start = strchr (p, '?');
  if (query_start)
    {
      hier_part_end = query_start++;
      fragment_start = strchr (query_start, '#');
      if (fragment_start)
        {
          decoded->query = g_strndup (query_start, fragment_start - query_start);
          decoded->fragment = g_strdup (fragment_start+1);
        }
      else
        {
          decoded->query = g_strdup (query_start);
          decoded->fragment = NULL;
        }
    }
  else
    {
      /* No query */
      decoded->query = NULL;
      fragment_start = strchr (p, '#');
      if (fragment_start)
        {
          hier_part_end = fragment_start++;
          decoded->fragment = g_strdup (fragment_start);
        }
      else
        {
          hier_part_end = p + strlen (p);
          decoded->fragment = NULL;
        }
    }

  /*  3:
      hier-part   = "//" authority path-abempty
                  / path-absolute
                  / path-rootless
                  / path-empty

  */

  if (hier_part_start[0] == '/' &&
      hier_part_start[1] == '/')
    {
      const char *authority_start, *authority_end;
      const char *userinfo_start, *userinfo_end;
      const char *host_start, *host_end;
      const char *port_start;
      
      authority_start = hier_part_start + 2;
      /* authority is always followed by / or nothing */
      authority_end = memchr (authority_start, '/', hier_part_end - authority_start);
      if (authority_end == NULL)
        authority_end = hier_part_end;

      /* 3.2:
              authority   = [ userinfo "@" ] host [ ":" port ]
      */

      /* Look for the last so that any multiple @ signs are put in the username part.
       * This is not quite correct, as @ should be escaped here, but this happens
       * in practice, so lets handle it the "nicer" way at least. */
      userinfo_end = g_strrstr_len (authority_start,
                                    authority_end - authority_start, "@");
      if (userinfo_end)
        {
          userinfo_start = authority_start;
          decoded->userinfo = g_uri_unescape_segment (userinfo_start, userinfo_end, NULL);
          if (decoded->userinfo == NULL)
            {
              deja_dup_decoded_uri_free (decoded);
              return NULL;
            }
          host_start = userinfo_end + 1;
        }
      else
        host_start = authority_start;

      /* We should handle hostnames in brackets, as those are used by IPv6 URIs
       * See http://tools.ietf.org/html/rfc2732 */
      if (*host_start == '[')
        {
          char *s;

          port_start = NULL;
          host_end = memchr (host_start, ']', authority_end - host_start);
          if (host_end == NULL)
            {
              deja_dup_decoded_uri_free (decoded);
              return NULL;
            }

          /* Look for the start of the port,
           * And we sure we don't have it start somewhere
           * in the path section */
          s = (char *) host_end;
          while (1)
            {
              if (*s == '/')
                {
                  port_start = NULL;
                  break;
                }
              else if (*s == ':')
                {
                  port_start = s;
                  break;
                }
              else if (*s == '\0')
                {
                  break;
                }

              s++;
            }
        }
      else
        {
          port_start = memchr (host_start, ':', authority_end - host_start);
        }

      if (port_start)
        {
          host_end = port_start++;

          decoded->port = atoi(port_start);
        }
      else
        {
          host_end = authority_end;
          decoded->port = -1;
        }

      decoded->host = g_uri_unescape_segment (host_start, host_end, NULL);

      hier_part_start = authority_end;
    }

  decoded->path = g_uri_unescape_segment (hier_part_start, hier_part_end, "/");

  if (decoded->path == NULL)
    {
      deja_dup_decoded_uri_free (decoded);
      return NULL;
    }
  
  return decoded;
}
Esempio n. 26
0
/* Entry containing domain name which may be added to list has changed */
static void _nojs_preferences_on_add_domain_entry_changed(NoJSPreferences *self,
															GtkEditable *inEditable)
{
	NoJSPreferencesPrivate	*priv=self->priv;
	gchar					*asciiDomain, *checkAsciiDomain;
	gchar					*asciiDomainStart, *asciiDomainEnd;
	gint					dots;
	gboolean				isValid=FALSE;

	/* Get ASCII representation of domain name entered */
	asciiDomain=g_hostname_to_ascii(gtk_entry_get_text(GTK_ENTRY(priv->addDomainEntry)));

	/* Trim whitespaces from start and end of entered domain name */
	asciiDomainStart=asciiDomain;
	while(*asciiDomainStart && g_ascii_isspace(*asciiDomainStart)) asciiDomainStart++;

	asciiDomainEnd=asciiDomain+strlen(asciiDomain)-1;
	while(*asciiDomainEnd && g_ascii_isspace(*asciiDomainEnd)) asciiDomainEnd--;

	/* We allow only domain names and not cookie domain name so entered name
	 * must not start with a dot
	 */
	checkAsciiDomain=asciiDomainStart;
	isValid=(*asciiDomainStart!='.' && *asciiDomainEnd!='.');

	/* Now check if ASCII domain name is valid (very very simple check)
	 * and contains a hostname besides TLD
	 */
	dots=0;

	while(*checkAsciiDomain &&
			checkAsciiDomain<=asciiDomainEnd &&
			isValid)
	{
		/* Check for dot as (at least the first one) seperates hostname from TLD */
		if(*checkAsciiDomain=='.') dots++;
			else
			{
				/* Check for valid characters in domain name.
				 * Valid domain name can only contain ASCII alphabetic letters,
				 * digits (0-9) and hyphens ('-')
				 */
				isValid=(g_ascii_isalpha(*checkAsciiDomain) ||
							g_ascii_isdigit(*checkAsciiDomain) ||
							*checkAsciiDomain=='-');
			}

		checkAsciiDomain++;
	}

	/* If we have not reached the trimmed end of string something must have gone wrong 
	 * and domain entered is invalid. If domain name entered excluding dots is longer
	 * than 255 character it is also invalid.
	 */
	if(checkAsciiDomain<asciiDomainEnd) isValid=FALSE;
		else if((checkAsciiDomain-asciiDomainStart-dots)>255) isValid=FALSE;

	/* We need at least one dot in domain name (minimum number of dots to seperate
	 * hostname from TLD)
	 */
	isValid=(isValid && dots>0);

	/* Activate "add" button if hostname (equal to domain name here) is valid */
	gtk_widget_set_sensitive(priv->addDomainButton, isValid);

	/* Free allocated resources */
	g_free(asciiDomain);
}
Esempio n. 27
0
/**
 * gedit_utils_decode_uri:
 * @uri: the uri to decode
 * @scheme: (out) (allow-none): return value pointer for the uri's
 * scheme (e.g. http, sftp, ...), or %NULL
 * @user: (out) (allow-none): return value pointer for the uri user info, or %NULL
 * @port: (out) (allow-none): return value pointer for the uri port, or %NULL
 * @host: (out) (allow-none): return value pointer for the uri host, or %NULL
 * @path: (out) (allow-none): return value pointer for the uri path, or %NULL
 *
 * Parse and break an uri apart in its individual components like the uri
 * scheme, user info, port, host and path. The return value pointer can be
 * %NULL to ignore certain parts of the uri. If the function returns %TRUE, then
 * all return value pointers should be freed using g_free
 *
 * Return value: %TRUE if the uri could be properly decoded, %FALSE otherwise.
 */
gboolean
gedit_utils_decode_uri (const gchar  *uri,
			gchar       **scheme,
			gchar       **user,
			gchar       **host,
			gchar       **port,
			gchar       **path)
{
	/* Largely copied from glib/gio/gdummyfile.c:_g_decode_uri. This
	 * functionality should be in glib/gio, but for now we implement it
	 * ourselves (see bug #546182) */

	const char *p, *in, *hier_part_start, *hier_part_end;
	char *out;
	char c;

	/* From RFC 3986 Decodes:
	 * URI = scheme ":" hier-part [ "?" query ] [ "#" fragment ]
	 */

	p = uri;

	null_ptr (scheme);
	null_ptr (user);
	null_ptr (port);
	null_ptr (host);
	null_ptr (path);

	/* Decode scheme:
	 * scheme = ALPHA *( ALPHA / DIGIT / "+" / "-" / "." )
	 */

	if (!g_ascii_isalpha (*p))
		return FALSE;

	while (1)
	{
		c = *p++;

		if (c == ':')
			break;

		if (!(g_ascii_isalnum(c) ||
		      c == '+' ||
		      c == '-' ||
		      c == '.'))
		{
			return FALSE;
		}
	}

	if (scheme)
	{
		*scheme = g_malloc (p - uri);
		out = *scheme;

		for (in = uri; in < p - 1; in++)
		{
			*out++ = g_ascii_tolower (*in);
		}

		*out = '\0';
	}

	hier_part_start = p;
	hier_part_end = p + strlen (p);

	if (hier_part_start[0] == '/' && hier_part_start[1] == '/')
	{
		const char *authority_start, *authority_end;
		const char *userinfo_start, *userinfo_end;
		const char *host_start, *host_end;
		const char *port_start;

		authority_start = hier_part_start + 2;
		/* authority is always followed by / or nothing */
		authority_end = memchr (authority_start, '/', hier_part_end - authority_start);

		if (authority_end == NULL)
			authority_end = hier_part_end;

		/* 3.2:
		 * authority = [ userinfo "@" ] host [ ":" port ]
		 */

		userinfo_end = memchr (authority_start, '@', authority_end - authority_start);

		if (userinfo_end)
		{
			userinfo_start = authority_start;

			if (user)
				*user = g_uri_unescape_segment (userinfo_start, userinfo_end, NULL);

			if (user && *user == NULL)
			{
				if (scheme)
					g_free (*scheme);

				return FALSE;
			}

			host_start = userinfo_end + 1;
		}
		else
		{
			host_start = authority_start;
		}

		port_start = memchr (host_start, ':', authority_end - host_start);

		if (port_start)
		{
			host_end = port_start++;

			if (port)
				*port = g_strndup (port_start, authority_end - port_start);
		}
		else
		{
			host_end = authority_end;
		}

		if (host)
			*host = g_strndup (host_start, host_end - host_start);

		hier_part_start = authority_end;
	}

	if (path)
		*path = g_uri_unescape_segment (hier_part_start, hier_part_end, "/");

	return TRUE;
}
Esempio n. 28
0
gboolean parse_line (PREFS *images, gchar *prefsline)
{
	/* Parse a given line (prefsline). Return FALSE if unable to parse. */
	gboolean key_found = FALSE;
	int x;
	
	/* Do a quick check to make sure it's not a comment */
	if (g_ascii_isalpha (prefsline[0]))
	{
		/* Not a comment, attempt to parse it */
		for (x = 0; x < KEY_WORDS; x++)
		{
			key_found = FALSE;
			switch (x)
			{
				case 0:
					/* KEY_BIOS_IMAGE */
					key_found = parse_value (&images[0], KEY_BIOS_IMAGE, prefsline, WIDGET_BIOS_IMAGE);
					break;
				case 1:
					/* KEY_CARTRIDGE_IMAGE */
					key_found = parse_value (&images[0], KEY_CARTRIDGE_IMAGE, prefsline, WIDGET_CARTRIDGE_IMAGE);
					break;
				case 2:
					/* KEY_FLOPPY_IMAGES */
					key_found = parse_value (&images[0], KEY_FLOPPY_IMAGES, prefsline, WIDGET_FLOPPY_IMAGES);
					break;
				case 3:
					/* KEY_HDD_IMAGE */
					key_found = parse_value (&images[0], KEY_HDD_IMAGE, prefsline, WIDGET_HDD_IMAGE);
					break;
				case 4:
					/* KEY_MESS_EXECUTABLE */
					key_found = parse_value (&images[0], KEY_MESS_EXECUTABLE, prefsline, WIDGET_MESS_EXECUTABLE);
					break;
				case 5:
					/* KEY_IMAGES_DIRECTORY */
					key_found = parse_value (&images[0], KEY_IMAGES_DIRECTORY, prefsline, WIDGET_IMAGES_DIRECTORY);
					break;
				case 6:
					/* KEY_BIOS_DIRECTORY */
					key_found = parse_value (&images[0], KEY_BIOS_DIRECTORY, prefsline, WIDGET_BIOS_DIRECTORY);
					break;
				case 7:
					/* KEY_DISPLAY_COMMAND */
					key_found = parse_value (&images[0], KEY_DISPLAY_COMMAND, prefsline, WIDGET_DISPLAY_COMMAND);
					break;
				default:
					break;
			}
			
			/* If it found the key, break out of the loop */
			if (key_found)
				break;
		}
	
		/* No key was found. Return an error. */
		if (!key_found)
			return FALSE;

	}
	return TRUE;
}
Esempio n. 29
0
/**
 * as_utils_compare_versions:
 *
 * Compare alpha and numeric segments of two versions.
 * The version compare algorithm is also used by RPM.
 *
 * Returns: 1: a is newer than b
 *	    0: a and b are the same version
 *	   -1: b is newer than a
 */
gint
as_utils_compare_versions (const gchar* a, const gchar *b)
{
	/* easy comparison to see if versions are identical */
	if (g_strcmp0 (a, b) == 0)
		return 0;

	if (a == NULL)
		return -1;
	if (b == NULL)
		return 1;

	gchar oldch1, oldch2;
	gchar abuf[strlen(a)+1], bbuf[strlen(b)+1];
	gchar *str1 = abuf, *str2 = bbuf;
	gchar *one, *two;
	int rc;
	gboolean isnum;

	strcpy (str1, a);
	strcpy (str2, b);

	one = str1;
	two = str2;

	/* loop through each version segment of str1 and str2 and compare them */
	while (*one || *two) {
		while (*one && !g_ascii_isalnum (*one) && *one != '~') one++;
		while (*two && !g_ascii_isalnum (*two) && *two != '~') two++;

		/* handle the tilde separator, it sorts before everything else */
		if (*one == '~' || *two == '~') {
			if (*one != '~') return 1;
			if (*two != '~') return -1;
			one++;
			two++;
			continue;
		}

		/* If we ran to the end of either, we are finished with the loop */
		if (!(*one && *two)) break;

		str1 = one;
		str2 = two;

		/* grab first completely alpha or completely numeric segment */
		/* leave one and two pointing to the start of the alpha or numeric */
		/* segment and walk str1 and str2 to end of segment */
		if (g_ascii_isdigit (*str1)) {
			while (*str1 && g_ascii_isdigit (*str1)) str1++;
			while (*str2 && g_ascii_isdigit (*str2)) str2++;
			isnum = TRUE;
		} else {
			while (*str1 && g_ascii_isalpha (*str1)) str1++;
			while (*str2 && g_ascii_isalpha (*str2)) str2++;
			isnum = FALSE;
		}

		/* save character at the end of the alpha or numeric segment */
		/* so that they can be restored after the comparison */
		oldch1 = *str1;
		*str1 = '\0';
		oldch2 = *str2;
		*str2 = '\0';

		/* this cannot happen, as we previously tested to make sure that */
		/* the first string has a non-null segment */
		if (one == str1) return -1;	/* arbitrary */

		/* take care of the case where the two version segments are */
		/* different types: one numeric, the other alpha (i.e. empty) */
		/* numeric segments are always newer than alpha segments */
		if (two == str2) return (isnum ? 1 : -1);

		if (isnum) {
			size_t onelen, twolen;
			/* this used to be done by converting the digit segments */
			/* to ints using atoi() - it's changed because long  */
			/* digit segments can overflow an int - this should fix that. */

			/* throw away any leading zeros - it's a number, right? */
			while (*one == '0') one++;
			while (*two == '0') two++;

			/* whichever number has more digits wins */
			onelen = strlen (one);
			twolen = strlen (two);
			if (onelen > twolen) return 1;
			if (twolen > onelen) return -1;
		}

		/* strcmp will return which one is greater - even if the two */
		/* segments are alpha or if they are numeric.  don't return  */
		/* if they are equal because there might be more segments to */
		/* compare */
		rc = strcmp (one, two);
		if (rc) return (rc < 1 ? -1 : 1);

		/* restore character that was replaced by null above */
		*str1 = oldch1;
		one = str1;
		*str2 = oldch2;
		two = str2;
	}

	/* this catches the case where all numeric and alpha segments have */
	/* compared identically but the segment sepparating characters were */
	/* different */
	if ((!*one) && (!*two)) return 0;

	/* whichever version still has characters left over wins */
	if (!*one) return -1; else return 1;
}
Esempio n. 30
0
/* NB: Buffer must be writable and nul-terminated, its initial part is
 * overwritten */
static gboolean
sdfile_read_header_text(gchar **buffer,
                        gsize *len,
                        SDFile *sdfile,
                        GError **error)
{
    gchar *val, *p;

    /* We do not need exact lenght of the minimum file */
    if (*len < SDF_MIN_TEXT_SIZE) {
        err_TOO_SHORT(error);
        return FALSE;
    }

    gwy_clear(sdfile, 1);
    p = *buffer;

    val = g_strstrip(gwy_str_next_line(&p));
    strncpy(sdfile->version, val, sizeof(sdfile->version));

    READ_STRING(p, "ManufacID", val, sdfile->manufacturer, error)
    READ_STRING(p, "CreateDate", val, sdfile->creation, error)
    READ_STRING(p, "ModDate", val, sdfile->modification, error)
    READ_INT(p, "NumPoints", val, sdfile->xres, TRUE, error)
    READ_INT(p, "NumProfiles", val, sdfile->yres, TRUE, error)
    READ_FLOAT(p, "Xscale", val, sdfile->xscale, TRUE, error)
    READ_FLOAT(p, "Yscale", val, sdfile->yscale, TRUE, error)
    READ_FLOAT(p, "Zscale", val, sdfile->zscale, TRUE, error)
    READ_FLOAT(p, "Zresolution", val, sdfile->zres, FALSE, error)
    READ_INT(p, "Compression", val, sdfile->compression, FALSE, error)
    READ_INT(p, "DataType", val, sdfile->data_type, FALSE, error)
    READ_INT(p, "CheckType", val, sdfile->check_type, FALSE, error)

    /* at least */
    if (sdfile->data_type < SDF_NTYPES)
        sdfile->expected_size = 2*sdfile->xres * sdfile->yres;
    else
        sdfile->expected_size = -1;

    /* Skip possible extra header lines */
    do {
        val = gwy_str_next_line(&p);
        if (!val)
            break;
        val = g_strstrip(val);
        if (g_ascii_isalpha(val[0])) {
            gwy_debug("Extra header line: <%s>\n", val);
        }
    } while (val[0] == ';' || g_ascii_isalpha(val[0]));

    if (!val || *val != '*') {
        g_set_error(error, GWY_MODULE_FILE_ERROR, GWY_MODULE_FILE_ERROR_DATA,
                    _("Missing data start marker (*)."));
        return FALSE;
    }

    *buffer = p;
    *len -= p - *buffer;
    sdfile->data = (gchar*)*buffer;
    return TRUE;
}