Example #1
0
gchar *
gedit_convert_to_utf8 (const gchar          *content,
		       gsize                 len,
		       const GeditEncoding **encoding,
		       gsize                *new_len,
		       GError              **error)
{
	gedit_debug (DEBUG_UTILS);

	g_return_val_if_fail (content != NULL, NULL);
	g_return_val_if_fail (encoding != NULL, NULL);

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

	if (*encoding != NULL)
	{
		const gchar* charset;
		
		charset = gedit_encoding_get_charset (*encoding);

		g_return_val_if_fail (charset != NULL, NULL);

		return gedit_convert_to_utf8_from_charset (content, 
							   len,
							   charset,
							   new_len,
							   error);
	}
	else
	{
		/* Automatically detect the encoding used */

		GSList *encodings;
		GSList *start;
		gchar *ret = NULL;

		gedit_debug_message (DEBUG_UTILS,
				     "Automatically detect the encoding used");

		encodings = gedit_prefs_manager_get_auto_detected_encodings ();

		if (encodings == NULL)
		{
			gedit_debug_message (DEBUG_UTILS, "encodings == NULL");

			if (g_utf8_validate (content, len, NULL))
			{
				gedit_debug_message (DEBUG_UTILS, "validate OK.");

				if (new_len != NULL)
					*new_len = len;
				
				return g_strndup (content, len);
			}
			else
			{
				gedit_debug_message (DEBUG_UTILS, "validate failed.");

				g_set_error (error, GEDIT_CONVERT_ERROR, 
					     GEDIT_CONVERT_ERROR_AUTO_DETECTION_FAILED,
				 	     "gedit was not able to automatically determine "
					     "the encoding of the file you want to open.");

				return NULL;
			}
		}

		gedit_debug_message (DEBUG_UTILS, "encodings != NULL");

		start = encodings;

		while (encodings != NULL) 
		{
			const GeditEncoding *enc;
			const gchar *charset;
			gchar *utf8_content;

			enc = (const GeditEncoding *)encodings->data;

			gedit_debug_message (DEBUG_UTILS, "Get charset");

			charset = gedit_encoding_get_charset (enc);
			g_return_val_if_fail (charset != NULL, NULL);

			gedit_debug_message (DEBUG_UTILS, "Trying to convert %lu bytes of data from '%s' to 'UTF-8'.", 
					(unsigned long) len, charset);

			utf8_content = gedit_convert_to_utf8_from_charset (content, 
									   len, 
									   charset, 
									   new_len,
									   NULL);

			if (utf8_content != NULL) 
			{
				*encoding = enc;
				ret = utf8_content;

				break;
			}

			encodings = g_slist_next (encodings);
		}

		if (ret == NULL)
		{
			gedit_debug_message (DEBUG_UTILS, "gedit has not been able to automatically determine the encoding of "
					     "the file you want to open.");

			g_set_error (error, GEDIT_CONVERT_ERROR,
				     GEDIT_CONVERT_ERROR_AUTO_DETECTION_FAILED,
			 	     "gedit was not able to automatically determine "
				     "the encoding of the file you want to open.");
		}

		g_slist_free (start);

		return ret;
	}

	g_return_val_if_reached (NULL);
}
Example #2
0
static void coincoin_message_ref(CoinCoinMessage* msg, GSList* messages)
{
	GString* s = g_string_sized_new(strlen(msg->message));
	gchar *start, *next;
	struct tm t;

	localtime_r(&msg->timestamp, &t);
	for(start = msg->message; *start; start = next)
	{
		next = g_utf8_next_char(start);
		/* totoz */
		if(*start == '[' && *(start+1) == ':')
		{
			gchar* end = start;
			while(*end && *end != ']')
				end = g_utf8_next_char(end);
			if(*end == ']')
			{
				++end;
				g_string_append(s, "<FONT COLOR=\"dark green\">");
				g_string_append_len(s, start, end-start);
				g_string_append(s, "</FONT>");
				next = end;
			}
			else
				g_string_append_len(s, start, next-start);
		}
		/* msg refs */
		else if((*start >= '0' && *start <= '9') || *start == ':')
		{
			unsigned ref = 1;
			gboolean ref_no_secs = FALSE;
			gchar* end = start;
			gchar* clock;

			while(*end && ((*end >= '0' && *end <= '9') || *end == ':'))
				end = g_utf8_next_char(end);

			/* Detect ¹²³ unicode refs. */
			if(*end == '\xc2')
			{
				if(end[1] == '\xb9') ref = 1;       // ¹
				else if(end[1] == '\xb2') ref = 2;  // ²
				else if(end[1] == '\xb3') ref = 3;  // ³
			}

			clock = g_strndup(start, end-start);
			if(sscanf(clock, "%02d:%02d:%02d:%u", &t.tm_hour, &t.tm_min, &t.tm_sec, &ref) == 4 ||
			   sscanf(clock, "%02d:%02d:%02d", &t.tm_hour, &t.tm_min, &t.tm_sec) == 3 ||
			   (sscanf(clock, "%02d:%02d", &t.tm_hour, &t.tm_min) == 2 && (ref_no_secs = TRUE)))
			{
				GSList* m;
				struct tm m_t;
				for(m = messages; m; m = m->next)
				{
					CoinCoinMessage* cur = m->data;
					localtime_r(&cur->timestamp, &m_t);
					if (t.tm_hour == m_t.tm_hour &&
					    t.tm_min == m_t.tm_min &&
					    (ref_no_secs || (t.tm_sec == m_t.tm_sec && cur->ref == ref)))
						break;
				}
				if(m)
				{
					g_string_append(s, ((CoinCoinMessage*)m->data)->from);
					g_string_append(s, ": ");
				}
				g_string_append(s, "<FONT COLOR=\"blue\">");
				g_string_append(s, clock);
				g_string_append(s, "</FONT>");
			}
			else
				g_string_append(s, clock);

			g_free(clock);

			next = end;
		}
		else
			g_string_append_len(s, start, next-start);
	}
	g_free(msg->message);
	msg->message = g_string_free(s, FALSE);
}
Example #3
0
void
plugin_list_modules(FILE *out, gboolean verbose)
{
  GlobalConfig *cfg;
  GModule *mod;
  gchar **mod_paths;
  gint i, j, k;
  gboolean first = TRUE;

  cfg = cfg_new(CFG_CURRENT_VERSION);
  mod_paths = g_strsplit(module_path, ":", 0);
  for (i = 0; mod_paths[i]; i++)
    {
      GDir *dir;
      const gchar *fname;

      dir = g_dir_open(mod_paths[i], 0, NULL);
      if (!dir)
        continue;
      while ((fname = g_dir_read_name(dir)))
        {
          if (g_str_has_suffix(fname, G_MODULE_SUFFIX))
            {
              gchar *module_name;
              ModuleInfo *module_info;
              gboolean success;

              if (g_str_has_prefix(fname, "lib"))
                fname += 3;
              module_name = g_strndup(fname, (gint) (strlen(fname) - strlen(G_MODULE_SUFFIX) - 1));

              mod = plugin_dlopen_module(module_name, module_path);
              if (mod)
                success = g_module_symbol(mod, "module_info", (gpointer *) &module_info);
              else
                success = FALSE;
              if (verbose)
                {
                  fprintf(out, "Module: %s\n", module_name);
                  if (mod)
                    {
                      if (!success || !module_info)
                        {
                          fprintf(out, "Status: Unable to resolve module_info variable, probably not a syslog-ng module\n");
                        }
                      else
                        {
                          if (strcmp(module_info->canonical_name, module_name) != 0)
                            {
                              fprintf(out, "Status: This module is to be loaded under the name %s instead of %s\n", module_info->canonical_name, module_name);
                            }
                          else
                            {
                              gchar **lines;

                              fprintf(out, "Status: ok\n"
                                           "Version: %s\n"
                                           "Core-Revision: %s\n"
                                           "Description:\n", module_info->version, module_info->core_revision);

                              lines = g_strsplit(module_info->description, "\n", 0);
                              for (k = 0; lines[k]; k++)
                                fprintf(out, "  %s\n", lines[k][0] ? lines[k] : ".");
                              g_strfreev(lines);

                              fprintf(out, "Plugins:\n");
                              for (j = 0; j < module_info->plugins_len; j++)
                                {
                                  Plugin *plugin = &module_info->plugins[j];

                                  fprintf(out, "  %-15s %s\n", cfg_lexer_lookup_context_name_by_type(plugin->type), plugin->name);
                                }
                            }
                        }
                    }
                  else
                    {
                      fprintf(out, "Status: Unable to dlopen shared object, probably not a syslog-ng module\n");
                    }
                  fprintf(out, "\n");
                }
              else if (success && module_info)
                {
                  fprintf(out, "%s%s", first ? "" : ",", module_name);
                  first = FALSE;
                }
              g_free(module_name);
              if (mod)
                g_module_close(mod);
            }
        }
      g_dir_close(dir);
    }
  g_strfreev(mod_paths);
  if (!verbose)
    fprintf(out, "\n");
}
Example #4
0
static GSList*
split_module_list (const char *str, const char *path)
{
  GSList *retval = NULL;
  const char *p;
  const char *start;
  ModuleSplitState state = OUTSIDE_MODULE;
  ModuleSplitState last_state = OUTSIDE_MODULE;

  /*   fprintf (stderr, "Parsing: '%s'\n", str); */
  
  start = str;
  p = str;

  while (*p)
    {
#if PARSE_SPEW
      fprintf (stderr, "p: %c state: %d last_state: %d\n", *p, state, last_state);
#endif
      
      switch (state)
        {
        case OUTSIDE_MODULE:
          if (!MODULE_SEPARATOR (*p))
            state = IN_MODULE_NAME;          
          break;

        case IN_MODULE_NAME:
          if (isspace ((guchar)*p))
            {
              /* Need to look ahead to determine next state */
              const char *s = p;
              while (*s && isspace ((guchar)*s))
                ++s;

              if (*s == '\0')
                state = OUTSIDE_MODULE;
              else if (MODULE_SEPARATOR (*s))
                state = OUTSIDE_MODULE;
              else if (OPERATOR_CHAR (*s))
                state = BEFORE_OPERATOR;
              else
                state = OUTSIDE_MODULE;
            }
          else if (MODULE_SEPARATOR (*p))
            state = OUTSIDE_MODULE; /* comma precludes any operators */
          break;

        case BEFORE_OPERATOR:
          /* We know an operator is coming up here due to lookahead from
           * IN_MODULE_NAME
           */
          if (isspace ((guchar)*p))
            ; /* no change */
          else if (OPERATOR_CHAR (*p))
            state = IN_OPERATOR;
          else
            g_assert_not_reached ();
          break;

        case IN_OPERATOR:
          if (!OPERATOR_CHAR (*p))
            state = AFTER_OPERATOR;
          break;

        case AFTER_OPERATOR:
          if (!isspace ((guchar)*p))
            state = IN_MODULE_VERSION;
          break;

        case IN_MODULE_VERSION:
          if (MODULE_SEPARATOR (*p))
            state = OUTSIDE_MODULE;
          break;
          
        default:
          g_assert_not_reached ();
        }

      if (state == OUTSIDE_MODULE &&
          last_state != OUTSIDE_MODULE)
        {
          /* We left a module */
          char *module = g_strndup (start, p - start);
          retval = g_slist_prepend (retval, module);

#if PARSE_SPEW
          fprintf (stderr, "found module: '%s'\n", module);
#endif
          
          /* reset start */
          start = p;
        }
      
      last_state = state;
      ++p;
    }

  if (p != start)
    {
      /* get the last module */
      char *module = g_strndup (start, p - start);
      retval = g_slist_prepend (retval, module);

#if PARSE_SPEW
      fprintf (stderr, "found module: '%s'\n", module);
#endif
      
    }
  
  retval = g_slist_reverse (retval);

  return retval;
}
Example #5
0
gchar* coincoin_convert_message(CoinCoinAccount* cca, const char* msg)
{
	GString* s;
	const gchar *start, *next;

	gchar* _msg = purple_markup_strip_html(msg);

	if(purple_account_get_bool(cca->account, "no_reformat_messages", FALSE))
		return _msg;

	s = g_string_sized_new(strlen(_msg));

	for(start = _msg; *start; start = next)
	{
		next = g_utf8_next_char(start);
		while(*next && *next != ' ')
			next = g_utf8_next_char(next);

		if(next > start+2 && *next && next[-1] == ':')
		{
			unsigned ref = 1;
			const gchar *end = start;
			gchar *nickname;

			while(*end && *end != ':' && *end != '\xc2')
				end = g_utf8_next_char(end);

			nickname = g_strndup(start, end-start);
			if (*end == ':')
				++end;
			if(*end >= '0' && *end <= '9')
			{
				ref = strtoul(end, NULL, 10);
			}
			else if(*end == '\xc2')
			{
				if(end[1] == '\xb9') ref = 1;       // ¹
				else if(end[1] == '\xb2') ref = 2;  // ²
				else if(end[1] == '\xb3') ref = 3;  // ³
			}

			GSList *m;
			CoinCoinMessage* cur = NULL;
			unsigned found = 0;
			for(m = cca->messages; m; m = m->next)
			{
				cur = m->data;
				if (!strcasecmp(cur->from, nickname) && ++found == ref)
					break;
			}
			g_free(nickname);
			if(m)
			{
				struct tm t;
				localtime_r(&cur->timestamp, &t);
				g_string_append_printf(s, "%02d:%02d:%02d", t.tm_hour, t.tm_min, t.tm_sec);
				if (cur->multiple)
					g_string_append_printf(s, ":%d", cur->ref);
				continue;
			}
		}
		if(*next == ' ')
			next = g_utf8_next_char(next);

		g_string_append_len(s, start, next-start);
	}
	g_free(_msg);
	return g_string_free(s, FALSE);
}
Example #6
0
char *phonebook_set_folder(const char *current_folder,
		const char *new_folder, uint8_t flags, int *err)
{
	gboolean root, child;
	char *fullname = NULL, *tmp1, *tmp2, *base;
	int ret = 0, len;

	root = (g_strcmp0("/", current_folder) == 0);
	child = (new_folder && strlen(new_folder) != 0);

	/* Evolution back-end will support telecom/pb folder only */

	switch (flags) {
	case 0x02:
		/* Go back to root */
		if (!child) {
			fullname = g_strdup("/");
			goto done;
		}

		/* Go down 1 level */
		fullname = g_build_filename(current_folder, new_folder, NULL);
		if (strcmp("/telecom", fullname) != 0 &&
				strcmp("/telecom/pb", fullname) != 0) {
			g_free(fullname);
			fullname = NULL;
			ret = -ENOENT;
		}

		break;
	case 0x03:
		/* Go up 1 level */
		if (root) {
			/* Already root */
			ret = -EBADR;
			goto done;
		}

		/*
		 * Removing one level of the current folder. Current folder
		 * contains AT LEAST one level since it is not at root folder.
		 * Use glib utility functions to handle invalid chars in the
		 * folder path properly.
		 */
		tmp1 = g_path_get_basename(current_folder);
		tmp2 = g_strrstr(current_folder, tmp1);
		len = tmp2 - (current_folder + 1);

		g_free(tmp1);

		if (len == 0)
			base = g_strdup("/");
		else
			base = g_strndup(current_folder, len);

		/* Return one level only */
		if (!child) {
			fullname = base;
			goto done;
		}

		fullname = g_build_filename(base, new_folder, NULL);
		if (strcmp(fullname, "/telecom") != 0 &&
				strcmp(fullname, "/telecom/pb") != 0) {
			g_free(fullname);
			fullname = NULL;
			ret = -ENOENT;
		}

		g_free(base);

		break;
	default:
		ret = -EBADR;
		break;
	}

done:
	if (err)
		*err = ret;

	return fullname;
}
Example #7
0
gchar *
qof_book_normalize_counter_format_internal(const gchar *p,
        const gchar *gint64_format, gchar **err_msg)
{
    const gchar *conv_start, *base, *tmp = NULL;
    gchar *normalized_str = NULL, *aux_str = NULL;

    /* Validate a counter format. This is a very simple "parser" that
     * simply checks for a single gint64 conversion specification,
     * allowing all modifiers and flags that printf(3) specifies (except
     * for the * width and precision, which need an extra argument). */
    base = p;

    /* Skip a prefix of any character except % */
    while (*p)
    {
        /* Skip two adjacent percent marks, which are literal percent
         * marks */
        if (p[0] == '%' && p[1] == '%')
        {
            p += 2;
            continue;
        }
        /* Break on a single percent mark, which is the start of the
         * conversion specification */
        if (*p == '%')
            break;
        /* Skip all other characters */
        p++;
    }

    if (!*p)
    {
        if (err_msg)
            *err_msg = g_strdup("Format string ended without any conversion specification");
        return NULL;
    }

    /* Store the start of the conversion for error messages */
    conv_start = p;

    /* Skip the % */
    p++;

    /* See whether we have already reached the correct format
     * specification (e.g. "li" on Unix, "I64i" on Windows). */
    tmp = strstr(p, gint64_format);

    if (!tmp)
    {
        if (err_msg)
            *err_msg = g_strdup_printf("Format string doesn't contain requested format specifier: %s", gint64_format);
        return NULL;
    }

    /* Skip any number of flag characters */
    while (*p && (tmp != p) && strchr("#0- +'I", *p))
    {
        p++;
        tmp = strstr(p, gint64_format);
    }

    /* Skip any number of field width digits,
     * and precision specifier digits (including the leading dot) */
    while (*p && (tmp != p) && strchr("0123456789.", *p))
    {
        p++;
        tmp = strstr(p, gint64_format);
    }

    if (!*p)
    {
        if (err_msg)
            *err_msg = g_strdup_printf("Format string ended during the conversion specification. Conversion seen so far: %s", conv_start);
        return NULL;
    }

    /* See if the format string starts with the correct format
     * specification. */
    tmp = strstr(p, gint64_format);
    if (tmp == NULL)
    {
        if (err_msg)
            *err_msg = g_strdup_printf("Invalid length modifier and/or conversion specifier ('%.4s'), it should be: %s", p, gint64_format);
        return NULL;
    }
    else if (tmp != p)
    {
        if (err_msg)
            *err_msg = g_strdup_printf("Garbage before length modifier and/or conversion specifier: '%*s'", (int)(tmp - p), p);
        return NULL;
    }

    /* Copy the string we have so far and add normalized format specifier for long int */
    aux_str = g_strndup (base, p - base);
    normalized_str = g_strconcat (aux_str, PRIi64, NULL);
    g_free (aux_str);

    /* Skip length modifier / conversion specifier */
    p += strlen(gint64_format);
    tmp = p;

    /* Skip a suffix of any character except % */
    while (*p)
    {
        /* Skip two adjacent percent marks, which are literal percent
         * marks */
        if (p[0] == '%' && p[1] == '%')
        {
            p += 2;
            continue;
        }
        /* Break on a single percent mark, which is the start of the
         * conversion specification */
        if (*p == '%')
        {
            if (err_msg)
                *err_msg = g_strdup_printf("Format string contains unescaped %% signs (or multiple conversion specifications) at '%s'", p);
            g_free (normalized_str);
            return NULL;
        }
        /* Skip all other characters */
        p++;
    }

    /* Add the suffix to our normalized string */
    aux_str = normalized_str;
    normalized_str = g_strconcat (aux_str, tmp, NULL);
    g_free (aux_str);

    /* If we end up here, the string was valid, so return no error
     * message */
    return normalized_str;
}
Example #8
0
/* expand a single {abstract ...data... } */
static char *theme_format_expand_abstract(THEME_REC *theme,
					  const char **formatp,
					  char default_fg, char default_bg,
					  int flags)
{
	const char *p, *format;
	char *abstract, *data, *ret;
	int len;

	format = *formatp;

	/* get abstract name first */
	p = format;
	while (*p != '\0' && *p != ' ' &&
	       *p != '{' && *p != '}') p++;
	if (*p == '\0' || p == format)
		return NULL; /* error */

	len = (int) (p-format);
	abstract = g_strndup(format, len);

	/* skip the following space, if there's any more spaces they're
	   treated as arguments */
	if (*p == ' ') {
		len++;
		if ((flags & EXPAND_FLAG_IGNORE_EMPTY) && data_is_empty(&p)) {
			*formatp = p;
			g_free(abstract);
			return NULL;
		}
	}
	*formatp = format+len;

	/* get the abstract data */
	data = g_hash_table_lookup(theme->abstracts, abstract);
	g_free(abstract);
	if (data == NULL) {
		/* unknown abstract, just display the data */
		data = "$0-";
	}
	abstract = g_strdup(data);

	/* we'll need to get the data part. it may contain
	   more abstracts, they are automatically expanded. */
	data = theme_format_expand_data(theme, formatp, default_fg, default_bg,
					NULL, NULL, flags);
	len = strlen(data);

	if (len > 1 && i_isdigit(data[len-1]) && data[len-2] == '$') {
		/* ends with $<digit> .. this breaks things if next
		   character is digit or '-' */
                char digit, *tmp;

		tmp = data;
		digit = tmp[len-1];
		tmp[len-1] = '\0';

		data = g_strdup_printf("%s{%c}", tmp, digit);
		g_free(tmp);
	}

	ret = parse_special_string(abstract, NULL, NULL, data, NULL,
				   PARSE_FLAG_ONLY_ARGS);
	g_free(abstract);
        g_free(data);
	abstract = ret;

	/* abstract may itself contain abstracts or replaces */
	p = abstract;
	ret = theme_format_expand_data(theme, &p, default_fg, default_bg,
				       &default_fg, &default_bg,
				       flags | EXPAND_FLAG_LASTCOLOR_ARG);
	g_free(abstract);
	return ret;
}
Example #9
0
/*
 * Like JSEnumerateOp, but enum provides contextual information as follows:
 *
 * JSENUMERATE_INIT: allocate private enum struct in state_p, return number
 * of elements in *id_p
 * JSENUMERATE_NEXT: return next property id in *id_p, and if no new property
 * free state_p and set to JSVAL_NULL
 * JSENUMERATE_DESTROY : destroy state_p
 *
 * Note that in a for ... in loop, this will be called first on the object,
 * then on its prototype.
 *
 */
static JSBool
importer_new_enumerate(JSContext  *context,
                       JSObject  **object,
                       JSIterateOp enum_op,
                       jsval      *state_p,
                       jsid       *id_p)
{
    ImporterIterator *iter;

    switch (enum_op) {
    case JSENUMERATE_INIT_ALL:
    case JSENUMERATE_INIT: {
        Importer *priv;
        JSObject *search_path;
        jsval search_path_val;
        guint32 search_path_len;
        guint32 i;

        if (state_p)
            *state_p = JSVAL_NULL;

        if (id_p)
            *id_p = INT_TO_JSID(0);

        priv = priv_from_js(context, *object);

        if (!priv)
            /* we are enumerating the prototype properties */
            return JS_TRUE;

        if (!gjs_object_require_property(context, *object, "importer", "searchPath", &search_path_val))
            return JS_FALSE;

        if (!JSVAL_IS_OBJECT(search_path_val)) {
            gjs_throw(context, "searchPath property on importer is not an object");
            return JS_FALSE;
        }

        search_path = JSVAL_TO_OBJECT(search_path_val);

        if (!JS_IsArrayObject(context, search_path)) {
            gjs_throw(context, "searchPath property on importer is not an array");
            return JS_FALSE;
        }

        if (!JS_GetArrayLength(context, search_path, &search_path_len)) {
            gjs_throw(context, "searchPath array has no length");
            return JS_FALSE;
        }

        iter = importer_iterator_new();

        for (i = 0; i < search_path_len; ++i) {
            char *dirname = NULL;
            char *init_path;
            const char *filename;
            jsval elem;
            GDir *dir = NULL;

            elem = JSVAL_VOID;
            if (!JS_GetElement(context, search_path, i, &elem)) {
                /* this means there was an exception, while elem == JSVAL_VOID
                 * means no element found
                 */
                importer_iterator_free(iter);
                return JS_FALSE;
            }

            if (JSVAL_IS_VOID(elem))
                continue;

            if (!JSVAL_IS_STRING(elem)) {
                gjs_throw(context, "importer searchPath contains non-string");
                importer_iterator_free(iter);
                return JS_FALSE;
            }

            if (!gjs_string_to_utf8(context, elem, &dirname)) {
                importer_iterator_free(iter);
                return JS_FALSE; /* Error message already set */
            }

            init_path = g_build_filename(dirname, MODULE_INIT_FILENAME,
                                         NULL);

            load_module_elements(context, *object, iter, init_path);

            g_free(init_path);

            dir = g_dir_open(dirname, 0, NULL);

            if (!dir) {
                g_free(dirname);
                continue;
            }

            while ((filename = g_dir_read_name(dir))) {
                char *full_path;

                /* skip hidden files and directories (.svn, .git, ...) */
                if (filename[0] == '.')
                    continue;

                /* skip module init file */
                if (strcmp(filename, MODULE_INIT_FILENAME) == 0)
                    continue;

                full_path = g_build_filename(dirname, filename, NULL);

                if (g_file_test(full_path, G_FILE_TEST_IS_DIR)) {
                    g_ptr_array_add(iter->elements, g_strdup(filename));
                } else {
                    if (g_str_has_suffix(filename, "."G_MODULE_SUFFIX) ||
                        g_str_has_suffix(filename, ".js")) {
                        g_ptr_array_add(iter->elements,
                                        g_strndup(filename, strlen(filename) - 3));
                    }
                }

                g_free(full_path);
            }
            g_dir_close(dir);

            g_free(dirname);
        }

        if (state_p)
            *state_p = PRIVATE_TO_JSVAL(iter);

        if (id_p)
            *id_p = INT_TO_JSID(iter->elements->len);

        break;
    }

    case JSENUMERATE_NEXT: {
        jsval element_val;

        if (!state_p) {
            gjs_throw(context, "Enumerate with no iterator set?");
            return JS_FALSE;
        }

        if (JSVAL_IS_NULL(*state_p)) /* Iterating prototype */
            return JS_TRUE;

        iter = JSVAL_TO_PRIVATE(*state_p);

        if (iter->index < iter->elements->len) {
            if (!gjs_string_from_utf8(context,
                                         g_ptr_array_index(iter->elements,
                                                           iter->index++),
                                         -1,
                                         &element_val))
                return JS_FALSE;

            if (!JS_ValueToId(context, element_val, id_p))
                return JS_FALSE;

            break;
        }
        /* else fall through to destroying the iterator */
    }

    case JSENUMERATE_DESTROY: {
        if (state_p && !JSVAL_IS_NULL(*state_p)) {
            iter = JSVAL_TO_PRIVATE(*state_p);

            importer_iterator_free(iter);

            *state_p = JSVAL_NULL;
        }
    }
    }

    return JS_TRUE;
}
Example #10
0
static void
svgtopng (const gchar *src)
{
  gchar *dest;
  gchar *tmp;
  GdkPixbuf *pix;
  gchar *link;
  gchar *newlink;
  GError *error = NULL;
  gchar *dirname;
  gchar *basename;
  gint icon_size;

  if (!g_str_has_suffix (src, ".svg"))
    return;

  /* get parent directory name */
  dirname = g_path_get_dirname (src);
  basename = g_path_get_basename (dirname);
  g_free (dirname);
  if (basename == NULL)
    return;

  /* to go get an icon size */
  icon_size = atoi (basename);
  g_free (basename);
  if (icon_size == 0)
    {
      g_message ("Unable to extract icon size from directory name %s", src);
      return;
    }

  tmp = g_strndup (src, strlen (src) - 3);
  dest = g_strconcat (tmp, "png", NULL);
  g_free (tmp);

  if (!g_file_test (dest, G_FILE_TEST_EXISTS))
    {
      if (g_file_test (src, G_FILE_TEST_IS_SYMLINK))
        {
          link = g_file_read_link (src, NULL);
          if (link
              && g_str_has_suffix (link, ".svg"))
            {
              tmp = g_strndup (link, strlen (link) - 3);
              newlink = g_strconcat (tmp, "png", NULL);
              g_free (tmp);

              if (symlink (newlink, dest) == -1)
                g_message ("failed to create symlink: %s", g_strerror (errno));

              g_free (newlink);
            }
          g_free (link);
        }
      else
        {
          pix = gdk_pixbuf_new_from_file (src, &error);
          if (pix)
            {
              if (gdk_pixbuf_get_width (pix) > icon_size
                  || gdk_pixbuf_get_height (pix) > icon_size)
                {
                  g_message ("Skipping %s, size too big (%dx%d instead of %dx%d)",
                             dest, gdk_pixbuf_get_width (pix),
                             gdk_pixbuf_get_height (pix),
                             icon_size, icon_size);

                  g_object_unref (pix);
                  return;
                }

              if (!gdk_pixbuf_save (pix, dest, "png", &error, NULL))
                {
                  g_message ("Failed to save pixmap to %s: %s", dest, error->message);
                  g_error_free (error);
                }
              g_object_unref (pix);
            }
          else
            {
              g_message ("Failed to load svg %s: %s", src, error->message);
              g_error_free (error);
            }
        }
    }

  g_free (dest);
}
static void web_mateconf_changed_cb(MateConfPropertyEditor* peditor, gchar* key, MateConfValue* value, MateDACapplet* capplet)
{
    MateConfChangeSet *cs;
    GError *error = NULL;
    GList *list_entry;

    /* This function is used to update HTTPS,ABOUT and UNKNOWN handlers, which
     * should also use the same value as HTTP
     */

    if (strcmp (key, DEFAULT_APPS_KEY_HTTP_EXEC) == 0) {
	gchar *short_browser, *pos;
	const gchar *value_str = mateconf_value_get_string (value);

	cs = mateconf_change_set_new ();

	mateconf_change_set_set (cs, DEFAULT_APPS_KEY_HTTPS_EXEC, value);
	mateconf_change_set_set (cs, DEFAULT_APPS_KEY_UNKNOWN_EXEC, value);
	mateconf_change_set_set (cs, DEFAULT_APPS_KEY_ABOUT_EXEC, value);
	pos = strstr (value_str, " ");
	if (pos == NULL)
	    short_browser = g_strdup (value_str);
	else
	    short_browser = g_strndup (value_str, pos - value_str);
	mateconf_change_set_set_string (cs, DEFAULT_APPS_KEY_BROWSER_EXEC, short_browser);
	g_free (short_browser);

	list_entry = g_list_find_custom (capplet->web_browsers,
					 value_str,
					 (GCompareFunc) web_item_comp);

	if (list_entry) {
	    MateDAWebItem *item = (MateDAWebItem *) list_entry->data;

	    mateconf_change_set_set_bool (cs, DEFAULT_APPS_KEY_BROWSER_NREMOTE, item->netscape_remote);
	}

	mateconf_client_commit_change_set (capplet->mateconf, cs, TRUE, &error);

	if (error != NULL) {
	    g_warning (_("Error saving configuration: %s"), error->message);
	    g_error_free (error);
	    error = NULL;
	}

	mateconf_change_set_unref (cs);
    }
    else if (strcmp (key, DEFAULT_APPS_KEY_HTTP_NEEDS_TERM) == 0) {
	gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (capplet->web_browser_terminal_checkbutton),
				      mateconf_value_get_bool (value));

	cs = mateconf_change_set_new ();

	mateconf_change_set_set (cs, DEFAULT_APPS_KEY_HTTPS_NEEDS_TERM, value);
	mateconf_change_set_set (cs, DEFAULT_APPS_KEY_UNKNOWN_NEEDS_TERM, value);
	mateconf_change_set_set (cs, DEFAULT_APPS_KEY_ABOUT_NEEDS_TERM, value);
	mateconf_change_set_set (cs, DEFAULT_APPS_KEY_BROWSER_NEEDS_TERM, value);

	mateconf_client_commit_change_set (capplet->mateconf, cs, TRUE, &error);

	if (error != NULL) {
	    g_warning (_("Error saving configuration: %s"), error->message);
	    g_error_free (error);
	    error = NULL;
	}

	mateconf_change_set_unref (cs);
    }
}
Example #12
0
/**
 * ajoute le séparateur des milliers passé en paramètre
 *
 * \param string to modify WARNING string is free
 *
 * \return a new allocated sring
 * */
gchar *gsb_real_add_thousands_sep ( gchar *str_number, const gchar *thousands_sep )
{
    gchar *mon_thousands_sep;
    gchar *result = NULL;
    gchar *ptr;
    gchar *dest;
    gchar *tmp_ptr;
    gchar **tab_str = NULL;
    gint nbre_char;
    gint i = 0;
    gint j = 0;
    gint sep = 0;
    gint longueur;

    if ( thousands_sep == NULL )
        return str_number;

    nbre_char = strlen ( str_number );
    str_number = g_strreverse ( str_number );
    ptr = str_number;

    if ( ( longueur = strlen ( thousands_sep ) ) == 1 )
        mon_thousands_sep = g_strndup ( thousands_sep, 1 );
    else
        mon_thousands_sep = g_strndup ( "&", 1 );

    dest = g_malloc0 ( 128 * sizeof ( gchar ) );
    tmp_ptr = dest;

    while ( i < nbre_char )
    {
        dest[i+sep] = ptr[0];

        ptr++;
        tmp_ptr++;
        i++;
        j++;
        if ( i < nbre_char && j == 3 )
        {
            tmp_ptr = g_stpcpy ( tmp_ptr, mon_thousands_sep );
            j = 0;
            sep++;
        }
    };

    result = g_strndup ( dest, nbre_char + sep );
    result = g_strreverse ( result );

    /* on met le bon séparateur si necessaire */
    if ( longueur > 1 )
    {
        tab_str = g_strsplit ( result, "&", 0 );
        g_free ( result );

        result = g_strjoinv ( thousands_sep, tab_str );
        g_strfreev ( tab_str );
    }

    g_free ( mon_thousands_sep );
    g_free ( str_number );
    g_free ( dest );

    return result;
}
Example #13
0
File: hime.c Project: Tetralet/hime
int main(int argc, char **argv)
{
  char *destroy = getenv("HIME_DESTROY_WINDOW");
  if (destroy)
    destroy_window = atoi(destroy);
//  printf("HIME_DESTROY_WINDOW=%d\n",destroy_window);

  gtk_init (&argc, &argv);

  signal(SIGCHLD, SIG_IGN);
  signal(SIGPIPE, SIG_IGN);

  if (getenv("HIME_DAEMON")) {
    daemon(1,1);
#if FREEBSD
    setpgid(0, getpid());
#else
    setpgrp();
#endif
  }

  set_is_chs();

  char *lc_ctype = getenv("LC_CTYPE");
  char *lc_all = getenv("LC_ALL");
  char *lang = getenv("LANG");
  if (!lc_ctype && lang)
    lc_ctype = lang;

  if (lc_all)
    lc_ctype = lc_all;

  if (!lc_ctype)
    lc_ctype = "zh_TW.Big5";
  dbg("hime get env LC_CTYPE=%s  LC_ALL=%s  LANG=%s\n", lc_ctype, lc_all, lang);

#if USE_XIM
  char *t = strchr(lc_ctype, '.');
  if (t) {
    int len = t - lc_ctype;
#if MAC_OS || FREEBSD
    lc = strdup(lc_ctype);
    lc[len] = 0;
#else
    lc = g_strndup(lc_ctype, len);
#endif
  }
  else
    lc = lc_ctype;

  dbg("hime XIM will use %s as the default encoding\n", lc_ctype);
#endif

  if (argc == 2 && (!strcmp(argv[1], "-v") || !strcmp(argv[1], "--version") || !strcmp(argv[1], "-h")) ) {
#if GIT_HAVE
    p_err(" version %s (git %s)\n", HIME_VERSION, GIT_HASH);
#else
    p_err(" version %s\n", HIME_VERSION);
#endif
  }

  init_TableDir();
  load_setttings();
  load_gtab_list(TRUE);


#if HIME_i18n_message
  bind_textdomain_codeset(GETTEXT_PACKAGE, "UTF-8");
  textdomain(GETTEXT_PACKAGE);
#endif

  dbg("after gtk_init\n");

  dpy = GDK_DISPLAY();
  root=DefaultRootWindow(dpy);
  get_dpy_xyl();
  g_signal_connect(gdk_screen_get_default(),"size-changed", G_CALLBACK(screen_size_changed), NULL);

  dbg("display width:%d height:%d\n", dpy_xl, dpy_yl);

  start_inmd_window();

#if USE_XIM
  open_xim();
#endif

  gdk_window_add_filter(NULL, my_gdk_filter, NULL);

  init_atom_property();
  signal(SIGINT, sig_do_exit);
  signal(SIGHUP, sig_do_exit);
  // disable the io handler abort
  // void *olderr =
    XSetErrorHandler((XErrorHandler)xerror_handler);

  init_hime_im_serv(xim_xwin);

  exec_setup_scripts();

  g_timeout_add(200, delayed_start_cb, NULL); // Old setting is 5000 here.

  dbg("before gtk_main\n");

  disp_win_kbm_capslock_init();

  gtk_main();

  return 0;
}
Example #14
0
static gchar *
gedit_convert_to_utf8_from_charset (const gchar  *content,
				    gsize         len,
				    const gchar  *charset,
				    gsize        *new_len,
				    GError 	**error)
{
	gchar *utf8_content = NULL;
	GError *conv_error = NULL;
	gchar* converted_contents = NULL;
	gsize bytes_read;
	
	g_return_val_if_fail (content != NULL, NULL);
	g_return_val_if_fail (len > 0, NULL);
	g_return_val_if_fail (charset != NULL, NULL);

	gedit_debug_message (DEBUG_UTILS, "Trying to convert from %s to UTF-8", charset);
	
	if (strcmp (charset, "UTF-8") == 0)
	{
		if (g_utf8_validate (content, len, NULL))
		{
			if (new_len != NULL)
				*new_len = len;
					
			return g_strndup (content, len);
		}
		else
		{	
			g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
				     "The file you are trying to open contains an invalid byte sequence.");
		
			return NULL;
		}
	}
	
	converted_contents = g_convert (content, 
					len, 
					"UTF-8",
					charset, 
					&bytes_read, 
					new_len,
					&conv_error); 

	gedit_debug_message (DEBUG_UTILS, "Bytes read: %" G_GSIZE_FORMAT, bytes_read);

	/* There is no way we can avoid to run 	g_utf8_validate on the converted text.
	 *
	 * <paolo> hmmm... but in that case g_convert should fail 
	 * <owen> paolo: g_convert() doesn't necessarily have the same definition
         * <owen> GLib just uses the system's iconv
         * <owen> paolo: I think we've explained what's going on. 
         * I have to define it as NOTABUG since g_convert() isn't going to 
         * start post-processing or checking what iconv() does and 
         * changing g_utf8_valdidate() wouldn't be API compatible even if I 
         * thought it was right
	 */			
	if ((conv_error != NULL) || 
	    !g_utf8_validate (converted_contents, *new_len, NULL) ||
	    (bytes_read != len))
	{
		gedit_debug_message (DEBUG_UTILS, "Couldn't convert from %s to UTF-8.",
			   	     charset);
				
		if (converted_contents != NULL)
			g_free (converted_contents);

		if (conv_error != NULL)
			g_propagate_error (error, conv_error);		
		else
		{
			gedit_debug_message (DEBUG_UTILS, "The file you are trying to open contains "
					     "an invalid byte sequence.");
			
			g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
				     "The file you are trying to open contains an invalid byte sequence.");
		}	
	} 
	else 
	{
		gedit_debug_message (DEBUG_UTILS,
				     "Converted from %s to UTF-8 (newlen = %" G_GSIZE_FORMAT ").", 
				     charset, *new_len);

		g_return_val_if_fail (converted_contents != NULL, NULL); 

		utf8_content = converted_contents;
	}

	return utf8_content;
}
Example #15
0
/**
 * Compares the URL of an image to the 'new' value. If the two
 * are different, the image at the 'new' URL is retrieved and replaces
 * the old one. The old one is freed.
 *
 * @param pcStorage Pointer to the storage location with the first value.
 * @param pImage Pointer to the image storage.
 * @param pczNewURL The new url.
 * @param szURLLength The length of the new URL.
 *
 * @return 0 on succes, -1 on failure.
 */
static gint
setImageIfDifferent(gchar ** pcStorage,
                    GdkPixbuf ** pImage,
                    const gchar * pczNewURL,
                    const gsize szURLLength)
{
  int err = 0;

  // if diffrent, clear and set
  if (g_strcmp0(*pcStorage, pczNewURL))
    {
      g_free(*pcStorage);

      *pcStorage = g_strndup(pczNewURL, szURLLength);

      if (*pImage)
        {
          g_object_unref(*pImage);

          *pImage = NULL;
        }
      
      // retrieve the URL and create the new image
      gint iRetCode = 0;
      gint iDataSize = 0;

      gpointer pResponse = getURL(pczNewURL, &iRetCode, &iDataSize);

      if (!pResponse || iRetCode != HTTP_STATUS_OK)
        {
          LXW_LOG(LXW_ERROR, "yahooutil::setImageIfDifferent(): Failed to get URL (%d, %d)", 
                  iRetCode, iDataSize);

          return -1;
        }

      GInputStream * pInputStream = g_memory_input_stream_new_from_data(pResponse,
                                                                        iDataSize,
                                                                        g_free);

      GError * pError = NULL;

      *pImage = gdk_pixbuf_new_from_stream(pInputStream,
                                           NULL,
                                           &pError);

      if (!*pImage)
        {
          LXW_LOG(LXW_ERROR, "yahooutil::setImageIfDifferent(): PixBuff allocation failed: %s",
                  pError->message);

          g_error_free(pError);
          
          err = -1;
        }

      if (!g_input_stream_close(pInputStream, NULL, &pError))
        {
          LXW_LOG(LXW_ERROR, "yahooutil::setImageIfDifferent(): InputStream closure failed: %s",
                  pError->message);

          g_error_free(pError);

          err = -1;
        }
      
    }

  return err;
}
int
main (int argc, char **argv)
{
  gchar *srcdir = getenv ("srcdir");
  gchar *testfile;
  gchar *contents;
  GError *error = NULL;
  gchar *p, *end;
  char *tmp;
  gint state = 0;
  gint line = 1;
  gint start_line = 0;		/* Quiet GCC */
  gchar *utf8 = NULL;		/* Quiet GCC */
  GArray *ucs4;
  Status status = VALID;	/* Quiet GCC */

  if (!srcdir)
    srcdir = ".";
  
  testfile = g_strconcat (srcdir, G_DIR_SEPARATOR_S "utf8.txt", NULL);
  
  g_file_get_contents (testfile, &contents, NULL, &error);
  if (error)
    croak ("Cannot open utf8.txt: %s", error->message);

  ucs4 = g_array_new (TRUE, FALSE, sizeof(gunichar));

  p = contents;

  /* Loop over lines */
  while (*p)
    {
      while (*p && (*p == ' ' || *p == '\t'))
	p++;

      end = p;
      while (*end && (*end != '\r' && *end != '\n'))
	end++;
      
      if (!*p || *p == '#' || *p == '\r' || *p == '\n')
	goto next_line;

      tmp = g_strstrip (g_strndup (p, end - p));
      
      switch (state)
	{
	case 0:
	  /* UTF-8 string */
	  start_line = line;
	  utf8 = tmp;
	  tmp = NULL;
	  break;
	  
	case 1:
	  /* Status */
	  if (!strcmp (tmp, "VALID"))
	    status = VALID;
	  else if (!strcmp (tmp, "INCOMPLETE"))
	    status = INCOMPLETE;
	  else if (!strcmp (tmp, "NOTUNICODE"))
	    status = NOTUNICODE;
	  else if (!strcmp (tmp, "OVERLONG"))
	    status = OVERLONG;
	  else if (!strcmp (tmp, "MALFORMED"))
	    status = MALFORMED;
	  else
	    croak ("Invalid status on line %d\n", line);

	  if (status != VALID && status != NOTUNICODE)
	    state++;		/* No UCS-4 data */
	  
	  break;
	  
	case 2:
	  /* UCS-4 version */

	  p = strtok (tmp, " \t");
	  while (p)
	    {
	      gchar *endptr;
	      
	      gunichar ch = strtoul (p, &endptr, 16);
	      if (*endptr != '\0')
		croak ("Invalid UCS-4 character on line %d\n", line);

	      g_array_append_val (ucs4, ch);
	      
	      p = strtok (NULL, " \t");
	    }

	  break;
	}

      g_free (tmp);
      state = (state + 1) % 3;

      if (state == 0)
	{
	  process (start_line, utf8, status, (gunichar *)ucs4->data, ucs4->len);
	  g_array_set_size (ucs4, 0);
	  g_free (utf8);
	}
      
    next_line:
      p = end;
      if (*p && *p == '\r')
	p++;
      if (*p && *p == '\n')
	p++;
      
      line++;
    }

  return exit_status;
}
Example #17
0
static void
dia_dnd_file_drag_data_received (GtkWidget        *widget,
                                 GdkDragContext   *context,
                                 gint              x,
                                 gint              y,
                                 GtkSelectionData *data,
                                 guint             info,
                                 guint             time,
				 DDisplay         *ddisp)
{
#if GTK_CHECK_VERSION(2,22,0)
  switch (gdk_drag_context_get_selected_action(context))
#else
  switch (context->action)
#endif
    {
    case GDK_ACTION_DEFAULT:
    case GDK_ACTION_COPY:
    case GDK_ACTION_MOVE:
    case GDK_ACTION_LINK:
    case GDK_ACTION_ASK:
    default:
      {
        Diagram *diagram = NULL;
        gchar *sPath = NULL, *pFrom, *pTo; 

        pFrom = strstr((gchar *) gtk_selection_data_get_data(data), "file:");
        while (pFrom) {
          GError *error = NULL;

          pTo = pFrom;
          while (*pTo != 0 && *pTo != 0xd && *pTo != 0xa) pTo ++;
          sPath = g_strndup(pFrom, pTo - pFrom);

          /* format changed with Gtk+2.0, use conversion */
          pFrom = g_filename_from_uri (sPath, NULL, &error);
	  if (!ddisp)
            diagram = diagram_load (pFrom, NULL);
	  else {
	    diagram = ddisp->diagram;
	    if (!diagram_load_into (diagram, pFrom, NULL)) {
	      /* the import filter is supposed to show the error message */
              gtk_drag_finish (context, TRUE, FALSE, time);
	      break;
	    }
	  }

          g_free (pFrom);
          g_free(sPath);

          if (diagram != NULL) {
            diagram_update_extents(diagram);
            layer_dialog_set_diagram(diagram);
            
	    if (diagram->displays == NULL) {
	      new_display(diagram);
	    }
          }

          pFrom = strstr(pTo, "file:");
        } /* while */
        gtk_drag_finish (context, TRUE, FALSE, time);
      }
      break;
    }
  return;
}
Example #18
0
gchar* trim_last_block(const gchar* str)
{
  g_assert(str != NULL);
  return g_strndup(str, strlen(str) - 22);
}
static void cd_exaile_getSongInfos(void)
{
	gchar *cQuery = cairo_dock_dbus_get_string (myData.dbus_proxy_player, "query");
	cd_debug ("MP : query : %s", cQuery);  // status: playing self: Jiken artist: Yoshihisa Hirano, Hideki Taniuchi album: Death Note Original Soundtrack length: 2:49 position: %4 [0:07]
	if (cQuery == NULL)
	{
		myData.iPlayingStatus = PLAYER_STOPPED;
		g_free (myData.cPlayingUri);
		myData.cPlayingUri = NULL;
		g_free (myData.cTitle);
		myData.cTitle = NULL;
		g_free (myData.cAlbum);
		myData.cAlbum = NULL;
		g_free (myData.cArtist);
		myData.cArtist = NULL;
		g_free (myData.cCoverPath);
		myData.cCoverPath = NULL;
		return ;
	}
	gchar *str, *str2;
	
	str = g_strstr_len (cQuery, -1, "status:");
	g_return_if_fail (str != NULL);
	str += 8;
	if (strncmp (str, "playing", 7) == 0)
		myData.iPlayingStatus = PLAYER_PLAYING;
	else if (strncmp (str, "paused", 6) == 0)
		myData.iPlayingStatus = PLAYER_PAUSED;
	else
		myData.iPlayingStatus = PLAYER_STOPPED;
	cd_debug ("  iPlayingStatus <- %d", myData.iPlayingStatus);
	if (myData.iPlayingStatus != PLAYER_PLAYING)
	{
		cd_debug ("exaile ne joue rien, on quitte\n");
		g_free (cQuery);
		return ;
	}
	
	str = g_strstr_len (str, -1, "self:");
	g_return_if_fail (str != NULL);
	str += 6;
	str2 = g_strstr_len (str, -1, "artist:");
	g_return_if_fail (str2 != NULL);
	g_free (myData.cTitle);
	myData.cTitle = g_strndup (str, str2 - str);
	cd_debug ("  cTitle <- %s", myData.cTitle);
	
	str = str2 + 8;
	str2 = g_strstr_len (str, -1, "album:");
	g_return_if_fail (str2 != NULL);
	g_free (myData.cArtist);
	myData.cArtist = g_strndup (str, str2 - str);
	cd_debug ("  cArtist <- %s", myData.cArtist);
	
	str = str2 + 7;
	str2 = g_strstr_len (str, -1, "length:");
	g_return_if_fail (str2 != NULL);
	g_free (myData.cAlbum);
	myData.cAlbum = g_strndup (str, str2 - str);
	cd_debug ("  cAlbum <- %s", myData.cAlbum);
	
	str = str2 + 8;
	str2 = g_strstr_len (str, -1, "position:");
	g_return_if_fail (str2 != NULL);
	myData.iSongLength = _get_time_from_string (str);
	cd_debug ("  iSongLength <- %d", myData.iSongLength);
	
	str = str2 + 10;
	str = strchr (str, '[');
	g_return_if_fail (str != NULL);
	myData.iCurrentTime = _get_time_from_string (str+1);
	cd_debug ("  iCurrentTime <- %d", myData.iCurrentTime);
	
	g_free (cQuery);
	
	g_free (myData.cRawTitle);
	myData.cRawTitle = g_strdup_printf ("%s - %s", myData.cAlbum, myData.cTitle);
}
Example #20
0
/**
 * thunar_util_expand_filename:
 * @filename          : a local filename.
 * @working_directory : #GFile of the current working directory.
 * @error             : return location for errors or %NULL.
 *
 * Takes a user-typed @filename and expands a tilde at the
 * beginning of the @filename. It also resolves paths prefixed with
 * '.' using the current working directory.
 *
 * The caller is responsible to free the returned string using
 * g_free() when no longer needed.
 *
 * Return value: the expanded @filename or %NULL on error.
 **/
gchar *
thunar_util_expand_filename (const gchar  *filename,
                             GFile        *working_directory,
                             GError      **error)
{
  struct passwd *passwd;
  const gchar   *replacement;
  const gchar   *remainder;
  const gchar   *slash;
  gchar         *username;
  gchar         *pwd;
  gchar         *result = NULL;

  g_return_val_if_fail (filename != NULL, NULL);

  /* check if we have a valid (non-empty!) filename */
  if (G_UNLIKELY (*filename == '\0'))
    {
      g_set_error (error, G_FILE_ERROR, G_FILE_ERROR_INVAL, _("Invalid path"));
      return NULL;
    }

  /* check if we start with a '~' */
  if (*filename == '~')
    {
      /* examine the remainder of the filename */
      remainder = filename + 1;

      /* if we have only the slash, then we want the home dir */
      if (G_UNLIKELY (*remainder == '\0'))
        return g_strdup (xfce_get_homedir ());

      /* lookup the slash */
      for (slash = remainder; *slash != '\0' && *slash != G_DIR_SEPARATOR; ++slash);

      /* check if a username was given after the '~' */
      if (G_LIKELY (slash == remainder))
        {
          /* replace the tilde with the home dir */
          replacement = xfce_get_homedir ();
        }
      else
        {
          /* lookup the pwd entry for the username */
          username = g_strndup (remainder, slash - remainder);
          passwd = getpwnam (username);
          g_free (username);

          /* check if we have a valid entry */
          if (G_UNLIKELY (passwd == NULL))
            {
              username = g_strndup (remainder, slash - remainder);
              g_set_error (error, G_FILE_ERROR, G_FILE_ERROR_INVAL, _("Unknown user \"%s\""), username);
              g_free (username);
              return NULL;
            }

          /* use the homedir of the specified user */
          replacement = passwd->pw_dir;
        }
    
      /* generate the filename */
      return g_build_filename (replacement, slash, NULL);
    }
  else if (*filename == '.')
    {
      /* examine the remainder of the filename */
      remainder = filename + 1;
      
      /* transform working directory into a filename string */
      if (G_LIKELY (working_directory != NULL))
        {
          pwd = g_file_get_path (working_directory);
    
          /* if we only have the slash then we want the working directory only */
          if (G_UNLIKELY (*remainder == '\0'))
            return pwd;

          /* concatenate working directory and remainder */
          result = g_build_filename (pwd, remainder, G_DIR_SEPARATOR_S, NULL);

          /* free the working directory string */
          g_free (pwd);
        }
      else
        result = g_strdup (filename);

      /* return the resulting path string */
      return result;
    }

  return g_strdup (filename);
}
Example #21
0
static char *
trim_and_sub (Package *pkg, const char *str, const char *path)
{
  char *trimmed;
  GString *subst;
  char *p;
  
  trimmed = trim_string (str);

  subst = g_string_new ("");

  p = trimmed;
  while (*p)
    {
      if (p[0] == '$' &&
          p[1] == '$')
        {
          /* escaped $ */
          g_string_append_c (subst, '$');
          p += 2;
        }
      else if (p[0] == '$' &&
               p[1] == '{')
        {
          /* variable */
          char *var_start;
          char *varname;
          char *varval;
          
          var_start = &p[2];

          /* Get up to close brace. */
          while (*p && *p != '}')
            ++p;

          varname = g_strndup (var_start, p - var_start);

          ++p; /* past brace */
          
          varval = package_get_var (pkg, varname);
          
          if (varval == NULL)
            {
              verbose_error ("Variable '%s' not defined in '%s'\n",
                             varname, path);
              
              exit (1);
            }

          g_free (varname);

          g_string_append (subst, varval);
          g_free (varval);
        }
      else
        {
          g_string_append_c (subst, *p);

          ++p;          
        }
    }

  g_free (trimmed);
  p = subst->str;
  g_string_free (subst, FALSE);

  return p;
}
Example #22
0
static void xa_parse_desktop_files(GSList **app_name_list,GSList **app_exe_list,GSList **app_icon_list,gchar *path,gchar *name)
{
	gchar *filename, *line, *key;
	gchar *app_name = NULL, *app_exe = NULL, *app_icon = NULL;
	GIOStatus status;
	GIOChannel *file;
	gboolean has_mimetype = FALSE;
	const gchar * const *langs, * const *l;
	gint size;

	filename = g_strconcat(path,"/",name,NULL);
	file = g_io_channel_new_file(filename,"r",NULL);
	g_free(filename);
	if (file == NULL)
		return;
	langs = g_get_language_names();
	g_io_channel_set_encoding(file,NULL,NULL);
	do
	{
		status = g_io_channel_read_line (file, &line, NULL, NULL, NULL);
		if (line != NULL)
		{
			if (g_str_has_prefix(line, "Name["))
			{
				l = langs;

				while (*l)
				{
					key = g_strconcat("Name[", *l, "]=", NULL);

					if (g_str_has_prefix(line, key))
					{
						g_free(app_name);
						app_name = g_strndup(line + strlen(key), strlen(line) - strlen(key) - 1);
						g_free(key);
						break;
					}

					g_free(key);
					l++;
				}
			}
			if (!app_name && g_str_has_prefix(line, "Name="))
			{
				app_name = g_strndup(line + 5,(strlen(line)-6));
				continue;
			}
			if (g_str_has_prefix(line,"Exec="))
			{
				app_exe = strstr(line," %");
				if (app_exe)
					app_exe = g_strndup(line + 5,app_exe - (line+5));
				else
					app_exe = g_strndup(line + 5,(strlen(line)-6));
				continue;
			}
			if (g_str_has_prefix(line,"Icon="))
			{
				app_icon = strrchr(line, '.');
				if (app_icon)
					app_icon = g_strndup(line + 5,app_icon - (line+5));
				else
					app_icon = g_strndup(line + 5,(strlen(line)-6));
				continue;
			}
			if (g_str_has_prefix(line,"MimeType="))
				has_mimetype = TRUE;
			g_free(line);
		}
	}
	while (status != G_IO_STATUS_EOF);
	if (has_mimetype)
	{
		*app_name_list	= g_slist_prepend(*app_name_list,app_name);
		*app_exe_list	= g_slist_prepend(*app_exe_list ,app_exe);
		if (app_icon == NULL)
			app_icon = "";
		if (gtk_combo_box_get_active(GTK_COMBO_BOX(prefs_window->combo_icon_size)) == 0)
			size = 40;
		else
			size = 24;
		*app_icon_list = g_slist_prepend(*app_icon_list, gtk_icon_theme_load_icon(icon_theme, app_icon, size, GTK_ICON_LOOKUP_FORCE_SIZE, NULL));
		g_io_channel_shutdown (file, TRUE, NULL);
		return;
	}
	if (app_name != NULL)
	{
		g_free(app_name);
		app_name = NULL;
	}
	if (app_exe != NULL)
	{
		g_free(app_exe);
		app_exe = NULL;
	}
	if (app_icon != NULL)
	{
		g_free(app_icon);
		app_icon = NULL;
	}
	g_io_channel_shutdown (file, TRUE, NULL);
}
Example #23
0
static void
parse_line (Package *pkg, const char *untrimmed, const char *path,
	    gboolean ignore_requires, gboolean ignore_private_libs,
	    gboolean ignore_requires_private)
{
  char *str;
  char *p;
  char *tag;

  debug_spew ("  line>%s\n", untrimmed);
  
  str = trim_string (untrimmed);
  
  if (*str == '\0') /* empty line */
    {
      g_free(str);
      return;
    }
  
  p = str;

  /* Get first word */
  while ((*p >= 'A' && *p <= 'Z') ||
	 (*p >= 'a' && *p <= 'z') ||
	 (*p >= '0' && *p <= '9') ||
	 *p == '_' || *p == '.')
    p++;

  tag = g_strndup (str, p - str);
  
  while (*p && isspace ((guchar)*p))
    ++p;

  if (*p == ':')
    {
      /* keyword */
      ++p;
      while (*p && isspace ((guchar)*p))
        ++p;

      if (strcmp (tag, "Name") == 0)
        parse_name (pkg, p, path);
      else if (strcmp (tag, "Description") == 0)
        parse_description (pkg, p, path);
      else if (strcmp (tag, "Version") == 0)
        parse_version (pkg, p, path);
      else if (strcmp (tag, "Requires.private") == 0)
	{
	  if (!ignore_requires_private)
	    parse_requires_private (pkg, p, path);
	}
      else if (strcmp (tag, "Requires") == 0)
	{
          if (ignore_requires == FALSE)
	    parse_requires (pkg, p, path);
          else
	    goto cleanup;
        }
      else if ((strcmp (tag, "Libs.private") == 0) && 
               ignore_private_libs == FALSE)
        parse_libs_private (pkg, p, path);
      else if (strcmp (tag, "Libs") == 0)
        parse_libs (pkg, p, path);
      else if (strcmp (tag, "Cflags") == 0 ||
               strcmp (tag, "CFlags") == 0)
        parse_cflags (pkg, p, path);
      else if (strcmp (tag, "Conflicts") == 0)
        parse_conflicts (pkg, p, path);
      else if (strcmp (tag, "URL") == 0)
        parse_url (pkg, p, path);
      else
        {
	  /* we don't error out on unknown keywords because they may
	   * represent additions to the .pc file format from future
	   * versions of pkg-config.  We do make a note of them in the
	   * debug spew though, in order to help catch mistakes in .pc
	   * files. */
          debug_spew ("Unknown keyword '%s' in '%s'\n",
		      tag, path);
        }
    }
  else if (*p == '=')
    {
      /* variable */
      char *varname;
      char *varval;
      
      ++p;
      while (*p && isspace ((guchar)*p))
        ++p;
      
      if (pkg->vars == NULL)
        pkg->vars = g_hash_table_new (g_str_hash, g_str_equal);

#ifdef G_OS_WIN32
      if (!dont_define_prefix && strcmp (tag, prefix_variable) == 0)
	{
	  /* This is the prefix variable. Try to guesstimate a value for it
	   * for this package from the location of the .pc file.
	   */

	  gchar *prefix = pkg->pcfiledir;
	  const int prefix_len = strlen (prefix);
	  const char *const lib_pkgconfig = "\\lib\\pkgconfig";
	  const char *const share_pkgconfig = "\\share\\pkgconfig";
	  const int lib_pkgconfig_len = strlen (lib_pkgconfig);
	  const int share_pkgconfig_len = strlen (share_pkgconfig);

	  if ((strlen (prefix) > lib_pkgconfig_len &&
	       pathnamecmp (prefix + prefix_len - lib_pkgconfig_len, lib_pkgconfig) == 0) ||
	      (strlen (prefix) > share_pkgconfig_len &&
	       pathnamecmp (prefix + prefix_len - share_pkgconfig_len, share_pkgconfig) == 0))
	    {
	      /* It ends in lib\pkgconfig or share\pkgconfig. Good. */
	      
	      gchar *q;
	      
	      orig_prefix = g_strdup (p);

	      prefix = g_strdup (prefix);
	      if (strlen (prefix) > lib_pkgconfig_len &&
		  pathnamecmp (prefix + prefix_len - lib_pkgconfig_len, lib_pkgconfig) == 0)
		prefix[prefix_len - lib_pkgconfig_len] = '\0';
	      else
		prefix[prefix_len - share_pkgconfig_len] = '\0';
	      
	      /* Turn backslashes into slashes or
	       * poptParseArgvString() will eat them when ${prefix}
	       * has been expanded in parse_libs().
	       */
	      q = prefix;
	      while (*q)
		{
		  if (*q == '\\')
		    *q = '/';
		  q++;
		}
	      varname = g_strdup (tag);
	      debug_spew (" Variable declaration, '%s' overridden with '%s'\n",
			  tag, prefix);
	      g_hash_table_insert (pkg->vars, varname, prefix);
	      goto cleanup;
	    }
	}
      else if (!dont_define_prefix &&
	       orig_prefix != NULL &&
	       strncmp (p, orig_prefix, strlen (orig_prefix)) == 0 &&
	       G_IS_DIR_SEPARATOR (p[strlen (orig_prefix)]))
	{
	  char *oldstr = str;

	  p = str = g_strconcat (g_hash_table_lookup (pkg->vars, prefix_variable), p + strlen (orig_prefix), NULL);
	  g_free (oldstr);
	}
#endif

      if (g_hash_table_lookup (pkg->vars, tag))
        {
          verbose_error ("Duplicate definition of variable '%s' in '%s'\n",
                         tag, path);

          exit (1);
        }

      varname = g_strdup (tag);
      varval = trim_and_sub (pkg, p, path);     

      debug_spew (" Variable declaration, '%s' has value '%s'\n",
                  varname, varval);
      g_hash_table_insert (pkg->vars, varname, varval);
  
    }

 cleanup:  
  g_free (str);
  g_free (tag);
}
Example #24
0
File: plugin.c Project: zzhhui/mlt
static void
plugin_create_aux_ports (plugin_t * plugin, guint copy, jack_rack_t * jack_rack)
{
    plugin_desc_t * desc;
//  plugin_slot_t * slot;
    unsigned long aux_channel = 1;
    unsigned long plugin_index = 1;
    unsigned long i;
    char port_name[64];
    char * plugin_name;
    char * ptr;
//  GList * list;
    ladspa_holder_t * holder;

    desc = plugin->desc;
    holder = plugin->holders + copy;

    holder->aux_ports = g_malloc (sizeof (jack_port_t *) * desc->aux_channels);

    /* make the plugin name jack worthy */
    ptr = plugin_name = g_strndup (plugin->desc->name, 7);
    while (*ptr != '\0')
    {
        if (*ptr == ' ')
            *ptr = '_';
        else
            *ptr = tolower (*ptr);

        ptr++;
    }

    /*
      for (list = jack_rack->slots; list; list = g_list_next (list))
        {
          slot = (plugin_slot_t *) list->data;

          if (slot->plugin->desc->id == plugin->desc->id)
            plugin_index++;
        }
    */

    for (i = 0; i < desc->aux_channels; i++, aux_channel++)
    {
        sprintf (port_name, "%s_%ld-%d_%c%ld",
                 plugin_name,
                 plugin_index,
                 copy + 1,
                 desc->aux_are_input ? 'i' : 'o',
                 aux_channel);

        holder->aux_ports[i] =
            jack_port_register (jack_rack->procinfo->jack_client,
                                port_name,
                                JACK_DEFAULT_AUDIO_TYPE,
                                desc->aux_are_input ? JackPortIsInput : JackPortIsOutput,
                                0);

        if (!holder->aux_ports[i])
        {
            mlt_log_panic( NULL, "Could not register jack port '%s'; aborting\n", port_name);
        }
    }

    g_free (plugin_name);
}
Example #25
0
/* From gcoincoin */
static gchar *strutf8( const gchar *pc, guint uMaxChar )
{
	gunichar     uCode ;
	guchar       b ;
	gsize        uLen ;
	GString     *pString ;
	guint        uChar ;
	const gchar *pcEnd ;

	if(( pc == NULL )||( *pc == 0 ))
	{
		return NULL ;
	}

	if( uMaxChar == 0 )
	{
		uMaxChar = G_MAXUINT ;
	}

	uLen  = strlen( pc );
	pcEnd = &pc[ uLen ];
	uChar = 0 ;

	if( g_utf8_validate( pc, (gssize) uLen, NULL ) )
	{
		const gchar *pcStart = pc ;
		while(( pc < pcEnd )&&( uChar < uMaxChar ))
		{
			pc = g_utf8_next_char(pc);
			uChar++ ;
		}
		return g_strndup( pcStart, pc - pcStart );
	}

	pString = g_string_sized_new( uLen );
	while(( pc < pcEnd )&&( uChar < uMaxChar ))
	{
		b = (guchar) *pc ;
		if( b < 128 )
		{
			/* Keep ASCII characters, but remove all control characters
			 * but CR, LF and TAB. */

			if(( b > 31 )&&( b != 127 ))
			{
				g_string_append_c( pString, b );
			}
			else
			{
				switch( b )
				{
					case '\n':
					case '\r':
					case '\t':
						break ;
					default:
						b = ' ' ;
				}
				g_string_append_c( pString, b );
			}
			pc++ ;
		}
		else
		{
			uCode = g_utf8_get_char_validated( pc, -1 );
			if(( uCode != (gunichar)-1 )&&( uCode != (gunichar)-2 ))
			{
				/* Keep a valid UTF-8 character as is */
				g_string_append_unichar( pString, uCode );
				pc = g_utf8_next_char(pc);
			}
			else
			{
				/* Consider an invalid byte as an ISO-8859-1 character code.
				 * We get rid of ASCII & ISO-8859-1 control characters. */

				if(( b > 0x1F )&&( b < 0x7F ))
				{
					/* ASCII characters, excluding control characters */
					g_string_append_c( pString, b );
				}
				else if( b > 0x9F )
				{
					/* ISO-8859-1 character, excluding control character (0x7F-0x9F) */
					g_string_append_unichar( pString, (gunichar)b );
				}
				else
				{
					g_string_append_c( pString, ' ' );
				}
				pc++ ;
			}
		}
		uChar++ ;
	}

	#ifdef DEBUG
		g_assert( g_utf8_validate( pString->str, -1, NULL ) );
	#endif

	return g_string_free( pString, FALSE );
}
Example #26
0
/**
 * gst_rtsp_url_parse:
 * @urlstr: the url string to parse
 * @url: (out): location to hold the result.
 *
 * Parse the RTSP @urlstr into a newly allocated #GstRTSPUrl. Free after usage
 * with gst_rtsp_url_free().
 *
 * Returns: a #GstRTSPResult.
 */
GstRTSPResult
gst_rtsp_url_parse (const gchar * urlstr, GstRTSPUrl ** url)
{
  GstRTSPUrl *res;
  gchar *p, *delim, *at, *col;
  gchar *host_end = NULL;
  guint i;

  g_return_val_if_fail (urlstr != NULL, GST_RTSP_EINVAL);
  g_return_val_if_fail (url != NULL, GST_RTSP_EINVAL);

  res = g_new0 (GstRTSPUrl, 1);

  p = (gchar *) urlstr;

  col = strstr (p, "://");
  if (col == NULL)
    goto invalid;

  for (i = 0; i < G_N_ELEMENTS (rtsp_schemes_map); i++) {
    if (g_ascii_strncasecmp (rtsp_schemes_map[i].scheme, p, col - p) == 0) {
      res->transports = rtsp_schemes_map[i].transports;
      p = col + 3;
      break;
    }
  }

  if (res->transports == GST_RTSP_LOWER_TRANS_UNKNOWN)
    goto invalid;

  delim = strpbrk (p, "/?");
  at = strchr (p, '@');

  if (at && delim && at > delim)
    at = NULL;

  if (at) {
    col = strchr (p, ':');

    /* must have a ':' and it must be before the '@' */
    if (col == NULL || col > at)
      goto invalid;

    res->user = g_strndup (p, col - p);
    col++;
    res->passwd = g_strndup (col, at - col);

    /* move to host */
    p = at + 1;
  }

  if (*p == '[') {
    res->family = GST_RTSP_FAM_INET6;

    /* we have an IPv6 address in the URL, find the ending ] which must be
     * before any delimiter */
    host_end = strchr (++p, ']');
    if (!host_end || (delim && host_end >= delim))
      goto invalid;

    /* a port specifier must follow the address immediately */
    col = host_end[1] == ':' ? host_end + 1 : NULL;
  } else {
    res->family = GST_RTSP_FAM_INET;

    col = strchr (p, ':');

    /* we have a ':' and a delimiter but the ':' is after the delimiter, it's
     * not really part of the hostname */
    if (col && delim && col >= delim)
      col = NULL;

    host_end = col ? col : delim;
  }

  if (!host_end)
    res->host = g_strdup (p);
  else {
    res->host = g_strndup (p, host_end - p);

    if (col) {
      res->port = strtoul (col + 1, NULL, 10);
    } else {
      /* no port specified, set to 0. gst_rtsp_url_get_port() will return the
       * default port */
      res->port = 0;
    }
  }
  p = delim;

  if (p && *p == '/') {
    delim = strchr (p, '?');
    if (!delim)
      res->abspath = g_strdup (p);
    else
      res->abspath = g_strndup (p, delim - p);
    p = delim;
  } else {
    res->abspath = g_strdup ("/");
  }

  if (p && *p == '?')
    res->query = g_strdup (p + 1);

  *url = res;

  return GST_RTSP_OK;

  /* ERRORS */
invalid:
  {
    gst_rtsp_url_free (res);
    return GST_RTSP_EINVAL;
  }
}
Example #27
0
void
plugin_load_candidate_modules(GlobalConfig *cfg)
{
  GModule *mod;
  gchar **mod_paths;
  gint i, j;

  mod_paths = g_strsplit(module_path, ":", 0);
  for (i = 0; mod_paths[i]; i++)
    {
      GDir *dir;
      const gchar *fname;

      dir = g_dir_open(mod_paths[i], 0, NULL);
      if (!dir)
        continue;
      while ((fname = g_dir_read_name(dir)))
        {
          if (g_str_has_suffix(fname, G_MODULE_SUFFIX))
            {
              gchar *module_name;
              ModuleInfo *module_info;
              gboolean success;

              if (g_str_has_prefix(fname, "lib"))
                fname += 3;
              module_name = g_strndup(fname, (gint) (strlen(fname) - strlen(G_MODULE_SUFFIX) - 1));

              mod = plugin_dlopen_module(module_name, module_path);
              if (mod)
                success = g_module_symbol(mod, "module_info", (gpointer *) &module_info);
              else
                success = FALSE;

              if (success && module_info)
                {
                  for (j = 0; j < module_info->plugins_len; j++)
                    {
                      Plugin *plugin = &module_info->plugins[j];
                      PluginCandidate *candidate_plugin;

                      candidate_plugin = (PluginCandidate *) plugin_find_in_list(cfg, cfg->candidate_plugins, plugin->type, plugin->name);
                      if (candidate_plugin)
                        {
                          if (candidate_plugin->preference < module_info->preference)
                            {
                              plugin_candidate_set_module_name(candidate_plugin, module_info->canonical_name);
                              plugin_candidate_set_preference(candidate_plugin, module_info->preference);
                            }
                        }
                      else
                        {
                          cfg->candidate_plugins = g_list_prepend(cfg->candidate_plugins, plugin_candidate_new(plugin->type, plugin->name, module_info->canonical_name, module_info->preference));
                        }
                    }
                }
              g_free(module_name);
              if (mod)
                g_module_close(mod);
              else
                mod = NULL;
            }
        }
      g_dir_close(dir);
    }
  g_strfreev(mod_paths);
}
Example #28
0
File: text.c Project: mpuels/dia
static void
set_string(Text *text, const char *string)
{
  int numlines, i;
  const char *s,*s2;
  char *fallback = NULL;

  if (string && !g_utf8_validate (string, -1, NULL)) {
    GError *error = NULL;
    s = fallback = g_locale_to_utf8 (string, -1, NULL, NULL, &error);
    if (!fallback) {
      g_warning ("Invalid string data, neither UTF-8 nor locale: %s", error->message);
      string = NULL;
    }
  } else {
    s = string;
  }
  numlines = 1;
  if (s != NULL) 
    while ( (s = g_utf8_strchr(s, -1, '\n')) != NULL ) {
      numlines++;
      if (*s) {
	s = g_utf8_next_char(s);
      }
    }
  text->numlines = numlines;
  text->lines = g_new0(TextLine *, numlines);
  for (i = 0; i < numlines; i++) {
    text->lines[i] = text_line_new("", text->font, text->height);
  }

  s = fallback ? fallback : string;
  if (s == NULL) {
    text_set_line_text(text, 0, "");
    return;
  }

  for (i = 0; i < numlines; i++) {
    gchar *string_line;
    s2 = g_utf8_strchr(s, -1, '\n');
    if (s2 == NULL) { /* No newline */
      s2 = s + strlen(s);
    }
    string_line = g_strndup(s, s2 - s);
    text_set_line_text(text, i, string_line);
    g_free(string_line);
    s = s2;
    if (*s) {
      s = g_utf8_next_char(s);
    }
  }

  if (text->cursor_row >= text->numlines) {
    text->cursor_row = text->numlines - 1;
  }
  
  if (text->cursor_pos > text_get_line_strlen(text, text->cursor_row)) {
    text->cursor_pos = text_get_line_strlen(text, text->cursor_row);
  }
  g_free (fallback);
}
Example #29
0
/**
 * dh_assistant_view_set_link:
 * @view: an devhelp assistant view
 * @link: the #DhLink
 *
 * Open @link in the assistant view, if %NULL the view will be blanked.
 *
 * Return value: %TRUE if the requested link is open, %FALSE otherwise.
 **/
gboolean
dh_assistant_view_set_link (DhAssistantView *view,
                            DhLink          *link)
{
        DhAssistantViewPriv *priv;
        gchar               *uri;
        const gchar         *anchor;
        gchar               *filename;
        GMappedFile         *file;
        const gchar         *contents;
        gsize                length;
        gchar               *key;
        gsize                key_length;
        gsize                offset = 0;
        const gchar         *start;
        const gchar         *end;

        g_return_val_if_fail (DH_IS_ASSISTANT_VIEW (view), FALSE);

        priv = GET_PRIVATE (view);

        if (priv->link == link) {
                return TRUE;
        }

        if (priv->link) {
                dh_link_unref (priv->link);
                priv->link = NULL;
        }

        if (link) {
                link = dh_link_ref (link);
        } else {
                webkit_web_view_load_uri (WEBKIT_WEB_VIEW (view), "about:blank");
                return TRUE;
        }

        uri = dh_link_get_uri (link);
        anchor = strrchr (uri, '#');
        if (anchor) {
                filename = g_strndup (uri, anchor - uri);
                anchor++;
                g_free (uri);
        } else {
                g_free (uri);
                return FALSE;
        }

        if (g_str_has_prefix (filename, "file://"))
            offset = 7;

        file = g_mapped_file_new (filename + offset, FALSE, NULL);
        if (!file) {
                g_free (filename);
                return FALSE;
        }

        contents = g_mapped_file_get_contents (file);
        length = g_mapped_file_get_length (file);

        key = g_strdup_printf ("<a name=\"%s\"", anchor);
        key_length = strlen (key);

        start = find_in_buffer (contents, key, length, key_length);
        g_free (key);

        end = NULL;

        if (start) {
                const gchar *start_key;
                const gchar *end_key;

                length -= start - contents;

                start_key = "<pre class=\"programlisting\">";

                start = find_in_buffer (start,
                                        start_key,
                                        length,
                                        strlen (start_key));

                end_key = "<div class=\"refsect";

                if (start) {
                        end = find_in_buffer (start, end_key,
                                              length - strlen (start_key),
                                              strlen (end_key));
                        if (!end) {
                                end_key = "<div class=\"footer";
                                end = find_in_buffer (start, end_key,
                                                      length - strlen (start_key),
                                                      strlen (end_key));
                        }
                }
        }

        if (start && end) {
                gchar       *buf;
                gboolean     break_line;
                const gchar *function;
                gchar       *stylesheet;
                gchar       *javascript;
                gchar       *html;

                buf = g_strndup (start, end-start);

                /* Try to reformat function signatures so they take less
                 * space and look nicer. Don't reformat things that don't
                 * look like functions.
                 */
                switch (dh_link_get_link_type (link)) {
                case DH_LINK_TYPE_FUNCTION:
                        break_line = TRUE;
                        function = "onload=\"reformatSignature()\"";
                        break;
                case DH_LINK_TYPE_MACRO:
                        break_line = TRUE;
                        function = "onload=\"cleanupSignature()\"";
                        break;
                default:
                        break_line = FALSE;
                        function = "";
                        break;
                }

                if (break_line) {
                        gchar *name;

                        name = strstr (buf, dh_link_get_name (link));
                        if (name && name > buf) {
                                name[-1] = '\n';
                        }
                }

                stylesheet = dh_util_build_data_filename ("devhelp",
                                                          "assistant",
                                                          "assistant.css",
                                                          NULL);
                javascript = dh_util_build_data_filename ("devhelp",
                                                          "assistant",
                                                          "assistant.js",
                                                          NULL);

                html = g_strdup_printf (
                        "<html>"
                        "<head>"
                        "<link rel=\"stylesheet\" type=\"text/css\" href=\"file://%s\"/>"
                        "<script src=\"file://%s\"></script>"
                        "</head>"
                        "<body %s>"
                        "<div class=\"title\">%s: <a href=\"%s\">%s</a></div>"
                        "<div class=\"subtitle\">%s %s</div>"
                        "<div class=\"content\">%s</div>"
                        "</body>"
                        "</html>",
                        stylesheet,
                        javascript,
                        function,
                        dh_link_get_type_as_string (link),
                        dh_link_get_uri (link),
                        dh_link_get_name (link),
                        _("Book:"),
                        dh_link_get_book_name (link),
                        buf);
                g_free (buf);

                g_free (stylesheet);
                g_free (javascript);

                priv->snippet_loaded = FALSE;
                webkit_web_view_load_string (
                        WEBKIT_WEB_VIEW (view),
                        html,
                        "text/html",
                        NULL,
                        filename);

                g_free (html);
        } else {
                webkit_web_view_load_uri (WEBKIT_WEB_VIEW (view), "about:blank");
        }

#if GLIB_CHECK_VERSION(2,21,3)
        g_mapped_file_unref (file);
#else
        g_mapped_file_free (file);
#endif

        g_free (filename);

        return TRUE;
}
Example #30
0
gchar *password_decrypt_gnutls(const gchar *password,
		const gchar *decryption_passphrase)
{
	gchar **tokens, *tmp;
	gnutls_cipher_algorithm_t algo;
	gnutls_cipher_hd_t handle;
	gnutls_datum_t key, iv;
	int keylen, blocklen, ret;
	gsize len;
	unsigned char *buf;
	guint rounds;
	size_t commapos;

	g_return_val_if_fail(password != NULL, NULL);
	g_return_val_if_fail(decryption_passphrase != NULL, NULL);

	tokens = g_strsplit_set(password, "{}", 3);

	/* Parse the string, retrieving algorithm and encrypted data.
	 * We expect "{algorithm,rounds}base64encodedciphertext". */
	if (tokens[0] == NULL || strlen(tokens[0]) != 0 ||
			tokens[1] == NULL || strlen(tokens[1]) == 0 ||
			tokens[2] == NULL || strlen(tokens[2]) == 0) {
		debug_print("Garbled password string.\n");
		g_strfreev(tokens);
		return NULL;
	}

	commapos = strcspn(tokens[1], ",");
	if (commapos == strlen(tokens[1]) || commapos == 0) {
		debug_print("Garbled algorithm substring.\n");
		g_strfreev(tokens);
		return NULL;
	}

	buf = g_strndup(tokens[1], commapos);
	if ((algo = gnutls_cipher_get_id(buf)) == GNUTLS_CIPHER_UNKNOWN) {
		debug_print("Password string has unknown algorithm: '%s'\n", buf);
		g_free(buf);
		g_strfreev(tokens);
		return NULL;
	}
	g_free(buf);

	if ((rounds = atoi(tokens[1] + commapos + 1)) <= 0) {
		debug_print("Invalid number of rounds: %d\n", rounds);
		g_strfreev(tokens);
		return NULL;
	}

/*	ivlen = gnutls_cipher_get_iv_size(algo); */
	keylen = gnutls_cipher_get_key_size(algo);
	blocklen = gnutls_cipher_get_block_size(algo);
/*	digestlen = gnutls_hash_get_len(digest); */

	/* Take the passphrase and compute a key derivation of suitable
	 * length to be used as encryption key for our block cipher. */
	key.data = _make_key_deriv(decryption_passphrase, rounds, keylen);
	key.size = keylen;

	/* Prepare random IV for cipher */
	iv.data = malloc(IVLEN);
	iv.size = IVLEN;
	if (!get_random_bytes(iv.data, IVLEN)) {
		g_free(key.data);
		g_free(iv.data);
		g_strfreev(tokens);
		return NULL;
	}

	/* Prepare encrypted password string for decryption. */
	tmp = g_base64_decode(tokens[2], &len);
	g_strfreev(tokens);

	/* Initialize the decryption */
	ret = gnutls_cipher_init(&handle, algo, &key, &iv);
	if (ret < 0) {
		debug_print("Cipher init failed: %s\n", gnutls_strerror(ret));
		g_free(key.data);
		g_free(iv.data);
		return NULL;
	}

	buf = malloc(BUFSIZE + blocklen);
	memset(buf, 0, BUFSIZE + blocklen);
	ret = gnutls_cipher_decrypt2(handle, tmp, len,
			buf, BUFSIZE + blocklen);
	if (ret < 0) {
		debug_print("Decryption failed: %s\n", gnutls_strerror(ret));
		g_free(key.data);
		g_free(iv.data);
		g_free(buf);
		gnutls_cipher_deinit(handle);
		return NULL;
	}

	/* Cleanup */
	gnutls_cipher_deinit(handle);
	g_free(key.data);
	g_free(iv.data);

	tmp = g_strndup(buf + blocklen, MIN(strlen(buf + blocklen), BUFSIZE));
	g_free(buf);
	return tmp;
}