Exemple #1
0
gboolean prepare_for_upload(gint fd)
{
	gint res = 0;
	gchar buf[1024];
	gchar * message = NULL;

	res = write(fd,"W",1);
	if (res != 1)
	{
		output("Error trying to initiate ECU wipe\n",FALSE);
		return FALSE;
	}
	flush_serial(fd,OUTBOUND);
	g_usleep(1000000); /* 1000ms timeout for flash to erase */
	res = read(fd,&buf,1024);
	message = g_strndup(((gchar *)buf),res);
	if (g_strrstr_len(buf,res,"Complete"))
	{
		g_free(message);
		output("ECU Wipe complete\n",FALSE);
		res = write(fd,"U",1);
		if (res != 1)
		{
			output("Error trying to initiate ECU upgrade\n",FALSE);
			return FALSE;
		}
		flush_serial(fd,OUTBOUND);
		g_usleep(2000000); /* 2000ms timeout for flash to erase */
		res = read(fd,&buf,1024);
		if (g_strrstr_len(buf,res,"waiting"))
		{
			output("Ready to update ECU firmware\n",FALSE);
			return TRUE;
		}
		else
		{
			message = g_strndup(buf,res);
			output(g_strdup_printf("ECU returned \"%s\"\n",message),TRUE);	
			g_free(message);
			output("Error getting \"ready to update\" message from ECU\n",FALSE);
			return FALSE;
		}
	}
	else
	{
		output(g_strdup_printf("Error wiping ECU, result \"%s\"\n",message),TRUE);
		g_free(message);
		return FALSE;
	}
}
Exemple #2
0
static const char *
str_ascii_search_last (const char *text, const char *search, int case_sen)
{
    char *fold_text;
    char *fold_search;
    const char *match;

    fold_text = (case_sen) ? (char *) text : g_ascii_strdown (text, -1);
    fold_search = (case_sen) ? (char *) search : g_ascii_strdown (search, -1);

    match = g_strrstr_len (fold_text, -1, fold_search);
    if (match != NULL)
    {
        size_t offset;

        offset = match - fold_text;
        match = text + offset;
    }

    if (!case_sen)
    {
        g_free (fold_text);
        g_free (fold_search);
    }

    return match;
}
Exemple #3
0
/*
 * Check whether a number is a complex
 * If yes - returns true, no - false
 * If re and/or im!=NULL, in them stored values
 * of real and imaginary components
 */
gboolean cmplx_conv(gchar *value, double *re, double *im){
	double sign = 1.;
	double r,i;
	gchar *ptr1, *ptr2, *eptr;
	ptr1 = g_strstr_len(value, -1, "(");
	if(ptr1){ // form is (re, im) or (re im)
		ptr1++;
		ptr2 = g_strstr_len(ptr1, -1, ")");
		if(ptr2) *ptr2 = 0;
		ptr2 = g_strstr_len(ptr1, -1, ",");
		if(!ptr2)
			ptr2 = g_strstr_len(ptr1, -1, " ");
	}
	else{ // form is re + iim or re + jim
		ptr1 = value;
		ptr2 = g_strstr_len(ptr1, -1, "i");
		if(!ptr2)
			ptr2 = g_strstr_len(ptr1, -1, "j");
	}
	if(ptr2){
		*ptr2 = 0;
		ptr2++;
	}
	else
		return FALSE;
	if(g_strrstr_len(ptr1, 3, "-")) sign=-1.;
	r = strtod(ptr1, &eptr);
	if(eptr == ptr1) return FALSE;
	i = sign*strtod(ptr2, &eptr);
	if(eptr == ptr2) return FALSE;
	if(re) *re = r;
	if(im) *im = i;
	return TRUE;
}
void on_streamer_ready() {
	char endpoint[1024] = {0};
	size_t size = sizeof(endpoint) / sizeof(char);
	int opt = -1;
	char *port_str = NULL;
	int port = 0;

	app.zmq_context = zmq_ctx_new();
	g_assert(app.zmq_context != NULL);
	app.zmq_stream_sock = zmq_socket(app.zmq_context, ZMQ_PUSH);
	g_assert(app.zmq_stream_sock != NULL);

	// There is no reason to wait for last screenshot to be sent
	opt = 0;
	g_assert(zmq_setsockopt(app.zmq_stream_sock, ZMQ_LINGER, &opt, sizeof(int)) == 0);

	// Clients are interested in the most recent screenshots
	opt = 1;
	g_assert(zmq_setsockopt(app.zmq_stream_sock, ZMQ_CONFLATE, &opt, sizeof(int)) == 0);

	// Be explicity and don't let first frame to sit in the queue.
	opt = 1;
	g_assert(zmq_setsockopt(app.zmq_stream_sock, ZMQ_IMMEDIATE, &opt, sizeof(int)) == 0);

	// By binding to ephemeral port we minimize chance of a situation when no ports are available.
	g_assert(zmq_bind(app.zmq_stream_sock, "tcp://*:*") == 0);
	g_assert(zmq_getsockopt(app.zmq_stream_sock, ZMQ_LAST_ENDPOINT, endpoint, &size) == 0);
	port_str = g_strrstr_len(endpoint, size, ":");
	port = (gint)(g_ascii_strtoll(port_str + 1, NULL, 10));
	g_assert(port > 0 && port <= 65535);
	g_atomic_int_set(&app.zmq_stream_sock_port, port);
	g_message("Streaming data on port %d", app.zmq_stream_sock_port);
}
Exemple #5
0
/**
 * ephy_string_collate_key_for_domain:
 * @host:
 * @len: the length of @host, or -1 to use the entire null-terminated @host string
 *
 * Return value: a collation key for @host.
 */
char *
ephy_string_collate_key_for_domain (const char *str,
                                    gssize      len)
{
  GString *result;
  const char *dot;
  gssize newlen;

  if (len < 0)
    len = strlen (str);

  result = g_string_sized_new (len + 6 * strlen (COLLATION_SENTINEL));

  /* Note that we could do even better by using
   * g_utf8_collate_key_for_filename on the dot-separated
   * components, but this seems good enough for now.
   */
  while ((dot = g_strrstr_len (str, len, ".")) != NULL) {
    newlen = dot - str;

    g_string_append_len (result, dot + 1, len - newlen - 1);
    g_string_append (result, COLLATION_SENTINEL);

    len = newlen;
  }

  if (len > 0)
    g_string_append_len (result, str, len);

  return g_string_free (result, FALSE);
}
static gchar *
_stat_name (const char *prefix, const char *tail, gchar *d, gsize dlen)
{
	if (g_str_has_prefix(tail, P))
		dlen = g_snprintf (d, dlen, "%s.%s", prefix, tail+sizeof(P)-1);
	else if (g_str_has_prefix(tail, PROXYD_PREFIX))
		dlen = g_snprintf (d, dlen, "%s.%s", prefix, tail+sizeof(PROXYD_PREFIX)-1);
	else
		dlen = g_snprintf (d, dlen, "%s.%s", prefix, tail);

	/* replace ugly characters by '_' */
	for (int i=strlen (prefix)+1; d[i] ;++i) {
		if (!g_ascii_isalnum (d[i]))
			d[i]='_';
	}

	gchar *s;
	/* agregate subsequent '_' */
	while (NULL != (s = g_strrstr_len(d, dlen, "__"))) {
		for (;*s;++s)
			*s = *(s+1);
	}

	return d;
}
Exemple #7
0
/**
 * @brief	A PHP-like reverse strpos implementation 
 * @param 	const gchar*	haystack
 * @param   const gchar*	needle 
 * @return	gint	position or -1 if not found
 * 
 */
gint
strrpos(const gchar *haystack, const gchar *needle)
{
   char *p = g_strrstr_len(haystack, -1, needle);
   if (p)
	  return p - haystack;
   return -1;   // not found
}
Exemple #8
0
static int 
string_rindex(struct objlist *obj,N_VALUE *inst,N_VALUE *rval,int argc,char **argv)
{
  int pos, size, len;
  char *str, *pattern, *ptr, *find;

  rval->i = -1;

  pattern = (char *) argv[2];
  pos = * (int *) argv[3];

  if (pattern == NULL || pattern[0] == '\0') {
    return 1;
  }

  if (_getobj(obj, "length", inst, &size)) {
    return 2;
  }

  if (! g_utf8_validate(pattern, -1, NULL)) {
    error(obj, ERR_INVALID_UTF8);
    return 2;
  }

  if (pos < 0) {
    pos += size;
  }

  if (pos < 0 || pos >= size) {
    return 1;
  }

  if (_getobj(obj, "@", inst, &str)) {
    return 1;
  }

  if(str == NULL || str[0] == '\0') {
    return 1;
  }

  ptr = g_utf8_offset_to_pointer(str, pos);
  len = ptr - str + 1;
  if (len < 1) {
    return 1;
  }

  find = g_strrstr_len(str, len, pattern);
  if (find == NULL) {
    return 1;
  }

  rval->i = g_utf8_pointer_to_offset(str, find);

  return 0;
}
Exemple #9
0
/**
 * g_utf8_strrchr:
 * @p: a nul-terminated UTF-8 encoded string
 * @len: the maximum length of @p
 * @c: a Unicode character
 * 
 * Find the rightmost occurrence of the given Unicode character
 * in a UTF-8 encoded string, while limiting the search to @len bytes.
 * If @len is -1, allow unbounded search.
 * 
 * Returns: %NULL if the string does not contain the character, 
 *     otherwise, a pointer to the start of the rightmost occurrence
 *     of the character in the string.
 */
gchar *
g_utf8_strrchr (const char *p,
		gssize      len,
		gunichar    c)
{
  gchar ch[10];

  gint charlen = g_unichar_to_utf8 (c, ch);
  ch[charlen] = '\0';
  
  return g_strrstr_len (p, len, ch);
}
Exemple #10
0
gchar* clamd_get_virus_name(gchar* msg) {
	gchar *head, *tail, *name;

	tail = g_strrstr_len(msg, strlen(msg), "FOUND");
	if (! tail)
		return NULL;
	head = g_strstr_len(msg, strlen(msg), ":");
	++head;
	name = g_strndup(head, tail - head);
	g_strstrip(name);
	return name;
}
Exemple #11
0
void gaym_fetch_thumbnail_cb(void *user_data, const char *pic_data,
                             size_t len)
{
    if (!user_data)
        return;
    struct gaym_fetch_thumbnail_data *d = user_data;
    if (!pic_data) {
        return;
    }

    if (len && !g_strrstr_len(pic_data, len, "Server Error")) {
        char *dir =
            g_build_filename(gaim_user_dir(), "icons", "gaym", d->who,
                             NULL);
        char *filename = g_strdup(d->filename);
        char *path = g_build_filename(dir, filename, NULL);
        gaim_debug_misc("gayminfo", "dir: %s\n", dir);
        gaim_debug_misc("gayminfo", "filename: %s\n", filename);
        gaim_debug_misc("gayminfo", "path: %s\n", path);
        if (!g_file_test(dir, G_FILE_TEST_EXISTS))
            gaim_build_dir(dir, S_IRUSR | S_IWUSR | S_IXUSR);

        if (path && !g_file_test(path, G_FILE_TEST_EXISTS)) {
            FILE *file;
            if ((file = g_fopen(path, "wb"))) {
                fwrite(pic_data, 1, len, file);
                fclose(file);
            } else {
                gaim_debug_misc("fetch_thumbnail_cb",
                                "Couldn't write file\n");
            }
            g_free(filename);
            g_free(path);
            g_free(dir);
        }
    }
    if (GAIM_CONNECTION_IS_VALID(d->gc) && len) {
        gaim_signal_emit(gaim_accounts_get_handle(), "info-updated",
                         d->gc, NULL, d->who);
        if (gaim_find_conversation_with_account(d->who, d->gc->account)) {
            //gaim_buddy_icons_set_for_user(gaim_connection_get_account
            //                              (d->gc), d->who,
            //                              (void *) pic_data, len);
        }

    } else {
        gaim_debug_error("gaym", "Fetching buddy icon failed.\n");
    }

    g_free(d->who);
    g_free(d);
}
Exemple #12
0
void gaym_fetch_thumbnail_cb(GaimUtilFetchUrlData *url_data, void *user_data, const gchar *pic_data,
                             gsize len, const gchar* error_message)
{
    if (!user_data)
        return;
    struct gaym_fetch_thumbnail_data *d = user_data;
    if (!pic_data) {
        return;
    }
     
    if (!d->gc)
	return;
    if (len && !g_strrstr_len(pic_data, len, "Server Error")) {
	gaim_debug_misc("gaym","Setting buddy icon for %s\n",d->who);
	if(len<1024) {
	    void* new_pic_data=NULL;
	    gaim_debug_misc("gaym","Short icon file, padding to 1024\n");
	    new_pic_data=g_malloc0(1024);
	    memcpy(new_pic_data, pic_data, len);
	    len=1024;
	    gaim_buddy_icon_new(d->gc->account, d->who, (void*)new_pic_data, len);
	    g_free(new_pic_data);
	}
	else {
	    gaim_buddy_icon_new(d->gc->account, d->who, (void*)pic_data, len);
	}
	//GaimBuddyIcon *icon=gaim_buddy_icons_find(d->gc->account,d->who);
	//guint len;
	//const guchar* data=gaim_buddy_icon_get_data(icon, &len);
    }
    if (GAIM_CONNECTION_IS_VALID(d->gc) && len) {
        gaim_signal_emit(gaim_accounts_get_handle(), "info-updated",
                         d->gc->account, d->who);
      /*  if (gaim_find_conversation_with_account(d->who, d->gc->account)) {
	    
	    gaim_debug_misc("fetch_thumbnail_cb","setting buddy icon\n");
            gaim_buddy_icons_set_for_user(gaim_connection_get_account
             (d->gc), d->who,
             (void *) pic_data, len);
        }*/

    } else {
        gaim_debug_error("gaym", "Fetching buddy icon failed.\n");
    }

    g_free(d->who);
    g_free(d);
}
Exemple #13
0
void archive_add_file(gchar* path) {
	struct file_info* file = archive_new_file_info();
	gchar* filename = NULL;

	g_return_if_fail(path != NULL);

#ifndef _TEST
	debug_print("add %s to list\n", path);
#endif
	filename = g_strrstr_len(path, strlen(path), "/");
	if (! filename)
		g_warning("%s\n", path);
	g_return_if_fail(filename != NULL);

	filename++;
	file->name = g_strdup(filename);
	file->path = strip_leading_dot_slash(dirname(path));
	archive_add_to_list(file);
}
Exemple #14
0
char *
strrstr_skip_count (const char *haystack, const char *needle, size_t skip_count)
{
    char *semi;
    ssize_t len;

    len = strlen (haystack);

    do
    {
        semi = g_strrstr_len (haystack, len, needle);
        if (semi == NULL)
            return NULL;
        len = semi - haystack - 1;
    }
    while (skip_count-- != 0);

    return semi;
}
Exemple #15
0
static const char *
str_utf8_search_last (const char *text, const char *search, int case_sen)
{
    char *fold_text;
    char *deco_text;
    char *match;
    const char *result = NULL;
    const char *m;

    fold_text = (case_sen) ? (char *) text : g_utf8_casefold (text, -1);
    deco_text = g_utf8_normalize (fold_text, -1, G_NORMALIZE_ALL);

    do
    {
	match = g_strrstr_len (deco_text, -1, search);
	if (match != NULL)
	{
	    if ((!str_utf8_iscombiningmark (match) || (match == deco_text)) &&
		!str_utf8_iscombiningmark (match + strlen (search)))
	    {

		result = text;
		m = deco_text;
		while (m < match)
		{
		    str_utf8_cnext_noncomb_char (&m);
		    str_utf8_cnext_noncomb_char (&result);
		}
	    }
	    else
	    {
		match[0] = '\0';
	    }
	}
    }
    while (match != NULL && result == NULL);

    g_free (deco_text);
    if (!case_sen)
	g_free (fold_text);

    return result;
}
Exemple #16
0
/**
 * file_utils_uri_get_ext:
 * @uri:
 *
 * Returns the position of the extension (including the .) for an URI. If
 * there is no extension the returned position is right after the
 * string, at the terminating NULL character.
 *
 * Returns:
 **/
const gchar *
file_utils_uri_get_ext (const gchar *uri)
{
  const gchar *ext        = NULL;
  int          uri_len    = strlen (uri);
  int          search_len = 0;

  if (g_strrstr (uri, ".gz"))
    search_len = uri_len - 3;
  else if (g_strrstr (uri, ".bz2"))
    search_len = uri_len - 4;
  else
    search_len = uri_len;

  ext = g_strrstr_len (uri, search_len, ".");

  if (! ext)
    ext = uri + uri_len;

  return ext;
}
Exemple #17
0
char *
http_path_get_basename (const char *path)
{
  const char *parent;
  char       *basename;
  size_t      len;

  if (path == NULL || *path == '\0')
    return NULL;

  /* remove any leading slashes */
  while (*path != '\0' && *path == '/')
    path++;

  len = strlen (path);
  if (len == 0)
    return g_strdup ("/");

  /* remove any trailing slashes */
  while (len)
    {
      char c = path[len - 1];
      if (c != '/')
	break;

      len--;
    }

  parent = g_strrstr_len (path, len, "/");

  if (parent)
    {
      parent++; /* skip the found / char */
      basename = g_strndup (parent, (len - (parent - path)));
    }
  else
    basename = g_strndup (path, len);

  return basename;
}
Exemple #18
0
void fetch_thumbnail_cb(void *user_data, const char *pic_data, size_t len)
{
    if (!user_data)
        return;
    struct fetch_thumbnail_data *d = user_data;
    if (!pic_data) {
        return;
    }
    if (len && !g_strrstr_len(pic_data, len, "Server Error")) {
        char *dir;
        if ((dir =
             g_build_filename(gaim_user_dir(), "icons", "gaym",
                              NULL)) != NULL) {
            d->pic_data = pic_data;
            d->pic_data_len = len;
            gaim_build_dir(dir, S_IRUSR | S_IWUSR | S_IXUSR);
            char *filename = g_strdup_printf("%s.jpg", d->who);
            char *path = g_build_filename(dir, filename, NULL);
            FILE *file;
            if ((file = g_fopen(path, "wb"))) {
                fwrite(pic_data, 1, len, file);
                fclose(file);
            } else {
                gaim_debug_misc("chaticon", "Couldn't write file\n");
            }
            g_free(filename);
            g_free(path);
            g_free(dir);
        }
    } else {
        d->pic_data = 0;
        d->pic_data_len = 0;
    }

    g_hash_table_foreach_remove(pending_updates,
                                (GHRFunc) check_for_update, d);
    g_free(d);
}
Exemple #19
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;
}
Exemple #20
0
gboolean get_ecu_signature(gint fd)
{
	gint res = 0;
	gint size = 128;
	guchar buf[128];
	guchar *ptr = buf;
	gint total_read = 0;
	gint total_wanted = 0;
	gint zerocount = 0;
	gchar  *message = NULL;
	gint attempt = 0;

	/* Probe for response 
	 * First check for signature (running state)
	 * If that fails, see if we are in bootloader mode already
	 */

	flush_serial(fd,BOTH);
sig_check:
	if (attempt > 1)
		return FALSE;
	res = write (fd,"S",1);
	flush_serial(fd,OUTBOUND);
	if (res != 1)
		output("Failure sending signature request!\n",FALSE);
	g_usleep(300000); /* 300ms timeout */
	total_read = 0;
	total_wanted = size;
	zerocount = 0;
	while ((total_read < total_wanted ) && (total_wanted-total_read) > 0 )
	{
		total_read += res = read(fd,
				ptr+total_read,
				total_wanted-total_read);
		/* If we get nothing back (i.e. timeout, assume done)*/
		if (res <= 0)
			break;
	}
	if (total_read > 0)
	{
		message = g_strndup(((gchar *)buf),total_read);
		/* Check for "what" or "Boot" */
		if (g_strrstr_len(message,total_read, "Vector"))
		{
			g_free(message);
			output("ECU has corrupted firmware!\n",FALSE);
			return FALSE;
		}
		else if (g_strrstr_len(message,total_read, "what"))
		{
			g_free(message);
			attempt++;
			output("ECU is in bootloader mode, attempting reboot\n",FALSE);
			res = write (fd,"X",1);
			flush_serial(fd,BOTH);
			g_usleep(500000);
			goto sig_check;
		}
		else if (g_strrstr_len(message,total_read, "Boot"))
		{
			g_free(message);
			output("ECU is in bootloader mode, attempting reboot\n",FALSE);
			attempt++;
			res = write (fd,"X",1);
			flush_serial(fd,BOTH);
			g_usleep(500000);
			goto sig_check;
		}
		else	
		{
			output(g_strdup_printf("Detected signature: \"%s\"\n",message),TRUE);
			g_free(message);
			return TRUE;
		}
	}
	return FALSE;
}
Exemple #21
0
/**
 * gutachter_lookup_child:
 * @widget: the parent #GtkWidget or %NULL
 * @path: the path to the desired widget
 *
 * Lookup a child of @widget (or from the toplevel if @widget is %NULL).
 *
 * Returns: the child specified by @widget and @path or %NULL if not found.
 */
GtkWidget*
gutachter_lookup_child (GtkWidget  * widget,
                        gchar const* path)
{
  GtkWidget  * result = NULL;
  GList      * list;
  GList      * iterator;
  gchar const* lookup;
  gchar const* end;

  g_return_val_if_fail (path, NULL);
  if (!*path)
    {
      path = "urn:gtk:";
    }

  lookup = path;

  if (!g_str_has_prefix (lookup, "urn:"))
    {
      g_warning ("%s(%s): path is no URN: \"%s\" should start with \"urn:\"",
                 G_STRFUNC, G_STRLOC,
                 path);
      return NULL;
    }

  lookup += 4; /* path points to 32bit word boundary */

  if (!g_str_has_prefix (lookup, "gtk:"))
    {
      g_warning ("%s(%s): the URN's namespace doesn't match ours (\"gtk\"): %s",
                 G_STRFUNC, G_STRLOC,
                 path);
      return NULL;
    }

  lookup += 4; /* path points to 32bit and 64bit word boundary */

  if (widget)
    {
      result = widget;
    }
  else
    {
      if (!*lookup)
        {
          return NULL;
        }

      if (!g_str_has_prefix (lookup, "GtkWindow"))
        {
          g_warning ("the gtk namespace can only be used with GtkWindow functions");
          return NULL;
        }

      lookup += strlen ("GtkWindow");

      if (!g_str_has_prefix (lookup, "(\""))
        {
          g_warning ("GtkWindows can only be looked up by title right now (e.g. 'GtkWindow(\"window title\")'): %s",
                     path);
          return NULL;
        }

      lookup += 2;
      end = strstr (lookup, "\")");
      if (!end)
        {
          g_warning ("window title doesn't seem to be closed: %s", path);
          return NULL;
        }

      for (iterator = list = gtk_window_list_toplevels (); iterator; iterator = iterator->next)
        {
          gchar const* title = gtk_window_get_title (iterator->data);

          if (g_str_has_prefix (lookup, title) && *(title + (end - lookup)) == '\0')
            {
              result = iterator->data;
              break;
            }
        }
      g_list_free (list);

      if (!result)
        {
          /* no window found */
          return NULL;
        }

      lookup = end + 2; /* result holds the window now */

      if (*lookup == ':')
        {
          lookup++;
        }
    }

  while (*lookup != '\0')
    {
      gchar* type_name;
      GType  type;
      int    index;

      end = strstr (lookup, "[");
      if (!end)
        {
          g_warning ("the type starting at column %" G_GUINTPTR_FORMAT " doesn't have a lookup operator (\"[]\")",
                     lookup - path);
          return NULL;
        }

      type_name = g_strndup (lookup, end - lookup);
      type = g_type_from_name (type_name);
      if (!type)
        {
          g_warning ("couldn't lookup the type \"%s\". it is not registered. this "
                     "usually means that you have a typo in your string as the "
                     "creation of a widget would automatically register its type "
                     "(and its parent types)", type_name);
          g_free (type_name);
          return NULL;
        }
      g_free (type_name);

      lookup = end + 1;
      index = strtol (lookup, &type_name, 10); /* FIXME: watch for ERANGE in errno */
      end = type_name; /* use type_name because it is non-const */

      if (!end || *end != ']')
        {
          g_warning ("the index starting at column %" G_GUINTPTR_FORMAT " doesn't seem to be properly terminated: expected ']', got '%c': %s",
                     lookup - path, *end,
                     path);
          return NULL;
        }

      if (!GTK_IS_CONTAINER (result))
        {
          gchar* result_end = g_strrstr_len (path, lookup - path, ":");
          gchar* result_path = g_strndup (path, result_end - path);
          g_warning ("the widget specified by \"%s\" is a %s (which is not a GtkContainer)",
                     result_path,
                     G_OBJECT_TYPE_NAME (result));
          g_free (result_path);
          return NULL;
        }

      list = gtk_container_get_children (GTK_CONTAINER (result));
      iterator = g_list_nth (list, index);
      if (!iterator)
        {
          g_warning ("%s doesn't have a child with the index %d",
                     G_OBJECT_TYPE_NAME (result), index);
          g_list_free (list);
          return NULL;
        }
      result = iterator->data;
      g_list_free (list);

      lookup = end + 1;
      if (*lookup == '\0')
        {
          break;
        }
      else if (*lookup == ':')
        {
          lookup++;
          continue;
        }
      else
        {
          g_warning ("unexpected character after widget lookup (column %" G_GUINTPTR_FORMAT "): expected dereferencing (\":\") or end: '%c'",
                     lookup - path, *lookup);
          return NULL;
        }
    }

  return result;
}
Exemple #22
0
/*!
  \brief bind_data() is a recursive function that is called for every container
  widget in a glade frame and it's purpose is to search the datamap file passed
  for the widget names in the glade file and if it's fond in the datamap to
  load all the attribues listed and bind them to the object using GTK+'s
  object model.
  \param widget is the widget passed to load attributes on
  \param user_data is the pointer to a BingGroup structure.
  */
G_MODULE_EXPORT void bind_data(GtkWidget *widget, gpointer user_data)
{
	BindGroup *bindgroup = (BindGroup *)user_data;
	ConfigFile *cfgfile = bindgroup->cfgfile;
	GHashTable *groups = bindgroup->groups;
	gchar * tmpbuf = NULL;
	gchar * section = NULL;
	gchar ** keys = NULL;
	gint num_keys = 0;
	gint offset = 0;
	gint page = 0;
	gint index = 0;
	gchar * initializer = NULL;
	GdkColor color;
	gchar *size = NULL;
	gint count = 0;
	gint tmpi = 0;
	gboolean hidden = FALSE;
	gchar *ptr = NULL;
	gchar **vector = NULL;
	gchar **vec2 = NULL;
	void (*func)(void) = NULL;
	GList *list = NULL;
	GList *list2 = NULL;
	const gchar *name = NULL;
	gboolean indexed = FALSE;
	Firmware_Details *firmware = NULL;
	GList ***ecu_widgets = NULL;
	GList *tab_widgets = NULL;
	void (*load_dep_obj)(GObject *, ConfigFile *,const gchar *,const gchar *) = NULL;

	ENTER();
	MTXDBG(TABLOADER,_("Entered"));
	ecu_widgets = (GList ***)DATA_GET(global_data,"ecu_widgets");
	firmware = (Firmware_Details *)DATA_GET(global_data,"firmware");

	g_return_if_fail(ecu_widgets);
	g_return_if_fail(firmware);

	if (!GTK_IS_WIDGET(widget))
	{
		EXIT();
		return;
	}

	if (GTK_IS_WIDGET(widget))
		if (GTK_IS_CONTAINER(widget))
			gtk_container_foreach(GTK_CONTAINER(widget),bind_data,user_data);
	name = gtk_widget_get_name(widget);
	if (!name)
	{
		EXIT();
		return;
	}

	if (NULL != (ptr = g_strrstr_len(name,strlen(name),"_of_")))
	{
		indexed = TRUE;
		ptr = g_strrstr_len(name,ptr-name,"_");
		tmpbuf = g_strdelimit(g_strdup(ptr),"_",' ');
		section = g_strndup(name,ptr-name);
		/*printf("(indexed) section is %s\n",section);*/
		gint result = sscanf(tmpbuf,"%d of %d",&index,&count);
		/*printf("sscanf result %i\n",result);*
		* printf("Found indexed value for \"%s\", index %i, count %i\n",tmpbuf,index,count);
		*/
		g_free(tmpbuf);
	}
	else
		section = g_strdup(name);

	if(cfg_read_string(cfgfile, section, "keys", &tmpbuf))
	{
		keys = parse_keys(tmpbuf,&num_keys,",");
		MTXDBG(TABLOADER,_("Number of keys for %s is %i\n"),section,num_keys);
		g_free(tmpbuf);
	}
	else 
	{
		g_free(section);
		EXIT();
		return;
	}

	page = -1;
	/* Store ptr to self in qdata, needed for bind_to_lists from groups*/
	OBJ_SET(widget,"self",widget);
	/* Bind the data in the "defaults" group per tab to EVERY var in that
	 * tab
	 */
	page = bind_group_data(cfgfile, G_OBJECT(widget), groups, "defaults");

	if(cfg_read_string(cfgfile, section, "group", &tmpbuf))
	{
		page = bind_group_data(cfgfile,G_OBJECT(widget),groups,tmpbuf);
		g_free(tmpbuf);
	}

	if ((!cfg_read_int(cfgfile, section, "page", &page)) && (page == -1))
	{
		MTXDBG(TABLOADER|CRITICAL,_("Object %s doesn't have a page assigned!!!!\n"),section);	

	}
	/* Bind widgets to lists if they have the bind_to_list flag set...
	 */
	tmpbuf = NULL;
	if (cfg_read_string(cfgfile, section, "bind_to_list", &tmpbuf))
	{
		bind_to_lists(widget, tmpbuf);
		g_free(tmpbuf);
	}
	if (cfg_read_boolean(cfgfile,section,"ellipsize",&tmpi))
	{
		if ((GTK_IS_LABEL(widget)) && (tmpi))
		{
			OBJ_SET(widget,"ellipsize_preferred",GINT_TO_POINTER(TRUE));
			if (DATA_GET(global_data,"ellipsize_tabs"))
				gtk_label_set_ellipsize(GTK_LABEL(widget),PANGO_ELLIPSIZE_END);
		}
	}

	/* Color selections */
	if (cfg_read_string(cfgfile, section, "active_fg", &tmpbuf))
	{
		gdk_color_parse(tmpbuf, &color);
		gtk_widget_modify_fg(widget, GTK_STATE_NORMAL, &color);
		g_free(tmpbuf);
	}
	if (cfg_read_string(cfgfile, section, "inactive_fg", &tmpbuf))
	{
		gdk_color_parse(tmpbuf, &color);
		gtk_widget_modify_fg(widget, GTK_STATE_INSENSITIVE, &color);
		g_free(tmpbuf);
	}

	/* If this widget has a "depend_on" tag we need to load the dependancy
	 * information  and store it for use when needed...
	 */
	if (cfg_read_string(cfgfile,section,"depend_on",&tmpbuf))
	{
		if (get_symbol("load_dependencies_obj",(void **)&load_dep_obj))
			load_dep_obj(G_OBJECT(widget),cfgfile,section,"depend_on");
		g_free(tmpbuf);
	}

	/* If this widget (a textview) has "create_tags" we call a special
	 * handler just for that..
	 */
	if (cfg_read_string(cfgfile,section,"create_tags",&tmpbuf))
	{
		load_tags(G_OBJECT(widget),cfgfile,section);
		g_free(tmpbuf);
	}

	/* If this widget has "tooltip" set the tip on the widget */
	if (cfg_read_string(cfgfile,section,"tooltip",&tmpbuf))
	{
		gtk_widget_set_tooltip_text(widget,tmpbuf);
		g_free(tmpbuf);
	}

	/* If this widget (a label) has "set_label" we set the label on it
	 */
	if (cfg_read_string(cfgfile,section,"set_label",&tmpbuf))
	{
/*		printf("setting label on %s to \"%s\"\n",glade_get_widget_name(widget),tmpbuf);*/
		gtk_label_set_text(GTK_LABEL(widget),tmpbuf);
		g_free(tmpbuf);
	}

	/* If this widget is temp dependant, set the current units on it 
	 */
	if (cfg_read_string(cfgfile,section,"temp_dep",&tmpbuf))
	{
		OBJ_SET(widget,"widget_temp",DATA_GET(global_data,"mtx_temp_units"));
		g_free(tmpbuf);
	}

	/* If this widget has "register_as", register it with the supplied name
	 */
	if (cfg_read_string(cfgfile,section,"register_as",&tmpbuf))
	{
		register_widget(tmpbuf,widget);
		g_free(tmpbuf);
	}
	/* If this widget has visible_functions defined */
	if (cfg_read_string(cfgfile,section,"visible_functions",&tmpbuf))
	{
		vector = g_strsplit(tmpbuf,",",-1);
		g_free(tmpbuf);
		for (guint i=0;i<g_strv_length(vector);i++)
		{
			vec2 = g_strsplit(vector[i],":",2);
			if (g_strv_length(vec2) != 2)
			{
				printf("ERROR in %s, visible_functions param is missing the framerate parameter (func:fps)\n",cfgfile->filename);
				g_strfreev(vec2);
				continue;
			}
			gint fps = (GINT)g_strtod(vec2[1],NULL);
			get_symbol(vec2[0],(void **)&func);
			if (func)
			{
				list = g_list_prepend(list,(gpointer)func);
				list2 = g_list_prepend(list2,GINT_TO_POINTER(fps));
			}
			g_strfreev(vec2);
		}
		g_strfreev(vector);
		OBJ_SET_FULL(widget,"func_list",list,g_list_free);
		OBJ_SET_FULL(widget,"func_fps_list",list2,g_list_free);
	}

	/* If this widget has "initializer" there's a global variable 
	 * with it's name on it 
	 */
	if (cfg_read_string(cfgfile,section,"initializer",&initializer))
	{
		gint widget_type = 0;
		if (!cfg_read_string(cfgfile,section,"widget_type",&tmpbuf))
			MTXDBG(TABLOADER|CRITICAL,_("Object %s has initializer, but no widget_type!!!!\n"),section);
		else
			widget_type = translate_string(tmpbuf);
		g_free(tmpbuf);
		switch (widget_type)
		{
			case MTX_RANGE:
				gtk_range_set_value(GTK_RANGE(widget),(GINT)DATA_GET(global_data,initializer));
				break;

			case MTX_SPINBUTTON:
				gtk_spin_button_set_value(GTK_SPIN_BUTTON(widget),(GINT)DATA_GET(global_data,initializer));
				break;
			case MTX_ENTRY:
				gtk_entry_set_text(GTK_ENTRY(widget),(gchar *)DATA_GET(global_data,initializer));

			default:
				break;

		}
		g_free(initializer);
	}
	/* Hidden widgets have special handlers and should NOT be updated normally */
	cfg_read_boolean(cfgfile,section, "hidden", &hidden);
	offset = -1;
	cfg_read_int(cfgfile,section, "offset", &offset);
	if (offset >= 0 && indexed)
	{
		/*printf("indexed widget %s\n",name); */
		if (cfg_read_string(cfgfile, section, "size", &size))
		{
			offset += index * get_multiplier ((DataSize)translate_string (size));
			g_free(size);
		}
		else
		{
			if(OBJ_GET(widget, "size"))
			{
				offset += index * get_multiplier ((DataSize)(GINT)OBJ_GET(widget, "size"));
			}
			else
			{
				MTXDBG(TABLOADER|CRITICAL,_("Indexed Object %s has index and offset, but no size!!!!\n"),section);
				g_free(section);
				EXIT();
				return;
			}
		}
		/*printf("widget %s, offset %i\n",name,offset);*/
		OBJ_SET(widget,"offset",GINT_TO_POINTER(offset));
	}
	if (offset >= 0)
	{
		/* The way we do it now is to STORE widgets in LISTS for each
		 * offset, thus we can have multiple on screen controls bound
		 * to single data offset in the ECU
		 */
		if (page < 0)
		{
			MTXDBG(TABLOADER|CRITICAL,_("Attempting to append widget beyond bounds of Firmware Parameters,  there is a bug with this datamap widget %s, page %i, at offset %i...\n\n"),section,page,offset);
			g_free(section);
			EXIT();
			return;
		}
		if (page < firmware->total_pages)
		{
			if (offset >= firmware->page_params[page]->length)
				MTXDBG(TABLOADER|CRITICAL,_("Attempting to append widget beyond bounds of Firmware Parameters,  there is a bug with this datamap widget %s, at offset %i...\n\n"),section,offset);
			else if (!hidden)
			{

				tab_widgets = OBJ_GET(bindgroup->topframe,"tab_widgets");
				tab_widgets = g_list_prepend(tab_widgets, widget);
				OBJ_SET(bindgroup->topframe,"tab_widgets",tab_widgets);
				ecu_widgets[page][offset] = g_list_prepend(
						ecu_widgets[page][offset],
						(gpointer)widget);
			}
		}
		else
			MTXDBG(TABLOADER|CRITICAL,_("Attempting to append widget beyond bounds of Firmware Parameters, there is a bug with this datamap for widget %s, at page %i offset %i...\n\n"),section,page,offset);
	}

	/* If there is a "group" key in a section it means that it gets the
	 * rest of it's setting from the groupname listed.  This reduces
	 * redundant keys all throughout the file...
	 */
	bind_keys(G_OBJECT(widget), cfgfile, section, keys, num_keys);
	g_strfreev(keys);

	/* If this widget has the "choices" key (combobox)
	 */
	if (cfg_read_string(cfgfile,section,"choices",&tmpbuf))
	{
		combo_setup(G_OBJECT(widget),cfgfile,section);
		g_free(tmpbuf);
	}

	if (cfg_read_string(cfgfile,section,"post_functions_with_arg",&tmpbuf))
	{
		run_post_functions_with_arg(tmpbuf,widget);
		g_free(tmpbuf);
	}
	if (cfg_read_string(cfgfile,section,"post_functions",&tmpbuf))
	{
		run_post_functions(tmpbuf);
		g_free(tmpbuf);
	}
	if (cfg_read_boolean(cfgfile,section,"show_widget",&tmpi))
	{
		if (tmpi)
			gtk_widget_show(widget);
		else
			gtk_widget_hide(widget);
	}
	if (cfg_read_string(cfgfile,section,"set_tab_labels",&tmpbuf))
	{
		if (GTK_IS_NOTEBOOK(widget))
		{
			vector=g_strsplit(tmpbuf,",",-1);
			if (gtk_notebook_get_n_pages(GTK_NOTEBOOK(widget)) == g_strv_length(vector))
			{
				for (int i=0;i<g_strv_length(vector);i++)
				{
					gtk_notebook_set_tab_label_text(GTK_NOTEBOOK(widget),
							gtk_notebook_get_nth_page(GTK_NOTEBOOK(widget),i),
							vector[i]);
				}
			}
			g_strfreev(vector);
		}
		g_free(tmpbuf);
	}
	g_free(section);
	MTXDBG(TABLOADER,_("Leaving"));
	EXIT();
	return;
}
Exemple #23
0
static estr_t
_vfs_translate_path (const char *path, int size, GIConv defcnv, GString * buffer)
{
    estr_t state = ESTR_SUCCESS;
#ifdef HAVE_CHARSET
    const char *semi;
    const char *slash;

    if (size == 0)
        return ESTR_SUCCESS;

    size = (size > 0) ? size : (signed int) strlen (path);

    /* try found /#enc: */
    semi = g_strrstr_len (path, size, VFS_ENCODING_PREFIX);
    if (semi != NULL && (semi == path || *(semi - 1) == PATH_SEP))
    {
        char encoding[16];
        GIConv coder = INVALID_CONV;
        int ms;

        /* first must be translated part before #enc: */
        ms = semi - path;

        state = _vfs_translate_path (path, ms, defcnv, buffer);

        if (state != ESTR_SUCCESS)
            return state;

        /* now can be translated part after #enc: */
        semi += strlen (VFS_ENCODING_PREFIX);   /* skip "#enc:" */
        slash = strchr (semi, PATH_SEP);
        /* ignore slashes after size; */
        if (slash - path >= size)
            slash = NULL;

        ms = (slash != NULL) ? slash - semi : (int) strlen (semi);
        ms = min ((unsigned int) ms, sizeof (encoding) - 1);
        /* limit encoding size (ms) to path size (size) */
        if (semi + ms > path + size)
            ms = path + size - semi;
        memcpy (encoding, semi, ms);
        encoding[ms] = '\0';

        if (is_supported_encoding (encoding))
            coder = str_crt_conv_to (encoding);

        if (coder != INVALID_CONV)
        {
            if (slash != NULL)
                state = str_vfs_convert_to (coder, slash + 1, path + size - slash - 1, buffer);
            str_close_conv (coder);
            return state;
        }

        errno = EINVAL;
        state = ESTR_FAILURE;
    }
    else
    {
        /* path can be translated whole at once */
        state = str_vfs_convert_to (defcnv, path, size, buffer);
    }
#else
    (void) size;
    (void) defcnv;

    g_string_assign (buffer, path);
#endif /* HAVE_CHARSET */

    return state;
}
Exemple #24
0
EcuState detect_ecu(gint fd)
{
	gint res = 0;
	gint size = 1024;
	guchar buf[1024];
	guchar *ptr = buf;
	gint total_read = 0;
	gint total_wanted = 0;
	gint zerocount = 0;
	gchar  *message = NULL;

	/* Probe for response 
	 * First check for signature (running state)
	 * If that fails, see if we are in bootloader mode already
	 */

	res = write (fd,"S",1);
	flush_serial(fd,BOTH);
	if (res != 1)
		output("Failure sending signature request!\n",FALSE);
	g_usleep(300000); /* 300ms timeout */
	total_read = 0;
	total_wanted = size;
	zerocount = 0;
	while ((total_read < total_wanted ) && (total_wanted-total_read) > 0 )
	{
		total_read += res = read(fd,
				ptr+total_read,
				total_wanted-total_read);

		/* If we get nothing back (i.e. timeout, assume done)*/
		if (res <= 0)
			zerocount++;

		if (zerocount > 1)
			break;
	}
	if (total_read > 0)
	{
		message = g_strndup(((gchar *)buf),total_read);
		/* Check for "what" or "Boot" */
		if (g_strrstr_len(message,total_read, "what"))
		{
			g_free(message);
			return IN_BOOTLOADER;
		}
		else if (g_strrstr_len(message,total_read, "Boot"))
		{
			g_free(message);
			return IN_BOOTLOADER;
		}
		else	
		{
			output(g_strdup_printf("ECU signature: \"%s\"\n",message),TRUE);
			g_free(message);
			return  LIVE_MODE;
		}
	}

	return NOT_LISTENING;
}
Exemple #25
0
/* Trash everything. */
gboolean cmd_wipe_in_line(struct cmdline* cmd, enum direction dir) {
	gchar* CR_l;
	gchar* CR_r;
	int chars;

	switch (dir) {

		case D_RIGHT:	/* Clear to right (in this line) */

			/* Find the ^M to the right. */
			if (cmd->is_utf8) {
				CR_r = g_utf8_strchr(
						cmd->data->str + cmd->pos,
						cmd->data->len - cmd->pos,
						g_utf8_get_char("\015"));
			}
			else
				CR_r = strchr(cmd->data->str + cmd->pos, '\015');

			if (!CR_r) {
				/* Erase everything to the right -- no ^Ms to take into
				   account. */
				cmd->data = g_string_truncate(cmd->data, cmd->pos);
			}
			else {
				/* Erase to the right up to the first ^M. */
				if (cmd->is_utf8) {
					chars = g_utf8_pointer_to_offset(
							cmd->data->str + cmd->pos, CR_r);
				}
				else
					chars = (CR_r - cmd->data->str) - cmd->pos;

				cmd_del_chars(cmd, chars);

				/* If we were at pos 0, this is the new pos 0; delete the
				   CR. */
				if (cmd->pos == 0)
					cmd_del_chars(cmd, 1);
			}
			break;

		case D_LEFT:	/* Clear to left -- I've never seen this happen. */
			g_return_val_if_reached(FALSE);
			break;

		case D_ALL:	/* Clear all (in this line). */

			/* Find the ^M to the right. */
			if (cmd->is_utf8) {
				CR_r = g_utf8_strchr(
						cmd->data->str + cmd->pos,
						cmd->data->len - cmd->pos,
						g_utf8_get_char("\015"));
			}
			else
				CR_r = strchr(cmd->data->str + cmd->pos, '\015');

			if (!CR_r)
				CR_r = cmd->data->str + cmd->data->len;
			
			/* Find the ^M to the left. */
			if (cmd->is_utf8) {
				CR_l = g_utf8_strrchr(cmd->data->str, cmd->pos,
						g_utf8_get_char("\015"));
			}
			else
				CR_l = g_strrstr_len(cmd->data->str, cmd->pos, "\015");

			if (!CR_l)
				CR_l = cmd->data->str;

			/* Delete everything in-between. */
			cmd->pos = CR_l - cmd->data->str;

			if (cmd->is_utf8)
				chars = g_utf8_pointer_to_offset(CR_l, CR_r);
			else 
				chars = CR_r - CR_l;

			cmd_del_chars(cmd, chars);

			break;

		default:
			g_return_val_if_reached(FALSE);
			break;
	}

	action_queue(A_SEND_CMD);
	return TRUE;
}
Exemple #26
0
// getSong gets the name of the song and artist from the title of the winamp window
// and puts them in the buffers pointed to by title and artist
// len is the size of the title and artist buffers in bytes
// getSong returns FALSE if Winamp/foobar is closed or not playing, TRUE if it successfully got a song
static gboolean getSong(char** title, char** artist)
{
	wchar_t* wide_title;
	char* this_title;
	int count, playing, len;
	int titleSize = 0;
	HWND hwndPlayer;
	char *firsthyphen, *secondhyphen, *startString;

	if(privateMode)
	{
		return FALSE;
	}
	
	//get handle to winamp window
	hwndPlayer = FindWindow(winamp_wnd, NULL);
	if(hwndPlayer == NULL)
		return FALSE;

	playing = SendMessage(hwndPlayer, WM_WA_IPC, 0, IPC_ISPLAYING);
	switch (playing) {
	case 1: // PLAYING
		break;
	case 0: // STOPPED
	case 3: // PAUSED
	default:
		purple_debug_info("MusicInfo", "winamp isn't playing\n");
		return FALSE;
	}

	titleSize = GetWindowTextLength(hwndPlayer) + 1;
	if(titleSize > 0)
	{
		wide_title = g_malloc(titleSize * sizeof(wchar_t));	
		GetWindowText(hwndPlayer,wide_title,titleSize);
	}
	else
	{
		purple_debug_info("MusicInfo","title size was 0\n");
		return FALSE;
	}
		
	//convert to UTF8
	len = WideCharToMultiByte(CP_UTF8, 0, wide_title, -1, NULL, 0, NULL, NULL);
	this_title = g_malloc(len * sizeof(char));
	WideCharToMultiByte(CP_UTF8, 0, wide_title, -1, this_title, len, NULL, NULL);
	purple_debug_info("MusicInfo", "len=%d,this_title=%s\n", len, this_title); 
	g_free(wide_title);

	firsthyphen = g_strstr_len(this_title, len, " - ");

	if(firsthyphen == NULL)
	{
		purple_debug_info("MusicInfo","first hyphen was 0\n");
		g_free(this_title);
		return FALSE;
	}
	
	secondhyphen = g_strrstr_len(firsthyphen, len-(firsthyphen-this_title), " - ");

	startString = g_strstr_len(this_title, len, ".") + 2;

	count = 0;
	
	if(firsthyphen != secondhyphen) //we have an artist
	{
		len = firsthyphen - startString;
		*artist = g_strndup(startString, len);
		firsthyphen += 3;
	}
	else //no artist
	{
		*artist = g_strdup("Unknown");
		secondhyphen = firsthyphen;
		firsthyphen = startString;
	}

	//title should be between firsthyphen and secondhyphen
	purple_debug_info("MusicInfo", "artist is %s\n", *artist);
	len = secondhyphen - firsthyphen;
	*title = g_strndup(firsthyphen, len);
	purple_debug_info("MusicInfo", "title is %s\n", *title);

	g_free(this_title);

	return TRUE;
}