updateiconcache.c 38.7 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14
/* updateiconcache.c
 * Copyright (C) 2004  Anders Carlsson <andersca@gnome.org>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library 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
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public
Javier Jardón's avatar
Javier Jardón committed
15
 * License along with this library. If not, see <http://www.gnu.org/licenses/>.
16 17
 */

18
#include "config.h"
Manish Singh's avatar
Manish Singh committed
19

Matthias Clasen's avatar
Matthias Clasen committed
20
#include <locale.h>
21 22 23 24 25
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
26
#include <fcntl.h>
Ivan, Wong Yat Cheung's avatar
Ivan, Wong Yat Cheung committed
27
#ifdef HAVE_UNISTD_H
28
#include <unistd.h>
Ivan, Wong Yat Cheung's avatar
Ivan, Wong Yat Cheung committed
29
#endif
30
#include <errno.h>
Ivan, Wong Yat Cheung's avatar
Ivan, Wong Yat Cheung committed
31
#ifdef _MSC_VER
32
#include <io.h>
Ivan, Wong Yat Cheung's avatar
Ivan, Wong Yat Cheung committed
33 34
#include <sys/utime.h>
#else
35
#include <utime.h>
Ivan, Wong Yat Cheung's avatar
Ivan, Wong Yat Cheung committed
36
#endif
37 38

#include <glib.h>
39
#include <glib/gstdio.h>
Anders Carlsson's avatar
Anders Carlsson committed
40
#include <gdk-pixbuf/gdk-pixdata.h>
41
#include <glib/gi18n.h>
42
#include "gtkiconcachevalidator.h"
43

Matthias Clasen's avatar
Matthias Clasen committed
44
static gboolean force_update = FALSE;
45
static gboolean ignore_theme_index = FALSE;
Matthias Clasen's avatar
Matthias Clasen committed
46
static gboolean quiet = FALSE;
47
static gboolean index_only = TRUE;
48
static gboolean validate = FALSE;
49
static gchar *var_name = (gchar *) "-";
Matthias Clasen's avatar
Matthias Clasen committed
50

51 52 53 54 55
/* Quite ugly - if we just add the c file to the
 * list of sources in Makefile.am, libtool complains.
 */
#include "gtkiconcachevalidator.c"

56 57 58 59 60 61 62 63 64 65 66 67 68 69
#define CACHE_NAME "icon-theme.cache"

#define HAS_SUFFIX_XPM (1 << 0)
#define HAS_SUFFIX_SVG (1 << 1)
#define HAS_SUFFIX_PNG (1 << 2)
#define HAS_ICON_FILE  (1 << 3)

#define MAJOR_VERSION 1
#define MINOR_VERSION 0
#define HASH_OFFSET 12

#define ALIGN_VALUE(this, boundary) \
  (( ((unsigned long)(this)) + (((unsigned long)(boundary)) -1)) & (~(((unsigned long)(boundary))-1)))

70 71 72 73
#ifdef HAVE_FTW_H

#include <ftw.h>

74
static GStatBuf cache_dir_stat;
75 76
static gboolean cache_up_to_date;

Matthias Clasen's avatar
Matthias Clasen committed
77
static int check_dir_mtime (const char        *dir,
78
                            const GStatBuf    *sb,
79 80
                            int                tf)
{
81
  if (tf != FTW_NS && sb->st_mtime > cache_dir_stat.st_mtime)
82 83 84 85 86 87 88 89 90
    {
      cache_up_to_date = FALSE;
      /* stop tree walk */
      return 1;
    }

  return 0;
}

91 92 93
static gboolean
is_cache_up_to_date (const gchar *path)
{
94 95 96 97
  gchar *cache_path;
  gint retval;

  cache_path = g_build_filename (path, CACHE_NAME, NULL);
98
  retval = g_stat (cache_path, &cache_dir_stat);
99
  g_free (cache_path);
Matthias Clasen's avatar
Matthias Clasen committed
100

101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116
  if (retval < 0)
    {
      /* Cache file not found */
      return FALSE;
    }

  cache_up_to_date = TRUE;

  ftw (path, check_dir_mtime, 20);

  return cache_up_to_date;
}

#else  /* !HAVE_FTW_H */

gboolean
117 118
is_cache_up_to_date (const gchar *path)
{
119
  GStatBuf path_stat, cache_stat;
120
  gchar *cache_path;
Matthias Clasen's avatar
Matthias Clasen committed
121 122
  int retval;

123
  retval = g_stat (path, &path_stat);
124

Matthias Clasen's avatar
Matthias Clasen committed
125
  if (retval < 0)
126 127 128 129 130 131 132
    {
      /* We can't stat the path,
       * assume we have a updated cache */
      return TRUE;
    }

  cache_path = g_build_filename (path, CACHE_NAME, NULL);
133
  retval = g_stat (cache_path, &cache_stat);
134
  g_free (cache_path);
Matthias Clasen's avatar
Matthias Clasen committed
135

136
  if (retval < 0)
137 138 139 140 141 142
    {
      /* Cache file not found */
      return FALSE;
    }

  /* Check mtime */
143
  return cache_stat.st_mtime >= path_stat.st_mtime;
144 145
}

146 147
#endif  /* !HAVE_FTW_H */

148
static gboolean
149 150 151 152 153 154 155 156
has_theme_index (const gchar *path)
{
  gboolean result;
  gchar *index_path;

  index_path = g_build_filename (path, "index.theme", NULL);

  result = g_file_test (index_path, G_FILE_TEST_IS_REGULAR);
Matthias Clasen's avatar
Matthias Clasen committed
157

158 159 160 161 162 163
  g_free (index_path);

  return result;
}


Matthias Clasen's avatar
Matthias Clasen committed
164
typedef struct
165 166
{
  GdkPixdata pixdata;
167
  gboolean has_pixdata;
168
  guint32 offset;
169
  guint size;
170 171
} ImageData;

Matthias Clasen's avatar
Matthias Clasen committed
172
typedef struct
173 174 175
{
  int has_embedded_rect;
  int x0, y0, x1, y1;
Matthias Clasen's avatar
Matthias Clasen committed
176

177 178
  int n_attach_points;
  int *attach_points;
Matthias Clasen's avatar
Matthias Clasen committed
179

180 181 182 183 184 185 186
  int n_display_names;
  char **display_names;

  guint32 offset;
  gint size;
} IconData;

187
static GHashTable *image_data_hash = NULL;
188
static GHashTable *icon_data_hash = NULL;
189

190 191 192 193
typedef struct
{
  int flags;
  int dir_index;
Anders Carlsson's avatar
Anders Carlsson committed
194

195 196
  ImageData *image_data;
  guint pixel_data_size;
Anders Carlsson's avatar
Anders Carlsson committed
197

198 199
  IconData *icon_data;
  guint icon_data_size;
200 201
} Image;

202

203 204 205
static gboolean
foreach_remove_func (gpointer key, gpointer value, gpointer user_data)
{
206
  Image *image = (Image *)value;
207 208
  GHashTable *files = user_data;
  GList *list;
Matthias Clasen's avatar
Matthias Clasen committed
209
  gboolean free_key = FALSE;
210 211 212

  if (image->flags == HAS_ICON_FILE)
    {
213
      /* just a .icon file, throw away */
214
      g_free (key);
215
      g_free (image);
216 217 218 219

      return TRUE;
    }

220 221 222
  list = g_hash_table_lookup (files, key);
  if (list)
    free_key = TRUE;
Matthias Clasen's avatar
Matthias Clasen committed
223

224 225
  list = g_list_prepend (list, value);
  g_hash_table_insert (files, key, list);
Matthias Clasen's avatar
Matthias Clasen committed
226

227 228
  if (free_key)
    g_free (key);
Matthias Clasen's avatar
Matthias Clasen committed
229

230 231 232
  return TRUE;
}

233 234
static IconData *
load_icon_data (const char *path)
Anders Carlsson's avatar
Anders Carlsson committed
235 236 237 238 239 240 241 242 243 244 245
{
  GKeyFile *icon_file;
  char **split;
  gsize length;
  char *str;
  char *split_point;
  int i;
  gint *ivalues;
  GError *error = NULL;
  gchar **keys;
  gsize n_keys;
246
  IconData *data;
Matthias Clasen's avatar
Matthias Clasen committed
247

Anders Carlsson's avatar
Anders Carlsson committed
248 249 250 251 252 253
  icon_file = g_key_file_new ();
  g_key_file_set_list_separator (icon_file, ',');
  g_key_file_load_from_file (icon_file, path, G_KEY_FILE_KEEP_TRANSLATIONS, &error);
  if (error)
    {
      g_error_free (error);
254 255 256
      g_key_file_free (icon_file);

      return NULL;
Anders Carlsson's avatar
Anders Carlsson committed
257 258
    }

259 260
  data = g_new0 (IconData, 1);

Matthias Clasen's avatar
Matthias Clasen committed
261
  ivalues = g_key_file_get_integer_list (icon_file,
Anders Carlsson's avatar
Anders Carlsson committed
262 263 264 265 266 267
					 "Icon Data", "EmbeddedTextRectangle",
					 &length, NULL);
  if (ivalues)
    {
      if (length == 4)
	{
268 269 270 271 272
	  data->has_embedded_rect = TRUE;
	  data->x0 = ivalues[0];
	  data->y0 = ivalues[1];
	  data->x1 = ivalues[2];
	  data->y1 = ivalues[3];
Anders Carlsson's avatar
Anders Carlsson committed
273
	}
Matthias Clasen's avatar
Matthias Clasen committed
274

Anders Carlsson's avatar
Anders Carlsson committed
275 276
      g_free (ivalues);
    }
Matthias Clasen's avatar
Matthias Clasen committed
277

Anders Carlsson's avatar
Anders Carlsson committed
278 279 280 281
  str = g_key_file_get_string (icon_file, "Icon Data", "AttachPoints", NULL);
  if (str)
    {
      split = g_strsplit (str, "|", -1);
Matthias Clasen's avatar
Matthias Clasen committed
282

283 284
      data->n_attach_points = g_strv_length (split);
      data->attach_points = g_new (int, 2 * data->n_attach_points);
Anders Carlsson's avatar
Anders Carlsson committed
285 286

      i = 0;
287
      while (split[i] != NULL && i < data->n_attach_points)
Anders Carlsson's avatar
Anders Carlsson committed
288 289 290 291 292 293
	{
	  split_point = strchr (split[i], ',');
	  if (split_point)
	    {
	      *split_point = 0;
	      split_point++;
294 295
	      data->attach_points[2 * i] = atoi (split[i]);
	      data->attach_points[2 * i + 1] = atoi (split_point);
Anders Carlsson's avatar
Anders Carlsson committed
296 297 298
	    }
	  i++;
	}
Matthias Clasen's avatar
Matthias Clasen committed
299

Anders Carlsson's avatar
Anders Carlsson committed
300 301 302
      g_strfreev (split);
      g_free (str);
    }
Matthias Clasen's avatar
Matthias Clasen committed
303

Anders Carlsson's avatar
Anders Carlsson committed
304
  keys = g_key_file_get_keys (icon_file, "Icon Data", &n_keys, &error);
Matthias Clasen's avatar
Matthias Clasen committed
305
  data->display_names = g_new0 (gchar *, 2 * n_keys + 1);
306
  data->n_display_names = 0;
Matthias Clasen's avatar
Matthias Clasen committed
307

Anders Carlsson's avatar
Anders Carlsson committed
308 309 310
  for (i = 0; i < n_keys; i++)
    {
      gchar *lang, *name;
Matthias Clasen's avatar
Matthias Clasen committed
311

Anders Carlsson's avatar
Anders Carlsson committed
312 313 314
      if (g_str_has_prefix (keys[i], "DisplayName"))
	{
	  gchar *open, *close = NULL;
Matthias Clasen's avatar
Matthias Clasen committed
315

Anders Carlsson's avatar
Anders Carlsson committed
316 317 318 319 320 321 322 323
	  open = strchr (keys[i], '[');

	  if (open)
	    close = strchr (open, ']');

	  if (open && close)
	    {
	      lang = g_strndup (open + 1, close - open - 1);
Matthias Clasen's avatar
Matthias Clasen committed
324
	      name = g_key_file_get_locale_string (icon_file,
Anders Carlsson's avatar
Anders Carlsson committed
325 326 327 328 329 330
						   "Icon Data", "DisplayName",
						   lang, NULL);
	    }
	  else
	    {
	      lang = g_strdup ("C");
Matthias Clasen's avatar
Matthias Clasen committed
331
	      name = g_key_file_get_string (icon_file,
Anders Carlsson's avatar
Anders Carlsson committed
332 333 334
					    "Icon Data", "DisplayName",
					    NULL);
	    }
Matthias Clasen's avatar
Matthias Clasen committed
335

336 337 338
	  data->display_names[2 * data->n_display_names] = lang;
	  data->display_names[2 * data->n_display_names + 1] = name;
	  data->n_display_names++;
Anders Carlsson's avatar
Anders Carlsson committed
339 340 341 342
	}
    }

  g_strfreev (keys);
Matthias Clasen's avatar
Matthias Clasen committed
343

Anders Carlsson's avatar
Anders Carlsson committed
344
  g_key_file_free (icon_file);
345 346

  /* -1 means not computed yet, the real value depends
Matthias Clasen's avatar
Matthias Clasen committed
347 348
   * on string pool state, and will be computed
   * later
349 350 351 352
   */
  data->size = -1;

  return data;
Anders Carlsson's avatar
Anders Carlsson committed
353 354
}

355 356 357 358
/*
 * This function was copied from gtkfilesystemunix.c, it should
 * probably go to GLib
 */
Anders Carlsson's avatar
Anders Carlsson committed
359
static void
360
canonicalize_filename (gchar *filename)
Anders Carlsson's avatar
Anders Carlsson committed
361
{
362 363 364 365 366 367 368
  gchar *p, *q;
  gboolean last_was_slash = FALSE;

  p = filename;
  q = filename;

  while (*p)
Anders Carlsson's avatar
Anders Carlsson committed
369
    {
370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438
      if (*p == G_DIR_SEPARATOR)
	{
	  if (!last_was_slash)
	    *q++ = G_DIR_SEPARATOR;

	  last_was_slash = TRUE;
	}
      else
	{
	  if (last_was_slash && *p == '.')
	    {
	      if (*(p + 1) == G_DIR_SEPARATOR ||
		  *(p + 1) == '\0')
		{
		  if (*(p + 1) == '\0')
		    break;

		  p += 1;
		}
	      else if (*(p + 1) == '.' &&
		       (*(p + 2) == G_DIR_SEPARATOR ||
			*(p + 2) == '\0'))
		{
		  if (q > filename + 1)
		    {
		      q--;
		      while (q > filename + 1 &&
			     *(q - 1) != G_DIR_SEPARATOR)
			q--;
		    }

		  if (*(p + 2) == '\0')
		    break;

		  p += 2;
		}
	      else
		{
		  *q++ = *p;
		  last_was_slash = FALSE;
		}
	    }
	  else
	    {
	      *q++ = *p;
	      last_was_slash = FALSE;
	    }
	}

      p++;
    }

  if (q > filename + 1 && *(q - 1) == G_DIR_SEPARATOR)
    q--;

  *q = '\0';
}

static gchar *
follow_links (const gchar *path)
{
  gchar *target;
  gchar *d, *s;
  gchar *path2 = NULL;

  path2 = g_strdup (path);
  while (g_file_test (path2, G_FILE_TEST_IS_SYMLINK))
    {
      target = g_file_read_link (path2, NULL);
Matthias Clasen's avatar
Matthias Clasen committed
439

440 441
      if (target)
	{
442 443
	  if (g_path_is_absolute (target))
	    path2 = target;
444 445
	  else
	    {
446 447 448
	      d = g_path_get_dirname (path2);
	      s = g_build_filename (d, target, NULL);
	      g_free (d);
449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467
	      g_free (target);
	      g_free (path2);
	      path2 = s;
	    }
	}
      else
	break;
    }

  if (strcmp (path, path2) == 0)
    {
      g_free (path2);
      path2 = NULL;
    }

  return path2;
}

static void
Matthias Clasen's avatar
Matthias Clasen committed
468
maybe_cache_image_data (Image       *image,
469 470
			const gchar *path)
{
Matthias Clasen's avatar
Matthias Clasen committed
471
  if (!index_only && !image->image_data &&
472
      (g_str_has_suffix (path, ".png") || g_str_has_suffix (path, ".xpm")))
473 474 475 476 477 478 479 480 481 482 483 484 485
    {
      GdkPixbuf *pixbuf;
      ImageData *idata;
      gchar *path2;

      idata = g_hash_table_lookup (image_data_hash, path);
      path2 = follow_links (path);

      if (path2)
	{
	  ImageData *idata2;

	  canonicalize_filename (path2);
Matthias Clasen's avatar
Matthias Clasen committed
486

487 488 489
	  idata2 = g_hash_table_lookup (image_data_hash, path2);

	  if (idata && idata2 && idata != idata2)
490
	    g_error ("different idatas found for symlinked '%s' and '%s'\n",
491 492 493 494 495 496 497 498 499 500 501
		     path, path2);

	  if (idata && !idata2)
	    g_hash_table_insert (image_data_hash, g_strdup (path2), idata);

	  if (!idata && idata2)
	    {
	      g_hash_table_insert (image_data_hash, g_strdup (path), idata2);
	      idata = idata2;
	    }
	}
Matthias Clasen's avatar
Matthias Clasen committed
502

503 504 505 506 507
      if (!idata)
	{
	  idata = g_new0 (ImageData, 1);
	  g_hash_table_insert (image_data_hash, g_strdup (path), idata);
	  if (path2)
Matthias Clasen's avatar
Matthias Clasen committed
508
	    g_hash_table_insert (image_data_hash, g_strdup (path2), idata);
509 510 511
	}

      if (!idata->has_pixdata)
Anders Carlsson's avatar
Anders Carlsson committed
512
	{
513
	  pixbuf = gdk_pixbuf_new_from_file (path, NULL);
Matthias Clasen's avatar
Matthias Clasen committed
514 515

	  if (pixbuf)
516
	    {
517
G_GNUC_BEGIN_IGNORE_DEPRECATIONS;
518
	      gdk_pixdata_from_pixbuf (&idata->pixdata, pixbuf, FALSE);
519
G_GNUC_END_IGNORE_DEPRECATIONS;
520
	      idata->size = idata->pixdata.length + 8;
521 522
	      idata->has_pixdata = TRUE;
	    }
Anders Carlsson's avatar
Anders Carlsson committed
523
	}
524 525 526

      image->image_data = idata;

527
      g_free (path2);
Anders Carlsson's avatar
Anders Carlsson committed
528 529 530
    }
}

531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547
static void
maybe_cache_icon_data (Image       *image,
                       const gchar *path)
{
  if (g_str_has_suffix (path, ".icon"))
    {
      IconData *idata = NULL;
      gchar *path2 = NULL;

      idata = g_hash_table_lookup (icon_data_hash, path);
      path2 = follow_links (path);

      if (path2)
	{
	  IconData *idata2;

	  canonicalize_filename (path2);
Matthias Clasen's avatar
Matthias Clasen committed
548

549 550 551
	  idata2 = g_hash_table_lookup (icon_data_hash, path2);

	  if (idata && idata2 && idata != idata2)
552
	    g_error ("different idatas found for symlinked '%s' and '%s'\n",
553 554 555 556 557 558 559 560 561 562 563
		     path, path2);

	  if (idata && !idata2)
	    g_hash_table_insert (icon_data_hash, g_strdup (path2), idata);

	  if (!idata && idata2)
	    {
	      g_hash_table_insert (icon_data_hash, g_strdup (path), idata2);
	      idata = idata2;
	    }
	}
Matthias Clasen's avatar
Matthias Clasen committed
564

565 566 567 568 569
      if (!idata)
	{
	  idata = load_icon_data (path);
	  g_hash_table_insert (icon_data_hash, g_strdup (path), idata);
	  if (path2)
Matthias Clasen's avatar
Matthias Clasen committed
570
	    g_hash_table_insert (icon_data_hash, g_strdup (path2), idata);
571 572 573 574
        }

      image->icon_data = idata;

575
      g_free (path2);
576 577 578
    }
}

579
/*
580
 * Finds all dir separators and replaces them with “/”.
581 582 583 584 585 586 587 588 589 590 591 592 593 594 595
 * This makes sure that only /-separated paths are written in cache files,
 * maintaining compatibility with theme index files that use slashes as
 * directory separators on all platforms.
 */
static void
replace_backslashes_with_slashes (gchar *path)
{
  size_t i;
  if (path == NULL)
    return;
  for (i = 0; path[i]; i++)
    if (G_IS_DIR_SEPARATOR (path[i]))
      path[i] = '/';
}

596
static GList *
Matthias Clasen's avatar
Matthias Clasen committed
597 598 599
scan_directory (const gchar *base_path,
		const gchar *subdir,
		GHashTable  *files,
600 601 602 603 604 605 606 607 608
		GList       *directories,
		gint         depth)
{
  GHashTable *dir_hash;
  GDir *dir;
  const gchar *name;
  gchar *dir_path;
  gboolean dir_added = FALSE;
  guint dir_index = 0xffff;
Matthias Clasen's avatar
Matthias Clasen committed
609

610
  dir_path = g_build_path ("/", base_path, subdir, NULL);
611 612 613

  /* FIXME: Use the gerror */
  dir = g_dir_open (dir_path, 0, NULL);
Matthias Clasen's avatar
Matthias Clasen committed
614

615 616
  if (!dir)
    return directories;
Matthias Clasen's avatar
Matthias Clasen committed
617

618 619 620 621 622 623 624 625 626 627 628
  dir_hash = g_hash_table_new (g_str_hash, g_str_equal);

  while ((name = g_dir_read_name (dir)))
    {
      gchar *path;
      gboolean retval;
      int flags = 0;
      Image *image;
      gchar *basename, *dot;

      path = g_build_filename (dir_path, name, NULL);
629

630 631 632 633 634 635
      retval = g_file_test (path, G_FILE_TEST_IS_DIR);
      if (retval)
	{
	  gchar *subsubdir;

	  if (subdir)
636
	    subsubdir = g_build_path ("/", subdir, name, NULL);
637 638
	  else
	    subsubdir = g_strdup (name);
Matthias Clasen's avatar
Matthias Clasen committed
639
	  directories = scan_directory (base_path, subsubdir, files,
640 641 642 643 644 645
					directories, depth + 1);
	  g_free (subsubdir);

	  continue;
	}

646 647 648 649
      /* ignore images in the toplevel directory */
      if (subdir == NULL)
        continue;

650 651 652 653 654 655 656 657 658 659 660
      retval = g_file_test (path, G_FILE_TEST_IS_REGULAR);
      if (retval)
	{
	  if (g_str_has_suffix (name, ".png"))
	    flags |= HAS_SUFFIX_PNG;
	  else if (g_str_has_suffix (name, ".svg"))
	    flags |= HAS_SUFFIX_SVG;
	  else if (g_str_has_suffix (name, ".xpm"))
	    flags |= HAS_SUFFIX_XPM;
	  else if (g_str_has_suffix (name, ".icon"))
	    flags |= HAS_ICON_FILE;
Matthias Clasen's avatar
Matthias Clasen committed
661

662 663
	  if (flags == 0)
	    continue;
Matthias Clasen's avatar
Matthias Clasen committed
664

665 666 667
	  basename = g_strdup (name);
	  dot = strrchr (basename, '.');
	  *dot = '\0';
Matthias Clasen's avatar
Matthias Clasen committed
668

669
	  image = g_hash_table_lookup (dir_hash, basename);
670
	  if (!image)
671
	    {
Matthias Clasen's avatar
Matthias Clasen committed
672
	      if (!dir_added)
673 674 675 676 677 678 679 680 681 682
		{
		  dir_added = TRUE;
		  if (subdir)
		    {
		      dir_index = g_list_length (directories);
		      directories = g_list_append (directories, g_strdup (subdir));
		    }
		  else
		    dir_index = 0xffff;
		}
Matthias Clasen's avatar
Matthias Clasen committed
683

684 685 686 687 688
	      image = g_new0 (Image, 1);
	      image->dir_index = dir_index;
	      g_hash_table_insert (dir_hash, g_strdup (basename), image);
	    }

689
	  image->flags |= flags;
Matthias Clasen's avatar
Matthias Clasen committed
690

691 692
	  maybe_cache_image_data (image, path);
          maybe_cache_icon_data (image, path);
Matthias Clasen's avatar
Matthias Clasen committed
693

694 695
	  g_free (basename);
	}
Anders Carlsson's avatar
Anders Carlsson committed
696 697

      g_free (path);
698 699 700 701 702 703
    }

  g_dir_close (dir);

  /* Move dir into the big file hash */
  g_hash_table_foreach_remove (dir_hash, foreach_remove_func, files);
Matthias Clasen's avatar
Matthias Clasen committed
704

705 706 707 708 709 710 711 712 713 714 715 716
  g_hash_table_destroy (dir_hash);

  return directories;
}

typedef struct _HashNode HashNode;

struct _HashNode
{
  HashNode *next;
  gchar *name;
  GList *image_list;
717
  gint offset;
718 719 720 721 722
};

static guint
icon_name_hash (gconstpointer key)
{
723 724
  const signed char *p = key;
  guint32 h = *p;
725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743

  if (h)
    for (p += 1; *p != '\0'; p++)
      h = (h << 5) - h + *p;

  return h;
}

typedef struct {
  gint size;
  HashNode **nodes;
} HashContext;

static gboolean
convert_to_hash (gpointer key, gpointer value, gpointer user_data)
{
  HashContext *context = user_data;
  guint hash;
  HashNode *node;
Matthias Clasen's avatar
Matthias Clasen committed
744

745 746 747 748 749 750 751 752 753 754 755
  hash = icon_name_hash (key) % context->size;

  node = g_new0 (HashNode, 1);
  node->next = NULL;
  node->name = key;
  node->image_list = value;

  if (context->nodes[hash] != NULL)
    node->next = context->nodes[hash];

  context->nodes[hash] = node;
Matthias Clasen's avatar
Matthias Clasen committed
756

757 758 759
  return TRUE;
}

760
static GHashTable *string_pool = NULL;
Matthias Clasen's avatar
Matthias Clasen committed
761

762 763 764 765 766 767 768 769 770
static int
find_string (const gchar *n)
{
  return GPOINTER_TO_INT (g_hash_table_lookup (string_pool, n));
}

static void
add_string (const gchar *n, int offset)
{
771
  g_hash_table_insert (string_pool, (gpointer) n, GINT_TO_POINTER (offset));
772 773
}

774
static gboolean
775 776 777 778
write_string (FILE *cache, const gchar *n)
{
  gchar *s;
  int i, l;
Matthias Clasen's avatar
Matthias Clasen committed
779

780
  l = ALIGN_VALUE (strlen (n) + 1, 4);
Matthias Clasen's avatar
Matthias Clasen committed
781

782 783 784 785 786
  s = g_malloc0 (l);
  strcpy (s, n);

  i = fwrite (s, l, 1, cache);

787 788
  g_free (s);

789
  return i == 1;
Matthias Clasen's avatar
Matthias Clasen committed
790

791 792
}

793
static gboolean
794 795 796 797
write_card16 (FILE *cache, guint16 n)
{
  int i;

798
  n = GUINT16_TO_BE (n);
Matthias Clasen's avatar
Matthias Clasen committed
799

800
  i = fwrite ((char *)&n, 2, 1, cache);
801 802 803 804

  return i == 1;
}

805
static gboolean
806 807 808 809
write_card32 (FILE *cache, guint32 n)
{
  int i;

810
  n = GUINT32_TO_BE (n);
Matthias Clasen's avatar
Matthias Clasen committed
811

812
  i = fwrite ((char *)&n, 4, 1, cache);
813 814 815 816

  return i == 1;
}

Anders Carlsson's avatar
Anders Carlsson committed
817

818
static gboolean
819
write_image_data (FILE *cache, ImageData *image_data, int offset)
Anders Carlsson's avatar
Anders Carlsson committed
820 821
{
  guint8 *s;
822 823
  guint len;
  gint i;
824
  GdkPixdata *pixdata = &image_data->pixdata;
Anders Carlsson's avatar
Anders Carlsson committed
825 826 827 828 829

  /* Type 0 is GdkPixdata */
  if (!write_card32 (cache, 0))
    return FALSE;

830
G_GNUC_BEGIN_IGNORE_DEPRECATIONS;
Anders Carlsson's avatar
Anders Carlsson committed
831
  s = gdk_pixdata_serialize (pixdata, &len);
832
G_GNUC_END_IGNORE_DEPRECATIONS;
Anders Carlsson's avatar
Anders Carlsson committed
833 834 835 836 837 838 839 840

  if (!write_card32 (cache, len))
    {
      g_free (s);
      return FALSE;
    }

  i = fwrite (s, len, 1, cache);
Matthias Clasen's avatar
Matthias Clasen committed
841

Anders Carlsson's avatar
Anders Carlsson committed
842 843 844 845 846
  g_free (s);

  return i == 1;
}

847 848 849 850 851 852 853 854 855 856 857
static gboolean
write_icon_data (FILE *cache, IconData *icon_data, int offset)
{
  int ofs = offset + 12;
  int j;
  int tmp, tmp2;

  if (icon_data->has_embedded_rect)
    {
      if (!write_card32 (cache, ofs))
        return FALSE;
Matthias Clasen's avatar
Matthias Clasen committed
858

859
       ofs += 8;
Matthias Clasen's avatar
Matthias Clasen committed
860
    }
861 862 863 864 865
  else
    {
      if (!write_card32 (cache, 0))
        return FALSE;
    }
Matthias Clasen's avatar
Matthias Clasen committed
866

867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903
  if (icon_data->n_attach_points > 0)
    {
      if (!write_card32 (cache, ofs))
        return FALSE;

      ofs += 4 + 4 * icon_data->n_attach_points;
    }
  else
    {
      if (!write_card32 (cache, 0))
        return FALSE;
    }

  if (icon_data->n_display_names > 0)
    {
      if (!write_card32 (cache, ofs))
	return FALSE;
    }
  else
    {
      if (!write_card32 (cache, 0))
        return FALSE;
    }

  if (icon_data->has_embedded_rect)
    {
      if (!write_card16 (cache, icon_data->x0) ||
          !write_card16 (cache, icon_data->y0) ||
	  !write_card16 (cache, icon_data->x1) ||
	  !write_card16 (cache, icon_data->y1))
        return FALSE;
    }

  if (icon_data->n_attach_points > 0)
    {
      if (!write_card32 (cache, icon_data->n_attach_points))
        return FALSE;
Matthias Clasen's avatar
Matthias Clasen committed
904

905 906 907 908
      for (j = 0; j < 2 * icon_data->n_attach_points; j++)
        {
          if (!write_card16 (cache, icon_data->attach_points[j]))
            return FALSE;
Matthias Clasen's avatar
Matthias Clasen committed
909
        }
910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927
    }

  if (icon_data->n_display_names > 0)
    {
      if (!write_card32 (cache, icon_data->n_display_names))
        return FALSE;

      ofs += 4 + 8 * icon_data->n_display_names;

      tmp = ofs;
      for (j = 0; j < 2 * icon_data->n_display_names; j++)
        {
          tmp2 = find_string (icon_data->display_names[j]);
          if (tmp2 == 0 || tmp2 == -1)
            {
              tmp2 = tmp;
              tmp += ALIGN_VALUE (strlen (icon_data->display_names[j]) + 1, 4);
              /* We're playing a little game with negative
Matthias Clasen's avatar
Matthias Clasen committed
928
               * offsets here to handle duplicate strings in
929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956
               * the array.
               */
              add_string (icon_data->display_names[j], -tmp2);
            }
          else if (tmp2 < 0)
            {
              tmp2 = -tmp2;
            }

          if (!write_card32 (cache, tmp2))
            return FALSE;

        }

      g_assert (ofs == ftell (cache));
      for (j = 0; j < 2 * icon_data->n_display_names; j++)
        {
          tmp2 = find_string (icon_data->display_names[j]);
          g_assert (tmp2 != 0 && tmp2 != -1);
          if (tmp2 < 0)
            {
              tmp2 = -tmp2;
              g_assert (tmp2 == ftell (cache));
              add_string (icon_data->display_names[j], tmp2);
              if (!write_string (cache, icon_data->display_names[j]))
                return FALSE;
            }
        }
Matthias Clasen's avatar
Matthias Clasen committed
957
    }
958 959 960 961

  return TRUE;
}

962 963 964 965 966 967 968 969 970
static gboolean
write_header (FILE *cache, guint32 dir_list_offset)
{
  return (write_card16 (cache, MAJOR_VERSION) &&
	  write_card16 (cache, MINOR_VERSION) &&
	  write_card32 (cache, HASH_OFFSET) &&
	  write_card32 (cache, dir_list_offset));
}

971
static gint
Anders Carlsson's avatar
Anders Carlsson committed
972 973 974 975
get_image_meta_data_size (Image *image)
{
  gint i;

976 977 978
  /* The complication with storing the size in both
   * IconData and Image is necessary since we attribute
   * the size of the IconData only to the first Image
Matthias Clasen's avatar
Matthias Clasen committed
979
   * using it (at which time it is written out in the
980 981 982 983
   * cache). Later Images just refer to the written out
   * IconData via the offset.
   */
  if (image->icon_data_size == 0)
Anders Carlsson's avatar
Anders Carlsson committed
984
    {
985 986 987 988 989 990 991
      if (image->icon_data && image->icon_data->size < 0)
	{
          IconData *data = image->icon_data;

          data->size = 0;

          if (data->has_embedded_rect ||
992
              data->n_attach_points > 0 ||
993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006
              data->n_display_names > 0)
            data->size += 12;

          if (data->has_embedded_rect)
            data->size += 8;

          if (data->n_attach_points > 0)
            data->size += 4 + data->n_attach_points * 4;

          if (data->n_display_names > 0)
            {
              data->size += 4 + 8 * data->n_display_names;

              for (i = 0; data->display_names[i]; i++)
Matthias Clasen's avatar
Matthias Clasen committed
1007
                {
1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020
                  int poolv;
                  if ((poolv = find_string (data->display_names[i])) == 0)
                    {
                      data->size += ALIGN_VALUE (strlen (data->display_names[i]) + 1, 4);
                      /* Adding the string to the pool with -1
                       * to indicate that it hasn't been written out
                       * to the cache yet. We still need it in the
                       * pool in case the same string occurs twice
                       * during a get_single_node_size() calculation.
                       */
                      add_string (data->display_names[i], -1);
                    }
                }
Matthias Clasen's avatar
Matthias Clasen committed
1021
           }
1022 1023 1024 1025

	  image->icon_data_size = data->size;
	  data->size = 0;
	}
Anders Carlsson's avatar
Anders Carlsson committed
1026 1027
    }

1028 1029 1030
  g_assert (image->icon_data_size % 4 == 0);

  return image->icon_data_size;
Anders Carlsson's avatar
Anders Carlsson committed
1031 1032
}

1033
static gint
Anders Carlsson's avatar
Anders Carlsson committed
1034 1035
get_image_pixel_data_size (Image *image)
{
1036 1037 1038
  /* The complication with storing the size in both
   * ImageData and Image is necessary since we attribute
   * the size of the ImageData only to the first Image
Matthias Clasen's avatar
Matthias Clasen committed
1039
   * using it (at which time it is written out in the
1040 1041 1042
   * cache). Later Images just refer to the written out
   * ImageData via the offset.
   */
1043 1044
  if (image->pixel_data_size == 0)
    {
Matthias Clasen's avatar
Matthias Clasen committed
1045
      if (image->image_data &&
1046 1047
	  image->image_data->has_pixdata)
	{
1048 1049
	  image->pixel_data_size = image->image_data->size;
	  image->image_data->size = 0;
1050 1051
	}
    }
Anders Carlsson's avatar
Anders Carlsson committed
1052

1053 1054
  g_assert (image->pixel_data_size % 4 == 0);

1055
  return image->pixel_data_size;
Anders Carlsson's avatar
Anders Carlsson committed
1056
}
1057

1058
static gint
Anders Carlsson's avatar
Anders Carlsson committed
1059 1060
get_image_data_size (Image *image)
{
1061
  gint len;
Matthias Clasen's avatar
Matthias Clasen committed
1062

Anders Carlsson's avatar
Anders Carlsson committed
1063 1064 1065 1066
  len = 0;

  len += get_image_pixel_data_size (image);
  len += get_image_meta_data_size (image);
1067 1068

  /* Even if len is zero, we need to reserve space to
Matthias Clasen's avatar
Matthias Clasen committed
1069
   * write the ImageData, unless this is an .svg without
1070 1071 1072 1073
   * .icon, in which case both image_data and icon_data
   * are NULL.
   */
  if (len > 0 || image->image_data || image->icon_data)
Anders Carlsson's avatar
Anders Carlsson committed
1074 1075 1076 1077 1078
    len += 8;

  return len;
}

1079 1080
static void
get_single_node_size (HashNode *node, int *node_size, int *image_data_size)
1081
{
Anders Carlsson's avatar
Anders Carlsson committed
1082
  GList *list;
1083 1084

  /* Node pointers */
1085
  *node_size = 12;
1086 1087

  /* Name */
1088 1089 1090 1091 1092
  if (find_string (node->name) == 0)
    {
      *node_size += ALIGN_VALUE (strlen (node->name) + 1, 4);
      add_string (node->name, -1);
    }
1093 1094

  /* Image list */
1095
  *node_size += 4 + g_list_length (node->image_list) * 8;
Matthias Clasen's avatar
Matthias Clasen committed
1096

Anders Carlsson's avatar
Anders Carlsson committed
1097
  /* Image data */
1098 1099
  *image_data_size = 0;
  for (list = node->image_list; list; list = list->next)
1100
    {
1101
      Image *image = list->data;
1102

1103
      *image_data_size += get_image_data_size (image);
1104 1105 1106
    }
}

1107
static gboolean
1108 1109 1110 1111
write_bucket (FILE *cache, HashNode *node, int *offset)
{
  while (node != NULL)
    {
1112 1113
      int node_size, image_data_size;
      int next_offset, image_data_offset;
Anders Carlsson's avatar
Anders Carlsson committed
1114
      int data_offset;
1115 1116 1117 1118
      int name_offset;
      int name_size;
      int image_list_offset;
      int i, len;
1119
      GList *list;
1120 1121 1122 1123

      g_assert (*offset == ftell (cache));

      node->offset = *offset;
1124

1125 1126 1127 1128 1129
      get_single_node_size (node, &node_size, &image_data_size);
      g_assert (node_size % 4 == 0);
      g_assert (image_data_size % 4 == 0);
      image_data_offset = *offset + node_size;
      next_offset = *offset + node_size + image_data_size;
1130 1131
      /* Chain offset */
      if (node->next != NULL)
1132 1133 1134 1135
        {
          if (!write_card32 (cache, next_offset))
            return FALSE;
        }
1136
      else
1137 1138 1139 1140 1141
        {
          if (!write_card32 (cache, 0xffffffff))
            return FALSE;
        }

1142 1143 1144 1145 1146 1147 1148 1149 1150
      name_size = 0;
      name_offset = find_string (node->name);
      if (name_offset <= 0)
        {
          name_offset = *offset + 12;
          name_size = ALIGN_VALUE (strlen (node->name) + 1, 4);
          add_string (node->name, name_offset);
        }
      if (!write_card32 (cache, name_offset))
1151 1152
        return FALSE;

1153 1154
      image_list_offset = *offset + 12 + name_size;
      if (!write_card32 (cache, image_list_offset))
1155 1156
        return FALSE;

1157
      /* Icon name */
1158 1159 1160
      if (name_size > 0)
        {
          if (!write_string (cache, node->name))
1161
            return FALSE;
1162 1163
        }

1164 1165 1166
      /* Image list */
      len = g_list_length (node->image_list);
      if (!write_card32 (cache, len))
1167
        return FALSE;
Anders Carlsson's avatar
Anders Carlsson committed
1168

1169
      list = node->image_list;
Anders Carlsson's avatar
Anders Carlsson committed
1170
      data_offset = image_data_offset;
1171
      for (i = 0; i < len; i++)
1172 1173
        {
          Image *image = list->data;
1174
          int image_size = get_image_data_size (image);
1175

1176 1177 1178
          /* Directory index */
          if (!write_card16 (cache, image->dir_index))
            return FALSE;
Anders Carlsson's avatar
Anders Carlsson committed
1179

1180 1181 1182
          /* Flags */
          if (!write_card16 (cache, image->flags))
            return FALSE;
Anders Carlsson's avatar
Anders Carlsson committed
1183

1184
          /* Image data offset */
1185
          if (image_size > 0)
1186 1187 1188
            {
              if (!write_card32 (cache, data_offset))
                return FALSE;
1189
              data_offset += image_size;
1190 1191 1192 1193 1194 1195 1196 1197 1198
            }
          else
            {
              if (!write_card32 (cache, 0))
                return FALSE;
            }

          list = list->next;
        }
1199

Anders Carlsson's avatar
Anders Carlsson committed
1200 1201 1202
      /* Now write the image data */
      list = node->image_list;
      for (i = 0; i < len; i++, list = list->next)
1203 1204 1205 1206
        {
          Image *image = list->data;
          int pixel_data_size = get_image_pixel_data_size (image);
          int meta_data_size = get_image_meta_data_size (image);
Anders Carlsson's avatar
Anders Carlsson committed
1207

1208 1209
          if (get_image_data_size (image) == 0)
            continue;
Anders Carlsson's avatar
Anders Carlsson committed
1210

1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222
          /* Pixel data */
          if (pixel_data_size > 0)
            {
              image->image_data->offset = image_data_offset + 8;
              if (!write_card32 (cache, image->image_data->offset))
                return FALSE;
            }
          else
            {
              if (!write_card32 (cache, (guint32) (image->image_data ? image->image_data->offset : 0)))
                return FALSE;
            }
Anders Carlsson's avatar
Anders Carlsson committed
1223

1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234
          if (meta_data_size > 0)
            {
              image->icon_data->offset = image_data_offset + pixel_data_size + 8;
              if (!write_card32 (cache, image->icon_data->offset))
                return FALSE;
            }
          else
            {
              if (!write_card32 (cache, image->icon_data ? image->icon_data->offset : 0))
                return FALSE;
            }
Anders Carlsson's avatar
Anders Carlsson committed
1235

1236 1237 1238 1239 1240 1241 1242 1243
          if (pixel_data_size > 0)
            {
              if (!write_image_data (cache, image->image_data, image->image_data->offset))
                return FALSE;
            }

          if (meta_data_size > 0)
            {
1244 1245 1246
              if (!write_icon_data (cache, image->icon_data, image->icon_data->offset))
                return FALSE;
            }
Anders Carlsson's avatar
Anders Carlsson committed
1247

1248 1249 1250
          image_data_offset += pixel_data_size + meta_data_size + 8;
        }

1251 1252 1253
      *offset = next_offset;
      node = node->next;
    }
1254

1255 1256 1257
  return TRUE;
}

1258
static gboolean
1259 1260 1261 1262 1263 1264 1265 1266 1267
write_hash_table (FILE *cache, HashContext *context, int *new_offset)
{
  int offset = HASH_OFFSET;
  int node_offset;
  int i;

  if (!(write_card32 (cache, context->size)))
    return FALSE;

1268 1269
  offset += 4;
  node_offset = offset + context->size * 4;
Matthias Clasen's avatar
Matthias Clasen committed
1270
  /* Just write zeros here, we will rewrite this later */
1271 1272
  for (i = 0; i < context->size; i++)
    {
1273 1274
      if (!write_card32 (cache, 0))
	return FALSE;
1275 1276 1277 1278 1279 1280 1281 1282
    }

  /* Now write the buckets */
  for (i = 0; i < context->size; i++)
    {
      if (!context->nodes[i])
	continue;

1283
      g_assert (node_offset % 4 == 0);
1284 1285 1286 1287
      if (!write_bucket (cache, context->nodes[i], &node_offset))
	return FALSE;
    }

1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305
  *new_offset = node_offset;

  /* Now write out the bucket offsets */

  fseek (cache, offset, SEEK_SET);

  for (i = 0; i < context->size; i++)
    {
      if (context->nodes[i] != NULL)
        node_offset = context->nodes[i]->offset;
      else
	node_offset = 0xffffffff;
      if (!write_card32 (cache, node_offset))
        return FALSE;
    }

  fseek (cache, 0, SEEK_END);

1306 1307 1308
  return TRUE;
}

1309
static gboolean
1310 1311 1312 1313 1314
write_dir_index (FILE *cache, int offset, GList *directories)
{
  int n_dirs;
  GList *d;
  char *dir;
1315
  int tmp, tmp2;
1316 1317 1318 1319 1320 1321 1322 1323

  n_dirs = g_list_length (directories);

  if (!write_card32 (cache, n_dirs))
    return FALSE;

  offset += 4 + n_dirs * 4;

1324
  tmp = offset;
1325 1326 1327
  for (d = directories; d; d = d->next)
    {
      dir = d->data;
Matthias Clasen's avatar
Matthias Clasen committed
1328

1329
      tmp2 = find_string (dir);
Matthias Clasen's avatar
Matthias Clasen committed
1330

1331 1332 1333 1334 1335
      if (tmp2 == 0 || tmp2 == -1)
        {
          tmp2 = tmp;
          tmp += ALIGN_VALUE (strlen (dir) + 1, 4);
          /* We're playing a little game with negative
Matthias Clasen's avatar
Matthias Clasen committed
1336 1337
           * offsets here to handle duplicate strings in
           * the array, even though that should not
1338 1339 1340 1341 1342 1343 1344 1345 1346 1347
           * really happen for the directory index.
           */
          add_string (dir, -tmp2);
        }
      else if (tmp2 < 0)
        {
          tmp2 = -tmp2;
        }

      if (!write_card32 (cache, tmp2))
1348 1349 1350
	return FALSE;
    }

1351
  g_assert (offset == ftell (cache));
1352 1353 1354 1355
  for (d = directories; d; d = d->next)
    {
      dir = d->data;

1356 1357 1358 1359 1360 1361
      tmp2 = find_string (dir);
      g_assert (tmp2 != 0 && tmp2 != -1);
      if (tmp2 < 0)
        {
          tmp2 = -tmp2;
          g_assert (tmp2 == ftell (cache));
Matthias Clasen's avatar
Matthias Clasen committed
1362
          add_string (dir, tmp2);
1363 1364 1365
          if (!write_string (cache, dir))
	    return FALSE;
        }
1366
    }
Matthias Clasen's avatar
Matthias Clasen committed
1367

1368 1369 1370
  return TRUE;
}

1371
static gboolean
1372 1373 1374 1375 1376 1377 1378 1379 1380 1381
write_file (FILE *cache, GHashTable *files, GList *directories)
{
  HashContext context;
  int new_offset;

  /* Convert the hash table into something looking a bit more
   * like what we want to write to disk.
   */
  context.size = g_spaced_primes_closest (g_hash_table_size (files) / 3);
  context.nodes = g_new0 (HashNode *, context.size);
Matthias Clasen's avatar
Matthias Clasen committed
1382

1383 1384 1385 1386 1387 1388 1389
  g_hash_table_foreach_remove (files, convert_to_hash, &context);

  /* Now write the file */
  /* We write 0 as the directory list offset and go
   * back and change it later */
  if (!write_header (cache, 0))
    {
1390
      g_printerr (_("Failed to write header\n"));
1391 1392 1393 1394 1395
      return FALSE;
    }

  if (!write_hash_table (cache, &context, &new_offset))
    {
1396
      g_printerr (_("Failed to write hash table\n"));
1397 1398 1399 1400 1401
      return FALSE;
    }

  if (!write_dir_index (cache, new_offset, directories))
    {
Matthias Clasen's avatar
Matthias Clasen committed
1402
      g_printerr (_("Failed to write folder index\n"));
1403 1404
      return FALSE;
    }
Matthias Clasen's avatar
Matthias Clasen committed
1405

1406 1407 1408 1409
  rewind (cache);

  if (!write_header (cache, new_offset))
    {
1410
      g_printerr (_("Failed to rewrite header\n"));
1411 1412
      return FALSE;
    }
Matthias Clasen's avatar
Matthias Clasen committed
1413

1414 1415 1416
  return TRUE;
}

1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431
static gboolean
validate_file (const gchar *file)
{
  GMappedFile *map;
  CacheInfo info;

  map = g_mapped_file_new (file, FALSE, NULL);
  if (!map)
    return FALSE;

  info.cache = g_mapped_file_get_contents (map);
  info.cache_size = g_mapped_file_get_length (map);
  info.n_directories = 0;
  info.flags = CHECK_OFFSETS|CHECK_STRINGS|CHECK_PIXBUFS;

Matthias Clasen's avatar
Matthias Clasen committed
1432
  if (!_gtk_icon_cache_validate (&info))
1433
    {
1434
      g_mapped_file_unref (map);
1435 1436
      return FALSE;
    }
Matthias Clasen's avatar
Matthias Clasen committed
1437

1438
  g_mapped_file_unref (map);
1439 1440 1441 1442

  return TRUE;
}

1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459
/**
 * safe_fclose:
 * @f: A FILE* stream, must have underlying fd
 *
 * Unix defaults for data preservation after system crash
 * are unspecified, and many systems will eat your data
 * in this situation unless you explicitly fsync().
 *
 * Returns: %TRUE on success, %FALSE on failure, and will set errno()
 */
static gboolean
safe_fclose (FILE *f)
{
  int fd = fileno (f);
  g_assert (fd >= 0);
  if (fflush (f) == EOF)
    return FALSE;
Tor Lillqvist's avatar
Tor Lillqvist committed
1460
#ifndef G_OS_WIN32
1461 1462
  if (fsync (fd) < 0)
    return FALSE;
Tor Lillqvist's avatar
Tor Lillqvist committed
1463
#endif
1464 1465 1466 1467 1468
  if (fclose (f) == EOF)
    return FALSE;
  return TRUE;
}

1469
static void
1470 1471 1472
build_cache (const gchar *path)
{
  gchar *cache_path, *tmp_cache_path;
1473 1474 1475
#ifdef G_OS_WIN32
  gchar *bak_cache_path = NULL;
#endif
1476 1477
  GHashTable *files;
  FILE *cache;
1478
  GStatBuf path_stat, cache_stat;
1479 1480
  struct utimbuf utime_buf;
  GList *directories = NULL;
1481
  int fd;
1482
  int retry_count = 0;
1483
#ifndef G_OS_WIN32
1484
  mode_t mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH;
1485 1486 1487 1488 1489 1490 1491
#else
  int mode = _S_IWRITE | _S_IREAD;
#endif
#ifndef _O_BINARY
#define _O_BINARY 0
#endif

1492
  tmp_cache_path = g_build_filename (path, "."CACHE_NAME, NULL);
1493
  cache_path = g_build_filename (path, CACHE_NAME, NULL);
1494

1495
opentmp:
Tor Lillqvist's avatar
Tor Lillqvist committed
1496
  if ((fd = g_open (tmp_cache_path, O_WRONLY | O_CREAT | O_EXCL | O_TRUNC | _O_BINARY, mode)) == -1)
1497
    {
1498
      if (retry_count == 0)
1499 1500 1501 1502 1503
        {
          retry_count++;
          g_remove (tmp_cache_path);
          goto opentmp;
        }