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

3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
/* GIO - GLib Input, Output and Streaming Library
 * 
 * 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
 * version 2 of the License, or (at your option) any later version.
 *
 * 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
 * Public License along with this library; if not, write to the
 * Free Software Foundation, Inc., 59 Temple Place, Suite 330,
 * Boston, MA 02111-1307, USA.
 *
 * Author: Alexander Larsson <alexl@redhat.com>
 */

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

38

39 40
/**
 * SECTION:gcontenttype
Matthias Clasen's avatar
Matthias Clasen committed
41
 * @short_description: Platform-specific content typing
Matthias Clasen's avatar
Matthias Clasen committed
42
 * @include: gio/gio.h
43 44
 *
 * A content type is a platform specific string that defines the type
Matthias Clasen's avatar
Matthias Clasen committed
45
 * of a file. On UNIX it is a <ulink url="http://www.wikipedia.org/wiki/Internet_media_type">mime type</ulink> like "text/plain" or "image/png".
46 47 48
 * 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.
49
 **/
50 51 52 53 54 55

#ifdef G_OS_WIN32

#include <windows.h>

static char *
Matthias Clasen's avatar
Matthias Clasen committed
56
get_registry_classes_key (const char    *subdir,
Matthias Clasen's avatar
Matthias Clasen committed
57
                          const wchar_t *key_name)
58 59 60 61 62 63 64 65 66 67 68 69
{
  wchar_t *wc_key;
  HKEY reg_key = NULL;
  DWORD key_type;
  DWORD nbytes;
  char *value_utf8;

  value_utf8 = NULL;
  
  nbytes = 0;
  wc_key = g_utf8_to_utf16 (subdir, -1, NULL, NULL, NULL);
  if (RegOpenKeyExW (HKEY_CLASSES_ROOT, wc_key, 0,
Matthias Clasen's avatar
Matthias Clasen committed
70
                     KEY_QUERY_VALUE, &reg_key) == ERROR_SUCCESS &&
71
      RegQueryValueExW (reg_key, key_name, 0,
Matthias Clasen's avatar
Matthias Clasen committed
72
                        &key_type, NULL, &nbytes) == ERROR_SUCCESS &&
73
      (key_type == REG_SZ || key_type == REG_EXPAND_SZ))
74 75 76
    {
      wchar_t *wc_temp = g_new (wchar_t, (nbytes+1)/2 + 1);
      RegQueryValueExW (reg_key, key_name, 0,
Matthias Clasen's avatar
Matthias Clasen committed
77
                        &key_type, (LPBYTE) wc_temp, &nbytes);
78
      wc_temp[nbytes/2] = '\0';
79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94
      if (key_type == REG_EXPAND_SZ)
        {
          wchar_t dummy[1];
          int len = ExpandEnvironmentStringsW (wc_temp, dummy, 1);
          if (len > 0)
            {
              wchar_t *wc_temp_expanded = g_new (wchar_t, len);
              if (ExpandEnvironmentStringsW (wc_temp, wc_temp_expanded, len) == len)
                value_utf8 = g_utf16_to_utf8 (wc_temp_expanded, -1, NULL, NULL, NULL);
              g_free (wc_temp_expanded);
            }
        }
      else
        {
          value_utf8 = g_utf16_to_utf8 (wc_temp, -1, NULL, NULL, NULL);
        }
95
      g_free (wc_temp);
96
      
97 98 99 100 101 102 103 104 105 106
    }
  g_free (wc_key);
  
  if (reg_key != NULL)
    RegCloseKey (reg_key);

  return value_utf8;
}

gboolean
Matthias Clasen's avatar
Matthias Clasen committed
107 108
g_content_type_equals (const gchar *type1,
                       const gchar *type2)
109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131
{
  char *progid1, *progid2;
  gboolean res;
  
  g_return_val_if_fail (type1 != NULL, FALSE);
  g_return_val_if_fail (type2 != NULL, FALSE);

  if (g_ascii_strcasecmp (type1, type2) == 0)
    return TRUE;

  res = FALSE;
  progid1 = get_registry_classes_key (type1, NULL);
  progid2 = get_registry_classes_key (type2, NULL);
  if (progid1 != NULL && progid2 != NULL &&
      strcmp (progid1, progid2) == 0)
    res = TRUE;
  g_free (progid1);
  g_free (progid2);
  
  return res;
}

gboolean
Matthias Clasen's avatar
Matthias Clasen committed
132 133
g_content_type_is_a (const gchar *type,
                     const gchar *supertype)
134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153
{
  gboolean res;
  char *value_utf8;

  g_return_val_if_fail (type != NULL, FALSE);
  g_return_val_if_fail (supertype != NULL, FALSE);

  if (g_content_type_equals (type, supertype))
    return TRUE;

  res = FALSE;
  value_utf8 = get_registry_classes_key (type, L"PerceivedType");
  if (value_utf8 && strcmp (value_utf8, supertype) == 0)
    res = TRUE;
  g_free (value_utf8);
  
  return res;
}

gboolean
Matthias Clasen's avatar
Matthias Clasen committed
154
g_content_type_is_unknown (const gchar *type)
155 156 157 158 159 160
{
  g_return_val_if_fail (type != NULL, FALSE);

  return strcmp ("*", type) == 0;
}

Matthias Clasen's avatar
Matthias Clasen committed
161 162
gchar *
g_content_type_get_description (const gchar *type)
163 164 165 166 167 168 169 170 171 172 173 174 175
{
  char *progid;
  char *description;

  g_return_val_if_fail (type != NULL, NULL);

  progid = get_registry_classes_key (type, NULL);
  if (progid)
    {
      description = get_registry_classes_key (progid, NULL);
      g_free (progid);

      if (description)
Matthias Clasen's avatar
Matthias Clasen committed
176
        return description;
177 178 179 180 181 182 183
    }

  if (g_content_type_is_unknown (type))
    return g_strdup (_("Unknown type"));
  return g_strdup_printf (_("%s filetype"), type);
}

Matthias Clasen's avatar
Matthias Clasen committed
184 185
gchar *
g_content_type_get_mime_type (const gchar *type)
186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202
{
  char *mime;

  g_return_val_if_fail (type != NULL, NULL);

  mime = get_registry_classes_key (type, L"Content Type");
  if (mime)
    return mime;
  else if (g_content_type_is_unknown (type))
    return g_strdup ("application/octet-stream");
  else if (*type == '.')
    return g_strdup_printf ("application/x-ext-%s", type+1);
  /* TODO: Map "image" to "image/ *", etc? */

  return g_strdup ("application/octet-stream");
}

203 204 205
G_LOCK_DEFINE_STATIC (_type_icons);
static GHashTable *_type_icons = NULL;

206
GIcon *
Matthias Clasen's avatar
Matthias Clasen committed
207
g_content_type_get_icon (const gchar *type)
208
{
209 210 211
  GIcon *themed_icon;
  char *name = NULL;

212 213
  g_return_val_if_fail (type != NULL, NULL);

214
  /* In the Registry icons are the default value of
215 216 217 218 219
     HKEY_CLASSES_ROOT\<progid>\DefaultIcon with typical values like:
     <type>: <value>
     REG_EXPAND_SZ: %SystemRoot%\System32\Wscript.exe,3
     REG_SZ: shimgvw.dll,3
  */
220 221 222 223 224 225 226 227 228 229 230 231
  G_LOCK (_type_icons);
  if (!_type_icons)
    _type_icons = g_hash_table_new (g_str_hash, g_str_equal);
  name = g_hash_table_lookup (_type_icons, type);
  if (!name && type[0] == '.')
    {
      /* double lookup by extension */
      gchar *key = get_registry_classes_key (type, NULL);
      if (!key)
        key = g_strconcat (type+1, "file\\DefaultIcon", NULL);
      else
        {
Matthias Clasen's avatar
Matthias Clasen committed
232 233 234 235
          gchar *key2 = g_strconcat (key, "\\DefaultIcon", NULL);
          g_free (key);
          key = key2;
        }
236 237 238
      name = get_registry_classes_key (key, NULL);
      if (name && strcmp (name, "%1") == 0)
        {
Matthias Clasen's avatar
Matthias Clasen committed
239 240 241
          g_free (name);
          name = NULL;
        }
242 243 244 245 246 247 248 249 250 251 252 253 254 255
      if (name)
        g_hash_table_insert (_type_icons, g_strdup (type), g_strdup (name));
      g_free (key);
    }

  /* icon-name similar to how it was with gtk-2-12 */
  if (name)
    {
      themed_icon = g_themed_icon_new (name);
    }
  else
    {
      /* if not found an icon fall back to gtk-builtins */
      name = strcmp (type, "inode/directory") == 0 ? "gtk-directory" : 
Matthias Clasen's avatar
Matthias Clasen committed
256
                           g_content_type_can_be_executable (type) ? "gtk-execute" : "gtk-file";
257 258 259 260 261 262
      g_hash_table_insert (_type_icons, g_strdup (type), g_strdup (name));
      themed_icon = g_themed_icon_new_with_default_fallbacks (name);
    }
  G_UNLOCK (_type_icons);

  return G_ICON (themed_icon);
263 264 265
}

gboolean
Matthias Clasen's avatar
Matthias Clasen committed
266
g_content_type_can_be_executable (const gchar *type)
267 268 269 270 271 272 273
{
  g_return_val_if_fail (type != NULL, FALSE);

  if (strcmp (type, ".exe") == 0 ||
      strcmp (type, ".com") == 0 ||
      strcmp (type, ".bat") == 0)
    return TRUE;
Tor Lillqvist's avatar
Tor Lillqvist committed
274 275 276 277 278 279 280 281 282 283 284 285

  /* TODO: Also look at PATHEXT, which lists the extensions for
   * "scripts" in addition to those for true binary executables.
   *
   * (PATHEXT=.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH for me
   * right now, for instance). And in a sense, all associated file
   * types are "executable" on Windows... You can just type foo.jpg as
   * a command name in cmd.exe, and it will run the application
   * associated with .jpg. Hard to say what this API actually means
   * with "executable".
   */

286 287 288 289
  return FALSE;
}

static gboolean
Matthias Clasen's avatar
Matthias Clasen committed
290 291
looks_like_text (const guchar *data, 
                 gsize         data_size)
292 293 294 295 296 297
{
  gsize i;
  guchar c;
  for (i = 0; i < data_size; i++)
    {
      c = data[i];
298
      if (g_ascii_iscntrl (c) && !g_ascii_isspace (c) && c != '\b')
Matthias Clasen's avatar
Matthias Clasen committed
299
        return FALSE;
300 301 302 303
    }
  return TRUE;
}

Matthias Clasen's avatar
Matthias Clasen committed
304 305
gchar *
g_content_type_from_mime_type (const gchar *mime_type)
306 307 308 309 310 311 312 313 314 315 316 317
{
  char *key, *content_type;

  g_return_val_if_fail (mime_type != NULL, NULL);

  key = g_strconcat ("MIME\\DataBase\\Content Type\\", mime_type, NULL);
  content_type = get_registry_classes_key (key, L"Extension");
  g_free (key);

  return content_type;
}

Matthias Clasen's avatar
Matthias Clasen committed
318 319 320 321 322
gchar *
g_content_type_guess (const gchar  *filename,
                      const guchar *data,
                      gsize         data_size,
                      gboolean     *result_uncertain)
323 324 325 326 327 328 329
{
  char *basename;
  char *type;
  char *dot;

  type = NULL;

330 331 332
  if (result_uncertain)
    *result_uncertain = FALSE;

333 334 335 336 337
  if (filename)
    {
      basename = g_path_get_basename (filename);
      dot = strrchr (basename, '.');
      if (dot)
Matthias Clasen's avatar
Matthias Clasen committed
338
        type = g_strdup (dot);
339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363
      g_free (basename);
    }

  if (type)
    return type;

  if (data && looks_like_text (data, data_size))
    return g_strdup (".txt");

  return g_strdup ("*");
}

GList *
g_content_types_get_registered (void)
{
  DWORD index;
  wchar_t keyname[256];
  DWORD key_len;
  char *key_utf8;
  GList *types;

  types = NULL;
  index = 0;
  key_len = 256;
  while (RegEnumKeyExW(HKEY_CLASSES_ROOT,
Matthias Clasen's avatar
Matthias Clasen committed
364 365 366 367 368 369 370
                       index,
                       keyname,
                       &key_len,
                       NULL,
                       NULL,
                       NULL,
                       NULL) == ERROR_SUCCESS)
371 372 373
    {
      key_utf8 = g_utf16_to_utf8 (keyname, -1, NULL, NULL, NULL);
      if (key_utf8)
Matthias Clasen's avatar
Matthias Clasen committed
374 375 376 377 378 379
        {
          if (*key_utf8 == '.')
            types = g_list_prepend (types, key_utf8);
          else
            g_free (key_utf8);
        }
380 381 382 383 384 385 386
      index++;
      key_len = 256;
    }
  
  return g_list_reverse (types);
}

Matthias Clasen's avatar
Matthias Clasen committed
387
gchar **
388 389 390 391 392 393
g_content_type_guess_for_tree (GFile *root)
{
  /* FIXME: implement */
  return NULL;
}

394 395
#else /* !G_OS_WIN32 - Unix specific version */

396 397
#include <dirent.h>

398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415
#define XDG_PREFIX _gio_xdg
#include "xdgmime/xdgmime.h"

/* 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
416 417
gchar *
_g_unix_content_type_unalias (const gchar *type)
418
{
Matthias Clasen's avatar
Matthias Clasen committed
419 420
  gchar *res;

421 422 423
  G_LOCK (gio_xdgmime);
  res = g_strdup (xdg_mime_unalias_mime_type (type));
  G_UNLOCK (gio_xdgmime);
Matthias Clasen's avatar
Matthias Clasen committed
424

425 426 427
  return res;
}

Matthias Clasen's avatar
Matthias Clasen committed
428 429
gchar **
_g_unix_content_type_get_parents (const gchar *type)
430
{
Matthias Clasen's avatar
Matthias Clasen committed
431 432
  const gchar *umime;
  gchar **parents;
433 434 435 436
  GPtrArray *array;
  int i;

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

438
  G_LOCK (gio_xdgmime);
Matthias Clasen's avatar
Matthias Clasen committed
439

440
  umime = xdg_mime_unalias_mime_type (type);
Matthias Clasen's avatar
Matthias Clasen committed
441

442
  g_ptr_array_add (array, g_strdup (umime));
Matthias Clasen's avatar
Matthias Clasen committed
443

444
  parents = xdg_mime_list_mime_parents (umime);
445 446
  for (i = 0; parents && parents[i] != NULL; i++)
    g_ptr_array_add (array, g_strdup (parents[i]));
Matthias Clasen's avatar
Matthias Clasen committed
447

448
  free (parents);
Matthias Clasen's avatar
Matthias Clasen committed
449

450
  G_UNLOCK (gio_xdgmime);
Matthias Clasen's avatar
Matthias Clasen committed
451

452
  g_ptr_array_add (array, NULL);
Matthias Clasen's avatar
Matthias Clasen committed
453 454

  return (gchar **)g_ptr_array_free (array, FALSE);
455 456
}

Matthias Clasen's avatar
Matthias Clasen committed
457 458
/**
 * g_content_type_equals:
Matthias Clasen's avatar
Matthias Clasen committed
459 460
 * @type1: a content type string
 * @type2: a content type string
Matthias Clasen's avatar
Matthias Clasen committed
461 462 463 464
 *
 * Compares two content types for equality.
 *
 * Returns: %TRUE if the two strings are identical or equivalent,
Matthias Clasen's avatar
Matthias Clasen committed
465 466
 *     %FALSE otherwise.
 */
467
gboolean
Matthias Clasen's avatar
Matthias Clasen committed
468 469
g_content_type_equals (const gchar *type1,
                       const gchar *type2)
470 471
{
  gboolean res;
Matthias Clasen's avatar
Matthias Clasen committed
472

473 474
  g_return_val_if_fail (type1 != NULL, FALSE);
  g_return_val_if_fail (type2 != NULL, FALSE);
Matthias Clasen's avatar
Matthias Clasen committed
475

476 477 478
  G_LOCK (gio_xdgmime);
  res = xdg_mime_mime_type_equal (type1, type2);
  G_UNLOCK (gio_xdgmime);
Matthias Clasen's avatar
Matthias Clasen committed
479

480 481 482
  return res;
}

Matthias Clasen's avatar
Matthias Clasen committed
483 484
/**
 * g_content_type_is_a:
Matthias Clasen's avatar
Matthias Clasen committed
485 486
 * @type: a content type string
 * @supertype: a content type string
Matthias Clasen's avatar
Matthias Clasen committed
487
 *
Matthias Clasen's avatar
Matthias Clasen committed
488
 * Determines if @type is a subset of @supertype.
Matthias Clasen's avatar
Matthias Clasen committed
489 490
 *
 * Returns: %TRUE if @type is a kind of @supertype,
Matthias Clasen's avatar
Matthias Clasen committed
491 492
 *     %FALSE otherwise.
 */
493
gboolean
Matthias Clasen's avatar
Matthias Clasen committed
494 495
g_content_type_is_a (const gchar *type,
                     const gchar *supertype)
496 497
{
  gboolean res;
Matthias Clasen's avatar
Matthias Clasen committed
498

499 500
  g_return_val_if_fail (type != NULL, FALSE);
  g_return_val_if_fail (supertype != NULL, FALSE);
Matthias Clasen's avatar
Matthias Clasen committed
501

502 503 504
  G_LOCK (gio_xdgmime);
  res = xdg_mime_mime_type_subclass (type, supertype);
  G_UNLOCK (gio_xdgmime);
Matthias Clasen's avatar
Matthias Clasen committed
505

506 507 508
  return res;
}

Matthias Clasen's avatar
Matthias Clasen committed
509 510
/**
 * g_content_type_is_unknown:
Matthias Clasen's avatar
Matthias Clasen committed
511 512
 * @type: a content type string
 *
513
 * Checks if the content type is the generic "unknown" type.
Matthias Clasen's avatar
Matthias Clasen committed
514
 * On UNIX this is the "application/octet-stream" mimetype,
515
 * while on win32 it is "*".
Matthias Clasen's avatar
Matthias Clasen committed
516
 *
517
 * Returns: %TRUE if the type is the unknown type.
Matthias Clasen's avatar
Matthias Clasen committed
518
 */
519
gboolean
Matthias Clasen's avatar
Matthias Clasen committed
520
g_content_type_is_unknown (const gchar *type)
521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545
{
  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
546

547 548 549
  /* 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
550

551 552 553
  for (i = 0; lang_list[i]; i++)
    if (strcmp (lang_list[i], lang) == 0)
      return 1000-i;
Matthias Clasen's avatar
Matthias Clasen committed
554

555 556 557 558
  return 0;
}

static void
Matthias Clasen's avatar
Matthias Clasen committed
559
mime_info_start_element (GMarkupParseContext  *context,
Matthias Clasen's avatar
Matthias Clasen committed
560 561 562 563 564
                         const gchar          *element_name,
                         const gchar         **attribute_names,
                         const gchar         **attribute_values,
                         gpointer              user_data,
                         GError              **error)
565 566 567 568
{
  int i;
  const char *lang;
  MimeParser *parser = user_data;
Matthias Clasen's avatar
Matthias Clasen committed
569

570 571 572 573
  if (strcmp (element_name, "comment") == 0)
    {
      lang = "C";
      for (i = 0; attribute_names[i]; i++)
Matthias Clasen's avatar
Matthias Clasen committed
574 575 576 577 578 579
        if (strcmp (attribute_names[i], "xml:lang") == 0)
          {
            lang = attribute_values[i];
            break;
          }

580 581 582 583 584 585 586 587
      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
588
mime_info_end_element (GMarkupParseContext  *context,
Matthias Clasen's avatar
Matthias Clasen committed
589 590 591
                       const gchar          *element_name,
                       gpointer              user_data,
                       GError              **error)
592 593
{
  MimeParser *parser = user_data;
Matthias Clasen's avatar
Matthias Clasen committed
594

595 596 597 598
  parser->current_type = MIME_TAG_TYPE_OTHER;
}

static void
Matthias Clasen's avatar
Matthias Clasen committed
599
mime_info_text (GMarkupParseContext  *context,
Matthias Clasen's avatar
Matthias Clasen committed
600 601 602 603
                const gchar          *text,
                gsize                 text_len,
                gpointer              user_data,
                GError              **error)
604 605 606 607 608 609 610 611 612 613 614 615 616
{
  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
617
load_comment_for_mime_helper (const char *dir,
Matthias Clasen's avatar
Matthias Clasen committed
618
                              const char *basename)
619 620 621 622 623 624 625 626 627 628 629 630 631
{
  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
  };

  filename = g_build_filename (dir, "mime", basename, NULL);
Matthias Clasen's avatar
Matthias Clasen committed
632

633 634 635 636
  res = g_file_get_contents (filename,  &data,  &len,  NULL);
  g_free (filename);
  if (!res)
    return NULL;
Matthias Clasen's avatar
Matthias Clasen committed
637

638 639 640 641
  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
642

643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665
  if (!res)
    return NULL;

  return parse_data.comment;
}


static char *
load_comment_for_mime (const char *mimetype)
{
  const char * const* dirs;
  char *basename;
  char *comment;
  int i;

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

  comment = load_comment_for_mime_helper (g_get_user_data_dir (), basename);
  if (comment)
    {
      g_free (basename);
      return comment;
    }
Matthias Clasen's avatar
Matthias Clasen committed
666

667 668 669 670 671 672
  dirs = g_get_system_data_dirs ();

  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
673 674 675 676
        {
          g_free (basename);
          return comment;
        }
677 678
    }
  g_free (basename);
Matthias Clasen's avatar
Matthias Clasen committed
679

680 681 682
  return g_strdup_printf (_("%s type"), mimetype);
}

Matthias Clasen's avatar
Matthias Clasen committed
683 684
/**
 * g_content_type_get_description:
Matthias Clasen's avatar
Matthias Clasen committed
685 686
 * @type: a content type string
 *
Matthias Clasen's avatar
Matthias Clasen committed
687
 * Gets the human readable description of the content type.
Matthias Clasen's avatar
Matthias Clasen committed
688 689 690 691 692 693
 *
 * 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)
694 695
{
  static GHashTable *type_comment_cache = NULL;
Matthias Clasen's avatar
Matthias Clasen committed
696
  gchar *comment;
697 698

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

700
  G_LOCK (gio_xdgmime);
701 702
  type = xdg_mime_unalias_mime_type (type);

703 704 705 706 707 708
  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
709

710 711 712 713
  if (comment != NULL)
    return comment;

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

715 716
  G_LOCK (gio_xdgmime);
  g_hash_table_insert (type_comment_cache,
Matthias Clasen's avatar
Matthias Clasen committed
717 718
                       g_strdup (type),
                       g_strdup (comment));
719 720 721 722 723
  G_UNLOCK (gio_xdgmime);

  return comment;
}

Matthias Clasen's avatar
Matthias Clasen committed
724 725
/**
 * g_content_type_get_mime_type:
Matthias Clasen's avatar
Matthias Clasen committed
726 727 728 729 730 731 732
 * @type: a content type string
 *
 * Gets the mime type for the content type, if one is registered.
 *
 * Returns: (allow-none): the registered mime type for the given @type,
 *     or %NULL if unknown.
 */
733
char *
Matthias Clasen's avatar
Matthias Clasen committed
734
g_content_type_get_mime_type (const char *type)
735 736 737 738 739 740
{
  g_return_val_if_fail (type != NULL, NULL);

  return g_strdup (type);
}

Matthias Clasen's avatar
Matthias Clasen committed
741 742
/**
 * g_content_type_get_icon:
Matthias Clasen's avatar
Matthias Clasen committed
743 744
 * @type: a content type string
 *
Matthias Clasen's avatar
Matthias Clasen committed
745
 * Gets the icon for a content type.
Matthias Clasen's avatar
Matthias Clasen committed
746
 *
747
 * Returns: (transfer full): #GIcon corresponding to the content type. Free the returned
Matthias Clasen's avatar
Matthias Clasen committed
748 749
 *     object with g_object_unref()
 */
750
GIcon *
Matthias Clasen's avatar
Matthias Clasen committed
751
g_content_type_get_icon (const gchar *type)
752
{
Alexander Larsson's avatar
Alexander Larsson committed
753
  char *mimetype_icon, *generic_mimetype_icon, *q;
754
  char *xdg_mimetype_icon, *legacy_mimetype_icon;
755
  char *xdg_mimetype_generic_icon;
756
  char *icon_names[5];
757
  int n = 0;
Alexander Larsson's avatar
Alexander Larsson committed
758 759
  const char *p;
  GIcon *themed_icon;
Matthias Clasen's avatar
Matthias Clasen committed
760

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

763 764
  G_LOCK (gio_xdgmime);
  xdg_mimetype_icon = g_strdup (xdg_mime_get_icon (type));
765
  xdg_mimetype_generic_icon = g_strdup (xdg_mime_get_generic_icon (type));
766 767
  G_UNLOCK (gio_xdgmime);

768
  mimetype_icon = g_strdup (type);
Matthias Clasen's avatar
Matthias Clasen committed
769

Alexander Larsson's avatar
Alexander Larsson committed
770 771
  while ((q = strchr (mimetype_icon, '/')) != NULL)
    *q = '-';
Matthias Clasen's avatar
Matthias Clasen committed
772

773 774 775
  p = strchr (type, '/');
  if (p == NULL)
    p = type + strlen (type);
776 777 778

  /* Not all icons have migrated to the new icon theme spec, look for old names too */
  legacy_mimetype_icon = g_strconcat ("gnome-mime-", mimetype_icon, NULL);
Matthias Clasen's avatar
Matthias Clasen committed
779

780 781 782 783
  generic_mimetype_icon = g_malloc (p - type + strlen ("-x-generic") + 1);
  memcpy (generic_mimetype_icon, type, p - type);
  memcpy (generic_mimetype_icon + (p - type), "-x-generic", strlen ("-x-generic"));
  generic_mimetype_icon[(p - type) + strlen ("-x-generic")] = 0;
Matthias Clasen's avatar
Matthias Clasen committed
784

785 786 787 788 789
  if (xdg_mimetype_icon)
    icon_names[n++] = xdg_mimetype_icon;

  icon_names[n++] = mimetype_icon;
  icon_names[n++] = legacy_mimetype_icon;
790 791 792 793

  if (xdg_mimetype_generic_icon)
    icon_names[n++] = xdg_mimetype_generic_icon;

794
  icon_names[n++] = generic_mimetype_icon;
Matthias Clasen's avatar
Matthias Clasen committed
795

796
  themed_icon = g_themed_icon_new_from_names (icon_names, n);
Matthias Clasen's avatar
Matthias Clasen committed
797

798
  g_free (xdg_mimetype_icon);
799
  g_free (xdg_mimetype_generic_icon);
800
  g_free (mimetype_icon);
801
  g_free (legacy_mimetype_icon);
802
  g_free (generic_mimetype_icon);
Matthias Clasen's avatar
Matthias Clasen committed
803

Alexander Larsson's avatar
Alexander Larsson committed
804
  return themed_icon;
805 806 807 808
}

/**
 * g_content_type_can_be_executable:
Matthias Clasen's avatar
Matthias Clasen committed
809 810
 * @type: a content type string
 *
Matthias Clasen's avatar
Matthias Clasen committed
811 812
 * 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
813
 *
Matthias Clasen's avatar
Matthias Clasen committed
814
 * Returns: %TRUE if the file type corresponds to a type that
Matthias Clasen's avatar
Matthias Clasen committed
815 816
 *     can be executable, %FALSE otherwise.
 */
817
gboolean
Matthias Clasen's avatar
Matthias Clasen committed
818
g_content_type_can_be_executable (const gchar *type)
819 820 821 822 823 824 825 826 827 828 829 830 831 832
{
  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;
833
  char c;
Matthias Clasen's avatar
Matthias Clasen committed
834

835 836
  for (i = 0; i < data_size; i++)
    {
837
      c = data[i];
Matthias Clasen's avatar
Matthias Clasen committed
838

839
      if (g_ascii_iscntrl (c) &&
Matthias Clasen's avatar
Matthias Clasen committed
840 841 842
          !g_ascii_isspace (c) &&
          c != '\b')
        return FALSE;
843 844 845 846
    }
  return TRUE;
}

847 848
/**
 * g_content_type_from_mime_type:
Matthias Clasen's avatar
Matthias Clasen committed
849
 * @mime_type: a mime type string
850 851 852
 *
 * Tries to find a content type based on the mime type name.
 *
Matthias Clasen's avatar
Matthias Clasen committed
853 854
 * Returns: (allow-none): Newly allocated string with content type
 *     or %NULL. Free with g_free()
855 856 857
 *
 * Since: 2.18
 **/
Matthias Clasen's avatar
Matthias Clasen committed
858 859
gchar *
g_content_type_from_mime_type (const gchar *mime_type)
860
{
861 862
  char *umime;

863 864
  g_return_val_if_fail (mime_type != NULL, NULL);

865
  G_LOCK (gio_xdgmime);
866
  /* mime type and content type are same on unixes */
867
  umime = g_strdup (xdg_mime_unalias_mime_type (mime_type));
868
  G_UNLOCK (gio_xdgmime);
869 870

  return umime;
871 872
}

Matthias Clasen's avatar
Matthias Clasen committed
873 874
/**
 * g_content_type_guess:
Matthias Clasen's avatar
Matthias Clasen committed
875 876
 * @filename: (allow-none): a string, or %NULL
 * @data: (allow-none) (array length=data_size): a stream of data, or %NULL
877
 * @data_size: the size of @data
Matthias Clasen's avatar
Matthias Clasen committed
878 879 880 881
 * @result_uncertain: (allow-none) (out): return location for the certainty
 *     of the result, or %NULL
 *
 * Guesses the content type based on example data. If the function is
882 883 884
 * 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
885 886 887 888 889 890 891 892 893
 *
 * 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)
894 895 896 897 898 899 900 901 902 903 904 905 906 907
{
  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
908

909
  G_LOCK (gio_xdgmime);
Matthias Clasen's avatar
Matthias Clasen committed
910

911 912
  if (filename)
    {
913
      i = strlen (filename);
914 915 916 917 918 919 920 921 922 923 924 925 926 927
      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);
        }
928 929 930 931 932 933 934 935
    }

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

937 938 939 940
  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
941 942 943
          data &&
          looks_like_text (data, data_size))
        sniffed_mimetype = "text/plain";
944 945 946 947 948 949 950 951 952 953

      /* 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";
954
    }
Matthias Clasen's avatar
Matthias Clasen committed
955

956 957 958
  if (n_name_mimetypes == 0)
    {
      if (sniffed_mimetype == XDG_MIME_TYPE_UNKNOWN &&
Matthias Clasen's avatar
Matthias Clasen committed
959 960 961
          result_uncertain)
        *result_uncertain = TRUE;

962 963 964 965 966 967
      mimetype = g_strdup (sniffed_mimetype);
    }
  else
    {
      mimetype = NULL;
      if (sniffed_mimetype != XDG_MIME_TYPE_UNKNOWN)
Matthias Clasen's avatar
Matthias Clasen committed
968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989
        {
          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;
                    }
                }
            }
        }

990
      if (mimetype == NULL)
Matthias Clasen's avatar
Matthias Clasen committed
991 992 993 994 995 996 997 998
        {
          /* 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;
        }
999
    }
Matthias Clasen's avatar
Matthias Clasen committed
1000

1001 1002 1003 1004 1005 1006
  G_UNLOCK (gio_xdgmime);

  return mimetype;
}

static void
Matthias Clasen's avatar
Matthias Clasen committed
1007 1008
enumerate_mimetypes_subdir (const char *dir,
                            const char *prefix,
Matthias Clasen's avatar
Matthias Clasen committed
1009
                            GHashTable *mimetypes)
1010 1011 1012 1013 1014 1015 1016 1017 1018
{
  DIR *d;
  struct dirent *ent;
  char *mimetype;

  d = opendir (dir);
  if (d)
    {
      while ((ent = readdir (d)) != NULL)
Matthias Clasen's avatar
Matthias Clasen committed
1019 1020 1021 1022 1023 1024 1025
        {
          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);
            }
        }
1026 1027 1028 1029 1030
      closedir (d);
    }
}

static void
Matthias Clasen's avatar
Matthias Clasen committed
1031
enumerate_mimetypes_dir (const char *dir,
Matthias Clasen's avatar
Matthias Clasen committed
1032
                         GHashTable *mimetypes)
1033 1034 1035 1036 1037 1038 1039
{
  DIR *d;
  struct dirent *ent;
  char *mimedir;
  char *name;

  mimedir = g_build_filename (dir, "mime", NULL);
Matthias Clasen's avatar
Matthias Clasen committed
1040

1041 1042 1043 1044
  d = opendir (mimedir);
  if (d)
    {
      while ((ent = readdir (d)) != NULL)
Matthias Clasen's avatar
Matthias Clasen committed
1045 1046 1047 1048 1049 1050 1051 1052 1053
        {
          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);
            }
        }
1054 1055
      closedir (d);
    }
Matthias Clasen's avatar
Matthias Clasen committed
1056

1057 1058 1059
  g_free (mimedir);
}

Matthias Clasen's avatar
Matthias Clasen committed
1060 1061
/**
 * g_content_types_get_registered:
Matthias Clasen's avatar
Matthias Clasen committed
1062
 *
1063
 * Gets a list of strings containing all the registered content types
Matthias Clasen's avatar
Matthias Clasen committed
1064 1065
 * known to the system. The list and its data should be freed using
 * <programlisting>
1066
 * g_list_free_full (list, g_free);
Matthias Clasen's avatar
Matthias Clasen committed
1067 1068
 * </programlisting>
 *
1069
 * Returns: (element-type utf8) (transfer full): #GList of the registered content types
Matthias Clasen's avatar
Matthias Clasen committed
1070
 */
1071 1072 1073 1074 1075
GList *
g_content_types_get_registered (void)
{
  const char * const* dirs;
  GHashTable *mimetypes;
Matthias Clasen's avatar
Matthias Clasen committed
1076 1077
  GHashTableIter iter;
  gpointer key;
1078 1079 1080
  int i;
  GList *l;

1081
  mimetypes = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
1082 1083 1084 1085 1086 1087 1088 1089

  enumerate_mimetypes_dir (g_get_user_data_dir (), mimetypes);
  dirs = g_get_system_data_dirs ();

  for (i = 0; dirs[i] != NULL; i++)
    enumerate_mimetypes_dir (dirs[i], mimetypes);

  l = NULL;
Matthias Clasen's avatar
Matthias Clasen committed
1090 1091
  g_hash_table_iter_init (&iter, mimetypes);
  while (g_hash_table_iter_next (&iter, &key, NULL))
1092 1093 1094 1095
    {
      l = g_list_prepend (l, key);
      g_hash_table_iter_steal (&iter);
    }
Matthias Clasen's avatar
Matthias Clasen committed
1096

1097 1098 1099 1100 1101
  g_hash_table_destroy (mimetypes);

  return l;
}

1102 1103 1104 1105 1106 1107 1108

/* 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
1109
typedef struct
1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131
{
  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)
{
1132
  g_list_free_full (matchlet->matches, (GDestroyNotify) tree_matchlet_free);
1133 1134 1135 1136 1137 1138 1139 1140
  g_free (matchlet->path);
  g_free (matchlet->mimetype);
  g_slice_free (TreeMatchlet, matchlet);
}

static void
tree_match_free (TreeMatch *match)
{
1141
  g_list_free_full (match->matches, (GDestroyNotify) tree_matchlet_free);
1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156
  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
1157

1158 1159
  line[len - 1] = 0;
  s = strchr (line, ':');
Matthias Clasen's avatar
Matthias Clasen committed
1160

1161 1162 1163 1164 1165 1166 1167 1168
  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
1169 1170
parse_match_line (gchar *line,
                  gint  *depth)
1171 1172 1173 1174 1175 1176 1177 1178
{
  gchar *s, *p;
  TreeMatchlet *matchlet;
  gchar **parts;
  gint i;

  matchlet = g_slice_new0 (TreeMatchlet);

Matthias Clasen's avatar
Matthias Clasen committed
1179
  if (line[0] == '>')
1180 1181 1182 1183
    {
      *depth = 0;
      s = line;
    }
Matthias Clasen's avatar
Matthias Clasen committed
1184
  else
1185 1186 1187 1188
    {
      *depth = atoi (line);
      s = strchr (line, '>');
    }
Matthias Clasen's avatar
Matthias Clasen committed
1189
  s += 2;
1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213
  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
1214
      else
1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238
        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
1239 1240
insert_matchlet (TreeMatch    *match,
                 TreeMatchlet *matchlet,
1241 1242
                 gint          depth)
{
Matthias Clasen's avatar
Matthias Clasen committed
1243
  if (depth == 0)
1244
    match->matches = g_list_append (match->matches, matchlet);
Matthias Clasen's avatar
Matthias Clasen committed
1245
  else
1246 1247 1248 1249 1250
    {
      GList *last;
      TreeMatchlet *m;

      last = g_list_last (match->matches);
Matthias Clasen's avatar
Matthias Clasen committed
1251
      if (!last)
1252 1253 1254 1255 1256 1257 1258
        {
          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
1259
      while (--depth > 0)
1260 1261
        {
          last = g_list_last (m->matches);
Matthias Clasen's avatar
Matthias Clasen committed
1262
          if (!last)
1263 1264 1265 1266 1267
            {
              tree_matchlet_free (matchlet);
              g_warning ("can't insert tree matchlet at depth %d", depth);
              return;
            }
Matthias Clasen's avatar
Matthias Clasen committed
1268

1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288
          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;

  filename = g_build_filename (prefix, "mime", "treemagic", NULL);

Matthias Clasen's avatar
Matthias Clasen committed
1289
  if (g_file_get_contents (filename, &text, &len, NULL))
1290
    {
Matthias Clasen's avatar
Matthias Clasen committed
1291
      if (strcmp (text, "MIME-TreeMagic") == 0)
1292 1293 1294
        {
          lines = g_strsplit (text + strlen ("MIME-TreeMagic") + 2, "\n", 0);
          match = NULL;
Matthias Clasen's avatar
Matthias Clasen committed
1295
          for (i = 0; lines[i] && lines[i][0]; i++)
1296
            {
Matthias Clasen's avatar
Matthias Clasen committed
1297
              if (lines[i][0] == '[')
1298 1299 1300 1301
                {
                  match = parse_header (lines[i]);
                  insert_match (match);
                }
Matthias Clasen's avatar
Matthias Clasen committed
1302
              else
1303 1304 1305 1306 1307
                {
                  matchlet = parse_match_line (lines[i], &depth);
                  insert_matchlet (match, matchlet, depth);
                }
            }
Matthias Clasen's avatar
Matthias Clasen committed
1308

1309 1310
          g_strfreev (lines);
        }
Matthias Clasen's avatar
Matthias Clasen committed
1311
      else
1312 1313 1314 1315
        g_warning ("%s: header not found, skipping\n", filename);

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

1317 1318 1319 1320 1321 1322 1323 1324 1325 1326
  g_free (filename);
}


static void
xdg_mime_reload (void *user_data)
{
  need_reload = TRUE;
}

Matthias Clasen's avatar
Matthias Clasen committed
1327
static void
1328 1329
tree_magic_shutdown (void)
{
1330
  g_list_free_full (tree_matches, (GDestroyNotify) tree_match_free);
1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341
  tree_matches = NULL;
}

static void
tree_magic_init (void)
{
  static gboolean initialized = FALSE;
  const gchar *dir;
  const gchar * const * dirs;
  int i;

Matthias Clasen's avatar
Matthias Clasen committed
1342
  if (!initialized)
1343 1344 1345 1346 1347 1348 1349
    {
      initialized = TRUE;

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

Matthias Clasen's avatar
Matthias Clasen committed
1350
  if (need_reload)
1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365
    {
      need_reload = FALSE;

      tree_magic_shutdown ();

      dir = g_get_user_data_dir ();
      read_tree_magic_from_directory (dir);
      dirs = g_get_system_data_dirs ();
      for (i = 0; dirs[i]; i++)
        read_tree_magic_from_directory (dirs[i]);
    }
}

/* a filtering enumerator */

Matthias Clasen's avatar
Matthias Clasen committed
1366
typedef struct
1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377
{
  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
1378 1379
component_match (Enumerator  *e,
                 gint         depth,
1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402
                 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
1403
next_match_recurse (Enumerator *e,
1404 1405 1406 1407 1408 1409
                    gint        depth)
{
  GFile *file;
  GFileInfo *info;
  const gchar *name;

Matthias Clasen's avatar
Matthias Clasen committed
1410
  while (TRUE)
1411
    {
Matthias Clasen's avatar
Matthias Clasen committed
1412
      if (e->enumerators[depth] == NULL)
1413
        {
Matthias Clasen's avatar
Matthias Clasen committed
1414
          if (depth > 0)
1415 1416
            {
              file = next_match_recurse (e, depth - 1);
Matthias Clasen's avatar
Matthias Clasen committed
1417
              if (file)
1418 1419 1420 1421 1422
                {
                  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
1423 1424
                                                                     NULL,
                                                                     NULL);
1425 1426 1427 1428 1429 1430
                }
            }
          if (e->enumerators[depth] == NULL)
            return NULL;
        }

Matthias Clasen's avatar
Matthias Clasen committed
1431
      while ((info = g_file_enumerator_next_file (e->enumerators[depth], NULL, NULL)))
1432 1433
        {
          name = g_file_info_get_name (info);
Matthias Clasen's avatar
Matthias Clasen committed
1434
          if (component_match (e, depth, name))
1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457
            {
              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
1458
                const char *path,
1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470
                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
1471
  if (e->ignore_case)
1472 1473
    {
      e->case_components = g_new0 (char *, e->depth + 1);
Matthias Clasen's avatar
Matthias Clasen committed
1474
      for (i = 0; e->components[i]; i++)
1475 1476 1477 1478
        {
          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
1479
        }
1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498
    }

  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
1499 1500 1501
  for (i = 0; i < e->depth; i++)
    {
      if (e->enumerators[i])
1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527
        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
1528 1529

  do
1530 1531
    {
      file = enumerator_next (e);
Matthias Clasen's avatar
Matthias Clasen committed
1532
      if (!file)
1533
        {
Matthias Clasen's avatar
Matthias Clasen committed
1534
          enumerator_free (e);
1535 1536 1537 1538 1539 1540 1541 1542 1543 1544
          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
1545
      info = g_file_query_info (file,
1546 1547 1548 1549
                                attrs,
                                G_FILE_QUERY_INFO_NONE,
                                NULL,
                                NULL);
Matthias Clasen's avatar
Matthias Clasen committed
1550
      if (info)
1551 1552 1553 1554
        {
          result = TRUE;

          if (matchlet->type != G_FILE_TYPE_UNKNOWN &&
Matthias Clasen's avatar
Matthias Clasen committed
1555
              g_file_info_get_file_type (info) != matchlet->type)
1556 1557 1558 1559 1560
            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
1561 1562
        }
      else
1563 1564
        result = FALSE;

Matthias Clasen's avatar
Matthias Clasen committed
1565
      if (result && matchlet->non_empty)
1566 1567 1568 1569
        {
          GFileEnumerator *child_enum;
          GFileInfo *child_info;

Matthias Clasen's avatar
Matthias Clasen committed
1570
          child_enum = g_file_enumerate_children (file,
1571 1572 1573 1574
                                                  G_FILE_ATTRIBUTE_STANDARD_NAME,
                                                  G_FILE_QUERY_INFO_NONE,
                                                  NULL,
                                                  NULL);
Matthias Clasen's avatar
Matthias Clasen committed
1575 1576

          if (child_enum)
1577 1578 1579 1580
            {
              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
1581 1582
              else
                result = FALSE;
1583 1584
              g_object_unref (child_enum);
            }
Matthias Clasen's avatar
Matthias Clasen committed
1585
          else
1586 1587
            result = FALSE;
        }
Matthias Clasen's avatar
Matthias Clasen committed
1588 1589

      if (result && matchlet->mimetype)
1590
        {
Matthias Clasen's avatar
Matthias Clasen committed
1591
          if (strcmp (matchlet->mimetype, g_file_info_get_content_type (info)) != 0)
1592 1593
            result = FALSE;
        }
Matthias Clasen's avatar
Matthias Clasen committed
1594

1595 1596 1597 1598 1599 1600
      g_object_unref (info);
      g_object_unref (file);
    }
  while (!result);

  enumerator_free (e);
Matthias Clasen's avatar
Matthias Clasen committed
1601 1602

  if (!matchlet->matches)
1603 1604
    return TRUE;

Matthias Clasen's avatar
Matthias Clasen committed
1605
  for (l = matchlet->matches; l; l = l->next)
1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622
    {
      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
1623 1624

  for (l = match->matches; l; l = l->next)
1625 1626
    {
      TreeMatchlet *matchlet = l->data;
Matthias Clasen's avatar
Matthias Clasen committed
1627
      if (matchlet_match (matchlet, root))
1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643
        {
          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
1644
 * x-content/audio-cdda (for audio CDs) or x-content/image-dcf
1645 1646 1647
 * (for a camera memory card). See the <ulink url="http://www.freedesktop.org/wiki/Specifications/shared-mime-info-spec">shared-mime-info</ulink>
 * specification for more on x-content types.
 *