Пример #1
0
GSList *get_precompiled_patterns(gchar **patterns)
{
	guint i;
	GSList *pattern_list = NULL;

	if (!patterns)
		return NULL;

	for (i = 0; patterns[i] != NULL; i++)
	{
		GPatternSpec *pattern_spec = g_pattern_spec_new(patterns[i]);
		pattern_list = g_slist_prepend(pattern_list, pattern_spec);
	}
	return pattern_list;
}
Пример #2
0
/**
 * Make messages matching $pat, a g_pattern expression appear as if
 * they were informational (#g_info()).  By configuring mafw-log you
 * can get rid of those messages from the program output.
 *
 * NOTE @pat is matched against the message format string, which may
 * or may not be what you need.
 */
void checkmore_ignore(gchar const *pat)
{
	if (pat != NULL) {
		if (!Msg_filters)
			Msg_filters = g_ptr_array_new();
		g_ptr_array_add(Msg_filters, g_pattern_spec_new(pat));
	} else if (Msg_filters)
	{
		guint i;

		/* Clear all ignores. */
		for (i = 0; i < Msg_filters->len; i++)
			g_pattern_spec_free(Msg_filters->pdata[i]);
		g_ptr_array_set_size(Msg_filters, 0);
	}
}
Пример #3
0
/**
 * g_pattern_match_simple:
 * @pattern: the UTF-8 encoded pattern
 * @string: the UTF-8 encoded string to match
 * @Returns: %TRUE if @string matches @pspec
 *
 * Matches a string against a pattern given as a string. If this
 * function is to be called in a loop, it's more efficient to compile
 * the pattern once with g_pattern_spec_new() and call
 * g_pattern_match_string() repeatedly.
 **/
gboolean
g_pattern_match_simple (const gchar *pattern,
			const gchar *string)
{
  GPatternSpec *pspec;
  gboolean ergo;

  g_return_val_if_fail (pattern != NULL, FALSE);
  g_return_val_if_fail (string != NULL, FALSE);

  pspec = g_pattern_spec_new (pattern);
  ergo = g_pattern_match (pspec, strlen (string), string, NULL);
  g_pattern_spec_free (pspec);

  return ergo;
}
Пример #4
0
/**
 * gtk_accel_map_add_filter:
 * @filter_pattern: a pattern (see #GPatternSpec)
 *
 * Adds a filter to the global list of accel path filters.
 *
 * Accel map entries whose accel path matches one of the filters
 * are skipped by gtk_accel_map_foreach().
 *
 * This function is intended for GTK+ modules that create their own
 * menus, but don’t want them to be saved into the applications accelerator
 * map dump.
 */
void
gtk_accel_map_add_filter (const gchar *filter_pattern)
{
  GPatternSpec *pspec;
  GSList *slist;

  g_return_if_fail (filter_pattern != NULL);

  pspec = g_pattern_spec_new (filter_pattern);
  for (slist = accel_filters; slist; slist = slist->next)
    if (g_pattern_spec_equal (pspec, slist->data))
      {
	g_pattern_spec_free (pspec);
	return;
      }
  accel_filters = g_slist_prepend (accel_filters, pspec);
}
Пример #5
0
static void
_set_reporting_level_for_name (GstValidateRunner * runner,
    const gchar * pattern, GstValidateReportingDetails level)
{
  PatternLevel *pattern_level = g_malloc (sizeof (PatternLevel));
  GPatternSpec *pattern_spec = g_pattern_spec_new (pattern);

  pattern_level->pattern = pattern_spec;
  pattern_level->level = level;

  /* Allow the user to single out a pad with the "element-name__pad-name" syntax
   */
  if (g_strrstr (pattern, "__"))
    runner->priv->report_pattern_levels =
        g_list_prepend (runner->priv->report_pattern_levels, pattern_level);
  else
    runner->priv->report_pattern_levels =
        g_list_append (runner->priv->report_pattern_levels, pattern_level);
}
Пример #6
0
static void find_tags(const gchar *name, gboolean declaration, gboolean case_sensitive, MatchType match_type, gchar *utf8_path)
{
	gchar *utf8_base_path = get_project_base_path();
	gchar *locale_base_path = utils_get_locale_from_utf8(utf8_base_path);
	GPtrArray *tags_array = geany_data->app->tm_workspace->tags_array;
	guint i;
	gchar *name_case;
	GPatternSpec *pspec;

	if (case_sensitive)
		name_case = g_strdup(name);
	else
		name_case = g_utf8_strdown(name, -1);

	pspec = g_pattern_spec_new(name_case);

	msgwin_set_messages_dir(locale_base_path);
	msgwin_clear_tab(MSG_MESSAGE);
	for (i = 0; i < tags_array->len; i++) /* TODO: binary search */
	{
		TMTag *tag = tags_array->pdata[i];

		if (match(tag, name_case, declaration, case_sensitive, match_type, pspec, utf8_path))
		{
			gchar *scopestr = tag->scope ? g_strconcat(tag->scope, "::", NULL) : g_strdup("");
			gchar *utf8_fname = utils_get_utf8_from_locale(tag->file->file_name);
			gchar *relpath;

			relpath = get_relative_path(utf8_base_path, utf8_fname);
			msgwin_msg_add(COLOR_BLACK, -1, NULL, "%s:%lu:\n\t[%s]\t %s%s%s", relpath ? relpath : utf8_fname,
				tag->line, tm_tag_type_name(tag), scopestr, tag->name, tag->arglist ? tag->arglist : "");
			g_free(scopestr);
			g_free(relpath);
			g_free(utf8_fname);
		}
	}
	msgwin_switch_tab(MSG_MESSAGE, TRUE);

	g_free(name_case);
	g_pattern_spec_free(pspec);
	g_free(utf8_base_path);
	g_free(locale_base_path);
}
Пример #7
0
static void
gwy_app_recent_file_list_filter_apply(GtkEntry *entry,
                                      Controls *controls)
{
    GPatternSpec *oldpattern;
    GwyContainer *settings;
    gchar *s, *t;

    settings = gwy_app_settings_get();
    g_string_assign(controls->glob, gtk_entry_get_text(entry));
    gwy_container_set_string_by_name(settings, "/app/file/recent/glob",
                                     g_strdup(controls->glob->str));

    oldpattern = controls->pattern;

    if (controls->casesens) {
        if (!strchr(controls->glob->str, '*')
            && !strchr(controls->glob->str, '?'))
            s = g_strconcat("*", controls->glob->str, "*", NULL);
        else
            s = g_strdup(controls->glob->str);
    }
    else {
        /* FIXME: This is crude. */
        s = g_utf8_strdown(controls->glob->str, controls->glob->len);
        if (!strchr(s, '*') && !strchr(s, '?')) {
            t = s;
            s = g_strconcat("*", t, "*", NULL);
            g_free(t);
        }
    }
    controls->pattern = g_pattern_spec_new(s);
    g_free(s);

    if (oldpattern)
        g_pattern_spec_free(oldpattern);

    if (GTK_WIDGET_REALIZED(controls->window))
        gwy_app_wait_cursor_start(GTK_WINDOW(controls->window));
    gtk_tree_model_filter_refilter(GTK_TREE_MODEL_FILTER(controls->filter));
    if (GTK_WIDGET_REALIZED(controls->window))
        gwy_app_wait_cursor_finish(GTK_WINDOW(controls->window));
}
Пример #8
0
static void engine_scan_dir(gchar * dir)
{
    GDir * d;
    d = g_dir_open(dir,0,NULL);
    if (d)
    {
        gchar * n;
        GPatternSpec * ps;
        ps = g_pattern_spec_new("lib*.so");
        while ((n = (gchar *) g_dir_read_name(d)))
        {
            if (g_pattern_match_string(ps,n))
            {
                gchar * dln = g_strjoin("/",dir,n,NULL);
                append_engine(dln);
            }
        }
        g_pattern_spec_free(ps);
        g_dir_close(d);
    }
}
static char *
find_file_with_pattern (const char *dir, const char *pattern)
{
	GDir *filedir;
	char *found_filename;
	const char *filename;
	GPatternSpec *pat;

	filedir = g_dir_open (dir, 0, NULL);
	if (filedir == NULL)
		return NULL;

	pat = g_pattern_spec_new (pattern);
	if (pat == NULL)
	{
		g_dir_close (filedir);
		return NULL;
	}

	found_filename = NULL;

	while ((filename = g_dir_read_name (filedir)))
	{
		if (g_pattern_match_string (pat, filename))
		{
			char *tmp = g_build_filename (dir, filename, NULL);
			if (is_owned_by_user_and_socket (tmp))
				found_filename = g_strdup (filename);
			g_free (tmp);
		}

		if (found_filename != NULL)
			break;
	}

	g_pattern_spec_free (pat);
	g_dir_close (filedir);

	return found_filename;
}
Пример #10
0
GList* get_files_by_pattern(const gchar* dirpath, FcitxSubConfigPattern* pattern, int index)
{
    GList* result = NULL;

    DIR* dir = opendir(dirpath);
    if (!dir)
        return result;

    gchar* filter = pattern->patternlist[index];

    struct dirent* drt;
    GPatternSpec * patternspec = g_pattern_spec_new(filter);
    while ((drt = readdir(dir)) != NULL) {
        if (strcmp(drt->d_name , ".") == 0 || strcmp(drt->d_name, "..") == 0)
            continue;

        if (!g_pattern_match_string(patternspec, drt->d_name))
            continue;

        if (pattern->patternlist[index + 1] == 0) {
            char *path;
            asprintf(&path, "%s/%s", dirpath, drt->d_name);
            struct stat statbuf;
            if (stat(path, &statbuf) == 0) {
                result = g_list_append(result, realpath(path, NULL));
            }
            free(path);
        } else {
            char *path;
            asprintf(&path, "%s/%s", dirpath, drt->d_name);
            GList* r = get_files_by_pattern(path, pattern, index + 1);
            result = g_list_concat(result, r);
            free(path);
        }
    }

    closedir(dir);
    g_pattern_spec_free(patternspec);
    return result;
}
Пример #11
0
Vector<String> listDirectory(const String& path, const String& filter)
{
    Vector<String> entries;

    GUniquePtr<gchar> filename = unescapedFilename(path);
    if (!filename)
        return entries;

    GUniquePtr<GDir> dir(g_dir_open(filename.get(), 0, nullptr));
    if (!dir)
        return entries;

    GUniquePtr<GPatternSpec> pspec(g_pattern_spec_new((filter.utf8()).data()));
    while (const char* name = g_dir_read_name(dir.get())) {
        if (!g_pattern_match_string(pspec.get(), name))
            continue;

        GUniquePtr<gchar> entry(g_build_filename(filename.get(), name, nullptr));
        entries.append(filenameToString(entry.get()));
    }

    return entries;
}
Пример #12
0
static void swap_clean (void)
{
  const gchar  *swap_dir = gegl_swap_dir ();
  GDir         *dir;

  if (! swap_dir)
    return;

  dir = g_dir_open (gegl_swap_dir (), 0, NULL);

  if (dir != NULL)
    {
      GPatternSpec *pattern = g_pattern_spec_new ("*");
      const gchar  *name;

      while ((name = g_dir_read_name (dir)) != NULL)
        {
          if (g_pattern_match_string (pattern, name))
            {
              gint readpid = atoi (name);

              if (!pid_is_running (readpid))
                {
                  gchar *fname = g_build_filename (gegl_swap_dir (),
                                                   name,
                                                   NULL);
                  g_unlink (fname);
                  g_free (fname);
                }
            }
         }

      g_pattern_spec_free (pattern);
      g_dir_close (dir);
    }
}
Пример #13
0
static gboolean try_swap_header_source(gchar *file_name, gboolean is_header, GSList *file_list, GSList *header_patterns, GSList *source_patterns)
{
	gchar *name_pattern;
	gchar *base_name = NULL;
	GSList *elem;
	GPatternSpec *pattern;
	gboolean found = FALSE;

	name_pattern = g_path_get_basename(file_name);
	setptr(name_pattern, utils_remove_ext_from_filename(name_pattern));
	setptr(name_pattern, g_strconcat(name_pattern, ".*", NULL));
	pattern = g_pattern_spec_new(name_pattern);
	g_free(name_pattern);

	for (elem = file_list; elem != NULL; elem = g_slist_next(elem))
	{
		gchar *full_name = elem->data;
		base_name = g_path_get_basename(full_name);

		if (g_pattern_match_string(pattern, base_name) &&
		    gprj_project_is_in_project(full_name))
		{
			if ((is_header && patterns_match(source_patterns, base_name)) ||
				(!is_header && patterns_match(header_patterns, base_name)))
			{
				open_file(full_name);
				found = TRUE;
				break;
			}
		}
	}

	g_free(base_name);
	g_pattern_spec_free(pattern);
	return found;
}
Пример #14
0
/*! \brief Find all symbols matching a pattern.
 *
 *  \par Function Description
 *  Searches the library, returning all symbols whose
 *  names match \a pattern.
 *
 *  Two search modes are available: \b CLIB_EXACT, where \a pattern is
 *  compared to the symbol name using strcmp(), and \b CLIB_GLOB,
 *  where \a pattern is assumed to be a glob pattern (see the GLib
 *  documentation for details of the glob syntax applicable).
 *
 *  \warning The #CLibSymbol instances in the \b GList returned belong
 *  to the component library, and should be considered constants; they
 *  should not be manipulated or free()'d.  On the other hand, the \b
 *  GList returned must be freed with \b g_list_free() when no longer
 *  needed.  Note that the values returned will be invalidated by a
 *  call to s_clib_free() or s_clib_refresh().
 *
 *  \param pattern The pattern to match against.
 *  \param mode    The search mode to use.
 *  \return A \b GList of matching #CLibSymbol structures.
 */
GList *s_clib_search (const gchar *pattern, const CLibSearchMode mode)
{
  GList *sourcelist;
  GList *symlist;
  GList *result = NULL;
  CLibSource *source;
  CLibSymbol *symbol;
  GPatternSpec *globpattern = NULL;
  gchar *key;
  gchar keytype;

  if (pattern == NULL) return NULL;

  /* Use different cache keys depending on what sort of search is being done */
  switch (mode)
    {
    case CLIB_GLOB:
      keytype = 'g';
      break;
    case CLIB_EXACT:
      keytype = 's';
      break;
    default:
      g_critical ("s_clib_search: Bad search mode %1$i\n", mode);
      return NULL;
    }
  key = g_strdup_printf("%c%s", keytype, pattern);

  /* Check to see if the query is already in the cache */
  result = (GList *) g_hash_table_lookup (clib_search_cache, key);
  if (result != NULL) {
    g_free (key);
    return g_list_copy (result);
  }

  if (mode == CLIB_GLOB) {
    globpattern = g_pattern_spec_new(pattern);
  }

  for (sourcelist = clib_sources;
       sourcelist != NULL;
       sourcelist = g_list_next(sourcelist)) {

    source = (CLibSource *) sourcelist->data;

    for (symlist = source->symbols;
	 symlist != NULL;
	 symlist = g_list_next(symlist)) {

      symbol = (CLibSymbol *) symlist->data;

      switch (mode)
	{
	case CLIB_EXACT:
	  if (strcmp (pattern, symbol->name) == 0) {
	    result = g_list_prepend (result, symbol);
	  }
	  break;
	case CLIB_GLOB:
	  if (g_pattern_match_string (globpattern, symbol->name)) {
	    result = g_list_prepend (result, symbol);
	  }
	  break;
	}
    }
  }

  result = g_list_reverse (result);

  if (globpattern != NULL) {
    g_pattern_spec_free (globpattern);
  }

  g_hash_table_insert (clib_search_cache, key, g_list_copy (result));
  /* __don't__ free key here, it's stored by the hash table! */

  return result;
}
Пример #15
0
void
gegl_exit (void)
{
  if (!config)
    {
      g_warning("gegl_exit() called without matching call to gegl_init()");
      return;
    }

  GEGL_INSTRUMENT_START()

  gegl_tile_backend_swap_cleanup ();
  gegl_tile_cache_destroy ();
  gegl_operation_gtype_cleanup ();
  gegl_extension_handler_cleanup ();
  gegl_random_cleanup ();
  gegl_cl_cleanup ();

  gegl_temp_buffer_free ();

  if (module_db != NULL)
    {
      g_object_unref (module_db);
      module_db = NULL;
    }

  babl_exit ();

  GEGL_INSTRUMENT_END ("gegl", "gegl_exit")

  /* used when tracking buffer and tile leaks */
  if (g_getenv ("GEGL_DEBUG_BUFS") != NULL)
    {
      gegl_buffer_stats ();
      gegl_tile_backend_ram_stats ();
      gegl_tile_backend_file_stats ();
    }
  global_time = gegl_ticks () - global_time;
  gegl_instrument ("gegl", "gegl", global_time);

  if (gegl_instrument_enabled)
    {
      g_printf ("\n%s", gegl_instrument_utf8 ());
    }

  if (gegl_buffer_leaks ())
    {
      g_printf ("EEEEeEeek! %i GeglBuffers leaked\n", gegl_buffer_leaks ());
#ifdef GEGL_ENABLE_DEBUG
      if (!(gegl_debug_flags & GEGL_DEBUG_BUFFER_ALLOC))
        g_printerr ("To debug GeglBuffer leaks, set the environment "
                    "variable GEGL_DEBUG to \"buffer-alloc\"\n");
#endif
    }
  gegl_tile_cache_destroy ();

  if (gegl_swap_dir ())
    {
      /* remove all files matching <$GEGL_SWAP>/GEGL-<pid>-*.swap */

      guint         pid     = getpid ();
      GDir         *dir     = g_dir_open (gegl_swap_dir (), 0, NULL);

      gchar        *glob    = g_strdup_printf ("%i-*", pid);
      GPatternSpec *pattern = g_pattern_spec_new (glob);
      g_free (glob);

      if (dir != NULL)
        {
          const gchar *name;

          while ((name = g_dir_read_name (dir)) != NULL)
            {
              if (g_pattern_match_string (pattern, name))
                {
                  gchar *fname = g_build_filename (gegl_swap_dir (),
                                                   name,
                                                   NULL);
                  g_unlink (fname);
                  g_free (fname);
                }
            }

          g_dir_close (dir);
        }

      g_pattern_spec_free (pattern);
    }
  g_object_unref (config);
  config = NULL;
  global_time = 0;
}
Пример #16
0
static gint
search_button_clicked(GtkWidget * widget, gpointer data) {

    int valid;
    const char * key_string = gtk_entry_get_text(GTK_ENTRY(searchkey_entry));
    char key[MAXLEN];
    GPatternSpec * pattern;

    int i;
    GtkTreeIter list_iter;
    GtkTreeIter sfac_iter;

    GList * node = NULL;


    get_toggle_buttons_state();

    clear_search_store();

    valid = 0;
    for (i = 0; key_string[i] != '\0'; i++) {
        if ((key_string[i] != '?') && (key_string[i] != '*')) {
            valid = 1;
            break;
        }
    }
    if (!valid) {
        return TRUE;
    }

    if (!casesens) {
        key_string = g_utf8_strup(key_string, -1);
    }

    if (exactonly) {
        strcpy(key, key_string);
    } else {
        snprintf(key, MAXLEN-1, "*%s*", key_string);
    }

    pattern = g_pattern_spec_new(key);

    for (node = playlists; node; node = node->next) {

        playlist_t * pl = (playlist_t *)node->data;

        i = 0;
        while (gtk_tree_model_iter_nth_child(GTK_TREE_MODEL(pl->store),
                                             &list_iter, NULL, i++)) {

            if (gtk_tree_model_iter_has_child(GTK_TREE_MODEL(pl->store), &list_iter)) {

                int j = 0;
                GtkTreeIter iter;

                search_foreach(pl, pattern, &list_iter, 1/*album node*/);

                while (gtk_tree_model_iter_nth_child(GTK_TREE_MODEL(pl->store),
                                                     &iter, &list_iter, j++)) {
                    search_foreach(pl, pattern, &iter, 0/*track node*/);
                }
            } else {
                search_foreach(pl, pattern, &list_iter, 0/*track node*/);
            }
        }
    }

    g_pattern_spec_free(pattern);

    if (selectfc) {

        if (gtk_tree_model_get_iter_first(GTK_TREE_MODEL(search_store), &sfac_iter) == TRUE)
            gtk_tree_selection_select_iter(search_select, &sfac_iter);

        close_button_clicked(NULL, NULL);
    }

    return TRUE;
}
gboolean
check_arguments(struct CmdOptions *options,
                const char *input_dir,
                GError **err)
{
    assert(!err || *err == NULL);

    // Check outputdir
    if (options->outputdir && !g_file_test(options->outputdir, G_FILE_TEST_EXISTS|G_FILE_TEST_IS_DIR)) {
        g_set_error(err, ERR_DOMAIN, CRE_BADARG,
                    "Specified outputdir \"%s\" doesn't exists",
                    options->outputdir);
        return FALSE;
    }

    // Check workers
    if ((options->workers < 1) || (options->workers > 100)) {
        g_warning("Wrong number of workers - Using 5 workers.");
        options->workers = DEFAULT_WORKERS;
    }

    // Check changelog_limit
    if ((options->changelog_limit < -1)) {
        g_warning("Wrong changelog limit \"%d\" - Using 10", options->changelog_limit);
        options->changelog_limit = DEFAULT_CHANGELOG_LIMIT;
    }

    // Check simple filenames
    if (options->simple_md_filenames) {
        options->unique_md_filenames = FALSE;
    }

    // Check and set checksum type
    if (options->checksum) {
        cr_ChecksumType type;
        type = cr_checksum_type(options->checksum);
        if (type == CR_CHECKSUM_UNKNOWN) {
            g_set_error(err, ERR_DOMAIN, CRE_BADARG,
                        "Unknown/Unsupported checksum type \"%s\"",
                        options->checksum);
            return FALSE;
        }
        options->checksum_type = type;
    }

    // Check and set checksum type for repomd
    if (options->repomd_checksum) {
        cr_ChecksumType type;
        type = cr_checksum_type(options->repomd_checksum);
        if (type == CR_CHECKSUM_UNKNOWN) {
            g_set_error(err, ERR_DOMAIN, CRE_BADARG,
                        "Unknown/Unsupported checksum type \"%s\"",
                        options->repomd_checksum);
            return FALSE;
        }
        options->repomd_checksum_type = type;
    } else {
        options->repomd_checksum_type = options->checksum_type;
    }

    // Check and set compression type
    if (options->compress_type) {
        if (!check_and_set_compression_type(options->compress_type,
                                            &(options->compression_type),
                                            err)) {
            return FALSE;
        }
    }
    //options --xz has priority over compress_type, but not over general_compress_type
    if (options->xz_compression) {
        options->compression_type = CR_CW_XZ_COMPRESSION;
    }

    // Check and set general compression type
    if (options->general_compress_type) {
        if (!check_and_set_compression_type(options->general_compress_type,
                                            &(options->general_compression_type),
                                            err)) {
            return FALSE;
        }
    }

    int x;

    // Process exclude glob masks
    x = 0;
    while (options->excludes && options->excludes[x] != NULL) {
        GPatternSpec *pattern = g_pattern_spec_new(options->excludes[x]);
        options->exclude_masks = g_slist_prepend(options->exclude_masks,
                                                 (gpointer) pattern);
        x++;
    }

    // Process includepkgs
    x = 0;
    while (options->includepkg && options->includepkg[x] != NULL) {
        options->include_pkgs = g_slist_prepend(options->include_pkgs,
                                  (gpointer) g_strdup(options->includepkg[x]));
        x++;
    }

    // Check groupfile
    options->groupfile_fullpath = NULL;
    if (options->groupfile) {
        gboolean remote = FALSE;

        if (g_str_has_prefix(options->groupfile, "/")) {
            // Absolute local path
            options->groupfile_fullpath = g_strdup(options->groupfile);
        } else if (strstr(options->groupfile, "://")) {
            // Remote groupfile
            remote = TRUE;
            options->groupfile_fullpath = g_strdup(options->groupfile);
        } else {
            // Relative path (from intput_dir)
            options->groupfile_fullpath = g_strconcat(input_dir,
                                                      options->groupfile,
                                                      NULL);
        }

        if (!remote && !g_file_test(options->groupfile_fullpath, G_FILE_TEST_IS_REGULAR)) {
            g_set_error(err, ERR_DOMAIN, CRE_BADARG,
                        "groupfile %s doesn't exists",
                        options->groupfile_fullpath);
            return FALSE;
        }
    }

    // Process pkglist file
    if (options->pkglist) {
        if (!g_file_test(options->pkglist, G_FILE_TEST_IS_REGULAR)) {
            g_set_error(err, ERR_DOMAIN, CRE_BADARG,
                        "pkglist file \"%s\" doesn't exists", options->pkglist);
            return FALSE;
        } else {
            char *content = NULL;
            GError *tmp_err = NULL;
            if (!g_file_get_contents(options->pkglist, &content, NULL, &tmp_err)) {
                g_warning("Error while reading pkglist file: %s", tmp_err->message);
                g_error_free(tmp_err);
                g_free(content);
            } else {
                x = 0;
                char **pkgs = g_strsplit(content, "\n", 0);
                while (pkgs && pkgs[x] != NULL) {
                    if (strlen(pkgs[x])) {
                        options->include_pkgs = g_slist_prepend(options->include_pkgs,
                                                 (gpointer) g_strdup(pkgs[x]));
                    }
                    x++;
                }

                g_strfreev(pkgs);
                g_free(content);
            }
        }
    }

    // Process update_md_paths
    if (options->update_md_paths && !options->update)
        g_warning("Usage of --update-md-path without --update has no effect!");

    x = 0;
    while (options->update_md_paths && options->update_md_paths[x] != NULL) {
        char *path = options->update_md_paths[x];
        options->l_update_md_paths = g_slist_prepend(options->l_update_md_paths,
                                                     (gpointer) path);
        x++;
    }

    // Check keep-all-metadata
    if (options->keep_all_metadata && !options->update) {
        g_warning("--keep-all-metadata has no effect (--update is not used)");
    }

    // Process --distro tags
    x = 0;
    while (options->distro_tags && options->distro_tags[x]) {
        if (!strchr(options->distro_tags[x], ',')) {
            options->distro_cpeids = g_slist_append(options->distro_cpeids,
                                                    NULL);
            options->distro_values = g_slist_append(options->distro_values,
                                        g_strdup(options->distro_tags[x]));
            x++;
            continue;
        }

        gchar **items = g_strsplit(options->distro_tags[x++], ",", 2);
        if (!items) continue;
        if (!items[0] || !items[1] || items[1][0] == '\0') {
            g_strfreev(items);
            continue;
        }

        if (items[0][0] != '\0')
            options->distro_cpeids = g_slist_append(options->distro_cpeids,
                                                    g_strdup(items[0]));
        else
            options->distro_cpeids = g_slist_append(options->distro_cpeids,
                                                    NULL);
        options->distro_values = g_slist_append(options->distro_values,
                                                g_strdup(items[1]));
        g_strfreev(items);
    }

    // Check retain-old-md-by-age
    if (options->retain_old_md_by_age) {
        if (options->retain_old) {
            g_set_error(err, ERR_DOMAIN, CRE_BADARG,
                        "--retain-old-md-by-age cannot be combined "
                        "with --retain-old-md");
            return FALSE;
        }

        // Parse argument
        if (!parse_period_of_time(options->retain_old_md_by_age,
                                  &options->md_max_age,
                                  err))
            return FALSE;
    }

    // check if --revision is numeric, when --set-timestamp-to-revision is given
    if (options->set_timestamp_to_revision) {
        char *endptr;
        gint64 revision = strtoll(options->revision, &endptr, 0);
        if (endptr == options->revision || *endptr != '\0') {
            g_set_error(err, ERR_DOMAIN, CRE_BADARG,
                    "--set-timestamp-to-revision require numeric value for --revision");
            return FALSE;
        }
        if ((errno == ERANGE && revision == LLONG_MAX) || revision < 0) {
            g_set_error(err, ERR_DOMAIN, CRE_BADARG,
                    "--revision value out of range");
            return FALSE;
        }
    }

    // Check oldpackagedirs
    x = 0;
    while (options->oldpackagedirs && options->oldpackagedirs[x]) {
        char *path = options->oldpackagedirs[x];
        options->oldpackagedirs_paths = g_slist_prepend(
                                            options->oldpackagedirs_paths,
                                            (gpointer) path);
        x++;
    }

    // Check cut_dirs
    if (options->cut_dirs < 0) {
        g_set_error(err, ERR_DOMAIN, CRE_BADARG,
                    "--cur-dirs value must be possitive integer");
        return FALSE;
    }

    // Zchunk options
    if (options->zck_dict_dir && !options->zck_compression) {
        g_set_error(err, ERR_DOMAIN, CRE_BADARG,
                    "Cannot use --zck-dict-dir without setting --zck");
        return FALSE;
    }
    if (options->zck_dict_dir)
        options->zck_dict_dir = cr_normalize_dir_path(options->zck_dict_dir);

    return TRUE;
}
Пример #18
0
unsigned long
fill_filelist ()
{
	long i;
	unsigned long num = 0;
	GtkTreeIter iter = {};
	gchar *search;
	GPatternSpec *pattern = NULL;

	filling = TRUE;

	gtk_list_store_clear (GTK_LIST_STORE (filelist));
	search = (gchar *) gtk_entry_get_text (GTK_ENTRY (W(searchentry)));
	if (search && *search) {
		if (!strchr (search, '*')) {
			search = g_strdup_printf ("*%s*", search);
			pattern = g_pattern_spec_new (search);
			g_free (search);
		} else
			pattern = g_pattern_spec_new (search);
	}

	/* Detach list model from view to make insertion faster */
	g_object_ref (filelist);
	gtk_tree_view_set_model (GTK_TREE_VIEW (W(filelist)), NULL);

	/* We add items to the list in reversed order because for some reason
	   the list reverses the order again. i is not an unsigned long because
	   it will conflict with 'i >= 0' and 'i--' */
	for (i = (long) document.grf->nfiles - 1; i >= 0; i--) {
		char *filename = NULL;
		char *size = NULL;
		char *type;

		if (!document.grf->files[i].real_len)
			continue;

		/* Do not display folders */
		if (GRFFILE_IS_DIR(document.grf->files[i]))
			continue;

		/* Attempt to convert the filename to UTF-8 */
		if (!document.grf->files[i].name) {
			printf("%ld: %s\n", i, document.grf->files[i].name);
			continue;
		}
		filename = str_to_utf8 (document.grf->files[i].name, NULL);
		if (!filename)
			continue;

		if (pattern && !g_pattern_match_string (pattern, filename)) {
			g_free (filename);
			continue;
		}

		size = friendly_size_name (document.grf->files[i].real_len);
		type = get_type_name (filename);

		/* Add to list */
		gtk_list_store_prepend (GTK_LIST_STORE (filelist), &iter);
		gtk_list_store_set (GTK_LIST_STORE (filelist), &iter,
			INDEX_COL, i,
			DISPLAY_COL, filename,
			TYPE_COL, type,
			SIZE_COL, document.grf->files[i].real_len,
			SIZE_DISPLAY_COL, size,
			-1);
		num++;

		g_free (size);
		g_free (filename);
		g_free (type);
	}

	/* Re-attach model */
	gtk_tree_view_set_model (GTK_TREE_VIEW (W(filelist)), filelist);
	g_object_unref (filelist);

	filling = FALSE;

	if (pattern)
		g_pattern_spec_free (pattern);
	return num;
}
Пример #19
0
void
gegl_exit (void)
{
  glong timing = gegl_ticks ();

  gegl_tile_storage_cache_cleanup ();
  gegl_tile_cache_destroy ();
  gegl_operation_gtype_cleanup ();
  gegl_extension_handler_cleanup ();

  if (module_db != NULL)
    {
      g_object_unref (module_db);
      module_db = NULL;
    }

  babl_exit ();

  timing = gegl_ticks () - timing;
  gegl_instrument ("gegl", "gegl_exit", timing);

  /* used when tracking buffer and tile leaks */
  if (g_getenv ("GEGL_DEBUG_BUFS") != NULL)
    {
      gegl_buffer_stats ();
      gegl_tile_backend_ram_stats ();
      gegl_tile_backend_file_stats ();
#if HAVE_GIO
      gegl_tile_backend_tiledir_stats ();
#endif
    }
  global_time = gegl_ticks () - global_time;
  gegl_instrument ("gegl", "gegl", global_time);

  if (g_getenv ("GEGL_DEBUG_TIME") != NULL)
    {
      g_printf ("\n%s", gegl_instrument_utf8 ());
    }

  if (gegl_buffer_leaks ())
    g_printf ("  buffer-leaks: %i\n", gegl_buffer_leaks ());
  gegl_tile_cache_destroy ();

  if (gegl_swap_dir ())
    {
      /* remove all files matching <$GEGL_SWAP>/GEGL-<pid>-*.swap */

      guint         pid     = getpid ();
      GDir         *dir     = g_dir_open (gegl_swap_dir (), 0, NULL);

      gchar        *glob    = g_strdup_printf ("%i-*", pid);
      GPatternSpec *pattern = g_pattern_spec_new (glob);
      g_free (glob);

      if (dir != NULL)
        {
          const gchar *name;

          while ((name = g_dir_read_name (dir)) != NULL)
            {
              if (g_pattern_match_string (pattern, name))
                {
                  gchar *fname = g_build_filename (gegl_swap_dir (),
                                                   name,
                                                   NULL);
                  g_unlink (fname);
                  g_free (fname);
                }
            }

          g_dir_close (dir);
        }

      g_pattern_spec_free (pattern);
    }
  g_object_unref (config);
  config = NULL;
}
Пример #20
0
/* Funcion initDispatcher
 * Precondiciones:
 * Postcondiciones:
 * Entrada:
 * Salida:
 * Proceso:
 * */
gboolean
initDispatcher					(GData** dispatchConfig, gchar** error)
{
	gchar *routingFile, *msgLogFile, *buffer, **bufferSet;
	GIOChannel* routing;
	RoutingEntry* entry;
	GError* channelError;

	channelError = NULL;
	
	/* Checks for routing file. 
	 * */
	if ((routingFile = g_datalist_get_data(dispatchConfig, "routing")) == NULL)
	{
		routingFile = ROUTINGFILE;
	}
	
	if (!g_file_test(routingFile, G_FILE_TEST_EXISTS))
	{
		*error = g_strdup(CANNOTLOCATEROUTEFILE);
		return (FALSE);
	}
	
	/* Opens a GIOChannel to read whatever is into the file. */
	if ((routing = g_io_channel_new_file(routingFile, "r", &channelError)) == NULL)
	{
		if (channelError != NULL)
		{
			*error = g_strconcat(CANNOTOPENROUTINGFILE, ": ", channelError->message, NULL);
		}
		else
		{
			*error = g_strconcat(CANNOTOPENROUTINGFILE, ": ", NOERRORAVAILABLE, NULL);
		}
		
		return (FALSE);
	}
	
	/* Initialize routing table (queue). */
	routingTable = g_queue_new();

	while (g_io_channel_read_line(routing, &buffer, NULL, NULL, &channelError) == G_IO_STATUS_NORMAL)
	{
		/* Ignore commented (# prefixed) and empty lines. */
		if (!g_str_has_prefix(buffer, "#"))
		{
			bufferSet = g_strsplit(buffer, " ", 4);
			if (g_strv_length(bufferSet) == (guint)4)
			{
				entry = g_slice_new0(RoutingEntry);
				
				entry->msgProto = g_strdup(bufferSet[0]);
				entry->msgAddrPattern = g_pattern_spec_new(bufferSet[1]);
				entry->destProto = g_strdup(bufferSet[2]);
				entry->destAddress = g_strdup(bufferSet[3]);
				
				g_queue_push_tail(routingTable, entry);
			}
		}
	}
	
	/* TODO: warning message for previous error. */

	/* Close routing IO channel. */
	if (g_io_channel_shutdown(routing, FALSE, &channelError) == (G_IO_STATUS_ERROR | G_IO_STATUS_AGAIN))
	{
		*error = g_strconcat(CANNOTOPENROUTINGFILE, ": ", channelError->message, NULL);
		return (FALSE);
	}
	
	/* Check for message logging file. */
	if ((msgLogFile = g_datalist_get_data(dispatchConfig, "msglog")) == NULL)
	{
		msgLogFile = MSGLOGFILE;
	}
	
	if ((msgLog = g_io_channel_new_file(msgLogFile, "w+", &channelError)) == NULL)
	{
		if (channelError != NULL)
		{
			*error = g_strconcat(CANNOTOPENMSGLOGFILE, ": ", channelError->message, NULL);
		}
		else
		{
			*error = g_strconcat(CANNOTOPENMSGLOGFILE, ": ", NOERRORAVAILABLE, NULL);
		}
		
		return (FALSE);
	}
	
	return (TRUE);
}
Пример #21
0
static void grouplist_dialog_set_list(const gchar *pattern, gboolean refresh)
{
	static GdkCursor *watch_cursor = NULL;
	GSList *cur;
	GtkCMCTreeNode *node;
	GPatternSpec *pspec;
	GdkWindow *window;

	if (locked) return;
	locked = TRUE;

	if (!pattern || *pattern == '\0')
		pattern = "*";

	if (!watch_cursor)
		watch_cursor = gdk_cursor_new(GDK_WATCH);
	window = gtk_widget_get_window(dialog);
	gdk_window_set_cursor(window, watch_cursor);
	main_window_cursor_wait(mainwindow_get_mainwindow());
	GTK_EVENTS_FLUSH();
	
	if (refresh) {
		ack = TRUE;
		grouplist_clear();
		recv_set_ui_func(grouplist_recv_func, NULL);
		group_list = news_get_group_list(news_folder);
		group_list = g_slist_reverse(group_list);
		recv_set_ui_func(NULL, NULL);
		if (group_list == NULL && ack == TRUE) {
			alertpanel_error(_("Can't retrieve newsgroup list."));
			locked = FALSE;
			gdk_window_set_cursor(window, NULL);
			main_window_cursor_normal(mainwindow_get_mainwindow());
			return;
		}
	} else
		gtk_cmclist_clear(GTK_CMCLIST(ctree));

	gtk_entry_set_text(GTK_ENTRY(entry), pattern);

	grouplist_hash_init();

	gtk_cmclist_freeze(GTK_CMCLIST(ctree));

	pspec = g_pattern_spec_new(pattern);

	for (cur = group_list; cur != NULL ; cur = cur->next) {
		NewsGroupInfo *ginfo = (NewsGroupInfo *)cur->data;

		if (g_pattern_match_string(pspec, ginfo->name)) {
			node = grouplist_create_branch(ginfo, pattern);
			if (g_slist_find_custom(subscribed, ginfo->name,
						(GCompareFunc)g_ascii_strcasecmp)
			    != NULL)
				gtk_cmctree_select(GTK_CMCTREE(ctree), node);
		}
	}
	for (cur = subscribed; cur; cur = g_slist_next(cur))
		grouplist_expand_upwards(GTK_CMCTREE(ctree), (gchar *)cur->data);

	g_pattern_spec_free(pspec);

	gtk_cmclist_thaw(GTK_CMCLIST(ctree));

	grouplist_hash_done();

	gtk_label_set_text(GTK_LABEL(status_label), _("Done."));

	gdk_window_set_cursor(window, NULL);
	main_window_cursor_normal(mainwindow_get_mainwindow());

	locked = FALSE;
}
static gboolean
generate_all_deltas (OstreeRepo   *repo,
                     GPtrArray   **unwanted_deltas,
                     GCancellable *cancellable,
                     GError      **error)
{
  g_autoptr(GHashTable) all_refs = NULL;
  g_autoptr(GHashTable) all_deltas_hash = NULL;
  g_autoptr(GHashTable) wanted_deltas_hash = NULL;
  g_autoptr(GPtrArray) all_deltas = NULL;
  int i;
  GHashTableIter iter;
  gpointer key, value;
  g_autoptr(GVariantBuilder) parambuilder = NULL;
  g_autoptr(GVariant) params = NULL;
  int n_spawned_delta_generate = 0;
  g_autoptr(GMainContextPopDefault) context = NULL;
  g_autoptr(GPtrArray) ignore_patterns = g_ptr_array_new_with_free_func ((GDestroyNotify)g_pattern_spec_free);

  g_print ("Generating static deltas\n");

  parambuilder = g_variant_builder_new (G_VARIANT_TYPE ("a{sv}"));
  /* Fall back for 1 meg files */
  g_variant_builder_add (parambuilder, "{sv}",
                         "min-fallback-size", g_variant_new_uint32 (1));
  params = g_variant_ref_sink (g_variant_builder_end (parambuilder));

  if (!ostree_repo_list_static_delta_names (repo, &all_deltas,
                                            cancellable, error))
    return FALSE;

  wanted_deltas_hash = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);

  all_deltas_hash = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
  for (i = 0; i < all_deltas->len; i++)
    g_hash_table_insert (all_deltas_hash,
                         g_strdup (g_ptr_array_index (all_deltas, i)),
                         NULL);

  if (!ostree_repo_list_refs (repo, NULL, &all_refs,
                              cancellable, error))
    return FALSE;

  context = flatpak_main_context_new_default ();

  if (opt_static_delta_ignore_refs != NULL)
    {
      for (i = 0; opt_static_delta_ignore_refs[i] != NULL; i++)
        g_ptr_array_add (ignore_patterns,
                         g_pattern_spec_new (opt_static_delta_ignore_refs[i]));
    }

  g_hash_table_iter_init (&iter, all_refs);
  while (g_hash_table_iter_next (&iter, &key, &value))
    {
      const char *ref = key;
      const char *commit = value;
      g_autoptr(GVariant) variant = NULL;
      g_autoptr(GVariant) parent_variant = NULL;
      g_autofree char *parent_commit = NULL;
      g_autofree char *grandparent_commit = NULL;
      gboolean ignore_ref = FALSE;

      if (g_str_has_prefix (ref, "app/") || g_str_has_prefix (ref, "runtime/"))
        {
          g_auto(GStrv) parts = g_strsplit (ref, "/", 4);

          for (i = 0; i < ignore_patterns->len; i++)
            {
              GPatternSpec *pattern = g_ptr_array_index(ignore_patterns, i);
              if (g_pattern_match_string (pattern, parts[1]))
                {
                  ignore_ref = TRUE;
                  break;
                }
            }

        }
      else if (g_str_has_prefix (ref, "appstream/"))
        {
          /* Old appstream branch deltas poorly, and most users handle the new format */
          ignore_ref = TRUE;
        }
      else if (g_str_has_prefix (ref, "appstream2/"))
        {
          /* Always delta this */
          ignore_ref = FALSE;
        }
      else
        {
          /* Ignore unknown ref types */
          ignore_ref = FALSE;
        }

      if (ignore_ref)
        {
          g_debug ("Ignoring deltas for ref %s", ref);
          continue;
        }

      if (!ostree_repo_load_variant (repo, OSTREE_OBJECT_TYPE_COMMIT, commit,
                                     &variant, NULL))
        {
          g_warning ("Couldn't load commit %s", commit);
          continue;
        }

      /* From empty */
      if (!g_hash_table_contains (all_deltas_hash, commit))
        {
          if (!spawn_delta_generation (context, &n_spawned_delta_generate, repo, params,
                                       ref, NULL, commit,
                                       error))
            return FALSE;
        }

      /* Mark this one as wanted */
      g_hash_table_insert (wanted_deltas_hash, g_strdup (commit), GINT_TO_POINTER (1));

      parent_commit = ostree_commit_get_parent (variant);

      if (parent_commit != NULL &&
          !ostree_repo_load_variant (repo, OSTREE_OBJECT_TYPE_COMMIT, parent_commit,
                                     &parent_variant, NULL))
        {
          g_warning ("Couldn't load parent commit %s", parent_commit);
          continue;
        }

      /* From parent */
      if (parent_variant != NULL)
        {
          g_autofree char *from_parent = g_strdup_printf ("%s-%s", parent_commit, commit);

          if (!g_hash_table_contains (all_deltas_hash, from_parent))
            {
              if (!spawn_delta_generation (context, &n_spawned_delta_generate, repo, params,
                                           ref, parent_commit, commit,
                                           error))
                return FALSE;
            }

          /* Mark parent-to-current as wanted */
          g_hash_table_insert (wanted_deltas_hash, g_strdup (from_parent), GINT_TO_POINTER (1));

          /* We also want to keep around the parent and the grandparent-to-parent deltas
           * because otherwise these will be deleted immediately which may cause a race if
           * someone is currently downloading them.
           * However, there is no need to generate these if they don't exist.
           */

          g_hash_table_insert (wanted_deltas_hash, g_strdup (parent_commit), GINT_TO_POINTER (1));
          grandparent_commit = ostree_commit_get_parent (parent_variant);
          if (grandparent_commit != NULL)
            g_hash_table_insert (wanted_deltas_hash,
                                 g_strdup_printf ("%s-%s", grandparent_commit, parent_commit),
                                 GINT_TO_POINTER (1));
        }
    }

  while (n_spawned_delta_generate > 0)
    g_main_context_iteration (context, TRUE);

  *unwanted_deltas = g_ptr_array_new_with_free_func (g_free);
  for (i = 0; i < all_deltas->len; i++)
    {
      const char *delta = g_ptr_array_index (all_deltas, i);
      if (!g_hash_table_contains (wanted_deltas_hash, delta))
        g_ptr_array_add (*unwanted_deltas, g_strdup (delta));
    }

  return TRUE;
}
Пример #23
0
static void find_tags(const gchar *name, gboolean declaration, gboolean case_sensitive, MatchType match_type)
{
	tagFile *tf;
	GeanyProject *prj;
	gchar *tag_filename = NULL;
	tagEntry entry;
	tagFileInfo info;

	prj = geany_data->app->project;
	if (!prj)
		return;

	msgwin_clear_tab(MSG_MESSAGE);
	msgwin_set_messages_dir(prj->base_path);

	tag_filename = get_tags_filename();
	tf = tagsOpen(tag_filename, &info);

	if (tf)
	{
		if (find_first(tf, &entry, name, match_type))
		{
			GPatternSpec *name_pat;
			gchar *name_case;
			gchar *path = NULL; 
			gint num = 0;

			if (case_sensitive)
				name_case = g_strdup(name);
			else
				name_case = g_utf8_strdown(name, -1);

			SETPTR(name_case, g_strconcat("*", name_case, "*", NULL));
			name_pat = g_pattern_spec_new(name_case);

			if (!filter_tag(&entry, name_pat, declaration, case_sensitive))
			{
				path = g_build_filename(prj->base_path, entry.file, NULL);
				show_entry(&entry);
				num++;
			}
			
			while (find_next(tf, &entry, match_type))
			{
				if (!filter_tag(&entry, name_pat, declaration, case_sensitive))
				{
					if (!path)
						path = g_build_filename(prj->base_path, entry.file, NULL);
					show_entry(&entry);
					num++;
				}
			}
			
			if (num == 1)
			{
				GeanyDocument *doc = document_open_file(path, FALSE, NULL, NULL);
				if (doc != NULL)
				{
					navqueue_goto_line(document_get_current(), doc, entry.address.lineNumber);
					gtk_widget_grab_focus(GTK_WIDGET(doc->editor->sci));
				}
			}

			g_pattern_spec_free(name_pat);
			g_free(name_case);
			g_free(path);
		}

		tagsClose(tf);
	}

	msgwin_switch_tab(MSG_MESSAGE, TRUE);

	g_free(tag_filename);
}
/* Get desktop ID from window names.
 * Callee is responsible to free result with g_object_unref().
 */
static GAppInfo* _xfdashboard_application_tracker_get_desktop_id_from_window_names(XfdashboardApplicationTracker *self,
																					XfdashboardWindowTrackerWindow *inWindow)
{
	XfdashboardApplicationTrackerPrivate	*priv;
	GAppInfo								*foundAppInfo;
	gchar									**names;
	gchar									**iter;
	GList									*apps;

	g_return_val_if_fail(XFDASHBOARD_IS_APPLICATION_TRACKER(self), NULL);
	g_return_val_if_fail(XFDASHBOARD_IS_WINDOW_TRACKER_WINDOW(inWindow), NULL);

	priv=self->priv;
	foundAppInfo=NULL;

	/* Get list of applications */
	apps=xfdashboard_application_database_get_all_applications(priv->appDatabase);

	/* Get window's names */
	names=xfdashboard_window_tracker_window_get_instance_names(inWindow);

	/* Iterate through window's names to try to find matching desktop file */
	iter=names;
	while(iter && *iter)
	{
		GAppInfo							*appInfo;
		gchar								*iterName;
		gchar								*iterNameLowerCase;

		/* Build desktop ID from iterated name */
		if(!g_str_has_suffix(*iter, ".desktop")) iterName=g_strconcat(*iter, ".desktop", NULL);
			else iterName=g_strdup(*iter);

		iterNameLowerCase=g_utf8_strdown(iterName, -1);

		/* Lookup application from unmodified name */
		appInfo=xfdashboard_application_database_lookup_desktop_id(priv->appDatabase, iterName);

		/* Lookup application from to-lower-case converted name if previous
		 * lookup with unmodified name failed.
		 */
		if(!appInfo)
		{
			/* Lookup application from lower-case name */
			appInfo=xfdashboard_application_database_lookup_desktop_id(priv->appDatabase, iterNameLowerCase);
		}

		/* If no application was found for the name it may be an application
		 * located in a subdirectory. Then the desktop ID is prefixed with
		 * the subdirectory's name followed by a dash. So iterate through all
		 * applications and lookup with glob pattern '*-' followed by name
		 * and suffix '.desktop'.
		 */
		if(!appInfo)
		{
			GList							*iterApps;
			GList							*foundSubdirApps;
			gchar							*globName;
			GPatternSpec					*globPattern;
			GAppInfo						*globAppInfo;

			/* Build glob pattern */
			globAppInfo=NULL;
			globName=g_strconcat("*-", iterNameLowerCase, NULL);
			globPattern=g_pattern_spec_new(globName);

			/* Iterate through application and collect applications matching
			 * glob pattern.
			 */
			foundSubdirApps=NULL;
			for(iterApps=apps; iterApps; iterApps=g_list_next(iterApps))
			{
				if(!G_IS_APP_INFO(iterApps->data)) continue;
				globAppInfo=G_APP_INFO(iterApps->data);

				if(g_pattern_match_string(globPattern, g_app_info_get_id(globAppInfo)))
				{
					foundSubdirApps=g_list_prepend(foundSubdirApps, globAppInfo);
					g_debug("Found possible application '%s' for window '%s' using pattern '%s'",
							g_app_info_get_id(globAppInfo),
							xfdashboard_window_tracker_window_get_title(inWindow),
							globName);
				}
			}

			/* If exactly one application was collected because it matched
			 * the glob pattern then we found the application.
			 */
			if(g_list_length(foundSubdirApps)==1)
			{
				appInfo=G_APP_INFO(g_object_ref(G_OBJECT(foundSubdirApps->data)));

				g_debug("Found exactly one application named '%s' for window '%s' using pattern '%s'",
						g_app_info_get_id(appInfo),
						xfdashboard_window_tracker_window_get_title(inWindow),
						globName);
			}

			/* Release allocated resources */
			if(foundSubdirApps) g_list_free(foundSubdirApps);
			if(globPattern) g_pattern_spec_free(globPattern);
			if(globName) g_free(globName);
		}

		/* If we still did not find an application continue with next
		 * name in list.
		 */
		if(!appInfo)
		{
			/* Release allocated resources */
			if(iterName) g_free(iterName);
			if(iterNameLowerCase) g_free(iterNameLowerCase);

			/* Continue with next name in list */
			iter++;
			continue;
		}

		/* Check if found application info matches previous one. If it does not match
		 * the desktop IDs found previously are ambigous, so return NULL result.
		 */
		if(foundAppInfo &&
			!g_app_info_equal(foundAppInfo, appInfo))
		{
			g_debug("Resolved window names of '%s' are ambiguous - discarding desktop IDs '%s' and '%s'",
						xfdashboard_window_tracker_window_get_title(inWindow),
						g_app_info_get_id(foundAppInfo),
						g_app_info_get_id(appInfo));

			/* Release allocated resources */
			if(iterName) g_free(iterName);
			if(iterNameLowerCase) g_free(iterNameLowerCase);
			if(foundAppInfo) g_object_unref(foundAppInfo);
			if(appInfo) g_object_unref(appInfo);
			if(names) g_strfreev(names);
			if(apps) g_list_free_full(apps, g_object_unref);

			return(NULL);
		}

		/* If it is the first application info found, remember it */
		if(!foundAppInfo) foundAppInfo=g_object_ref(appInfo);

		/* Release allocated resources */
		if(iterName) g_free(iterName);
		if(iterNameLowerCase) g_free(iterNameLowerCase);
		if(appInfo) g_object_unref(appInfo);

		/* Continue with next name in list */
		iter++;
	}

	/* Release allocated resources */
	if(names) g_strfreev(names);
	if(apps) g_list_free_full(apps, g_object_unref);

	/* Return found application info */
	g_debug("Resolved window names of '%s' to desktop ID '%s'",
				xfdashboard_window_tracker_window_get_title(inWindow),
				foundAppInfo ? g_app_info_get_id(foundAppInfo) : "<nil>");

	return(foundAppInfo);
}
Пример #25
0
/* Search the given directory for candidate binaries matching the base binary.
 * Return a GHashTable of major/minor -> directory pairs
 */
static GHashTable *
get_candidates (const gchar * dir, const gchar * base)
{
  GDir *gdir;
  GError *error = NULL;
  const gchar *entry;
  gchar *path;
  gchar *suffix, *copy;

  gchar *pattern;
  GPatternSpec *spec, *specexe;

  gchar **dirs;
  gchar **cur;

  GHashTable *candidates = NULL;

  candidates = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, g_free);

  /* compile our pattern specs */
  pattern = g_strdup_printf ("%s-*.*", base);
  spec = g_pattern_spec_new (pattern);
  g_free (pattern);
  pattern = g_strdup_printf ("%s-*.*.exe", base);
  specexe = g_pattern_spec_new (pattern);
  g_free (pattern);

  /* get all dirs from the path and prepend with given dir */
  if (dir)
    path = g_strdup_printf ("%s%c%s",
        dir, G_SEARCHPATH_SEPARATOR, g_getenv ("PATH"));
  else
    path = (gchar *) g_getenv ("PATH");
  dirs = g_strsplit (path, G_SEARCHPATH_SEPARATOR_S, 0);
  if (dir)
    g_free (path);

  /* check all of these in reverse order by winding to bottom and going up  */
  cur = &dirs[0];
  while (*cur)
    ++cur;

  while (cur != &dirs[0]) {
    --cur;
    if (!g_file_test (*cur, G_FILE_TEST_EXISTS) ||
        !g_file_test (*cur, G_FILE_TEST_IS_DIR)) {
      continue;
    }

    gdir = g_dir_open (*cur, 0, &error);
    if (!gdir) {
      g_warning ("Could not open dir %s: %s", *cur, error->message);
      g_error_free (error);
      return NULL;
    }
    while ((entry = g_dir_read_name (gdir))) {
      if (g_pattern_match_string (spec, entry)
          || g_pattern_match_string (specexe, entry)) {
        gchar *full;

        /* is it executable ? */
        full = g_build_filename (*cur, entry, NULL);
        if (!g_file_test (full, G_FILE_TEST_IS_EXECUTABLE)) {
          g_free (full);
          continue;
        }
        g_free (full);

        /* strip base and dash from it */
        suffix = g_strdup (&(entry[strlen (base) + 1]));
        copy = g_strdup (suffix);

        /* strip possible .exe from copy */
        if (g_strrstr (copy, ".exe"))
          g_strrstr (copy, ".exe")[0] = '\0';

        /* stricter pattern check: check if it only contains digits or dots */
        g_strcanon (copy, "0123456789.", 'X');
        if (strstr (copy, "X")) {
          g_free (suffix);
          g_free (copy);
          continue;
        }
        g_free (copy);
        g_hash_table_insert (candidates, suffix, g_strdup (*cur));
      }
    }
  }

  g_strfreev (dirs);
  g_pattern_spec_free (spec);
  return candidates;
}
Пример #26
0
void    ZIP_SystemDir(void *archive, char *_directory, char *wildcard, bool recurse,
				       void(*dirCallback)(const char *dir, void *userdata),
					   void(*fileCallback)(const char *filename, void *userdata),
					   void *userdata)
{
	GPatternSpec* pattern;
	unz_s* s;
	unz_s unz_backup;
	int err, numFiles;
	char *slash, *fname;
	char filename[384] = {0};
	char directory[256] = {0};
	char enumdir[256] = {0};

	if (archive==NULL)
		return;
	s=(unz_s*)archive;

	if (!_directory || strlen(_directory) == 0)
		BPrintf(directory, 1024, "");
	else
		BPrintf(directory, 1024, "%s%s", (_directory[0] == '/') ? &_directory[1] : _directory, (_directory[strlen(_directory)-1] == '/') ? "" : "/");

	BPrintf(filename, 1024, "%s%s", directory, wildcard);
	pattern = g_pattern_spec_new(filename);

	Console_DPrintf("Doing a System_Dir in a ZIP file matching %s\n", filename);
	
	err = unzGoToFirstFile((unzFile)s);	

	numFiles = 0;
	while (err == UNZ_OK)
	{
		unzGetCurrentFileInfo((unzFile)s,NULL,
								filename,1023,
								NULL,0,NULL,0);
		filename[1023] = 0;

		//Console_DPrintf("...%s\n", filename);
		if (strcmp(filename, directory) != 0 && strstr(filename, "CVS/") == 0) //don't call a callback for the directory itself
		{
			if (g_pattern_match_string(pattern, filename))
			{
				bool goAhead;
				slash = strchr(&filename[strlen(directory)], '/');
				goAhead = (!slash || (slash == filename + strlen(filename) - 1) || recurse) != 0;
				// UTTAR: Hack: NOTE: Dircallbacks could be activated several times with this method now! :(
				//if (goAhead)
				{
					if (filename[strlen(filename)-1] != '/' && goAhead)
					{
						if (fileCallback)
						{
							goAhead = 0;
							slash = strrchr(filename, '/');
							if (!slash)
							{
								fname = filename;
								BPrintf(enumdir, 1, "");
							}
							else
							{
								fname = slash+1;
								BPrintf(enumdir, slash - filename + 1, "%s", filename);
							}
							Cvar_SetVar(&sys_enumdir, enumdir);
							//Console_DPrintf("calling fileCallback for %s (in %s)\n", fname, sys_enumdir.string);
							Mem_Copy(&unz_backup, s, sizeof(unz_s));
							fileCallback(fname, userdata);
							Mem_Copy(s, &unz_backup, sizeof(unz_s));
						}
					}
					if(dirCallback && goAhead)
					{
						if(slash)
							*slash = 0;
						if (dirCallback)
						{
							//Console_DPrintf("calling dirCallback for %s\n", filename);
							dirCallback(filename, userdata);
						}
					}
				}
			}
		}
		numFiles++;
		err = unzGoToNextFile((unzFile)s);
	}
	
	Console_DPrintf("Done reading zip file contents - %i files\n", numFiles);
	if (err != UNZ_END_OF_LIST_OF_FILE)
		Console_DPrintf("ZIP error: err was %i\n", err);

	Cvar_SetVar(&sys_enumdir, "");

	g_pattern_spec_free(pattern);
}
Пример #27
0
static void
test_g_pattern_spec (void)
{
  g_autoptr(GPatternSpec) val = g_pattern_spec_new ("plaid");
  g_assert (val != NULL);
}