Esempio n. 1
0
/* splits an input string into a date-time part and an optional operator part.
   operator can be any of "=", "<", ">", "<=", ">=" and "<>".
   range notation [x;y] can also be used
   datetime values should follow the pattern YYYY:mm:dd HH:MM:SS
   but only year part is mandatory

   datetime and operator are returned as pointers to null terminated strings in g_mallocated
   memory (to be g_free'd after use) - or NULL if no match is found.
*/
void dt_collection_split_operator_datetime(const gchar *input, char **number1, char **number2, char **operator)
{
  GRegex *regex;
  GMatchInfo *match_info;
  int match_count;

  *number1 = *number2 = *operator= NULL;

  // we test the range expression first
  // 2 elements : date-time1 and  date-time2
  regex = g_regex_new("^\\s*\\[\\s*(\\d{4}[:\\d\\s]*)\\s*;\\s*(\\d{4}[:\\d\\s]*)\\s*\\]\\s*$", 0, 0, NULL);
  g_regex_match_full(regex, input, -1, 0, 0, &match_info, NULL);
  match_count = g_match_info_get_match_count(match_info);

  if(match_count == 3)
  {
    gchar *txt = g_match_info_fetch(match_info, 1);
    gchar *txt2 = g_match_info_fetch(match_info, 2);

    *number1 = _dt_collection_compute_datetime(">=", txt);
    *number2 = _dt_collection_compute_datetime("<=", txt2);
    *operator= g_strdup("[]");

    g_free(txt);
    g_free(txt2);
    g_match_info_free(match_info);
    g_regex_unref(regex);
    return;
  }

  g_match_info_free(match_info);
  g_regex_unref(regex);

  // and we test the classic comparaison operators
  // 2 elements : operator and date-time
  regex = g_regex_new("^\\s*(=|<|>|<=|>=|<>)?\\s*(\\d{4}[:\\d\\s]*)?\\s*%?\\s*$", 0, 0, NULL);
  g_regex_match_full(regex, input, -1, 0, 0, &match_info, NULL);
  match_count = g_match_info_get_match_count(match_info);

  if(match_count == 3)
  {
    *operator= g_match_info_fetch(match_info, 1);
    gchar *txt = g_match_info_fetch(match_info, 2);

    if(strcmp(*operator, "") == 0 || strcmp(*operator, "=") == 0 || strcmp(*operator, "<>") == 0)
      *number1 = dt_util_dstrcat(*number1, "%s%%", txt);
    else
      *number1 = _dt_collection_compute_datetime(*operator, txt);

    g_free(txt);
  }

  // ensure operator is not null
  if(!*operator) *operator= g_strdup("");

  g_match_info_free(match_info);
  g_regex_unref(regex);
}
Esempio n. 2
0
int
s3_regexec_wrap(regex_t *regex,
           const char *str,
           size_t nmatch,
           regmatch_t pmatch[],
           int eflags)
{
    GMatchInfo *match_info;
    int ret = REG_NOERROR;
    guint i;

    g_assert(regex && *regex);
    g_regex_match(*regex, str, eflags, &match_info);
    if (g_match_info_matches(match_info)) {
        g_assert(g_match_info_get_match_count(match_info) <= (glong) nmatch);
        for (i = 0; i < nmatch; i++) {
            pmatch[i].rm_eo = pmatch[i].rm_so = -1;
            g_match_info_fetch_pos(match_info, i, &pmatch[i].rm_so, &pmatch[i].rm_eo);
        }
    } else {
        ret = REG_NOMATCH;
    }
    g_match_info_free(match_info);
    return ret;
}
Esempio n. 3
0
void
hook (GMatchInfo *minfo, gpointer user_data)
{
    GString *str = (GString *)user_data;

    g_string_append_printf (str, "FROM THE HOOK<br/><br/>\n");

    while (g_match_info_matches (minfo))
    {
        guint n = g_match_info_get_match_count (minfo);
        g_string_append_printf (str, "Match count: %d<br/><br/>\n", n);
        gchar *word = g_match_info_fetch (minfo, 0);
        g_string_append_printf (str, "Found: %s<br/><br/>\n", word);
        g_free (word);

        guint i;
        for (i = 1; i < n; i++)
        {
            gchar *word = g_match_info_fetch (minfo, i);
            g_string_append_printf (str, "sub %d: %s<br/><br/>\n", i, word);
            g_free (word);
        }

        if (n > 1)
        {
            word = g_match_info_fetch_named (minfo, "controller");
            g_string_append_printf (str, "sub named controller: %s<br/><br/>\n", word);
            g_free (word);
        }

        g_match_info_next (minfo, NULL);
    }
}
Esempio n. 4
0
static mc_search__found_cond_t
mc_search__regex_found_cond_one (mc_search_t * mc_search, mc_search_regex_t * regex,
                                 GString * search_str)
{
#ifdef SEARCH_TYPE_GLIB
    GError *error = NULL;

    if (!g_regex_match_full
        (regex, search_str->str, -1, 0, G_REGEX_MATCH_NEWLINE_ANY, &mc_search->regex_match_info,
         &error)) {
        g_match_info_free (mc_search->regex_match_info);
        mc_search->regex_match_info = NULL;
        if (error) {
            mc_search->error = MC_SEARCH_E_REGEX;
            mc_search->error_str = str_conv_gerror_message (error, _(" Regular expression error "));
            g_error_free (error);
            return COND__FOUND_ERROR;
        }
        return COND__NOT_FOUND;
    }
    mc_search->num_rezults = g_match_info_get_match_count (mc_search->regex_match_info);
#else /* SEARCH_TYPE_GLIB */
    mc_search->num_rezults = pcre_exec (regex, mc_search->regex_match_info,
                                        search_str->str, search_str->len - 1, 0, 0, mc_search->iovector,
                                        MC_SEARCH__NUM_REPLACE_ARGS);
    if (mc_search->num_rezults < 0) {
        return COND__NOT_FOUND;
    }
#endif /* SEARCH_TYPE_GLIB */
    return COND__FOUND_OK;

}
Esempio n. 5
0
/* splits an input string into a number part and an optional operator part.
   number can be a decimal integer or rational numerical item.
   operator can be any of "=", "<", ">", "<=", ">=" and "<>".

   number and operator are returned as pointers to null terminated strings in g_mallocated
   memory (to be g_free'd after use) - or NULL if no match is found.
*/
void
dt_collection_split_operator_number (const gchar *input, char **number, char **operator)
{
  GRegex *regex;
  GMatchInfo *match_info;
  int match_count;

  *number = *operator = NULL;
   
  regex = g_regex_new("\\s*(=|<|>|<=|>=|<>)?\\s*([0-9]+\\.?[0-9]*)\\s*", 0, 0, NULL);
  g_regex_match_full(regex, input, -1, 0, 0, &match_info, NULL);
  match_count = g_match_info_get_match_count(match_info);

  if(match_count == 3)
  {
    *operator = g_match_info_fetch(match_info, 1);
    *number = g_match_info_fetch(match_info, 2);

    if(*operator && strcmp(*operator, "") == 0)
    {
      g_free(*operator);
      *operator = NULL;
    }
  }

  g_match_info_free(match_info);
  g_regex_unref(regex);
} 
Esempio n. 6
0
File: irc.c Progetto: donthi/ircbot
irc_msg* irc_next_message(irc_connection *con)
{
    gboolean ret;
    GMatchInfo *info;
    irc_msg *ircmsg = NULL;
    char *raw_msg = irc_next_message_rawstr(con);

    if (!raw_msg) goto ircmsg_out;

    ret = g_regex_match(irc_msg_regex_pattern, raw_msg, 0, &info);

    int matches = g_match_info_get_match_count(info);
    if (matches != 5) goto ircmsg_out;

    ircmsg = malloc(sizeof(irc_msg));
    if (!ircmsg) goto ircmsg_out;

    Copy_match(info, 1, ircmsg->source);
    Copy_match(info, 2, ircmsg->command);
    Copy_match(info, 3, ircmsg->target);
    Copy_match(info, 4, ircmsg->params);

ircmsg_out:
    g_match_info_free(info);
    return ircmsg;
}
Esempio n. 7
0
/* splits an input string into a number part and an optional operator part.
   number can be a decimal integer or rational numerical item.
   operator can be any of "=", "<", ">", "<=", ">=" and "<>".
   range notation [x;y] can also be used

   number and operator are returned as pointers to null terminated strings in g_mallocated
   memory (to be g_free'd after use) - or NULL if no match is found.
*/
void dt_collection_split_operator_number(const gchar *input, char **number1, char **number2, char **operator)
{
  GRegex *regex;
  GMatchInfo *match_info;
  int match_count;

  *number1 = *number2 = *operator= NULL;

  // we test the range expression first
  regex = g_regex_new("^\\s*\\[\\s*([0-9]+\\.?[0-9]*)\\s*;\\s*([0-9]+\\.?[0-9]*)\\s*\\]\\s*$", 0, 0, NULL);
  g_regex_match_full(regex, input, -1, 0, 0, &match_info, NULL);
  match_count = g_match_info_get_match_count(match_info);

  if(match_count == 3)
  {
    *number1 = g_match_info_fetch(match_info, 1);
    *number2 = g_match_info_fetch(match_info, 2);
    *operator= g_strdup("[]");
    g_match_info_free(match_info);
    g_regex_unref(regex);
    return;
  }

  g_match_info_free(match_info);
  g_regex_unref(regex);

  // and we test the classic comparaison operators
  regex = g_regex_new("^\\s*(=|<|>|<=|>=|<>)?\\s*([0-9]+\\.?[0-9]*)\\s*$", 0, 0, NULL);
  g_regex_match_full(regex, input, -1, 0, 0, &match_info, NULL);
  match_count = g_match_info_get_match_count(match_info);

  if(match_count == 3)
  {
    *operator= g_match_info_fetch(match_info, 1);
    *number1 = g_match_info_fetch(match_info, 2);

    if(*operator&& strcmp(*operator, "") == 0)
    {
      g_free(*operator);
      *operator= NULL;
    }
  }

  g_match_info_free(match_info);
  g_regex_unref(regex);
}
Esempio n. 8
0
static void
cb_media_downloader_load_twitter_video (CbMediaDownloader *downloader,
                                        CbMedia           *media)
{
  SoupMessage *msg = soup_message_new ("GET", media->url);
  GRegex      *regex;
  GMatchInfo  *match_info;

  soup_session_send_message (downloader->soup_session, msg);
  if (msg->status_code != SOUP_STATUS_OK)
    {
      mark_invalid (media);
      g_object_unref (msg);
      return;
    }

  regex = g_regex_new ("<img src=\"(.*?)\" class=\"animated-gif-thumbnail", 0, 0, NULL);
  g_regex_match (regex, (const char *)msg->response_body->data, 0, &match_info);

  if (g_match_info_get_match_count (match_info) > 0)
    {
      g_assert (media->type == CB_MEDIA_TYPE_ANIMATED_GIF);
      media->url = g_match_info_fetch (match_info, 1);

      g_regex_unref (regex);
      g_match_info_free (match_info);
      g_object_unref (msg);
      return;
    }
  else
    {
      g_regex_unref (regex);
      g_match_info_free (match_info);

      regex = g_regex_new ("<source video-src=\"(.*?)\"", 0, 0, NULL);
      g_regex_match (regex, (const char *)msg->response_body->data, 0, &match_info);
      media->url = g_match_info_fetch (match_info, 1);
      media->type = CB_MEDIA_TYPE_TWITTER_VIDEO;
    }

  g_regex_unref (regex);
  g_match_info_free (match_info);

  regex = g_regex_new ("poster=\"(.*?)\"", 0, 0, NULL);
  g_regex_match (regex, (const char *)msg->response_body->data, 0, &match_info);
  media->thumb_url = g_match_info_fetch (match_info, 1);

  g_regex_unref (regex);
  g_match_info_free (match_info);
  g_object_unref (msg);
}
Esempio n. 9
0
File: ttx.c Progetto: djcb/ttx
static gboolean
get_address_maybe (TTXProviderMgr *prov_mgr, Opts *opts, GError **err)
{
	GRegex *rx;
	GMatchInfo *minfo;
	char* str;
	const char *addr;

	minfo = NULL;
	str   = NULL;

	if (!opts->params || !opts->params[0])
		return TRUE; /* nothing to do here */

	addr = opts->params[0];

	rx = g_regex_new ("(\\w+):(\\d{3})(/(\\d{1,2}))?", 0, 0, err);
	if (!rx)
		return FALSE;

	if (!g_regex_match (rx, addr, 0, &minfo)) {
		g_printerr (_("invalid link; expected: "
			      "<provider-id>:<page>[/<subpage>]\n"
			      "e.g., nos:101/1 or yle:200\n"));
		g_match_info_free (minfo);
		g_regex_unref (rx);
		return FALSE;
	}

	opts->prov_id = g_match_info_fetch (minfo, 1);
	str = g_match_info_fetch (minfo, 2);

	opts->page = atoi (str);
	g_free (str);

	if (g_match_info_get_match_count (minfo) < 5)
		opts->subpage = 1;
	else {
		str = g_match_info_fetch (minfo, 4);
		opts->subpage = atoi (str);
		g_free (str);
	}

	g_match_info_free (minfo);
	g_regex_unref (rx);

	return check_address (prov_mgr, opts->prov_id, opts->page,
			      opts->subpage);
}
Esempio n. 10
0
static gboolean
check_target_compat (GSSDPResourceBrowser *resource_browser,
                     const char           *st)
{
        GSSDPResourceBrowserPrivate *priv;
        GMatchInfo *info;
        int         version;
        char       *tmp;

        priv = gssdp_resource_browser_get_instance_private (resource_browser);

        if (g_str_equal (priv->target, GSSDP_ALL_RESOURCES))
                return TRUE;

        if (!g_regex_match (priv->target_regex,
                            st,
                            0,
                            &info)) {
                g_match_info_free (info);

                return FALSE;
        }

        /* If there was no version to match, we're done */
        if (priv->version == 0) {
                g_match_info_free (info);

                return TRUE;
        }

        if (g_match_info_get_match_count (info) != 2) {
                g_match_info_free (info);

                return FALSE;
        }

        version = atoi ((tmp = g_match_info_fetch (info, 1)));
        g_free (tmp);
        g_match_info_free (info);

        if (version < 0) {
            return FALSE;
        }

        return (guint) version >= priv->version;
}
Esempio n. 11
0
static void
cb_media_downloader_get_instagram_url (CbMediaDownloader *downloader,
                                       CbMedia           *media)
{
  SoupMessage *msg = soup_message_new ("GET", media->url);
  GRegex      *medium_regex;
  GRegex      *url_regex;
  GMatchInfo  *match_info;

  soup_session_send_message (downloader->soup_session, msg);
  if (msg->status_code != SOUP_STATUS_OK)
    {
      g_object_unref (msg);
      media->url = NULL;
      return;
    }

  medium_regex = g_regex_new ("<meta name=\"medium\" content=\"video\" />", 0, 0, NULL);
  g_regex_match (medium_regex, (const char *)msg->response_body->data, 0, &match_info);

  if (g_match_info_get_match_count (match_info) > 0)
    {
      g_match_info_free (match_info);

      /* Video! */
      url_regex = g_regex_new ("<meta property=\"og:video\" content=\"(.*?)\"", 0, 0, NULL);
      g_regex_match (url_regex, (const char *)msg->response_body->data, 0, &match_info);
      media->url = g_match_info_fetch (match_info, 1);
      g_regex_unref (url_regex);

      media->type = CB_MEDIA_TYPE_INSTAGRAM_VIDEO;
    }

  g_match_info_free (match_info);

  url_regex = g_regex_new ("<meta property=\"og:image\" content=\"(.*?)\"", 0, 0, NULL);
  g_regex_match (url_regex, (const char*)msg->response_body->data, 0, &match_info);

  media->thumb_url = g_match_info_fetch (match_info, 1);

  g_regex_unref (url_regex);
  g_regex_unref (medium_regex);
  g_match_info_free (match_info);
  g_object_unref (msg);
}
Esempio n. 12
0
/* unlike PCRE, partial matching won't return the actual substrings/matches */
static int Gregex_dfa_exec (lua_State *L)
{
  TArgExec argE;
  TGrgx *ud;
  gboolean res;

  checkarg_dfa_exec (L, &argE, &ud);

  gerror_free (ud);

  res = g_regex_match_all_full (ud->pr, argE.text, (int)argE.textlen,
    argE.startoffset, (GRegexMatchFlags)argE.eflags, &ud->match_info, &ud->error);

  if (ALG_ISMATCH (res)) {
    int i, start_pos, end_pos;
    int max = g_match_info_get_match_count (ud->match_info);
    g_match_info_fetch_pos (ud->match_info, 0, &start_pos, NULL);
    lua_pushinteger (L, start_pos + 1);         /* 1-st return value */
    lua_newtable (L);                            /* 2-nd return value */
    for (i=0; i<max; i++) {
      g_match_info_fetch_pos (ud->match_info, i, NULL, &end_pos);
      /* I don't know why these offsets aren't incremented by 1 to match Lua indexing? */
      lua_pushinteger (L, end_pos);
      lua_rawseti (L, -2, i+1);
    }
    lua_pushinteger (L, max);                    /* 3-rd return value */
    minfo_free (ud);
    return 3;
  }
  else if (g_match_info_is_partial_match(ud->match_info)) {
    lua_pushboolean(L,1);
    minfo_free (ud);
    return 1;
  }
  else {
    minfo_free (ud);
    if (ALG_NOMATCH (res))
      return lua_pushnil (L), 1;
    else
      return generate_error (L, ud, 0);
  }
}
Esempio n. 13
0
static VALUE
rg_match_count(VALUE self)
{
    return INT2NUM(g_match_info_get_match_count(_SELF(self)));
}
Esempio n. 14
0
void dt_collection_split_operator_datetime(const gchar *input, char **number1, char **number2, char **operator)
{
  GRegex *regex;
  GMatchInfo *match_info;
  int match_count;

  *number1 = *number2 = *operator= NULL;

  // we test the range expression first
  // 4 elements : date1 time1(optional) date2 time2(optional)
  regex = g_regex_new("^\\s*\\[\\s*(\\d{4}:\\d{2}:\\d{2})\\s*( "
                      "\\d{2}:\\d{2}:\\d{2})?\\s*;\\s*(\\d{4}:\\d{2}:\\d{2})\\s*( "
                      "\\d{2}:\\d{2}:\\d{2})?\\s*\\]\\s*$",
                      0, 0, NULL);
  g_regex_match_full(regex, input, -1, 0, 0, &match_info, NULL);
  match_count = g_match_info_get_match_count(match_info);

  if(match_count >= 4)
  {
    *number1 = g_match_info_fetch(match_info, 1);
    gchar *number1_time = g_match_info_fetch(match_info, 2);
    *number2 = g_match_info_fetch(match_info, 3);
    *operator= g_strdup("[]");

    if(!number1_time || strcmp(number1_time, "") == 0)
      *number1 = dt_util_dstrcat(*number1, " 00:00:00");
    else
      *number1 = dt_util_dstrcat(*number1, "%s", number1_time);

    if(match_count == 5)
    {
      gchar *number2_time = g_match_info_fetch(match_info, 4);
      *number2 = dt_util_dstrcat(*number2, "%s", number2_time);
      g_free(number2_time);
    }
    else
      *number2 = dt_util_dstrcat(*number2, " 23:59:59");

    if(number1_time) g_free(number1_time);
    g_match_info_free(match_info);
    g_regex_unref(regex);
    return;
  }

  g_match_info_free(match_info);
  g_regex_unref(regex);

  // and we test the classic comparaison operators
  // 2 elements : date time(optional)
  regex = g_regex_new("^\\s*(=|<|>|<=|>=|<>)?\\s*(\\d{4}:\\d{2}:\\d{2})\\s*( \\d{2}:\\d{2}:\\d{2})?\\s*$", 0,
                      0, NULL);
  g_regex_match_full(regex, input, -1, 0, 0, &match_info, NULL);
  match_count = g_match_info_get_match_count(match_info);

  if(match_count >= 3)
  {
    *operator= g_match_info_fetch(match_info, 1);
    *number1 = g_match_info_fetch(match_info, 2);
    // we fill the time part if it's not set
    if(match_count == 4)
    {
      gchar *nb_time = g_match_info_fetch(match_info, 3);
      *number1 = dt_util_dstrcat(*number1, "%s", nb_time);
      g_free(nb_time);
    }
    else if(*operator&& strcmp(*operator, ">") == 0)
      *number1 = dt_util_dstrcat(*number1, " 23:59:59");
    else if(*operator&& strcmp(*operator, ">=") == 0)
      *number1 = dt_util_dstrcat(*number1, " 00:00:00");
    else if(*operator&& strcmp(*operator, "<") == 0)
      *number1 = dt_util_dstrcat(*number1, " 00:00:00");
    else if(*operator&& strcmp(*operator, "<=") == 0)
      *number1 = dt_util_dstrcat(*number1, " 23:59:59");
    else if(*operator&& strcmp(*operator, "=") == 0)
      *number1 = dt_util_dstrcat(*number1, "%%");
    else if(*operator&& strcmp(*operator, "<>") == 0)
      *number1 = dt_util_dstrcat(*number1, "%%");
    else if(*operator&& strcmp(*operator, "") == 0)
      *number1 = dt_util_dstrcat(*number1, "%%");
    else if(!*operator)
      *number1 = dt_util_dstrcat(*number1, "%%");

    if(*operator&& strcmp(*operator, "") == 0)
    {
      g_free(*operator);
      *operator= NULL;
    }
  }

  g_match_info_free(match_info);
  g_regex_unref(regex);
}
Esempio n. 15
0
static GHashTable *
body_parser(GByteArray * buffer, GError ** err)
{
	GHashTable *result = NULL;
	GRegex *stat_regex = NULL;
	GMatchInfo *match_info = NULL;

	g_byte_array_append(buffer, (const guint8*)"", 1);

	stat_regex = g_regex_new("^(\\S+)[ \\t]+(\\S+).*$",
			G_REGEX_MULTILINE | G_REGEX_RAW, G_REGEX_MATCH_NOTEMPTY, err);

	if (!stat_regex) {
		GSETERROR(err, "Regex compilation error");
		return NULL;
	}

	if (!g_regex_match(stat_regex, (const gchar*)buffer->data, G_REGEX_MATCH_NOTEMPTY, &match_info)) {
		GSETERROR(err, "Invalid stat from the RAWX");
		goto error_label;
	}

	result = g_hash_table_new_full(g_str_hash, g_str_equal, g_free, g_free);
	if (!result) {
		GSETERROR(err, "Memory allocation failure");
		goto error_label;
	}

	do {
		if (!g_match_info_matches(match_info)) {
			GSETERROR(err, "Invalid matching");
			goto error_label;
		}
		else if (g_match_info_get_match_count(match_info) != 3) {
			GSETERROR(err, "Invalid matching, %d groups found", g_match_info_get_match_count(match_info));
			goto error_label;
		}
		else {
			gchar *str_key, *str_value;

			str_key = g_match_info_fetch(match_info, 1);
			str_value = g_match_info_fetch(match_info, 2);

			if (!str_key || !str_value) {
				GSETERROR(err, "Matching capture failure");
				if (str_value)
					g_free(str_value);
				if (str_key)
					g_free(str_key);
				if (result)
					g_hash_table_destroy(result);
				goto error_label;
			}

			g_hash_table_insert(result, str_key, str_value);
		}
	} while (g_match_info_next(match_info, NULL));

	g_match_info_free(match_info);
	g_regex_unref(stat_regex);

	return result;

error_label:
	if (match_info)
		g_match_info_free(match_info);
	if (result)
		g_hash_table_destroy(result);
	g_regex_unref(stat_regex);

	return NULL;
}
Esempio n. 16
0
// XXX step 2, basically the main function
static int
emit_package (lcmgen_t *lcm, _package_contents_t *pc)
{
    // create the package directory, if necessary
    char **dirs = g_strsplit (pc->name, ".", 0);
    char *pdname = build_filenamev (dirs);
    char package_dir[PATH_MAX];
    char package_dir_prefix[PATH_MAX];
    int have_package = dirs[0] != NULL;

    sprintf (package_dir_prefix, "%s%s", getopt_get_string(lcm->gopt, "lpath"),
            strlen(getopt_get_string(lcm->gopt, "lpath")) > 0 ?
            G_DIR_SEPARATOR_S : "");
    sprintf(package_dir, "%s%s%s", package_dir_prefix, pdname,
            have_package ? G_DIR_SEPARATOR_S : "");
    free (pdname);
    if (strlen (package_dir)) {
        if (! g_file_test (package_dir, G_FILE_TEST_EXISTS)) {
//            g_mkdir_with_parents (package_dir, 0755);
            mkdir_with_parents (package_dir, 0755);
        }
        if (!g_file_test (package_dir, G_FILE_TEST_IS_DIR)) {
            err ("Could not create directory %s\n", package_dir);
            return -1;
        }
    }

    // write the package init.lua files, if necessary
    FILE *init_lua_fp = NULL;
    GHashTable * initlua_requires = NULL;
    GHashTable * initlua_requires_subpack = NULL;

    if (have_package) {
        int ndirs = 0;
        for (ndirs=0; dirs[ndirs]; ndirs++);

        for (int i=0 ; i<ndirs; i++) {

        	// make filename
        	char *initlua_fname;

        	{
        		char *initlua_fname_parts[1024];
        		assert(ndirs + 4 < 1024);

        		initlua_fname_parts[0] = package_dir_prefix;
        		for (int j=0; j<=i; j++) {
        			initlua_fname_parts[j+1] = dirs[j];
        		}
        		initlua_fname_parts[i+2] = "init.lua";
        		initlua_fname_parts[i+3] = NULL;

        		initlua_fname = build_filenamev (initlua_fname_parts);
        	}

            // make current package name
        	char * package_name;

        	{
        		char * name_parts[1024];
        		assert(i < 1024);

        		for (int j = 0; j <= i; j++) {
        			name_parts[j] = dirs[j];
        		}
        		name_parts[i + 1] = NULL;

        		package_name = g_strjoinv(".", name_parts);
        	}

            if (initlua_requires) {
            	g_hash_table_destroy(initlua_requires);
            	initlua_requires = NULL;
            }

            if (initlua_requires_subpack) {
            	g_hash_table_destroy(initlua_requires_subpack);
            	initlua_requires_subpack = NULL;
            }

            initlua_requires = g_hash_table_new_full(g_str_hash, g_str_equal, g_free, g_free);
            initlua_requires_subpack = g_hash_table_new_full(g_str_hash, g_str_equal, g_free, g_free);

            // if the file already exists, read the contents
            if (g_file_test (initlua_fname, G_FILE_TEST_EXISTS)) {

            	init_lua_fp = fopen(initlua_fname, "r");

            	if (!init_lua_fp) {
            		perror ("fopen");
            		free (initlua_fname);
            		g_free(package_name);
            		return -1;
            	}

            	while(!feof(init_lua_fp)) {
            		char buf[4096];
            		memset(buf, 0, sizeof(buf));
            		char *result = fgets(buf, sizeof(buf)-1, init_lua_fp);
            		if(!result)
            			break;

            		// XXX get all of the previous types and packages

            		// this regex works because the first part is greedy
            		GRegex * regex = g_regex_new("require\\('([\\w+\\.]*\\.)(\\w+)'\\)( -- subpackage)?",
						(GRegexCompileFlags) 0, (GRegexMatchFlags) 0, NULL);
            		GMatchInfo * matchinfo;

            		if(g_regex_match(regex, buf, (GRegexMatchFlags) 0, &matchinfo)){
            			if(g_match_info_get_match_count(matchinfo) == 3){
            				// not a subpackage
            				gchar * classname = g_match_info_fetch(matchinfo, 2);
            				g_hash_table_insert(initlua_requires, g_strdup(classname), g_strdup(classname));
            			}else if(g_match_info_get_match_count(matchinfo) == 4){
            				// this is a subpackage
            				// XXX fprintf(stderr, "> buff: %s\n", buf);
            				gchar * superpackage = g_match_info_fetch(matchinfo, 1);
            				gchar * subpackage = g_match_info_fetch(matchinfo, 2);
            				// XXX fprintf(stderr, "> super: %s, sub: %s\n", superpackage, subpackage);
            				gchar * fullsubpackage = g_strjoin("", superpackage, subpackage, NULL);
            				// XXX fprintf(stderr, "> [2] inserting: %s\n", fullsubpackage);
            				g_hash_table_insert(initlua_requires_subpack, g_strdup(fullsubpackage), g_strdup(fullsubpackage));
            				g_free(fullsubpackage);
            			}
            		}

            		g_match_info_free(matchinfo);
            		g_regex_unref(regex);
            	}

            	fclose(init_lua_fp);
            	init_lua_fp = NULL;
            }

            init_lua_fp = fopen(initlua_fname, "w");
            // XXX fprintf(stderr, "> opened: %s\n", initlua_fname);

            if (!init_lua_fp) {
            	perror ("fopen");
            	free (initlua_fname);
            	g_free(package_name);
            	return -1;
            }

#ifndef WIN32
            // lock init.lua for exclusive write access
            // TODO do the equivalent in windows
            struct flock lockinfo;
            lockinfo.l_type = F_WRLCK;
            lockinfo.l_start = 0;
            lockinfo.l_whence = SEEK_SET;
            lockinfo.l_len = 0 ;
            lockinfo.l_pid = getpid();
            if(0 != fcntl(fileno(init_lua_fp), F_SETLKW, &lockinfo)) {
                perror("locking init.lua");
                free(initlua_fname);
                g_free(package_name);
                fclose(init_lua_fp);
                return -1;
            }
#endif

            fprintf (init_lua_fp, "--[[\n"
            		"LCM package init.lua file\n"
            		"This file automatically generated by lcm-gen.\n"
            		"DO NOT MODIFY BY HAND!!!!\n"
            		"--]]\n"
            		"\n"
            		"local M = {}\n"
            		"\n");

            // add in all previous types
            GList * package_types = g_hash_table_get_values(initlua_requires);

            for (int j = 0; j < g_list_length(package_types); j++) {
            	char * tn = (char *) g_list_nth_data(package_types, j);
            	char * fn = g_strjoin(".", package_name, tn, NULL);
            	fprintf(init_lua_fp, "M.%s = require('%s')\n", tn, fn);
            	g_free(fn);
            }

            g_list_free(package_types);

            // add in all previous packages
            GList * subpacks = g_hash_table_get_values(initlua_requires_subpack);

            for (int j = 0; j < g_list_length(subpacks); j++) {
            	char * spn = (char *) g_list_nth_data(subpacks, j);
            	// get the base of the package name
            	char ** tmpsplit = g_strsplit(spn, ".", -1);
            	char * sn = tmpsplit[g_strv_length(tmpsplit) - 1];
            	// XXX fprintf(stderr, "[1] sn: %s, spn: %s\n", sn, spn);
            	fprintf(init_lua_fp, "M.%s = require('%s') -- subpackage\n", sn, spn);
            	g_strfreev(tmpsplit);
            }

            g_list_free(subpacks);

            // if the current package has a subpackage (which eventually contains the target package)
            // add a `require` for that subpackage to the current (if it hasn't already)
            if (i + 1 < ndirs) {
            	char *subpack_name = g_strjoin(".", package_name, dirs[i + 1], NULL);

            	// check for the subpackage name
            	if (!g_hash_table_lookup(initlua_requires_subpack, subpack_name)) {

            		// add it if it didn't exist
            		g_hash_table_insert(initlua_requires_subpack, g_strdup(subpack_name), g_strdup(subpack_name));
            		// XXX fprintf(stderr, "[2] sn: %s, spn: %s\n", dirs[i + 1], subpack_name);
            		fprintf(init_lua_fp, "M.%s = require('%s') -- subpackage\n", dirs[i + 1], subpack_name);
            	}

            	g_free(subpack_name);
            }

            // not yet the target?
            if (i + 1 < ndirs) {

            	// close it out
            	fprintf(init_lua_fp, "\nreturn M\n\n");
            	fclose(init_lua_fp);
            	init_lua_fp = NULL;
            }

            free (initlua_fname);
            g_free(package_name);
        }
    }
    g_strfreev (dirs);

    ////////////////////////////////////////////////////////////
    // STRUCTS
    for (int i = 0; i<pc->structs->len; i++) {
        lcm_struct_t *ls = (lcm_struct_t *) g_ptr_array_index(pc->structs, i);

        char path[PATH_MAX];
        sprintf (path, "%s%s.lua", package_dir, ls->structname->shortname);

        if(init_lua_fp){

        	// XXX add the 'require' to the appropriate init.lua
        	if (!g_hash_table_lookup(initlua_requires, ls->structname->shortname)) {
        		fprintf(init_lua_fp, "M.%s = require('%s')\n", ls->structname->shortname, ls->structname->lctypename);
        	}

        	// XXX look for subpackages
        	for (unsigned int m = 0; m < g_ptr_array_size(ls->members); m++) {
        		lcm_member_t *lm = (lcm_member_t *) g_ptr_array_index(ls->members, m);

        		if(g_str_has_prefix(lm->type->package, pc->name)){

        			// make a regex starting with the current package...
        			gchar ** tmpsplit = g_strsplit(pc->name, ".", 0);
        			gchar * regexpackage = g_strjoinv("\\.", tmpsplit);

        			// only look for immediate submodules, not submodules of the submodules
        			gchar * regexstr = g_strjoin("", "^", regexpackage, "\\.(\\w+)", NULL);

        			GRegex * regex = g_regex_new(regexstr, (GRegexCompileFlags) 0, (GRegexMatchFlags) 0, NULL);
        			GMatchInfo * matchinfo;

        			g_strfreev(tmpsplit);
        			g_free(regexpackage);
        			g_free(regexstr);

        			if (g_regex_match(regex, lm->type->package, (GRegexMatchFlags) 0, &matchinfo)) {
        				if (g_match_info_get_match_count(matchinfo) == 2) {
        					gchar * fullsubpackage = g_match_info_fetch(matchinfo, 0);
        					gchar * subpackage = g_match_info_fetch(matchinfo, 1);

        					// was it already in the file?
        					if (!g_hash_table_lookup(initlua_requires_subpack, fullsubpackage)) {
        						// XXX fprintf(stderr, "> [1] inserting: %s\n", fullsubpackage);
        						g_hash_table_insert(initlua_requires_subpack, g_strdup(fullsubpackage), g_strdup(fullsubpackage));
        						fprintf(init_lua_fp, "M.%s = require('%s') -- subpackage\n", subpackage, fullsubpackage);
        					}
        				}
        			}

        			g_match_info_free(matchinfo);
        			g_regex_unref(regex);
        		}
        	}
        }

        if (!lcm_needs_generation(lcm, ls->lcmfile, path))
            continue;

        FILE *f = fopen(path, "w");
        if (f==NULL) return -1;

        fprintf(f, "--[[\n"
        		"LCM type definitions\n"
        		"This file automatically generated by lcm.\n"
        		"DO NOT MODIFY BY HAND!!!!\n"
        		"--]]\n"
        		"\n"
        		"local lcm = require('lcm')\n\n");

        emit_lua_dependencies (lcm, f, ls);

        // XXX added this...
        emit_lua_locals(lcm, f, ls);
        emit_lua_buffer_helper(lcm, f, ls);

        // XXX step 3, start making the object
        emit(0, "local %s = {}", ls->structname->shortname);
        emit(0, "%s.__index = %s", ls->structname->shortname, ls->structname->shortname);
        emit(0, "");

        // CONSTANTS
        for (unsigned int cn = 0; cn < g_ptr_array_size(ls->constants); cn++) {
            lcm_constant_t *lc = (lcm_constant_t *) g_ptr_array_index(ls->constants, cn);
            assert(lcm_is_legal_const_type(lc->lctypename));
            emit(1, "%s.%s = %s", ls->structname->shortname,
            		lc->membername, lc->val_str);
        }
        if (g_ptr_array_size(ls->constants) > 0)
            emit(0, "");

        // NAMES
        emit(0, "%s.name = '%s'", ls->structname->shortname, ls->structname->lctypename);
        emit(0, "%s.packagename = '%s'", ls->structname->shortname, ls->structname->package);
        emit(0, "%s.shortname = '%s'", ls->structname->shortname, ls->structname->shortname);
        emit(0, "");

        emit_lua_new (lcm, f, ls);
        emit_lua_fingerprint (lcm, f, ls);
        emit_lua_encode (lcm, f, ls);
        emit_lua_encode_one (lcm, f, ls);
        emit_lua_decode (lcm, f, ls);
        emit_lua_decode_one (lcm, f, ls);

        emit(0, "return %s", ls->structname->shortname);
        emit(0, "");

        fclose (f);
    }

    if(init_lua_fp){
    	fprintf(init_lua_fp, "\nreturn M\n\n");
        fclose(init_lua_fp);
    }

    g_hash_table_destroy(initlua_requires);
    return 0;
}
Esempio n. 17
0
static int recv_conf_u123x(const struct sr_dev_inst *sdi, GMatchInfo *match)
{
	struct dev_context *devc;
	char *mstr, *rstr;
	int i, resolution;

	sr_spew("CONF? response '%s'.", g_match_info_get_string(match));
	devc = sdi->priv;
	i = devc->cur_conf->index;

	rstr = g_match_info_fetch(match, 2);
	if (rstr)
		sr_atoi(rstr, &resolution);
	g_free(rstr);

	mstr = g_match_info_fetch(match, 1);
	if (!strcmp(mstr, "V")) {
		devc->cur_mq[i] = SR_MQ_VOLTAGE;
		devc->cur_unit[i] = SR_UNIT_VOLT;
		devc->cur_mqflags[i] = 0;
		devc->cur_exponent[i] = 0;
		devc->cur_digits[i] = 4 - resolution;
	} else if (!strcmp(mstr, "MV")) {
		if (devc->mode_tempaux) {
			devc->cur_mq[i] = SR_MQ_TEMPERATURE;
			/* No way to detect whether Fahrenheit or Celsius
			 * is used, so we'll just default to Celsius. */
			devc->cur_unit[i] = SR_UNIT_CELSIUS;
			devc->cur_mqflags[i] = 0;
			devc->cur_exponent[i] = 0;
			devc->cur_digits[i] = 1;
		} else {
			devc->cur_mq[i] = SR_MQ_VOLTAGE;
			devc->cur_unit[i] = SR_UNIT_VOLT;
			devc->cur_mqflags[i] = 0;
			devc->cur_exponent[i] = -3;
			devc->cur_digits[i] = 5 - resolution;
		}
	} else if (!strcmp(mstr, "A")) {
		devc->cur_mq[i] = SR_MQ_CURRENT;
		devc->cur_unit[i] = SR_UNIT_AMPERE;
		devc->cur_mqflags[i] = 0;
		devc->cur_exponent[i] = 0;
		devc->cur_digits[i] = 3 - resolution;
	} else if (!strcmp(mstr, "UA")) {
		devc->cur_mq[i] = SR_MQ_CURRENT;
		devc->cur_unit[i] = SR_UNIT_AMPERE;
		devc->cur_mqflags[i] = 0;
		devc->cur_exponent[i] = -6;
		devc->cur_digits[i] = 8 - resolution;
	} else if (!strcmp(mstr, "FREQ")) {
		devc->cur_mq[i] = SR_MQ_FREQUENCY;
		devc->cur_unit[i] = SR_UNIT_HERTZ;
		devc->cur_mqflags[i] = 0;
		devc->cur_exponent[i] = 0;
		devc->cur_digits[i] = 2 - resolution;
	} else if (!strcmp(mstr, "RES")) {
		if (devc->mode_continuity) {
			devc->cur_mq[i] = SR_MQ_CONTINUITY;
			devc->cur_unit[i] = SR_UNIT_BOOLEAN;
		} else {
			devc->cur_mq[i] = SR_MQ_RESISTANCE;
			devc->cur_unit[i] = SR_UNIT_OHM;
		}
		devc->cur_mqflags[i] = 0;
		devc->cur_exponent[i] = 0;
		devc->cur_digits[i] = 1 - resolution;
	} else if (!strcmp(mstr, "DIOD")) {
		devc->cur_mq[i] = SR_MQ_VOLTAGE;
		devc->cur_unit[i] = SR_UNIT_VOLT;
		devc->cur_mqflags[i] = SR_MQFLAG_DIODE | SR_MQFLAG_DC;
		devc->cur_exponent[i] = 0;
		devc->cur_digits[i] = 3;
	} else if (!strcmp(mstr, "CAP")) {
		devc->cur_mq[i] = SR_MQ_CAPACITANCE;
		devc->cur_unit[i] = SR_UNIT_FARAD;
		devc->cur_mqflags[i] = 0;
		devc->cur_exponent[i] = 0;
		devc->cur_digits[i] = 9 - resolution;
	} else
		sr_dbg("Unknown first argument.");
	g_free(mstr);

	/* This is based on guess, supposing similarity with other models. */
	devc->cur_encoding[i] = devc->cur_digits[i] + 1;

	if (g_match_info_get_match_count(match) == 4) {
		mstr = g_match_info_fetch(match, 3);
		/* Third value, if present, is always AC or DC. */
		if (!strcmp(mstr, "AC")) {
			devc->cur_mqflags[i] |= SR_MQFLAG_AC;
			if (devc->cur_mq[i] == SR_MQ_VOLTAGE)
				devc->cur_mqflags[i] |= SR_MQFLAG_RMS;
		} else if (!strcmp(mstr, "DC")) {
			devc->cur_mqflags[i] |= SR_MQFLAG_DC;
		} else {
			sr_dbg("Unknown first argument '%s'.", mstr);
		}
		g_free(mstr);
	} else
		devc->cur_mqflags[i] &= ~(SR_MQFLAG_AC | SR_MQFLAG_DC);

	return JOB_CONF;
}
Esempio n. 18
0
void parse_metadata(RIP_MANAGER_INFO * rmi, TRACK_INFO * ti)
{
	int i;
	int eflags;
	int rc;
	int matched;
	mchar query_string[MAX_TRACK_LEN];
	Parse_Rule *rulep;

	/* Has any m/.../s rule matched? */
	BOOL save_track_matched = FALSE;

	/* Has any m/.../x rule matched? */
	BOOL exclude_track_matched = FALSE;

	ti->artist[0] = 0;
	ti->title[0] = 0;
	ti->album[0] = 0;
	ti->composed_metadata[0] = 0;
	ti->save_track = TRUE;

	/* Loop through rules, if we find a matching rule, then use it */
	/* For now, only default rules supported with ascii 
	   regular expressions. */
	debug_printf("Converting query string to wide\n");
	gstring_from_string(rmi, query_string, MAX_TRACK_LEN, ti->raw_metadata, CODESET_METADATA);
	for (rulep = rmi->parse_rules; rulep->cmd; rulep++) {
#if !defined (USE_GLIB_REGEX)
		regmatch_t pmatch[MAX_SUBMATCHES + 1];
#endif
		eflags = 0;
		if (rulep->cmd == PARSERULE_CMD_MATCH) {
			debug_mprintf(m_("Testing match rule: ") m_S m_(" vs. ") m_S m_("\n"),
				      query_string, rulep->match);
			if (rulep->flags & PARSERULE_SKIP) {
#if defined (USE_GLIB_REGEX)
				rc = g_regex_match(rulep->reg, query_string, 0, NULL);
				matched = rc;
#else
				rc = mregexec(rulep->reg, query_string, 0, NULL, eflags);
				matched = !rc;
#endif
				if (!matched) {
					continue;
				}
				/* GCS FIX: We need to return to the 
				   caller that the metadata should be dropped. */
				debug_printf("Skip rule matched\n");
				ti->save_track = FALSE;
				ti->have_track_info = 0;
				return;
			} else if (rulep->flags & PARSERULE_SAVE) {
#if defined (USE_GLIB_REGEX)
				rc = g_regex_match(rulep->reg, query_string, 0, NULL);
				matched = rc;
#else
				rc = mregexec(rulep->reg, query_string, 0, NULL, eflags);
				matched = !rc;
#endif
				if (!matched) {
					if (!save_track_matched)
						ti->save_track = FALSE;
					continue;
				}
				if (!exclude_track_matched) {
					ti->save_track = TRUE;
					save_track_matched = TRUE;
				}
			} else if (rulep->flags & PARSERULE_EXCLUDE) {
#if defined (USE_GLIB_REGEX)
				rc = g_regex_match(rulep->reg, query_string, 0, NULL);
				matched = rc;
#else
				rc = mregexec(rulep->reg, query_string, 0, NULL, eflags);
				matched = !rc;
#endif
				if (matched && !save_track_matched) {
					/* Rule matched => Exclude track */
					ti->save_track = FALSE;
					exclude_track_matched = TRUE;
				}
			} else {
#if defined (USE_GLIB_REGEX)
				GMatchInfo *match_info;
				gint nmatch;

				rc = g_regex_match(rulep->reg, query_string, 0, &match_info);
				if (rc == 0) {
					/* Didn't match rule. */
					continue;
				}
				nmatch = g_match_info_get_match_count(match_info);
				debug_printf("Got %d matches\n", nmatch);
				for (i = 0; i < nmatch; i++) {
					gchar *match = g_match_info_fetch(match_info, i);
					debug_printf("[%d] = %s\n", i, match);
					g_free(match);
				}
				copy_rule_result(ti->artist, match_info, rulep->artist_idx);
				copy_rule_result(ti->title, match_info, rulep->title_idx);
				copy_rule_result(ti->album, match_info, rulep->album_idx);
				copy_rule_result(ti->track_p, match_info, rulep->trackno_idx);
				copy_rule_result(ti->year, match_info, rulep->year_idx);
				g_match_info_free(match_info);
#else
				eflags = 0;
				rc = mregexec(rulep->reg, query_string, MAX_SUBMATCHES + 1, pmatch, eflags);
				if (rc != 0) {
					/* Didn't match rule. */
					continue;
				}

				for (i = 0; i < MAX_SUBMATCHES + 1; i++) {
					debug_printf("pmatch[%d]: (so,eo) = (%d,%d)\n", i,
						     pmatch[i].rm_so, pmatch[i].rm_eo);
				}
				copy_rule_result(ti->artist, query_string, pmatch, rulep->artist_idx);
				copy_rule_result(ti->title, query_string, pmatch, rulep->title_idx);
				copy_rule_result(ti->album, query_string, pmatch, rulep->album_idx);
				copy_rule_result(ti->track_p, query_string, pmatch, rulep->trackno_idx);
				copy_rule_result(ti->year, query_string, pmatch, rulep->year_idx);
#endif
				ti->have_track_info = 1;
				compose_metadata(rmi, ti);
				debug_mprintf(m_("Parsed track info.\n")
					      m_("ARTIST: ") m_S m_("\n")
					      m_("TITLE: ") m_S m_("\n")
					      m_("ALBUM: ") m_S m_("\n")
					      m_("TRACK: ") m_S m_("\n")
					      m_("YEAR: ") m_S m_("\n"),
					      ti->artist, ti->title, ti->album, ti->track_p, ti->year);
				return;
			}
		} else if (rulep->cmd == PARSERULE_CMD_SUBST) {
#if defined (USE_GLIB_REGEX)
			GMatchInfo *match_info;
			gint start_pos, end_pos;
			gchar *tmp, *subst_string;

			debug_mprintf(m_("Testing subst rule: ") m_S m_(" vs. ") m_S m_("\n"),
				      query_string, rulep->match);
			rc = g_regex_match(rulep->reg, query_string, 0, &match_info);
			if (rc == 0) {
				/* Didn't match rule. */
				continue;
			}
			rc = g_match_info_fetch_pos(match_info, 0, &start_pos, &end_pos);
			if (!rc) {
				debug_printf("g_match_info_fetch_pos returned 0\n");
				g_match_info_free(match_info);
				continue;
			}
			debug_printf("Matched at (%d,%d)\n", start_pos, end_pos);
			if (start_pos == -1) {
				g_match_info_free(match_info);
				continue;
			}
			tmp = g_strndup(query_string, start_pos);
			tmp[start_pos] = 0;
			subst_string = g_strconcat(tmp, rulep->subst, &tmp[end_pos], NULL);
			g_free(tmp);
			g_match_info_free(match_info);
			mstrncpy(query_string, subst_string, MAX_TRACK_LEN);
#else
			mchar subst_string[MAX_TRACK_LEN];
			int used, left;
			debug_mprintf(m_("Testing subst rule: ") m_S m_(" vs. ") m_S m_("\n"),
				      query_string, rulep->match);
			rc = mregexec(rulep->reg, query_string, 1, pmatch, eflags);
			if (rc != 0) {
				/* Didn't match rule. */
				continue;
			}
			/* Update the query string and continue. */
			debug_printf("Matched at (%d,%d)\n", pmatch[0].rm_so, pmatch[0].rm_eo);
			mstrncpy(subst_string, query_string, pmatch[0].rm_so + 1);
			debug_mprintf(m_("(1) subst_string = ") m_S m_("\n"), subst_string);
			used = pmatch[0].rm_so;
			left = MAX_TRACK_LEN - used;
			mstrncpy(subst_string + used, rulep->subst, left);
			debug_mprintf(m_("(2) subst_string = ") m_S m_("\n"), subst_string);
			used += mstrlen(rulep->subst);
			left = MAX_TRACK_LEN - used;
			mstrncpy(subst_string + used, query_string + pmatch[0].rm_eo, left);
			debug_mprintf(m_("(3) subst_string = ") m_S m_("\n"), subst_string);
			mstrncpy(query_string, subst_string, MAX_TRACK_LEN);
			debug_mprintf(m_("(4) query_string = ") m_S m_("\n"), query_string);
#endif
		}
	}
	debug_printf("Fell through while parsing data...\n");
	mstrncpy(ti->title, query_string, MAX_TRACK_LEN);
	ti->have_track_info = 1;
	compose_metadata(rmi, ti);
}
Esempio n. 19
0
static int recv_conf_u123x(const struct sr_dev_inst *sdi, GMatchInfo *match)
{
	struct dev_context *devc;
	char *mstr;

	sr_spew("CONF? response '%s'.", g_match_info_get_string(match));
	devc = sdi->priv;
	mstr = g_match_info_fetch(match, 1);
	if (!strcmp(mstr, "V")) {
		devc->cur_mq = SR_MQ_VOLTAGE;
		devc->cur_unit = SR_UNIT_VOLT;
		devc->cur_mqflags = 0;
		devc->cur_divider = 0;
	} else if (!strcmp(mstr, "MV")) {
		if (devc->mode_tempaux) {
			devc->cur_mq = SR_MQ_TEMPERATURE;
			/* No way to detect whether Fahrenheit or Celsius
			 * is used, so we'll just default to Celsius. */
			devc->cur_unit = SR_UNIT_CELSIUS;
		devc->cur_mqflags = 0;
		devc->cur_divider = 0;
		} else {
			devc->cur_mq = SR_MQ_VOLTAGE;
			devc->cur_unit = SR_UNIT_VOLT;
			devc->cur_mqflags = 0;
			devc->cur_divider = 1000;
		}
	} else if (!strcmp(mstr, "A")) {
		devc->cur_mq = SR_MQ_CURRENT;
		devc->cur_unit = SR_UNIT_AMPERE;
		devc->cur_mqflags = 0;
		devc->cur_divider = 0;
	} else if (!strcmp(mstr, "UA")) {
		devc->cur_mq = SR_MQ_CURRENT;
		devc->cur_unit = SR_UNIT_AMPERE;
		devc->cur_mqflags = 0;
		devc->cur_divider = 1000000;
	} else if (!strcmp(mstr, "FREQ")) {
		devc->cur_mq = SR_MQ_FREQUENCY;
		devc->cur_unit = SR_UNIT_HERTZ;
		devc->cur_mqflags = 0;
		devc->cur_divider = 0;
	} else if (!strcmp(mstr, "RES")) {
		if (devc->mode_continuity) {
			devc->cur_mq = SR_MQ_CONTINUITY;
			devc->cur_unit = SR_UNIT_BOOLEAN;
		} else {
			devc->cur_mq = SR_MQ_RESISTANCE;
			devc->cur_unit = SR_UNIT_OHM;
		}
		devc->cur_mqflags = 0;
		devc->cur_divider = 0;
	} else if (!strcmp(mstr, "CAP")) {
		devc->cur_mq = SR_MQ_CAPACITANCE;
		devc->cur_unit = SR_UNIT_FARAD;
		devc->cur_mqflags = 0;
		devc->cur_divider = 0;
	} else
		sr_dbg("Unknown first argument.");
	g_free(mstr);

	if (g_match_info_get_match_count(match) == 4) {
		mstr = g_match_info_fetch(match, 3);
		/* Third value, if present, is always AC or DC. */
		if (!strcmp(mstr, "AC")) {
			devc->cur_mqflags |= SR_MQFLAG_AC;
			if (devc->cur_mq == SR_MQ_VOLTAGE)
				devc->cur_mqflags |= SR_MQFLAG_RMS;
		} else if (!strcmp(mstr, "DC")) {
			devc->cur_mqflags |= SR_MQFLAG_DC;
		} else {
		sr_dbg("Unknown first argument '%s'.", mstr);
		}
		g_free(mstr);
	} else
		devc->cur_mqflags &= ~(SR_MQFLAG_AC | SR_MQFLAG_DC);

	return SR_OK;
}
gboolean mm_huawei_parse_nwtime_response (const gchar *response,
                                          gchar **iso8601p,
                                          MMNetworkTimezone **tzp,
                                          GError **error)
{
    GRegex *r;
    GMatchInfo *match_info = NULL;
    GError *match_error = NULL;
    guint year = 0, month = 0, day = 0, hour = 0, minute = 0, second = 0, dt = 0;
    gint tz = 0;
    gboolean ret = FALSE;

    g_assert (iso8601p || tzp); /* at least one */

    r = g_regex_new ("\\^NWTIME:\\s*(\\d+)/(\\d+)/(\\d+),(\\d+):(\\d+):(\\d*)([\\-\\+\\d]+),(\\d+)$", 0, 0, NULL);
    g_assert (r != NULL);

    if (!g_regex_match_full (r, response, -1, 0, 0, &match_info, &match_error)) {
        if (match_error) {
            g_propagate_error (error, match_error);
            g_prefix_error (error, "Could not parse ^NWTIME results: ");
        } else {
            g_set_error_literal (error,
                                 MM_CORE_ERROR,
                                 MM_CORE_ERROR_FAILED,
                                 "Couldn't match ^NWTIME reply");
        }
    } else {
        /* Remember that g_match_info_get_match_count() includes match #0 */
        g_assert (g_match_info_get_match_count (match_info) >= 9);

        if (mm_get_uint_from_match_info (match_info, 1, &year) &&
            mm_get_uint_from_match_info (match_info, 2, &month) &&
            mm_get_uint_from_match_info (match_info, 3, &day) &&
            mm_get_uint_from_match_info (match_info, 4, &hour) &&
            mm_get_uint_from_match_info (match_info, 5, &minute) &&
            mm_get_uint_from_match_info (match_info, 6, &second) &&
            mm_get_int_from_match_info  (match_info, 7, &tz) &&
            mm_get_uint_from_match_info (match_info, 8, &dt)) {
            /* adjust year */
            if (year < 100)
                year += 2000;
            /*
             * tz = timezone offset in 15 minute intervals
             * dt = daylight adjustment, 0 = none, 1 = 1 hour, 2 = 2 hours
             *      other values are marked reserved.
             */
            if (iso8601p) {
                /* Return ISO-8601 format date/time string */
                *iso8601p = mm_new_iso8601_time (year, month, day, hour,
                                                 minute, second,
                                                 TRUE, (tz * 15) + (dt * 60));
            }
            if (tzp) {
                *tzp = mm_network_timezone_new ();
                mm_network_timezone_set_offset (*tzp, tz * 15);
                mm_network_timezone_set_dst_offset (*tzp, dt * 60);
            }

            ret = TRUE;
        } else {
            g_set_error_literal (error,
                                 MM_CORE_ERROR,
                                 MM_CORE_ERROR_FAILED,
                                 "Failed to parse ^NWTIME reply");
        }
    }

    if (match_info)
        g_match_info_free (match_info);
    g_regex_unref (r);

    return ret;
}
gboolean
mm_huawei_parse_sysinfo_response (const char *reply,
                                  guint *out_srv_status,
                                  guint *out_srv_domain,
                                  guint *out_roam_status,
                                  guint *out_sys_mode,
                                  guint *out_sim_state,
                                  gboolean *out_sys_submode_valid,
                                  guint *out_sys_submode,
                                  GError **error)
{
    gboolean matched;
    GRegex *r;
    GMatchInfo *match_info = NULL;
    GError *match_error = NULL;

    g_assert (out_srv_status != NULL);
    g_assert (out_srv_domain != NULL);
    g_assert (out_roam_status != NULL);
    g_assert (out_sys_mode != NULL);
    g_assert (out_sim_state != NULL);
    g_assert (out_sys_submode_valid != NULL);
    g_assert (out_sys_submode != NULL);

    /* Format:
     *
     * ^SYSINFO: <srv_status>,<srv_domain>,<roam_status>,<sys_mode>,<sim_state>[,<reserved>,<sys_submode>]
     */

    /* Can't just use \d here since sometimes you get "^SYSINFO:2,1,0,3,1,,3" */
    r = g_regex_new ("\\^SYSINFO:\\s*(\\d+),(\\d+),(\\d+),(\\d+),(\\d+),?(\\d+)?,?(\\d+)?$", 0, 0, NULL);
    g_assert (r != NULL);

    matched = g_regex_match_full (r, reply, -1, 0, 0, &match_info, &match_error);
    if (!matched) {
        if (match_error) {
            g_propagate_error (error, match_error);
            g_prefix_error (error, "Could not parse ^SYSINFO results: ");
        } else {
            g_set_error_literal (error,
                                 MM_CORE_ERROR,
                                 MM_CORE_ERROR_FAILED,
                                 "Couldn't match ^SYSINFO reply");
        }
    } else {
        mm_get_uint_from_match_info (match_info, 1, out_srv_status);
        mm_get_uint_from_match_info (match_info, 2, out_srv_domain);
        mm_get_uint_from_match_info (match_info, 3, out_roam_status);
        mm_get_uint_from_match_info (match_info, 4, out_sys_mode);
        mm_get_uint_from_match_info (match_info, 5, out_sim_state);

        /* Remember that g_match_info_get_match_count() includes match #0 */
        if (g_match_info_get_match_count (match_info) >= 8) {
            *out_sys_submode_valid = TRUE;
            mm_get_uint_from_match_info (match_info, 7, out_sys_submode);
        }
    }

    if (match_info)
        g_match_info_free (match_info);
    g_regex_unref (r);
    return matched;
}
gboolean mm_huawei_parse_time_response (const gchar *response,
                                        gchar **iso8601p,
                                        MMNetworkTimezone **tzp,
                                        GError **error)
{
    GRegex *r;
    GMatchInfo *match_info = NULL;
    GError *match_error = NULL;
    guint year, month, day, hour, minute, second;
    gboolean ret = FALSE;

    g_assert (iso8601p || tzp); /* at least one */

    /* TIME response cannot ever provide TZ info */
    if (tzp) {
        g_set_error_literal (error,
                             MM_CORE_ERROR,
                             MM_CORE_ERROR_UNSUPPORTED,
                             "^TIME does not provide timezone information");
        return FALSE;
    }

    /* Already in ISO-8601 format, but verify just to be sure */
    r = g_regex_new ("\\^TIME:\\s*(\\d+)/(\\d+)/(\\d+)\\s*(\\d+):(\\d+):(\\d*)$", 0, 0, NULL);
    g_assert (r != NULL);

    if (!g_regex_match_full (r, response, -1, 0, 0, &match_info, &match_error)) {
        if (match_error) {
            g_propagate_error (error, match_error);
            g_prefix_error (error, "Could not parse ^TIME results: ");
        } else {
            g_set_error_literal (error,
                                 MM_CORE_ERROR,
                                 MM_CORE_ERROR_FAILED,
                                 "Couldn't match ^TIME reply");
        }
    } else {
        /* Remember that g_match_info_get_match_count() includes match #0 */
        g_assert (g_match_info_get_match_count (match_info) >= 7);

        if (mm_get_uint_from_match_info (match_info, 1, &year) &&
            mm_get_uint_from_match_info (match_info, 2, &month) &&
            mm_get_uint_from_match_info (match_info, 3, &day) &&
            mm_get_uint_from_match_info (match_info, 4, &hour) &&
            mm_get_uint_from_match_info (match_info, 5, &minute) &&
            mm_get_uint_from_match_info (match_info, 6, &second)) {
            /* adjust year */
            if (year < 100)
                year += 2000;
            /* Return ISO-8601 format date/time string */
            if (iso8601p)
                *iso8601p = mm_new_iso8601_time (year, month, day, hour,
                                                 minute, second, FALSE, 0);
            ret = TRUE;
        } else {
            g_set_error_literal (error,
                                 MM_CORE_ERROR,
                                 MM_CORE_ERROR_FAILED,
                                 "Failed to parse ^TIME reply");
        }
    }

    if (match_info)
        g_match_info_free (match_info);
    g_regex_unref (r);

    return ret;
}
Esempio n. 23
0
static void
sysinfo_done (MMAtSerialPort *port,
              GString *response,
              GError *error,
              gpointer user_data)
{
    MMCallbackInfo *info = (MMCallbackInfo *) user_data;
    GRegex *r;
    GMatchInfo *match_info;
    const char *reply;

    /* If the modem has already been removed, return without
     * scheduling callback */
    if (mm_callback_info_check_modem_removed (info))
        return;

    if (error) {
        /* Leave superclass' reg state alone if AT^SYSINFO isn't supported */
        goto done;
    }

    reply = strip_response (response->str, "^SYSINFO:");

    /* Format is "<srv_status>,<srv_domain>,<roam_status>,<sys_mode>,<sim_state>" */
    r = g_regex_new ("\\s*(\\d+)\\s*,\\s*(\\d+)\\s*,\\s*(\\d+)\\s*,\\s*(\\d+)\\s*,\\s*(\\d+)",
                     G_REGEX_RAW | G_REGEX_OPTIMIZE, 0, NULL);
    if (!r) {
        mm_warn ("Huawei: ^SYSINFO parse regex creation failed.");
        goto done;
    }

    g_regex_match (r, reply, 0, &match_info);
    if (g_match_info_get_match_count (match_info) >= 5) {
        MMModemCdmaRegistrationState reg_state;
        guint32 val = 0;

        /* At this point the generic code already knows we've been registered */
        reg_state = MM_MODEM_CDMA_REGISTRATION_STATE_REGISTERED;

        if (uint_from_match_item (match_info, 1, &val)) {
            if (val == 2) {
                /* Service available, check roaming state */
                val = 0;
                if (uint_from_match_item (match_info, 3, &val)) {
                    if (val == 0)
                        reg_state = MM_MODEM_CDMA_REGISTRATION_STATE_HOME;
                    else if (val == 1)
                        reg_state = MM_MODEM_CDMA_REGISTRATION_STATE_ROAMING;
                }
            }
        }

        /* Check service type */
        val = 0;
        if (uint_from_match_item (match_info, 4, &val)) {
            if (val == 2)
                mm_generic_cdma_query_reg_state_set_callback_1x_state (info, reg_state);
            else if (val == 4)
                mm_generic_cdma_query_reg_state_set_callback_evdo_state (info, reg_state);
            else if (val == 8) {
                mm_generic_cdma_query_reg_state_set_callback_1x_state (info, reg_state);
                mm_generic_cdma_query_reg_state_set_callback_evdo_state (info, reg_state);
            }
        } else {
            /* Say we're registered to something even though sysmode parsing failed */
            mm_generic_cdma_query_reg_state_set_callback_1x_state (info, reg_state);
        }
    } else
        mm_warn ("Huawei: failed to parse ^SYSINFO response.");

    g_match_info_free (match_info);
    g_regex_unref (r);

done:
    mm_callback_info_schedule (info);
}
Esempio n. 24
0
static void _hwp_hwp3_parser_parse_summary_info (HwpHWP3Parser *parser,
                                                 HwpHWP3File   *file,
                                                 GError       **error)
{
  g_return_if_fail (HWP_IS_HWP3_FILE (file));

  GString *string[9];
  guint16  c;
  guint8   count = 0;
  HwpListenableInterface *iface;
  iface = HWP_LISTENABLE_GET_IFACE (parser->listenable);

  for (guint i = 0; i < 9; i++)
  {
    count = 0;
    string[i] = g_string_new (NULL);

    while (count < 112)
    {
      hwp_hwp3_parser_read_uint16 (parser, &c);
      count += 2;

      if (c != 0)
      {
        gchar *str = hwp_hnchar_to_utf8 (c);
        g_string_append (string[i], str);
        g_free (str);
      } else {
        hwp_hwp3_parser_skip (parser, 112 - count);
        break;
      }
    }
  } /* for */

  if (iface->summary_info) {
    HwpSummaryInfo *info = hwp_summary_info_new ();

    info->title = g_string_free (string[0], FALSE);
    info->subject = g_string_free (string[1], FALSE);
    info->creator = g_string_free (string[2], FALSE);

    /* str format: "2001년 10월 11일 목요일, 20시 48분" */
    gchar *s = g_string_free (string[3], FALSE);
    GRegex *regex;
    regex = g_regex_new ("^([0-9]{4})년 ([0-9]{1,2})월 ([0-9]{1,2})일 .요일, ([0-9]{1,2})시 ([0-9]{1,2})분", 0, 0, error);
    GMatchInfo *match_info;
    g_regex_match (regex, s, 0, &match_info);
    gint match_num = g_match_info_get_match_count (match_info);

    gchar *year   = NULL;
    gchar *month  = NULL;
    gchar *day    = NULL;
    gchar *hour   = NULL;
    gchar *minute = NULL;

    if (match_num == 6) {
      year   = g_match_info_fetch (match_info, 1);
      month  = g_match_info_fetch (match_info, 2);
      day    = g_match_info_fetch (match_info, 3);
      hour   = g_match_info_fetch (match_info, 4);
      minute = g_match_info_fetch (match_info, 5);



      GDateTime *datetime = g_date_time_new_local (atoi (year),
                                                   atoi (month),
                                                   atoi (day),
                                                   atoi (hour),
                                                   atoi (minute),
                                                   0.0);

      g_free (year);
      g_free (month);
      g_free (day);
      g_free (hour);
      g_free (minute);

      GTime time = g_date_time_to_unix (datetime);

      info->mod_date = time;
    }

    g_match_info_free (match_info);
    g_regex_unref (regex);

    iface->summary_info (parser->listenable,
                         info,
                         parser->user_data,
                         error);
  }
  /* TODO */
  /* 4 ~ 8 */
}
static gboolean
parse_nwltime_reply (const char *response,
                     gchar **out_iso_8601,
                     MMNetworkTimezone **out_tz,
                     GError **error)
{
    GRegex *r;
    GMatchInfo *match_info = NULL;
    GError *match_error = NULL;
    guint year, month, day, hour, minute, second;
    gchar *result = NULL;
    gint utc_offset = 0;
    gboolean success = FALSE;

    /* Sample reply: 2013.3.27.15.47.19.2.-5 */
    r = g_regex_new ("(\\d+)\\.(\\d+)\\.(\\d+)\\.(\\d+)\\.(\\d+)\\.(\\d+)\\.(\\d+)\\.([\\-\\+\\d]+)$", 0, 0, NULL);
    g_assert (r != NULL);

    if (!g_regex_match_full (r, response, -1, 0, 0, &match_info, &match_error)) {
        if (match_error) {
            g_propagate_error (error, match_error);
            g_prefix_error (error, "Could not parse $NWLTIME results: ");
        } else {
            g_set_error_literal (error,
                                 MM_CORE_ERROR,
                                 MM_CORE_ERROR_FAILED,
                                 "Couldn't match $NWLTIME reply");
        }
    } else {
        /* Remember that g_match_info_get_match_count() includes match #0 */
        g_assert (g_match_info_get_match_count (match_info) >= 9);

        if (mm_get_uint_from_match_info (match_info, 1, &year) &&
            mm_get_uint_from_match_info (match_info, 2, &month) &&
            mm_get_uint_from_match_info (match_info, 3, &day) &&
            mm_get_uint_from_match_info (match_info, 4, &hour) &&
            mm_get_uint_from_match_info (match_info, 5, &minute) &&
            mm_get_uint_from_match_info (match_info, 6, &second) &&
            mm_get_int_from_match_info (match_info, 8, &utc_offset)) {

            result = mm_new_iso8601_time (year, month, day, hour, minute, second,
                                          TRUE, utc_offset * 60);
            if (out_tz) {
                *out_tz = mm_network_timezone_new ();
                mm_network_timezone_set_offset (*out_tz, utc_offset * 60);
            }

            success = TRUE;
        } else {
            g_set_error_literal (error,
                                 MM_CORE_ERROR,
                                 MM_CORE_ERROR_FAILED,
                                 "Failed to parse $NWLTIME reply");
        }
    }

    if (out_iso_8601)
        *out_iso_8601 = result;
    else
        g_free (result);

    if (match_info)
        g_match_info_free (match_info);
    g_regex_unref (r);
    return success;
}
Esempio n. 26
0
static void
gb_source_view_update_search (GbSourceView *view)
{
   GbSourceViewPrivate *priv;
   GRegexCompileFlags flags = 0;
   GtkTextBuffer *buffer;
   GtkTextIter begin;
   GtkTextIter end;
   GMatchInfo *match_info = NULL;
   GtkTextTag *search_tag;
   gboolean has_matches = FALSE;
   GRegex *regex = NULL;
   gchar *text;
   gchar *escaped;

   g_assert(GB_IS_SOURCE_VIEW(view));

   priv = view->priv;

   buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(view));
   gtk_text_buffer_get_bounds(buffer, &begin, &end);

   search_tag = gb_source_view_ref_search_tag(view);
   gtk_text_buffer_remove_tag(buffer, search_tag, &begin, &end);

   if (g_str_empty0(priv->search_text) && !priv->search_regex) {
      goto cleanup;
   }

   if (priv->search_text) {
      if (!priv->search_case_sensitive) {
         flags = G_REGEX_CASELESS;
      }
      escaped = g_regex_escape_string(priv->search_text, -1);
      regex = g_regex_new(escaped, flags, 0, NULL);
      g_free(escaped);
   } else if (priv->search_regex) {
      regex = g_regex_ref(priv->search_regex);
   }

   if (regex) {
      text = gtk_text_buffer_get_text(buffer, &begin, &end, TRUE);
      if (g_regex_match(regex, text, 0, &match_info)) {
         guint count;
         guint i;
         gint begin_pos;
         gint end_pos;

         do {
            count = g_match_info_get_match_count(match_info);
            for (i = 0; i < count; i++) {
               if (g_match_info_fetch_pos(match_info, i, &begin_pos, &end_pos)) {
                  gtk_text_buffer_get_iter_at_offset(buffer, &begin, begin_pos);
                  gtk_text_buffer_get_iter_at_offset(buffer, &end, end_pos);
                  gtk_text_buffer_apply_tag(buffer, search_tag, &begin, &end);
                  has_matches = TRUE;
               }
            }
         } while (g_match_info_next(match_info, NULL));
      }
      g_match_info_free(match_info);
      g_regex_unref(regex);
      g_free(text);
   }

cleanup:
   if (priv->has_matches != has_matches) {
      priv->has_matches = has_matches;
      g_object_notify_by_pspec(G_OBJECT(view), gParamSpecs[PROP_HAS_MATCHES]);
   }

   gtk_widget_queue_draw(GTK_WIDGET(view));
   g_object_unref(search_tag);
}