gcontenttype.c 37.1 KB
Newer Older
1 2
/* -*- mode: C; c-file-style: "gnu"; indent-tabs-mode: nil; -*- */

3
/* GIO - GLib Input, Output and Streaming Library
Matthias Clasen's avatar
Matthias Clasen committed
4
 *
5 6 7 8 9
 * Copyright (C) 2006-2007 Red Hat, Inc.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
10
 * version 2.1 of the License, or (at your option) any later version.
11 12 13 14 15 16 17
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General
18
 * Public License along with this library; if not, see <http://www.gnu.org/licenses/>.
19 20 21 22
 *
 * Author: Alexander Larsson <alexl@redhat.com>
 */

23
#include "config.h"
24
#include <sys/types.h>
25
#include <stdlib.h>
26 27 28
#include <string.h>
#include <stdio.h>
#include "gcontenttypeprivate.h"
29
#include "gthemedicon.h"
Cody Russell's avatar
Cody Russell committed
30
#include "gicon.h"
31 32 33
#include "gfile.h"
#include "gfileenumerator.h"
#include "gfileinfo.h"
34 35
#include "glibintl.h"

36

37 38
/**
 * SECTION:gcontenttype
Matthias Clasen's avatar
Matthias Clasen committed
39
 * @short_description: Platform-specific content typing
Matthias Clasen's avatar
Matthias Clasen committed
40
 * @include: gio/gio.h
41 42
 *
 * A content type is a platform specific string that defines the type
43
 * of a file. On UNIX it is a
44 45 46 47 48 49 50
 * [MIME type](http://www.wikipedia.org/wiki/Internet_media_type)
 * like `text/plain` or `image/png`.
 * On Win32 it is an extension string like `.doc`, `.txt` or a perceived
 * string like `audio`. Such strings can be looked up in the registry at
 * `HKEY_CLASSES_ROOT`.
 * On macOS it is a [Uniform Type Identifier](https://en.wikipedia.org/wiki/Uniform_Type_Identifier)
 * such as `com.apple.application`.
51
 **/
52

53 54
#include <dirent.h>

55 56 57
#define XDG_PREFIX _gio_xdg
#include "xdgmime/xdgmime.h"

58 59
static void tree_magic_schedule_reload (void);

60 61 62 63 64 65 66 67 68 69 70 71 72 73 74
/* We lock this mutex whenever we modify global state in this module.  */
G_LOCK_DEFINE_STATIC (gio_xdgmime);

gsize
_g_unix_content_type_get_sniff_len (void)
{
  gsize size;

  G_LOCK (gio_xdgmime);
  size = xdg_mime_get_max_buffer_extents ();
  G_UNLOCK (gio_xdgmime);

  return size;
}

Matthias Clasen's avatar
Matthias Clasen committed
75 76
gchar *
_g_unix_content_type_unalias (const gchar *type)
77
{
Matthias Clasen's avatar
Matthias Clasen committed
78 79
  gchar *res;

80 81 82
  G_LOCK (gio_xdgmime);
  res = g_strdup (xdg_mime_unalias_mime_type (type));
  G_UNLOCK (gio_xdgmime);
Matthias Clasen's avatar
Matthias Clasen committed
83

84 85 86
  return res;
}

Matthias Clasen's avatar
Matthias Clasen committed
87 88
gchar **
_g_unix_content_type_get_parents (const gchar *type)
89
{
Matthias Clasen's avatar
Matthias Clasen committed
90 91
  const gchar *umime;
  gchar **parents;
92 93 94 95
  GPtrArray *array;
  int i;

  array = g_ptr_array_new ();
Matthias Clasen's avatar
Matthias Clasen committed
96

97
  G_LOCK (gio_xdgmime);
Matthias Clasen's avatar
Matthias Clasen committed
98

99
  umime = xdg_mime_unalias_mime_type (type);
Matthias Clasen's avatar
Matthias Clasen committed
100

101
  g_ptr_array_add (array, g_strdup (umime));
Matthias Clasen's avatar
Matthias Clasen committed
102

103
  parents = xdg_mime_list_mime_parents (umime);
104 105
  for (i = 0; parents && parents[i] != NULL; i++)
    g_ptr_array_add (array, g_strdup (parents[i]));
Matthias Clasen's avatar
Matthias Clasen committed
106

107
  free (parents);
Matthias Clasen's avatar
Matthias Clasen committed
108

109
  G_UNLOCK (gio_xdgmime);
Matthias Clasen's avatar
Matthias Clasen committed
110

111
  g_ptr_array_add (array, NULL);
Matthias Clasen's avatar
Matthias Clasen committed
112 113

  return (gchar **)g_ptr_array_free (array, FALSE);
114 115
}

116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215
G_LOCK_DEFINE_STATIC (global_mime_dirs);
static gchar **global_mime_dirs = NULL;

static void
_g_content_type_set_mime_dirs_locked (const char * const *dirs)
{
  g_clear_pointer (&global_mime_dirs, g_strfreev);

  if (dirs != NULL)
    {
      global_mime_dirs = g_strdupv ((gchar **) dirs);
    }
  else
    {
      GPtrArray *mime_dirs = g_ptr_array_new_with_free_func (g_free);
      const gchar * const *system_dirs = g_get_system_data_dirs ();

      g_ptr_array_add (mime_dirs, g_build_filename (g_get_user_data_dir (), "mime", NULL));
      for (; *system_dirs != NULL; system_dirs++)
        g_ptr_array_add (mime_dirs, g_build_filename (*system_dirs, "mime", NULL));
      g_ptr_array_add (mime_dirs, NULL);  /* NULL terminator */

      global_mime_dirs = (gchar **) g_ptr_array_free (mime_dirs, FALSE);
    }

  xdg_mime_set_dirs ((const gchar * const *) global_mime_dirs);
  tree_magic_schedule_reload ();
}

/**
 * g_content_type_set_mime_dirs:
 * @dirs: (array zero-terminated=1) (nullable): %NULL-terminated list of
 *    directories to load MIME data from, including any `mime/` subdirectory,
 *    and with the first directory to try listed first
 *
 * Set the list of directories used by GIO to load the MIME database.
 * If @dirs is %NULL, the directories used are the default:
 *
 *  - the `mime` subdirectory of the directory in `$XDG_DATA_HOME`
 *  - the `mime` subdirectory of every directory in `$XDG_DATA_DIRS`
 *
 * This function is intended to be used when writing tests that depend on
 * information stored in the MIME database, in order to control the data.
 *
 * Typically, in case your tests use %G_TEST_OPTION_ISOLATE_DIRS, but they
 * depend on the system’s MIME database, you should call this function
 * with @dirs set to %NULL before calling g_test_init(), for instance:
 *
 * |[<!-- language="C" -->
 *   // Load MIME data from the system
 *   g_content_type_set_mime_dirs (NULL);
 *   // Isolate the environment
 *   g_test_init (&argc, &argv, G_TEST_OPTION_ISOLATE_DIRS, NULL);
 *
 *   …
 *
 *   return g_test_run ();
 * ]|
 *
 * Since: 2.60
 */
/*< private >*/
void
g_content_type_set_mime_dirs (const gchar * const *dirs)
{
  G_LOCK (global_mime_dirs);
  _g_content_type_set_mime_dirs_locked (dirs);
  G_UNLOCK (global_mime_dirs);
}

/**
 * g_content_type_get_mime_dirs:
 *
 * Get the list of directories which MIME data is loaded from. See
 * g_content_type_set_mime_dirs() for details.
 *
 * Returns: (transfer none) (array zero-terminated=1): %NULL-terminated list of
 *    directories to load MIME data from, including any `mime/` subdirectory,
 *    and with the first directory to try listed first
 * Since: 2.60
 */
/*< private >*/
const gchar * const *
g_content_type_get_mime_dirs (void)
{
  const gchar * const *mime_dirs;

  G_LOCK (global_mime_dirs);

  if (global_mime_dirs == NULL)
    _g_content_type_set_mime_dirs_locked (NULL);

  mime_dirs = (const gchar * const *) global_mime_dirs;

  G_UNLOCK (global_mime_dirs);

  g_assert (mime_dirs != NULL);
  return mime_dirs;
}

Matthias Clasen's avatar
Matthias Clasen committed
216 217
/**
 * g_content_type_equals:
Matthias Clasen's avatar
Matthias Clasen committed
218 219
 * @type1: a content type string
 * @type2: a content type string
Matthias Clasen's avatar
Matthias Clasen committed
220 221 222 223
 *
 * Compares two content types for equality.
 *
 * Returns: %TRUE if the two strings are identical or equivalent,
Matthias Clasen's avatar
Matthias Clasen committed
224 225
 *     %FALSE otherwise.
 */
226
gboolean
Matthias Clasen's avatar
Matthias Clasen committed
227 228
g_content_type_equals (const gchar *type1,
                       const gchar *type2)
229 230
{
  gboolean res;
Matthias Clasen's avatar
Matthias Clasen committed
231

232 233
  g_return_val_if_fail (type1 != NULL, FALSE);
  g_return_val_if_fail (type2 != NULL, FALSE);
Matthias Clasen's avatar
Matthias Clasen committed
234

235 236 237
  G_LOCK (gio_xdgmime);
  res = xdg_mime_mime_type_equal (type1, type2);
  G_UNLOCK (gio_xdgmime);
Matthias Clasen's avatar
Matthias Clasen committed
238

239 240 241
  return res;
}

Matthias Clasen's avatar
Matthias Clasen committed
242 243
/**
 * g_content_type_is_a:
Matthias Clasen's avatar
Matthias Clasen committed
244 245
 * @type: a content type string
 * @supertype: a content type string
Matthias Clasen's avatar
Matthias Clasen committed
246
 *
Matthias Clasen's avatar
Matthias Clasen committed
247
 * Determines if @type is a subset of @supertype.
Matthias Clasen's avatar
Matthias Clasen committed
248 249
 *
 * Returns: %TRUE if @type is a kind of @supertype,
Matthias Clasen's avatar
Matthias Clasen committed
250 251
 *     %FALSE otherwise.
 */
252
gboolean
Matthias Clasen's avatar
Matthias Clasen committed
253 254
g_content_type_is_a (const gchar *type,
                     const gchar *supertype)
255 256
{
  gboolean res;
Matthias Clasen's avatar
Matthias Clasen committed
257

258 259
  g_return_val_if_fail (type != NULL, FALSE);
  g_return_val_if_fail (supertype != NULL, FALSE);
Matthias Clasen's avatar
Matthias Clasen committed
260

261 262 263
  G_LOCK (gio_xdgmime);
  res = xdg_mime_mime_type_subclass (type, supertype);
  G_UNLOCK (gio_xdgmime);
Matthias Clasen's avatar
Matthias Clasen committed
264

265 266 267
  return res;
}

268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287
/**
 * g_content_type_is_mime_type:
 * @type: a content type string
 * @mime_type: a mime type string
 *
 * Determines if @type is a subset of @mime_type.
 * Convenience wrapper around g_content_type_is_a().
 *
 * Returns: %TRUE if @type is a kind of @mime_type,
 *     %FALSE otherwise.
 *
 * Since: 2.52
 */
gboolean
g_content_type_is_mime_type (const gchar *type,
                             const gchar *mime_type)
{
  return g_content_type_is_a (type, mime_type);
}

Matthias Clasen's avatar
Matthias Clasen committed
288 289
/**
 * g_content_type_is_unknown:
Matthias Clasen's avatar
Matthias Clasen committed
290 291
 * @type: a content type string
 *
292
 * Checks if the content type is the generic "unknown" type.
Matthias Clasen's avatar
Matthias Clasen committed
293
 * On UNIX this is the "application/octet-stream" mimetype,
294 295
 * while on win32 it is "*" and on OSX it is a dynamic type
 * or octet-stream.
Matthias Clasen's avatar
Matthias Clasen committed
296
 *
297
 * Returns: %TRUE if the type is the unknown type.
Matthias Clasen's avatar
Matthias Clasen committed
298
 */
299
gboolean
Matthias Clasen's avatar
Matthias Clasen committed
300
g_content_type_is_unknown (const gchar *type)
301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325
{
  g_return_val_if_fail (type != NULL, FALSE);

  return strcmp (XDG_MIME_TYPE_UNKNOWN, type) == 0;
}


typedef enum {
  MIME_TAG_TYPE_OTHER,
  MIME_TAG_TYPE_COMMENT
} MimeTagType;

typedef struct {
  int current_type;
  int current_lang_level;
  int comment_lang_level;
  char *comment;
} MimeParser;


static int
language_level (const char *lang)
{
  const char * const *lang_list;
  int i;
Matthias Clasen's avatar
Matthias Clasen committed
326

327 328 329
  /* The returned list is sorted from most desirable to least
     desirable and always contains the default locale "C". */
  lang_list = g_get_language_names ();
Matthias Clasen's avatar
Matthias Clasen committed
330

331 332 333
  for (i = 0; lang_list[i]; i++)
    if (strcmp (lang_list[i], lang) == 0)
      return 1000-i;
Matthias Clasen's avatar
Matthias Clasen committed
334

335 336 337 338
  return 0;
}

static void
Matthias Clasen's avatar
Matthias Clasen committed
339
mime_info_start_element (GMarkupParseContext  *context,
Matthias Clasen's avatar
Matthias Clasen committed
340 341 342 343 344
                         const gchar          *element_name,
                         const gchar         **attribute_names,
                         const gchar         **attribute_values,
                         gpointer              user_data,
                         GError              **error)
345 346 347 348
{
  int i;
  const char *lang;
  MimeParser *parser = user_data;
Matthias Clasen's avatar
Matthias Clasen committed
349

350 351 352 353
  if (strcmp (element_name, "comment") == 0)
    {
      lang = "C";
      for (i = 0; attribute_names[i]; i++)
Matthias Clasen's avatar
Matthias Clasen committed
354 355 356 357 358 359
        if (strcmp (attribute_names[i], "xml:lang") == 0)
          {
            lang = attribute_values[i];
            break;
          }

360 361 362 363 364 365 366 367
      parser->current_lang_level = language_level (lang);
      parser->current_type = MIME_TAG_TYPE_COMMENT;
    }
  else
    parser->current_type = MIME_TAG_TYPE_OTHER;
}

static void
Matthias Clasen's avatar
Matthias Clasen committed
368
mime_info_end_element (GMarkupParseContext  *context,
Matthias Clasen's avatar
Matthias Clasen committed
369 370 371
                       const gchar          *element_name,
                       gpointer              user_data,
                       GError              **error)
372 373
{
  MimeParser *parser = user_data;
Matthias Clasen's avatar
Matthias Clasen committed
374

375 376 377 378
  parser->current_type = MIME_TAG_TYPE_OTHER;
}

static void
Matthias Clasen's avatar
Matthias Clasen committed
379
mime_info_text (GMarkupParseContext  *context,
Matthias Clasen's avatar
Matthias Clasen committed
380 381 382 383
                const gchar          *text,
                gsize                 text_len,
                gpointer              user_data,
                GError              **error)
384 385 386 387 388 389 390 391 392 393 394 395 396
{
  MimeParser *parser = user_data;

  if (parser->current_type == MIME_TAG_TYPE_COMMENT &&
      parser->current_lang_level > parser->comment_lang_level)
    {
      g_free (parser->comment);
      parser->comment = g_strndup (text, text_len);
      parser->comment_lang_level = parser->current_lang_level;
    }
}

static char *
Matthias Clasen's avatar
Matthias Clasen committed
397
load_comment_for_mime_helper (const char *dir,
Matthias Clasen's avatar
Matthias Clasen committed
398
                              const char *basename)
399 400 401 402 403 404 405 406 407 408 409 410
{
  GMarkupParseContext *context;
  char *filename, *data;
  gsize len;
  gboolean res;
  MimeParser parse_data = {0};
  GMarkupParser parser = {
    mime_info_start_element,
    mime_info_end_element,
    mime_info_text
  };

411
  filename = g_build_filename (dir, basename, NULL);
Matthias Clasen's avatar
Matthias Clasen committed
412

413 414 415 416
  res = g_file_get_contents (filename,  &data,  &len,  NULL);
  g_free (filename);
  if (!res)
    return NULL;
Matthias Clasen's avatar
Matthias Clasen committed
417

418 419 420 421
  context = g_markup_parse_context_new   (&parser, 0, &parse_data, NULL);
  res = g_markup_parse_context_parse (context, data, len, NULL);
  g_free (data);
  g_markup_parse_context_free (context);
Matthias Clasen's avatar
Matthias Clasen committed
422

423 424 425 426 427 428 429 430 431 432
  if (!res)
    return NULL;

  return parse_data.comment;
}


static char *
load_comment_for_mime (const char *mimetype)
{
433
  const char * const *dirs;
434 435
  char *basename;
  char *comment;
436
  gsize i;
437 438 439

  basename = g_strdup_printf ("%s.xml", mimetype);

440
  dirs = g_content_type_get_mime_dirs ();
441 442 443 444
  for (i = 0; dirs[i] != NULL; i++)
    {
      comment = load_comment_for_mime_helper (dirs[i], basename);
      if (comment)
Matthias Clasen's avatar
Matthias Clasen committed
445 446 447 448
        {
          g_free (basename);
          return comment;
        }
449 450
    }
  g_free (basename);
Matthias Clasen's avatar
Matthias Clasen committed
451

452 453 454
  return g_strdup_printf (_("%s type"), mimetype);
}

Matthias Clasen's avatar
Matthias Clasen committed
455 456
/**
 * g_content_type_get_description:
Matthias Clasen's avatar
Matthias Clasen committed
457 458
 * @type: a content type string
 *
Matthias Clasen's avatar
Matthias Clasen committed
459
 * Gets the human readable description of the content type.
Matthias Clasen's avatar
Matthias Clasen committed
460 461 462 463 464 465
 *
 * Returns: a short description of the content type @type. Free the
 *     returned string with g_free()
 */
gchar *
g_content_type_get_description (const gchar *type)
466 467
{
  static GHashTable *type_comment_cache = NULL;
Matthias Clasen's avatar
Matthias Clasen committed
468
  gchar *comment;
469 470

  g_return_val_if_fail (type != NULL, NULL);
Matthias Clasen's avatar
Matthias Clasen committed
471

472
  G_LOCK (gio_xdgmime);
473 474
  type = xdg_mime_unalias_mime_type (type);

475 476 477 478 479 480
  if (type_comment_cache == NULL)
    type_comment_cache = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, g_free);

  comment = g_hash_table_lookup (type_comment_cache, type);
  comment = g_strdup (comment);
  G_UNLOCK (gio_xdgmime);
Matthias Clasen's avatar
Matthias Clasen committed
481

482 483 484 485
  if (comment != NULL)
    return comment;

  comment = load_comment_for_mime (type);
Matthias Clasen's avatar
Matthias Clasen committed
486

487 488
  G_LOCK (gio_xdgmime);
  g_hash_table_insert (type_comment_cache,
Matthias Clasen's avatar
Matthias Clasen committed
489 490
                       g_strdup (type),
                       g_strdup (comment));
491 492 493 494 495
  G_UNLOCK (gio_xdgmime);

  return comment;
}

Matthias Clasen's avatar
Matthias Clasen committed
496 497
/**
 * g_content_type_get_mime_type:
Matthias Clasen's avatar
Matthias Clasen committed
498 499 500 501
 * @type: a content type string
 *
 * Gets the mime type for the content type, if one is registered.
 *
502 503
 * Returns: (nullable) (transfer full): the registered mime type for the
 *     given @type, or %NULL if unknown; free with g_free().
Matthias Clasen's avatar
Matthias Clasen committed
504
 */
505
char *
Matthias Clasen's avatar
Matthias Clasen committed
506
g_content_type_get_mime_type (const char *type)
507 508 509 510 511 512
{
  g_return_val_if_fail (type != NULL, NULL);

  return g_strdup (type);
}

513 514 515
static GIcon *
g_content_type_get_icon_internal (const gchar *type,
                                  gboolean     symbolic)
516
{
517
  char *mimetype_icon;
518
  char *generic_mimetype_icon = NULL;
519
  char *q;
520
  char *icon_names[6];
521
  int n = 0;
Alexander Larsson's avatar
Alexander Larsson committed
522
  GIcon *themed_icon;
523
  const char  *xdg_icon;
524
  int i;
Matthias Clasen's avatar
Matthias Clasen committed
525

526
  g_return_val_if_fail (type != NULL, NULL);
Matthias Clasen's avatar
Matthias Clasen committed
527

528
  G_LOCK (gio_xdgmime);
529
  xdg_icon = xdg_mime_get_icon (type);
530 531
  G_UNLOCK (gio_xdgmime);

532 533
  if (xdg_icon)
    icon_names[n++] = g_strdup (xdg_icon);
Matthias Clasen's avatar
Matthias Clasen committed
534

535
  mimetype_icon = g_strdup (type);
Alexander Larsson's avatar
Alexander Larsson committed
536 537
  while ((q = strchr (mimetype_icon, '/')) != NULL)
    *q = '-';
Matthias Clasen's avatar
Matthias Clasen committed
538

539
  icon_names[n++] = mimetype_icon;
540

541
  generic_mimetype_icon = g_content_type_get_generic_icon_name (type);
542 543
  if (generic_mimetype_icon)
    icon_names[n++] = generic_mimetype_icon;
Matthias Clasen's avatar
Matthias Clasen committed
544

545 546 547 548 549 550 551 552 553 554 555
  if (symbolic)
    {
      for (i = 0; i < n; i++)
        {
          icon_names[n + i] = icon_names[i];
          icon_names[i] = g_strconcat (icon_names[i], "-symbolic", NULL);
        }

      n += n;
    }

556
  themed_icon = g_themed_icon_new_from_names (icon_names, n);
Matthias Clasen's avatar
Matthias Clasen committed
557

558 559
  for (i = 0; i < n; i++)
    g_free (icon_names[i]);
Matthias Clasen's avatar
Matthias Clasen committed
560

Alexander Larsson's avatar
Alexander Larsson committed
561
  return themed_icon;
562 563
}

564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595
/**
 * g_content_type_get_icon:
 * @type: a content type string
 *
 * Gets the icon for a content type.
 *
 * Returns: (transfer full): #GIcon corresponding to the content type. Free the returned
 *     object with g_object_unref()
 */
GIcon *
g_content_type_get_icon (const gchar *type)
{
  return g_content_type_get_icon_internal (type, FALSE);
}

/**
 * g_content_type_get_symbolic_icon:
 * @type: a content type string
 *
 * Gets the symbolic icon for a content type.
 *
 * Returns: (transfer full): symbolic #GIcon corresponding to the content type.
 *     Free the returned object with g_object_unref()
 *
 * Since: 2.34
 */
GIcon *
g_content_type_get_symbolic_icon (const gchar *type)
{
  return g_content_type_get_icon_internal (type, TRUE);
}

596 597 598 599 600 601
/**
 * g_content_type_get_generic_icon_name:
 * @type: a content type string
 *
 * Gets the generic icon name for a content type.
 *
602 603
 * See the
 * [shared-mime-info](http://www.freedesktop.org/wiki/Specifications/shared-mime-info-spec)
604 605
 * specification for more on the generic icon name.
 *
606
 * Returns: (nullable): the registered generic icon name for the given @type,
607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642
 *     or %NULL if unknown. Free with g_free()
 *
 * Since: 2.34
 */
gchar *
g_content_type_get_generic_icon_name (const gchar *type)
{
  const gchar *xdg_icon_name;
  gchar *icon_name;

  G_LOCK (gio_xdgmime);
  xdg_icon_name = xdg_mime_get_generic_icon (type);
  G_UNLOCK (gio_xdgmime);

  if (!xdg_icon_name)
    {
      const char *p;
      const char *suffix = "-x-generic";

      p = strchr (type, '/');
      if (p == NULL)
        p = type + strlen (type);

      icon_name = g_malloc (p - type + strlen (suffix) + 1);
      memcpy (icon_name, type, p - type);
      memcpy (icon_name + (p - type), suffix, strlen (suffix));
      icon_name[(p - type) + strlen (suffix)] = 0;
    }
  else
    {
      icon_name = g_strdup (xdg_icon_name);
    }

  return icon_name;
}

643 644
/**
 * g_content_type_can_be_executable:
Matthias Clasen's avatar
Matthias Clasen committed
645 646
 * @type: a content type string
 *
Matthias Clasen's avatar
Matthias Clasen committed
647 648
 * Checks if a content type can be executable. Note that for instance
 * things like text files can be executables (i.e. scripts and batch files).
Matthias Clasen's avatar
Matthias Clasen committed
649
 *
Matthias Clasen's avatar
Matthias Clasen committed
650
 * Returns: %TRUE if the file type corresponds to a type that
Matthias Clasen's avatar
Matthias Clasen committed
651 652
 *     can be executable, %FALSE otherwise.
 */
653
gboolean
Matthias Clasen's avatar
Matthias Clasen committed
654
g_content_type_can_be_executable (const gchar *type)
655 656 657 658 659 660 661 662 663 664 665 666 667 668
{
  g_return_val_if_fail (type != NULL, FALSE);

  if (g_content_type_is_a (type, "application/x-executable")  ||
      g_content_type_is_a (type, "text/plain"))
    return TRUE;

  return FALSE;
}

static gboolean
looks_like_text (const guchar *data, gsize data_size)
{
  gsize i;
669
  char c;
Matthias Clasen's avatar
Matthias Clasen committed
670

671 672
  for (i = 0; i < data_size; i++)
    {
673
      c = data[i];
Matthias Clasen's avatar
Matthias Clasen committed
674

675
      if (g_ascii_iscntrl (c) &&
Matthias Clasen's avatar
Matthias Clasen committed
676 677 678
          !g_ascii_isspace (c) &&
          c != '\b')
        return FALSE;
679 680 681 682
    }
  return TRUE;
}

683 684
/**
 * g_content_type_from_mime_type:
Matthias Clasen's avatar
Matthias Clasen committed
685
 * @mime_type: a mime type string
686 687 688
 *
 * Tries to find a content type based on the mime type name.
 *
689 690
 * Returns: (nullable): Newly allocated string with content type or
 *     %NULL. Free with g_free()
691 692 693
 *
 * Since: 2.18
 **/
Matthias Clasen's avatar
Matthias Clasen committed
694 695
gchar *
g_content_type_from_mime_type (const gchar *mime_type)
696
{
697 698
  char *umime;

699 700
  g_return_val_if_fail (mime_type != NULL, NULL);

701
  G_LOCK (gio_xdgmime);
702
  /* mime type and content type are same on unixes */
703
  umime = g_strdup (xdg_mime_unalias_mime_type (mime_type));
704
  G_UNLOCK (gio_xdgmime);
705 706

  return umime;
707 708
}

Matthias Clasen's avatar
Matthias Clasen committed
709 710
/**
 * g_content_type_guess:
711 712
 * @filename: (nullable): a string, or %NULL
 * @data: (nullable) (array length=data_size): a stream of data, or %NULL
713
 * @data_size: the size of @data
714
 * @result_uncertain: (out) (optional): return location for the certainty
Matthias Clasen's avatar
Matthias Clasen committed
715 716 717
 *     of the result, or %NULL
 *
 * Guesses the content type based on example data. If the function is
718 719 720
 * uncertain, @result_uncertain will be set to %TRUE. Either @filename
 * or @data may be %NULL, in which case the guess will be based solely
 * on the other argument.
Matthias Clasen's avatar
Matthias Clasen committed
721 722 723 724 725 726 727 728 729
 *
 * Returns: a string indicating a guessed content type for the
 *     given data. Free with g_free()
 */
gchar *
g_content_type_guess (const gchar  *filename,
                      const guchar *data,
                      gsize         data_size,
                      gboolean     *result_uncertain)
730 731 732 733 734 735 736 737 738 739 740 741 742 743
{
  char *basename;
  const char *name_mimetypes[10], *sniffed_mimetype;
  char *mimetype;
  int i;
  int n_name_mimetypes;
  int sniffed_prio;

  sniffed_prio = 0;
  n_name_mimetypes = 0;
  sniffed_mimetype = XDG_MIME_TYPE_UNKNOWN;

  if (result_uncertain)
    *result_uncertain = FALSE;
Matthias Clasen's avatar
Matthias Clasen committed
744

745 746 747 748
  /* our test suite and potentially other code used -1 in the past, which is
   * not documented and not allowed; guard against that */
  g_return_val_if_fail (data_size != (gsize) -1, g_strdup (XDG_MIME_TYPE_UNKNOWN));

749
  G_LOCK (gio_xdgmime);
Matthias Clasen's avatar
Matthias Clasen committed
750

751 752
  if (filename)
    {
753
      i = strlen (filename);
754 755 756 757 758 759 760 761 762 763 764 765 766 767
      if (filename[i - 1] == '/')
        {
          name_mimetypes[0] = "inode/directory";
          name_mimetypes[1] = NULL;
          n_name_mimetypes = 1;
          if (result_uncertain)
            *result_uncertain = TRUE;
        }
      else
        {
          basename = g_path_get_basename (filename);
          n_name_mimetypes = xdg_mime_get_mime_types_from_file_name (basename, name_mimetypes, 10);
          g_free (basename);
        }
768 769 770 771 772
    }

  /* Got an extension match, and no conflicts. This is it. */
  if (n_name_mimetypes == 1)
    {
773
      gchar *s = g_strdup (name_mimetypes[0]);
774
      G_UNLOCK (gio_xdgmime);
775
      return s;
776
    }
Matthias Clasen's avatar
Matthias Clasen committed
777

778 779 780 781
  if (data)
    {
      sniffed_mimetype = xdg_mime_get_mime_type_for_data (data, data_size, &sniffed_prio);
      if (sniffed_mimetype == XDG_MIME_TYPE_UNKNOWN &&
Matthias Clasen's avatar
Matthias Clasen committed
782 783 784
          data &&
          looks_like_text (data, data_size))
        sniffed_mimetype = "text/plain";
785 786 787 788 789 790 791 792 793 794

      /* For security reasons we don't ever want to sniff desktop files
       * where we know the filename and it doesn't have a .desktop extension.
       * This is because desktop files allow executing any application and
       * we don't want to make it possible to hide them looking like something
       * else.
       */
      if (filename != NULL &&
          strcmp (sniffed_mimetype, "application/x-desktop") == 0)
        sniffed_mimetype = "text/plain";
795
    }
Matthias Clasen's avatar
Matthias Clasen committed
796

797 798 799
  if (n_name_mimetypes == 0)
    {
      if (sniffed_mimetype == XDG_MIME_TYPE_UNKNOWN &&
Matthias Clasen's avatar
Matthias Clasen committed
800 801 802
          result_uncertain)
        *result_uncertain = TRUE;

803 804 805 806 807 808
      mimetype = g_strdup (sniffed_mimetype);
    }
  else
    {
      mimetype = NULL;
      if (sniffed_mimetype != XDG_MIME_TYPE_UNKNOWN)
Matthias Clasen's avatar
Matthias Clasen committed
809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830
        {
          if (sniffed_prio >= 80) /* High priority sniffing match, use that */
            mimetype = g_strdup (sniffed_mimetype);
          else
            {
              /* There are conflicts between the name matches and we
               * have a sniffed type, use that as a tie breaker.
               */
              for (i = 0; i < n_name_mimetypes; i++)
                {
                  if ( xdg_mime_mime_type_subclass (name_mimetypes[i], sniffed_mimetype))
                    {
                      /* This nametype match is derived from (or the same as)
                       * the sniffed type). This is probably it.
                       */
                      mimetype = g_strdup (name_mimetypes[i]);
                      break;
                    }
                }
            }
        }

831
      if (mimetype == NULL)
Matthias Clasen's avatar
Matthias Clasen committed
832 833 834 835 836 837 838 839
        {
          /* Conflicts, and sniffed type was no help or not there.
           * Guess on the first one
           */
          mimetype = g_strdup (name_mimetypes[0]);
          if (result_uncertain)
            *result_uncertain = TRUE;
        }
840
    }
Matthias Clasen's avatar
Matthias Clasen committed
841

842 843 844 845 846 847
  G_UNLOCK (gio_xdgmime);

  return mimetype;
}

static void
Matthias Clasen's avatar
Matthias Clasen committed
848 849
enumerate_mimetypes_subdir (const char *dir,
                            const char *prefix,
Matthias Clasen's avatar
Matthias Clasen committed
850
                            GHashTable *mimetypes)
851 852 853 854 855 856 857 858 859
{
  DIR *d;
  struct dirent *ent;
  char *mimetype;

  d = opendir (dir);
  if (d)
    {
      while ((ent = readdir (d)) != NULL)
Matthias Clasen's avatar
Matthias Clasen committed
860 861 862 863 864 865 866
        {
          if (g_str_has_suffix (ent->d_name, ".xml"))
            {
              mimetype = g_strdup_printf ("%s/%.*s", prefix, (int) strlen (ent->d_name) - 4, ent->d_name);
              g_hash_table_replace (mimetypes, mimetype, NULL);
            }
        }
867 868 869 870 871
      closedir (d);
    }
}

static void
Matthias Clasen's avatar
Matthias Clasen committed
872
enumerate_mimetypes_dir (const char *dir,
Matthias Clasen's avatar
Matthias Clasen committed
873
                         GHashTable *mimetypes)
874 875 876
{
  DIR *d;
  struct dirent *ent;
877
  const char *mimedir;
878 879
  char *name;

880
  mimedir = dir;
Matthias Clasen's avatar
Matthias Clasen committed
881

882 883 884 885
  d = opendir (mimedir);
  if (d)
    {
      while ((ent = readdir (d)) != NULL)
Matthias Clasen's avatar
Matthias Clasen committed
886 887 888 889 890 891 892 893 894
        {
          if (strcmp (ent->d_name, "packages") != 0)
            {
              name = g_build_filename (mimedir, ent->d_name, NULL);
              if (g_file_test (name, G_FILE_TEST_IS_DIR))
                enumerate_mimetypes_subdir (name, ent->d_name, mimetypes);
              g_free (name);
            }
        }
895 896 897 898
      closedir (d);
    }
}

Matthias Clasen's avatar
Matthias Clasen committed
899 900
/**
 * g_content_types_get_registered:
Matthias Clasen's avatar
Matthias Clasen committed
901
 *
902
 * Gets a list of strings containing all the registered content types
Matthias Clasen's avatar
Matthias Clasen committed
903
 * known to the system. The list and its data should be freed using
904
 * `g_list_free_full (list, g_free)`.
Matthias Clasen's avatar
Matthias Clasen committed
905
 *
906 907
 * Returns: (element-type utf8) (transfer full): list of the registered
 *     content types
Matthias Clasen's avatar
Matthias Clasen committed
908
 */
909 910 911
GList *
g_content_types_get_registered (void)
{
912
  const char * const *dirs;
913
  GHashTable *mimetypes;
Matthias Clasen's avatar
Matthias Clasen committed
914 915
  GHashTableIter iter;
  gpointer key;
916
  gsize i;
917 918
  GList *l;

919
  mimetypes = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
920

921
  dirs = g_content_type_get_mime_dirs ();
922 923 924 925
  for (i = 0; dirs[i] != NULL; i++)
    enumerate_mimetypes_dir (dirs[i], mimetypes);

  l = NULL;
Matthias Clasen's avatar
Matthias Clasen committed
926 927
  g_hash_table_iter_init (&iter, mimetypes);
  while (g_hash_table_iter_next (&iter, &key, NULL))
928 929 930 931
    {
      l = g_list_prepend (l, key);
      g_hash_table_iter_steal (&iter);
    }
Matthias Clasen's avatar
Matthias Clasen committed
932

933 934 935 936 937
  g_hash_table_destroy (mimetypes);

  return l;
}

938 939 940 941 942 943 944

/* tree magic data */
static GList *tree_matches = NULL;
static gboolean need_reload = FALSE;

G_LOCK_DEFINE_STATIC (gio_treemagic);

Matthias Clasen's avatar
Matthias Clasen committed
945
typedef struct
946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967
{
  gchar *path;
  GFileType type;
  guint match_case : 1;
  guint executable : 1;
  guint non_empty  : 1;
  guint on_disc    : 1;
  gchar *mimetype;
  GList *matches;
} TreeMatchlet;

typedef struct
{
  gchar *contenttype;
  gint priority;
  GList *matches;
} TreeMatch;


static void
tree_matchlet_free (TreeMatchlet *matchlet)
{
968
  g_list_free_full (matchlet->matches, (GDestroyNotify) tree_matchlet_free);
969 970 971 972 973 974 975 976
  g_free (matchlet->path);
  g_free (matchlet->mimetype);
  g_slice_free (TreeMatchlet, matchlet);
}

static void
tree_match_free (TreeMatch *match)
{
977
  g_list_free_full (match->matches, (GDestroyNotify) tree_matchlet_free);
978 979 980 981 982 983 984 985 986 987 988 989 990 991 992
  g_free (match->contenttype);
  g_slice_free (TreeMatch, match);
}

static TreeMatch *
parse_header (gchar *line)
{
  gint len;
  gchar *s;
  TreeMatch *match;

  len = strlen (line);

  if (line[0] != '[' || line[len - 1] != ']')
    return NULL;
Matthias Clasen's avatar
Matthias Clasen committed
993

994 995
  line[len - 1] = 0;
  s = strchr (line, ':');
Matthias Clasen's avatar
Matthias Clasen committed
996

997 998 999 1000 1001 1002 1003 1004
  match = g_slice_new0 (TreeMatch);
  match->priority = atoi (line + 1);
  match->contenttype = g_strdup (s + 1);

  return match;
}

static TreeMatchlet *
Matthias Clasen's avatar
Matthias Clasen committed
1005 1006
parse_match_line (gchar *line,
                  gint  *depth)
1007 1008 1009 1010 1011 1012 1013 1014
{
  gchar *s, *p;
  TreeMatchlet *matchlet;
  gchar **parts;
  gint i;

  matchlet = g_slice_new0 (TreeMatchlet);

Matthias Clasen's avatar
Matthias Clasen committed
1015
  if (line[0] == '>')
1016 1017 1018 1019
    {
      *depth = 0;
      s = line;
    }
Matthias Clasen's avatar
Matthias Clasen committed
1020
  else
1021 1022 1023 1024
    {
      *depth = atoi (line);
      s = strchr (line, '>');
    }
Matthias Clasen's avatar
Matthias Clasen committed
1025
  s += 2;
1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049
  p = strchr (s, '"');
  *p = 0;

  matchlet->path = g_strdup (s);
  s = p + 1;
  parts = g_strsplit (s, ",", 0);
  if (strcmp (parts[0], "=file") == 0)
    matchlet->type = G_FILE_TYPE_REGULAR;
  else if (strcmp (parts[0], "=directory") == 0)
    matchlet->type = G_FILE_TYPE_DIRECTORY;
  else if (strcmp (parts[0], "=link") == 0)
    matchlet->type = G_FILE_TYPE_SYMBOLIC_LINK;
  else
    matchlet->type = G_FILE_TYPE_UNKNOWN;
  for (i = 1; parts[i]; i++)
    {
      if (strcmp (parts[i], "executable") == 0)
        matchlet->executable = 1;
      else if (strcmp (parts[i], "match-case") == 0)
        matchlet->match_case = 1;
      else if (strcmp (parts[i], "non-empty") == 0)
        matchlet->non_empty = 1;
      else if (strcmp (parts[i], "on-disc") == 0)
        matchlet->on_disc = 1;
Matthias Clasen's avatar
Matthias Clasen committed
1050
      else
1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074
        matchlet->mimetype = g_strdup (parts[i]);
    }

  g_strfreev (parts);

  return matchlet;
}

static gint
cmp_match (gconstpointer a, gconstpointer b)
{
  const TreeMatch *aa = (const TreeMatch *)a;
  const TreeMatch *bb = (const TreeMatch *)b;

  return bb->priority - aa->priority;
}

static void
insert_match (TreeMatch *match)
{
  tree_matches = g_list_insert_sorted (tree_matches, match, cmp_match);
}

static void
Matthias Clasen's avatar
Matthias Clasen committed
1075 1076
insert_matchlet (TreeMatch    *match,
                 TreeMatchlet *matchlet,
1077 1078
                 gint          depth)
{
Matthias Clasen's avatar
Matthias Clasen committed
1079
  if (depth == 0)
1080
    match->matches = g_list_append (match->matches, matchlet);
Matthias Clasen's avatar
Matthias Clasen committed
1081
  else
1082 1083 1084 1085 1086
    {
      GList *last;
      TreeMatchlet *m;

      last = g_list_last (match->matches);
Matthias Clasen's avatar
Matthias Clasen committed
1087
      if (!last)
1088 1089 1090 1091 1092 1093 1094
        {
          tree_matchlet_free (matchlet);
          g_warning ("can't insert tree matchlet at depth %d", depth);
          return;
        }

      m = (TreeMatchlet *) last->data;
Matthias Clasen's avatar
Matthias Clasen committed
1095
      while (--depth > 0)
1096 1097
        {
          last = g_list_last (m->matches);
Matthias Clasen's avatar
Matthias Clasen committed
1098
          if (!last)
1099 1100 1101 1102 1103
            {
              tree_matchlet_free (matchlet);
              g_warning ("can't insert tree matchlet at depth %d", depth);
              return;
            }
Matthias Clasen's avatar
Matthias Clasen committed
1104

1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122
          m = (TreeMatchlet *) last->data;
        }
      m->matches = g_list_append (m->matches, matchlet);
    }
}

static void
read_tree_magic_from_directory (const gchar *prefix)
{
  gchar *filename;
  gchar *text;
  gsize len;
  gchar **lines;
  gint i;
  TreeMatch *match;
  TreeMatchlet *matchlet;
  gint depth;

1123
  filename = g_build_filename (prefix, "treemagic", NULL);
1124

Matthias Clasen's avatar
Matthias Clasen committed
1125
  if (g_file_get_contents (filename, &text, &len, NULL))
1126
    {
Matthias Clasen's avatar
Matthias Clasen committed
1127
      if (strcmp (text, "MIME-TreeMagic") == 0)
1128 1129 1130
        {
          lines = g_strsplit (text + strlen ("MIME-TreeMagic") + 2, "\n", 0);
          match = NULL;
Matthias Clasen's avatar
Matthias Clasen committed
1131
          for (i = 0; lines[i] && lines[i][0]; i++)
1132
            {
Matthias Clasen's avatar
Matthias Clasen committed
1133
              if (lines[i][0] == '[')
1134 1135 1136 1137
                {
                  match = parse_header (lines[i]);
                  insert_match (match);
                }
1138
              else if (match != NULL)
1139 1140 1141 1142
                {
                  matchlet = parse_match_line (lines[i], &depth);
                  insert_matchlet (match, matchlet, depth);
                }
1143 1144
              else
                {
1145
                  g_warning ("%s: header corrupt; skipping", filename);
1146 1147
                  break;
                }
1148
            }
Matthias Clasen's avatar
Matthias Clasen committed
1149

1150 1151
          g_strfreev (lines);
        }
Matthias Clasen's avatar
Matthias Clasen committed
1152
      else
1153
        g_warning ("%s: header not found, skipping", filename);
1154 1155 1156

      g_free (text);
    }
Matthias Clasen's avatar
Matthias Clasen committed
1157

1158 1159 1160
  g_free (filename);
}

1161 1162 1163 1164 1165
static void
tree_magic_schedule_reload (void)
{
  need_reload = TRUE;
}
1166 1167 1168 1169

static void
xdg_mime_reload (void *user_data)
{
1170
  tree_magic_schedule_reload ();
1171 1172
}

Matthias Clasen's avatar
Matthias Clasen committed
1173
static void
1174 1175
tree_magic_shutdown (void)
{
1176
  g_list_free_full (tree_matches, (GDestroyNotify) tree_match_free);
1177 1178 1179 1180 1181 1182 1183
  tree_matches = NULL;
}

static void
tree_magic_init (void)
{
  static gboolean initialized = FALSE;
1184
  gsize i;
1185

Matthias Clasen's avatar
Matthias Clasen committed
1186
  if (!initialized)
1187 1188 1189 1190 1191 1192 1193
    {
      initialized = TRUE;

      xdg_mime_register_reload_callback (xdg_mime_reload, NULL, NULL);
      need_reload = TRUE;
    }

Matthias Clasen's avatar
Matthias Clasen committed
1194
  if (need_reload)
1195
    {
1196 1197
      const char * const *dirs;

1198 1199 1200 1201
      need_reload = FALSE;

      tree_magic_shutdown ();

1202 1203
      dirs = g_content_type_get_mime_dirs ();
      for (i = 0; dirs[i] != NULL; i++)
1204 1205 1206 1207 1208 1209
        read_tree_magic_from_directory (dirs[i]);
    }
}

/* a filtering enumerator */

Matthias Clasen's avatar
Matthias Clasen committed
1210
typedef struct
1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221
{
  gchar *path;
  gint depth;
  gboolean ignore_case;
  gchar **components;
  gchar **case_components;
  GFileEnumerator **enumerators;
  GFile **children;
} Enumerator;

static gboolean
Matthias Clasen's avatar
Matthias Clasen committed
1222 1223
component_match (Enumerator  *e,
                 gint         depth,
1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246
                 const gchar *name)
{
  gchar *case_folded, *key;
  gboolean found;

  if (strcmp (name, e->components[depth]) == 0)
    return TRUE;

  if (!e->ignore_case)
    return FALSE;

  case_folded = g_utf8_casefold (name, -1);
  key = g_utf8_collate_key (case_folded, -1);

  found = strcmp (key, e->case_components[depth]) == 0;

  g_free (case_folded);
  g_free (key);

  return found;
}

static GFile *
Matthias Clasen's avatar
Matthias Clasen committed
1247
next_match_recurse (Enumerator *e,
1248 1249 1250 1251 1252 1253
                    gint        depth)
{
  GFile *file;
  GFileInfo *info;
  const gchar *name;

Matthias Clasen's avatar
Matthias Clasen committed
1254
  while (TRUE)
1255
    {
Matthias Clasen's avatar
Matthias Clasen committed
1256
      if (e->enumerators[depth] == NULL)
1257
        {
Matthias Clasen's avatar
Matthias Clasen committed
1258
          if (depth > 0)
1259 1260
            {
              file = next_match_recurse (e, depth - 1);
Matthias Clasen's avatar
Matthias Clasen committed
1261
              if (file)
1262 1263 1264 1265 1266
                {
                  e->children[depth] = file;
                  e->enumerators[depth] = g_file_enumerate_children (file,
                                                                     G_FILE_ATTRIBUTE_STANDARD_NAME,
                                                                     G_FILE_QUERY_INFO_NONE,
Matthias Clasen's avatar
Matthias Clasen committed
1267 1268
                                                                     NULL,
                                                                     NULL);
1269 1270 1271 1272 1273 1274
                }
            }
          if (e->enumerators[depth] == NULL)
            return NULL;
        }

Matthias Clasen's avatar
Matthias Clasen committed
1275
      while ((info = g_file_enumerator_next_file (e->enumerators[depth], NULL, NULL)))
1276 1277
        {
          name = g_file_info_get_name (info);
Matthias Clasen's avatar
Matthias Clasen committed
1278
          if (component_match (e, depth, name))
1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301
            {
              file = g_file_get_child (e->children[depth], name);
              g_object_unref (info);
              return file;
            }
          g_object_unref (info);
        }

      g_object_unref (e->enumerators[depth]);
      e->enumerators[depth] = NULL;
      g_object_unref (e->children[depth]);
      e->children[depth] = NULL;
    }
}

static GFile *
enumerator_next (Enumerator *e)
{
  return next_match_recurse (e, e->depth - 1);
}

static Enumerator *
enumerator_new (GFile      *root,
Matthias Clasen's avatar
Matthias Clasen committed
1302
                const char *path,
1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314
                gboolean    ignore_case)
{
  Enumerator *e;
  gint i;
  gchar *case_folded;

  e = g_new0 (Enumerator, 1);
  e->path = g_strdup (path);
  e->ignore_case = ignore_case;

  e->components = g_strsplit (e->path, G_DIR_SEPARATOR_S, -1);
  e->depth = g_strv_length (e->components);
Matthias Clasen's avatar
Matthias Clasen committed
1315
  if (e->ignore_case)
1316 1317
    {
      e->case_components = g_new0 (char *, e->depth + 1);
Matthias Clasen's avatar
Matthias Clasen committed
1318
      for (i = 0; e->components[i]; i++)
1319 1320 1321 1322
        {
          case_folded = g_utf8_casefold (e->components[i], -1);
          e->case_components[i] = g_utf8_collate_key (case_folded, -1);
          g_free (case_folded);
Matthias Clasen's avatar
Matthias Clasen committed
1323
        }
1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342
    }

  e->children = g_new0 (GFile *, e->depth);
  e->children[0] = g_object_ref (root);
  e->enumerators = g_new0 (GFileEnumerator *, e->depth);
  e->enumerators[0] = g_file_enumerate_children (root,
                                                 G_FILE_ATTRIBUTE_STANDARD_NAME,
                                                 G_FILE_QUERY_INFO_NONE,
                                                 NULL,
                                                 NULL);

  return e;
}

static void
enumerator_free (Enumerator *e)
{
  gint i;

Matthias Clasen's avatar
Matthias Clasen committed
1343 1344 1345
  for (i = 0; i < e->depth; i++)
    {
      if (e->enumerators[i])
1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371
        g_object_unref (e->enumerators[i]);
      if (e->children[i])
        g_object_unref (e->children[i]);
    }

  g_free (e->enumerators);
  g_free (e->children);
  g_strfreev (e->components);
  if (e->case_components)
    g_strfreev (e->case_components);
  g_free (e->path);
  g_free (e);
}

static gboolean
matchlet_match (TreeMatchlet *matchlet,
                GFile        *root)
{
  GFile *file;
  GFileInfo *info;
  gboolean result;
  const gchar *attrs;
  Enumerator *e;
  GList *l;

  e = enumerator_new (root, matchlet->path, !matchlet->match_case);
Matthias Clasen's avatar
Matthias Clasen committed
1372 1373

  do
1374 1375
    {
      file = enumerator_next (e);
Matthias Clasen's avatar
Matthias Clasen committed
1376
      if (!file)
1377
        {
Matthias Clasen's avatar
Matthias Clasen committed
1378
          enumerator_free (e);
1379 1380 1381 1382 1383 1384 1385 1386 1387 1388
          return FALSE;
        }

      if (matchlet->mimetype)
        attrs = G_FILE_ATTRIBUTE_STANDARD_TYPE ","
                G_FILE_ATTRIBUTE_ACCESS_CAN_EXECUTE ","
                G_FILE_ATTRIBUTE_STANDARD_CONTENT_TYPE;
      else
        attrs = G_FILE_ATTRIBUTE_STANDARD_TYPE ","
                G_FILE_ATTRIBUTE_ACCESS_CAN_EXECUTE;
Matthias Clasen's avatar
Matthias Clasen committed
1389
      info = g_file_query_info (file,
1390 1391 1392 1393
                                attrs,
                                G_FILE_QUERY_INFO_NONE,
                                NULL,
                                NULL);
Matthias Clasen's avatar
Matthias Clasen committed
1394
      if (info)
1395 1396 1397 1398
        {
          result = TRUE;

          if (matchlet->type != G_FILE_TYPE_UNKNOWN &&
Matthias Clasen's avatar
Matthias Clasen committed
1399
              g_file_info_get_file_type (info) != matchlet->type)
1400 1401 1402 1403 1404
            result = FALSE;

          if (matchlet->executable &&
              !g_file_info_get_attribute_boolean (info, G_FILE_ATTRIBUTE_ACCESS_CAN_EXECUTE))
            result = FALSE;
Matthias Clasen's avatar
Matthias Clasen committed
1405 1406
        }
      else
1407 1408
        result = FALSE;

Matthias Clasen's avatar
Matthias Clasen committed
1409
      if (result && matchlet->non_empty)
1410 1411 1412 1413
        {
          GFileEnumerator *child_enum;
          GFileInfo *child_info;

Matthias Clasen's avatar
Matthias Clasen committed
1414
          child_enum = g_file_enumerate_children (file,
1415 1416 1417 1418
                                                  G_FILE_ATTRIBUTE_STANDARD_NAME,
                                                  G_FILE_QUERY_INFO_NONE,
                                                  NULL,
                                                  NULL);
Matthias Clasen's avatar
Matthias Clasen committed
1419 1420

          if (child_enum)
1421 1422 1423 1424
            {
              child_info = g_file_enumerator_next_file (child_enum, NULL, NULL);
              if (child_info)
                g_object_unref (child_info);
Matthias Clasen's avatar
Matthias Clasen committed
1425 1426
              else
                result = FALSE;
1427 1428
              g_object_unref (child_enum);
            }
Matthias Clasen's avatar
Matthias Clasen committed
1429
          else
1430 1431
            result = FALSE;
        }
Matthias Clasen's avatar
Matthias Clasen committed
1432 1433

      if (result && matchlet->mimetype)
1434
        {
Matthias Clasen's avatar
Matthias Clasen committed
1435
          if (strcmp (matchlet->mimetype, g_file_info_get_content_type (info)) != 0)
1436 1437
            result = FALSE;
        }
Matthias Clasen's avatar
Matthias Clasen committed
1438

1439 1440
      if (info)
        g_object_unref (info);
1441 1442 1443 1444 1445
      g_object_unref (file);
    }
  while (!result);

  enumerator_free (e);
Matthias Clasen's avatar
Matthias Clasen committed
1446 1447

  if (!matchlet->matches)
1448 1449
    return TRUE;

Matthias Clasen's avatar
Matthias Clasen committed
1450
  for (l = matchlet->matches; l; l = l->next)
1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467
    {
      TreeMatchlet *submatchlet;

      submatchlet = l->data;
      if (matchlet_match (submatchlet, root))
        return TRUE;
    }

  return FALSE;
}

static void
match_match (TreeMatch    *match,
             GFile        *root,
             GPtrArray    *types)
{
  GList *l;
Matthias Clasen's avatar
Matthias Clasen committed
1468 1469

  for (l = match->matches; l; l = l->next)
1470 1471
    {
      TreeMatchlet *matchlet = l->data;
Matthias Clasen's avatar
Matthias Clasen committed
1472
      if (matchlet_match (matchlet, root))
1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488
        {
          g_ptr_array_add (types, g_strdup (match->contenttype));
          break;
        }
    }
}

/**
 * g_content_type_guess_for_tree:
 * @root: the root of the tree to guess a type for
 *
 * Tries to guess the type of the tree with root @root, by
 * looking at the files it contains. The result is an array
 * of content types, with the best guess coming first.
 *
 * The types returned all have the form x-content/foo, e.g.
Matthias Clasen's avatar
Matthias Clasen committed
1489
 * x-content/audio-cdda (for audio CDs) or x-content/image-dcf
1490 1491
 * (for a camera memory card). See the
 * [shared-mime-info](http://www.freedesktop.org/wiki/Specifications/shared-mime-info-spec)
1492 1493
 * specification for more on x-content types.
 *
Matthias Clasen's avatar
Matthias Clasen committed
1494 1495
 * This function is useful in the implementation of
 * g_mount_guess_content_type().
1496
 *
1497
 * Returns: (transfer full) (array zero-terminated=1): an %NULL-terminated
1498
 *     array of zero or more content types. Free with g_strfreev()
1499 1500 1501
 *
 * Since: 2.18
 */
Matthias Clasen's avatar
Matthias Clasen committed
1502
gchar **
1503 1504 1505 1506 1507 1508 1509 1510 1511 1512
g_content_type_guess_for_tree (GFile *root)
{
  GPtrArray *types;
  GList *l;

  types = g_ptr_array_new ();

  G_LOCK (gio_treemagic);

  tree_magic_init ();
Matthias Clasen's avatar
Matthias Clasen committed
1513
  for (l = tree_matches; l; l = l->next)
1514 1515 1516 1517 1518 1519 1520 1521 1522
    {
      TreeMatch *match = l->data;
      match_match (match, root, types);
    }

  G_UNLOCK (gio_treemagic);

  g_ptr_array_add (types, NULL);

Matthias Clasen's avatar
Matthias Clasen committed
1523
  return (gchar **)g_ptr_array_free (types, FALSE);
1524
}