]> git.wh0rd.org Git - fontconfig.git/blob - src/fccache.c
Was losing local cached dirs in global cache list
[fontconfig.git] / src / fccache.c
1 /*
2  * $XFree86: xc/lib/fontconfig/src/fccache.c,v 1.12 2002/08/22 07:36:44 keithp Exp $
3  *
4  * Copyright © 2000 Keith Packard, member of The XFree86 Project, Inc.
5  *
6  * Permission to use, copy, modify, distribute, and sell this software and its
7  * documentation for any purpose is hereby granted without fee, provided that
8  * the above copyright notice appear in all copies and that both that
9  * copyright notice and this permission notice appear in supporting
10  * documentation, and that the name of Keith Packard not be used in
11  * advertising or publicity pertaining to distribution of the software without
12  * specific, written prior permission.  Keith Packard makes no
13  * representations about the suitability of this software for any purpose.  It
14  * is provided "as is" without express or implied warranty.
15  *
16  * KEITH PACKARD DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
17  * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO
18  * EVENT SHALL KEITH PACKARD BE LIABLE FOR ANY SPECIAL, INDIRECT OR
19  * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE,
20  * DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
21  * TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
22  * PERFORMANCE OF THIS SOFTWARE.
23  */
24
25 #include "fcint.h"
26
27 /*
28  * POSIX has broken stdio so that getc must do thread-safe locking,
29  * this is a serious performance problem for applications doing large
30  * amounts of IO with getc (as is done here).  If available, use
31  * the getc_unlocked varient instead.
32  */
33  
34 #if defined(getc_unlocked) || defined(_IO_getc_unlocked)
35 #define GETC(f) getc_unlocked(f)
36 #define PUTC(c,f) putc_unlocked(c,f)
37 #else
38 #define GETC(f) getc(f)
39 #define PUTC(c,f) putc(c,f)
40 #endif
41
42 #define FC_DBG_CACHE_REF    1024
43
44 static FcChar8 *
45 FcCacheReadString (FILE *f, FcChar8 *dest, int len)
46 {
47     int         c;
48     FcBool      escape;
49     FcChar8     *d;
50     int         size;
51     int         i;
52
53     while ((c = GETC (f)) != EOF)
54         if (c == '"')
55             break;
56     if (c == EOF)
57         return FcFalse;
58     if (len == 0)
59         return FcFalse;
60     
61     size = len;
62     i = 0;
63     d = dest;
64     escape = FcFalse;
65     while ((c = GETC (f)) != EOF)
66     {
67         if (!escape)
68         {
69             switch (c) {
70             case '"':
71                 c = '\0';
72                 break;
73             case '\\':
74                 escape = FcTrue;
75                 continue;
76             }
77         }
78         if (i == size)
79         {
80             FcChar8 *new = malloc (size * 2);   /* freed in caller */
81             if (!new)
82                 break;
83             memcpy (new, d, size);
84             size *= 2;
85             if (d != dest)
86                 free (d);
87             d = new;
88         }
89         d[i++] = c;
90         if (c == '\0')
91             return d;
92         escape = FcFalse;
93     }
94     if (d != dest)
95         free (d);
96     return 0;
97 }
98
99 static FcBool
100 FcCacheReadUlong (FILE *f, unsigned long *dest)
101 {
102     unsigned long   t;
103     int             c;
104
105     while ((c = GETC (f)) != EOF)
106     {
107         if (!isspace (c))
108             break;
109     }
110     if (c == EOF)
111         return FcFalse;
112     t = 0;
113     for (;;)
114     {
115         if (c == EOF || isspace (c))
116             break;
117         if (!isdigit (c))
118             return FcFalse;
119         t = t * 10 + (c - '0');
120         c = GETC (f);
121     }
122     *dest = t;
123     return FcTrue;
124 }
125
126 static FcBool
127 FcCacheReadInt (FILE *f, int *dest)
128 {
129     unsigned long   t;
130     FcBool          ret;
131
132     ret = FcCacheReadUlong (f, &t);
133     if (ret)
134         *dest = (int) t;
135     return ret;
136 }
137
138 static FcBool
139 FcCacheReadTime (FILE *f, time_t *dest)
140 {
141     unsigned long   t;
142     FcBool          ret;
143
144     ret = FcCacheReadUlong (f, &t);
145     if (ret)
146         *dest = (time_t) t;
147     return ret;
148 }
149
150 static FcBool
151 FcCacheWriteChars (FILE *f, const FcChar8 *chars)
152 {
153     FcChar8    c;
154     while ((c = *chars++))
155     {
156         switch (c) {
157         case '"':
158         case '\\':
159             if (PUTC ('\\', f) == EOF)
160                 return FcFalse;
161             /* fall through */
162         default:
163             if (PUTC (c, f) == EOF)
164                 return FcFalse;
165         }
166     }
167     return FcTrue;
168 }
169
170 static FcBool
171 FcCacheWriteString (FILE *f, const FcChar8 *string)
172 {
173
174     if (PUTC ('"', f) == EOF)
175         return FcFalse;
176     if (!FcCacheWriteChars (f, string))
177         return FcFalse;
178     if (PUTC ('"', f) == EOF)
179         return FcFalse;
180     return FcTrue;
181 }
182
183 static FcBool
184 FcCacheWritePath (FILE *f, const FcChar8 *dir, const FcChar8 *file)
185 {
186     if (PUTC ('"', f) == EOF)
187         return FcFalse;
188     if (dir)
189         if (!FcCacheWriteChars (f, dir))
190             return FcFalse;
191     if (dir && dir[strlen((const char *) dir) - 1] != '/')
192         if (PUTC ('/', f) == EOF)
193             return FcFalse;
194     if (!FcCacheWriteChars (f, file))
195         return FcFalse;
196     if (PUTC ('"', f) == EOF)
197         return FcFalse;
198     return FcTrue;
199 }
200
201 static FcBool
202 FcCacheWriteUlong (FILE *f, unsigned long t)
203 {
204     int     pow;
205     unsigned long   temp, digit;
206
207     temp = t;
208     pow = 1;
209     while (temp >= 10)
210     {
211         temp /= 10;
212         pow *= 10;
213     }
214     temp = t;
215     while (pow)
216     {
217         digit = temp / pow;
218         if (PUTC ((char) digit + '0', f) == EOF)
219             return FcFalse;
220         temp = temp - pow * digit;
221         pow = pow / 10;
222     }
223     return FcTrue;
224 }
225
226 static FcBool
227 FcCacheWriteInt (FILE *f, int i)
228 {
229     return FcCacheWriteUlong (f, (unsigned long) i);
230 }
231
232 static FcBool
233 FcCacheWriteTime (FILE *f, time_t t)
234 {
235     return FcCacheWriteUlong (f, (unsigned long) t);
236 }
237
238 static FcBool
239 FcCacheFontSetAdd (FcFontSet        *set,
240                    FcStrSet         *dirs,
241                    const FcChar8    *dir,
242                    int              dir_len,
243                    const FcChar8    *file,
244                    const FcChar8    *name)
245 {
246     FcChar8     path_buf[8192], *path;
247     int         len;
248     FcBool      ret = FcFalse;
249     FcPattern   *font;
250     FcPattern   *frozen;
251
252     path = path_buf;
253     len = (dir_len + 1 + strlen ((const char *) file) + 1);
254     if (len > sizeof (path_buf))
255     {
256         path = malloc (len);    /* freed down below */
257         if (!path)
258             return FcFalse;
259     }
260     strncpy ((char *) path, (const char *) dir, dir_len);
261     if (dir[dir_len - 1] != '/')
262         path[dir_len++] = '/';
263     strcpy ((char *) path + dir_len, (const char *) file);
264     if (!FcStrCmp (name, FC_FONT_FILE_DIR))
265     {
266         if (FcDebug () & FC_DBG_CACHEV)
267             printf (" dir cache dir \"%s\"\n", path);
268         ret = FcStrSetAdd (dirs, path);
269     }
270     else if (!FcStrCmp (name, FC_FONT_FILE_INVALID))
271     {
272         ret = FcTrue;
273     }
274     else
275     {
276         font = FcNameParse (name);
277         if (font)
278         {
279             if (FcDebug () & FC_DBG_CACHEV)
280                 printf (" dir cache file \"%s\"\n", file);
281             ret = FcPatternAddString (font, FC_FILE, path);
282             if (ret)
283             {
284                 frozen = FcPatternFreeze (font);
285                 ret = (frozen != 0);
286                 if (ret)
287                    ret = FcFontSetAdd (set, frozen);
288             }
289             FcPatternDestroy (font);
290         }
291     }
292     if (path != path_buf) free (path);
293     return ret;
294     
295 }
296
297 static unsigned int
298 FcCacheHash (const FcChar8 *string)
299 {
300     unsigned int    h = 0;
301     FcChar8         c;
302
303     while ((c = *string++))
304         h = (h << 1) ^ c;
305     return 0;
306 }
307
308 /*
309  * Verify the saved timestamp for a file
310  */
311 FcBool
312 FcGlobalCacheCheckTime (FcGlobalCacheInfo *info)
313 {
314     struct stat     statb;
315
316     if (stat ((char *) info->file, &statb) < 0)
317     {
318         if (FcDebug () & FC_DBG_CACHE)
319             printf (" file missing\n");
320         return FcFalse;
321     }
322     if (statb.st_mtime != info->time)
323     {
324         if (FcDebug () & FC_DBG_CACHE)
325             printf (" timestamp mismatch (was %d is %d)\n",
326                     (int) info->time, (int) statb.st_mtime);
327         return FcFalse;
328     }
329     return FcTrue;
330 }
331
332 void
333 FcGlobalCacheReferenced (FcGlobalCache      *cache,
334                          FcGlobalCacheInfo  *info)
335 {
336     if (!info->referenced)
337     {
338         info->referenced = FcTrue;
339         cache->referenced++;
340         if (FcDebug () & FC_DBG_CACHE_REF)
341             printf ("Reference %d %s\n", cache->referenced, info->file);
342     }
343 }
344
345 /*
346  * Break a path into dir/base elements and compute the base hash
347  * and the dir length.  This is shared between the functions
348  * which walk the file caches
349  */
350
351 typedef struct _FcFilePathInfo {
352     const FcChar8   *dir;
353     int             dir_len;
354     const FcChar8   *base;
355     unsigned int    base_hash;
356 } FcFilePathInfo;
357
358 static FcFilePathInfo
359 FcFilePathInfoGet (const FcChar8    *path)
360 {
361     FcFilePathInfo  i;
362     FcChar8         *slash;
363
364     slash = (FcChar8 *) strrchr ((const char *) path, '/');
365     if (slash)
366     {
367         i.dir = path;
368         i.dir_len = slash - path;
369         if (!i.dir_len)
370             i.dir_len = 1;
371         i.base = slash + 1;
372     }
373     else
374     {
375         i.dir = (const FcChar8 *) ".";
376         i.dir_len = 1;
377         i.base = path;
378     }
379     i.base_hash = FcCacheHash (i.base);
380     return i;
381 }
382
383 FcGlobalCacheDir *
384 FcGlobalCacheDirGet (FcGlobalCache  *cache,
385                      const FcChar8  *dir,
386                      int            len,
387                      FcBool         create_missing)
388 {
389     unsigned int        hash = FcCacheHash (dir);
390     FcGlobalCacheDir    *d, **prev;
391
392     for (prev = &cache->ents[hash % FC_GLOBAL_CACHE_DIR_HASH_SIZE];
393          (d = *prev);
394          prev = &(*prev)->next)
395     {
396         if (d->info.hash == hash && d->len == len &&
397             !strncmp ((const char *) d->info.file,
398                       (const char *) dir, len))
399             break;
400     }
401     if (!(d = *prev))
402     {
403         int     i;
404         if (!create_missing)
405             return 0;
406         d = malloc (sizeof (FcGlobalCacheDir) + len + 1);
407         if (!d)
408             return 0;
409         FcMemAlloc (FC_MEM_CACHE, sizeof (FcGlobalCacheDir) + len + 1);
410         d->next = *prev;
411         *prev = d;
412         d->info.hash = hash;
413         d->info.file = (FcChar8 *) (d + 1);
414         strncpy ((char *) d->info.file, (const char *) dir, len);
415         d->info.file[len] = '\0';
416         d->info.time = 0;
417         d->info.referenced = FcFalse;
418         d->len = len;
419         for (i = 0; i < FC_GLOBAL_CACHE_FILE_HASH_SIZE; i++)
420             d->ents[i] = 0;
421         d->subdirs = 0;
422     }
423     return d;
424 }
425
426 static FcGlobalCacheInfo *
427 FcGlobalCacheDirAdd (FcGlobalCache  *cache,
428                      const FcChar8  *dir,
429                      time_t         time,
430                      FcBool         replace)
431 {
432     FcGlobalCacheDir    *d;
433     FcFilePathInfo      i;
434     FcGlobalCacheSubdir *subdir;
435     FcGlobalCacheDir    *parent;
436
437     /*
438      * Add this directory to the cache
439      */
440     d = FcGlobalCacheDirGet (cache, dir, strlen ((const char *) dir), FcTrue);
441     if (!d)
442         return 0;
443     d->info.time = time;
444     i = FcFilePathInfoGet (dir);
445     /*
446      * Add this directory to the subdirectory list of the parent
447      */
448     parent = FcGlobalCacheDirGet (cache, i.dir, i.dir_len, FcTrue);
449     if (!parent)
450         return 0;
451     subdir = malloc (sizeof (FcGlobalCacheSubdir));
452     if (!subdir)
453         return 0;
454     FcMemAlloc (FC_MEM_CACHE, sizeof (FcGlobalCacheSubdir));
455     subdir->ent = d;
456     subdir->next = parent->subdirs;
457     parent->subdirs = subdir;
458     return &d->info;
459 }
460
461 static void
462 FcGlobalCacheDirDestroy (FcGlobalCacheDir *d)
463 {
464     FcGlobalCacheFile   *f, *next;
465     int                 h;
466     FcGlobalCacheSubdir *s, *nexts;
467
468     for (h = 0; h < FC_GLOBAL_CACHE_FILE_HASH_SIZE; h++)
469         for (f = d->ents[h]; f; f = next)
470         {
471             next = f->next;
472             FcMemFree (FC_MEM_CACHE, sizeof (FcGlobalCacheFile) +
473                        strlen ((char *) f->info.file) + 1 +
474                        strlen ((char *) f->name) + 1);
475             free (f);
476         }
477     for (s = d->subdirs; s; s = nexts)
478     {
479         nexts = s->next;
480         FcMemFree (FC_MEM_CACHE, sizeof (FcGlobalCacheSubdir));
481         free (s);
482     }
483     FcMemFree (FC_MEM_CACHE, sizeof (FcGlobalCacheDir) + d->len + 1);
484     free (d);
485 }
486
487 FcBool
488 FcGlobalCacheScanDir (FcFontSet         *set,
489                       FcStrSet          *dirs,
490                       FcGlobalCache     *cache,
491                       const FcChar8     *dir)
492 {
493     FcGlobalCacheDir    *d = FcGlobalCacheDirGet (cache, dir,
494                                                   strlen ((const char *) dir),
495                                                   FcFalse);
496     FcGlobalCacheFile   *f;
497     int                 h;
498     int                 dir_len;
499     FcGlobalCacheSubdir *subdir;
500
501     if (FcDebug() & FC_DBG_CACHE)
502         printf ("FcGlobalCacheScanDir %s\n", dir);
503     
504     if (!d)
505     {
506         if (FcDebug () & FC_DBG_CACHE)
507             printf ("\tNo dir cache entry\n");
508         return FcFalse;
509     }
510
511     if (!FcGlobalCacheCheckTime (&d->info))
512     {
513         if (FcDebug () & FC_DBG_CACHE)
514             printf ("\tdir cache entry time mismatch\n");
515         return FcFalse;
516     }
517
518     dir_len = strlen ((const char *) dir);
519     for (h = 0; h < FC_GLOBAL_CACHE_FILE_HASH_SIZE; h++)
520         for (f = d->ents[h]; f; f = f->next)
521         {
522             if (FcDebug() & FC_DBG_CACHEV)
523                 printf ("FcGlobalCacheScanDir add file %s\n", f->info.file);
524             if (!FcCacheFontSetAdd (set, dirs, dir, dir_len,
525                                     f->info.file, f->name))
526             {
527                 cache->broken = FcTrue;
528                 return FcFalse;
529             }
530             FcGlobalCacheReferenced (cache, &f->info);
531         }
532     for (subdir = d->subdirs; subdir; subdir = subdir->next)
533     {
534         FcFilePathInfo  info = FcFilePathInfoGet (subdir->ent->info.file);
535         
536         if (!FcCacheFontSetAdd (set, dirs, dir, dir_len,
537                                 info.base, FC_FONT_FILE_DIR))
538         {
539             cache->broken = FcTrue;
540             return FcFalse;
541         }
542         FcGlobalCacheReferenced (cache, &subdir->ent->info);
543     }
544     
545     FcGlobalCacheReferenced (cache, &d->info);
546
547     return FcTrue;
548 }
549
550 /*
551  * Locate the cache entry for a particular file
552  */
553 FcGlobalCacheFile *
554 FcGlobalCacheFileGet (FcGlobalCache *cache,
555                       const FcChar8 *file,
556                       int           id,
557                       int           *count)
558 {
559     FcFilePathInfo      i = FcFilePathInfoGet (file);
560     FcGlobalCacheDir    *d = FcGlobalCacheDirGet (cache, i.dir, 
561                                                   i.dir_len, FcFalse);
562     FcGlobalCacheFile   *f, *match = 0;
563     int                 max = -1;
564
565     if (!d)
566         return 0;
567     for (f = d->ents[i.base_hash % FC_GLOBAL_CACHE_FILE_HASH_SIZE]; f; f = f->next)
568     {
569         if (f->info.hash == i.base_hash &&
570             !strcmp ((const char *) f->info.file, (const char *) i.base))
571         {
572             if (f->id == id)
573                 match = f;
574             if (f->id > max)
575                 max = f->id;
576         }
577     }
578     if (count)
579         *count = max;
580     return match;
581 }
582     
583 /*
584  * Add a file entry to the cache
585  */
586 static FcGlobalCacheInfo *
587 FcGlobalCacheFileAdd (FcGlobalCache *cache,
588                       const FcChar8 *path,
589                       int           id,
590                       time_t        time,
591                       const FcChar8 *name,
592                       FcBool        replace)
593 {
594     FcFilePathInfo      i = FcFilePathInfoGet (path);
595     FcGlobalCacheDir    *d = FcGlobalCacheDirGet (cache, i.dir, 
596                                                   i.dir_len, FcTrue);
597     FcGlobalCacheFile   *f, **prev;
598     int                 size;
599
600     if (!d)
601         return 0;
602     for (prev = &d->ents[i.base_hash % FC_GLOBAL_CACHE_FILE_HASH_SIZE];
603          (f = *prev);
604          prev = &(*prev)->next)
605     {
606         if (f->info.hash == i.base_hash && 
607             f->id == id &&
608             !strcmp ((const char *) f->info.file, (const char *) i.base))
609         {
610             break;
611         }
612     }
613     if (*prev)
614     {
615         if (!replace)
616             return 0;
617
618         f = *prev;
619         if (f->info.referenced)
620             cache->referenced--;
621         *prev = f->next;
622         FcMemFree (FC_MEM_CACHE, sizeof (FcGlobalCacheFile) +
623                    strlen ((char *) f->info.file) + 1 +
624                    strlen ((char *) f->name) + 1);
625         free (f);
626     }
627     size = (sizeof (FcGlobalCacheFile) +
628             strlen ((char *) i.base) + 1 +
629             strlen ((char *) name) + 1);
630     f = malloc (size);
631     if (!f)
632         return 0;
633     FcMemAlloc (FC_MEM_CACHE, size);
634     f->next = *prev;
635     *prev = f;
636     f->info.hash = i.base_hash;
637     f->info.file = (FcChar8 *) (f + 1);
638     f->info.time = time;
639     f->info.referenced = FcFalse;
640     f->id = id;
641     f->name = f->info.file + strlen ((char *) i.base) + 1;
642     strcpy ((char *) f->info.file, (const char *) i.base);
643     strcpy ((char *) f->name, (const char *) name);
644     return &f->info;
645 }
646
647 FcGlobalCache *
648 FcGlobalCacheCreate (void)
649 {
650     FcGlobalCache   *cache;
651     int             h;
652
653     cache = malloc (sizeof (FcGlobalCache));
654     if (!cache)
655         return 0;
656     FcMemAlloc (FC_MEM_CACHE, sizeof (FcGlobalCache));
657     for (h = 0; h < FC_GLOBAL_CACHE_DIR_HASH_SIZE; h++)
658         cache->ents[h] = 0;
659     cache->entries = 0;
660     cache->referenced = 0;
661     cache->updated = FcFalse;
662     cache->broken = FcFalse;
663     return cache;
664 }
665
666 void
667 FcGlobalCacheDestroy (FcGlobalCache *cache)
668 {
669     FcGlobalCacheDir    *d, *next;
670     int                 h;
671
672     for (h = 0; h < FC_GLOBAL_CACHE_DIR_HASH_SIZE; h++)
673     {
674         for (d = cache->ents[h]; d; d = next)
675         {
676             next = d->next;
677             FcGlobalCacheDirDestroy (d);
678         }
679     }
680     FcMemFree (FC_MEM_CACHE, sizeof (FcGlobalCache));
681     free (cache);
682 }
683
684 /*
685  * Cache file syntax is quite simple:
686  *
687  * "file_name" id time "font_name" \n
688  */
689  
690 void
691 FcGlobalCacheLoad (FcGlobalCache    *cache,
692                    const FcChar8    *cache_file)
693 {
694     FILE                *f;
695     FcChar8             file_buf[8192], *file;
696     int                 id;
697     time_t              time;
698     FcChar8             name_buf[8192], *name;
699     FcGlobalCacheInfo   *info;
700
701     f = fopen ((char *) cache_file, "r");
702     if (!f)
703         return;
704
705     cache->updated = FcFalse;
706     file = 0;
707     name = 0;
708     while ((file = FcCacheReadString (f, file_buf, sizeof (file_buf))) &&
709            FcCacheReadInt (f, &id) &&
710            FcCacheReadTime (f, &time) &&
711            (name = FcCacheReadString (f, name_buf, sizeof (name_buf))))
712     {
713         if (FcDebug () & FC_DBG_CACHEV)
714             printf ("FcGlobalCacheLoad \"%s\" \"%20.20s\"\n", file, name);
715         if (!FcStrCmp (name, FC_FONT_FILE_DIR))
716             info = FcGlobalCacheDirAdd (cache, file, time, FcFalse);
717         else
718             info = FcGlobalCacheFileAdd (cache, file, id, time, name, FcFalse);
719         if (!info)
720             cache->broken = FcTrue;
721         else
722             cache->entries++;
723         if (FcDebug () & FC_DBG_CACHE_REF)
724             printf ("FcGlobalCacheLoad entry %d %s\n",
725                     cache->entries, file);
726         if (file != file_buf)
727             free (file);
728         if (name != name_buf)
729             free (name);
730         file = 0;
731         name = 0;
732     }
733     if (file && file != file_buf)
734         free (file);
735     if (name && name != name_buf)
736         free (name);
737     fclose (f);
738 }
739
740 FcBool
741 FcGlobalCacheUpdate (FcGlobalCache  *cache,
742                      const FcChar8  *file,
743                      int            id,
744                      const FcChar8  *name)
745 {
746     const FcChar8       *match;
747     struct stat         statb;
748     FcGlobalCacheInfo   *info;
749
750     match = file;
751
752     if (stat ((char *) file, &statb) < 0)
753         return FcFalse;
754     if (S_ISDIR (statb.st_mode))
755         info = FcGlobalCacheDirAdd (cache, file, statb.st_mtime, 
756                                    FcTrue);
757     else
758         info = FcGlobalCacheFileAdd (cache, file, id, statb.st_mtime, 
759                                     name, FcTrue);
760     if (info)
761     {
762         FcGlobalCacheReferenced (cache, info);
763         cache->updated = FcTrue;
764     }
765     else
766         cache->broken = FcTrue;
767     return info != 0;
768 }
769
770 FcBool
771 FcGlobalCacheSave (FcGlobalCache    *cache,
772                    const FcChar8    *cache_file)
773 {
774     FILE                *f;
775     int                 dir_hash, file_hash;
776     FcGlobalCacheDir    *dir;
777     FcGlobalCacheFile   *file;
778     FcAtomic            *atomic;
779
780     if (!cache->updated && cache->referenced == cache->entries)
781         return FcTrue;
782     
783     if (cache->broken)
784         return FcFalse;
785
786     /* Set-UID programs can't safely update the cache */
787     if (getuid () != geteuid ())
788         return FcFalse;
789     
790     atomic = FcAtomicCreate (cache_file);
791     if (!atomic)
792         goto bail0;
793     if (!FcAtomicLock (atomic))
794         goto bail1;
795     f = fopen ((char *) FcAtomicNewFile(atomic), "w");
796     if (!f)
797         goto bail2;
798
799     for (dir_hash = 0; dir_hash < FC_GLOBAL_CACHE_DIR_HASH_SIZE; dir_hash++)
800     {
801         for (dir = cache->ents[dir_hash]; dir; dir = dir->next)
802         {
803             if (!dir->info.referenced)
804                 continue;
805             if (!FcCacheWriteString (f, dir->info.file))
806                 goto bail4;
807             if (PUTC (' ', f) == EOF)
808                 goto bail4;
809             if (!FcCacheWriteInt (f, 0))
810                 goto bail4;
811             if (PUTC (' ', f) == EOF)
812                 goto bail4;
813             if (!FcCacheWriteTime (f, dir->info.time))
814                 goto bail4;
815             if (PUTC (' ', f) == EOF)
816                 goto bail4;
817             if (!FcCacheWriteString (f, (FcChar8 *) FC_FONT_FILE_DIR))
818                 goto bail4;
819             if (PUTC ('\n', f) == EOF)
820                 goto bail4;
821             
822             for (file_hash = 0; file_hash < FC_GLOBAL_CACHE_FILE_HASH_SIZE; file_hash++)
823             {
824                 for (file = dir->ents[file_hash]; file; file = file->next)
825                 {
826                     if (!file->info.referenced)
827                         continue;
828                     if (!FcCacheWritePath (f, dir->info.file, file->info.file))
829                         goto bail4;
830                     if (PUTC (' ', f) == EOF)
831                         goto bail4;
832                     if (!FcCacheWriteInt (f, file->id < 0 ? 0 : file->id))
833                         goto bail4;
834                     if (PUTC (' ', f) == EOF)
835                         goto bail4;
836                     if (!FcCacheWriteTime (f, file->info.time))
837                         goto bail4;
838                     if (PUTC (' ', f) == EOF)
839                         goto bail4;
840                     if (!FcCacheWriteString (f, file->name))
841                         goto bail4;
842                     if (PUTC ('\n', f) == EOF)
843                         goto bail4;
844                 }
845             }
846         }
847     }
848
849     if (fclose (f) == EOF)
850         goto bail3;
851     
852     if (!FcAtomicReplaceOrig (atomic))
853         goto bail3;
854     
855     FcAtomicUnlock (atomic);
856     FcAtomicDestroy (atomic);
857
858     cache->updated = FcFalse;
859     return FcTrue;
860
861 bail4:
862     fclose (f);
863 bail3:
864     FcAtomicDeleteNew (atomic);
865 bail2:
866     FcAtomicUnlock (atomic);
867 bail1:
868     FcAtomicDestroy (atomic);
869 bail0:
870     return FcFalse;
871 }
872
873 FcBool
874 FcDirCacheValid (const FcChar8 *dir)
875 {
876     FcChar8     *cache_file = FcStrPlus (dir, (FcChar8 *) "/" FC_DIR_CACHE_FILE);
877     struct stat file_stat, dir_stat;
878
879     if (stat ((char *) dir, &dir_stat) < 0)
880     {
881         FcStrFree (cache_file);
882         return FcFalse;
883     }
884     if (stat ((char *) cache_file, &file_stat) < 0)
885     {
886         FcStrFree (cache_file);
887         return FcFalse;
888     }
889     FcStrFree (cache_file);
890     /*
891      * If the directory has been modified more recently than
892      * the cache file, the cache is not valid
893      */
894     if (dir_stat.st_mtime - file_stat.st_mtime > 0)
895         return FcFalse;
896     return FcTrue;
897 }
898
899 FcBool
900 FcDirCacheReadDir (FcFontSet *set, FcStrSet *dirs, const FcChar8 *dir)
901 {
902     FcChar8         *cache_file = FcStrPlus (dir, (FcChar8 *) "/" FC_DIR_CACHE_FILE);
903     FILE            *f;
904     FcChar8         *base;
905     int             id;
906     int             dir_len;
907     FcChar8         file_buf[8192], *file;
908     FcChar8         name_buf[8192], *name;
909     FcBool          ret = FcFalse;
910
911     if (!cache_file)
912         goto bail0;
913     
914     if (FcDebug () & FC_DBG_CACHE)
915         printf ("FcDirCacheReadDir cache_file \"%s\"\n", cache_file);
916     
917     f = fopen ((char *) cache_file, "r");
918     if (!f)
919     {
920         if (FcDebug () & FC_DBG_CACHE)
921             printf (" no cache file\n");
922         goto bail1;
923     }
924
925     if (!FcDirCacheValid (dir))
926     {
927         if (FcDebug () & FC_DBG_CACHE)
928             printf (" cache file older than directory\n");
929         goto bail2;
930     }
931     
932     base = (FcChar8 *) strrchr ((char *) cache_file, '/');
933     if (!base)
934         goto bail2;
935     base++;
936     dir_len = base - cache_file;
937     
938     file = 0;
939     name = 0;
940     while ((file = FcCacheReadString (f, file_buf, sizeof (file_buf))) &&
941            FcCacheReadInt (f, &id) &&
942            (name = FcCacheReadString (f, name_buf, sizeof (name_buf))))
943     {
944         if (!FcCacheFontSetAdd (set, dirs, cache_file, dir_len,
945                                 file, name))
946             goto bail3;
947         if (file != file_buf)
948             free (file);
949         if (name != name_buf)
950             free (name);
951         file = name = 0;
952     }
953     if (FcDebug () & FC_DBG_CACHE)
954         printf (" cache loaded\n");
955     
956     ret = FcTrue;
957 bail3:
958     if (file && file != file_buf)
959         free (file);
960     if (name && name != name_buf)
961         free (name);
962 bail2:
963     fclose (f);
964 bail1:
965     FcStrFree (cache_file);
966 bail0:
967     return ret;
968 }
969
970 /*
971  * return the path from the directory containing 'cache' to 'file'
972  */
973
974 static const FcChar8 *
975 FcFileBaseName (const FcChar8 *cache, const FcChar8 *file)
976 {
977     const FcChar8   *cache_slash;
978
979     cache_slash = (const FcChar8 *) strrchr ((const char *) cache, '/');
980     if (cache_slash && !strncmp ((const char *) cache, (const char *) file,
981                                  (cache_slash + 1) - cache))
982         return file + ((cache_slash + 1) - cache);
983     return file;
984 }
985
986 FcBool
987 FcDirCacheWriteDir (FcFontSet *set, FcStrSet *dirs, const FcChar8 *dir)
988 {
989     FcChar8         *cache_file = FcStrPlus (dir, (FcChar8 *) "/" FC_DIR_CACHE_FILE);
990     FcPattern       *font;
991     FILE            *f;
992     FcChar8         *name;
993     const FcChar8   *file, *base;
994     int             n;
995     int             id;
996     FcBool          ret;
997     FcStrList       *list;
998
999     if (!cache_file)
1000         goto bail0;
1001     if (FcDebug () & FC_DBG_CACHE)
1002         printf ("FcDirCacheWriteDir cache_file \"%s\"\n", cache_file);
1003     
1004     f = fopen ((char *) cache_file, "w");
1005     if (!f)
1006     {
1007         if (FcDebug () & FC_DBG_CACHE)
1008             printf (" can't create \"%s\"\n", cache_file);
1009         goto bail1;
1010     }
1011     
1012     list = FcStrListCreate (dirs);
1013     if (!list)
1014         goto bail2;
1015     
1016     while ((dir = FcStrListNext (list)))
1017     {
1018         base = FcFileBaseName (cache_file, dir);
1019         if (!FcCacheWriteString (f, base))
1020             goto bail3;
1021         if (PUTC (' ', f) == EOF)
1022             goto bail3;
1023         if (!FcCacheWriteInt (f, 0))
1024             goto bail3;
1025         if (PUTC (' ', f) == EOF)
1026             goto bail3;
1027         if (!FcCacheWriteString (f, FC_FONT_FILE_DIR))
1028             goto bail3;
1029         if (PUTC ('\n', f) == EOF)
1030             goto bail3;
1031     }
1032     
1033     for (n = 0; n < set->nfont; n++)
1034     {
1035         font = set->fonts[n];
1036         if (FcPatternGetString (font, FC_FILE, 0, (FcChar8 **) &file) != FcResultMatch)
1037             goto bail3;
1038         base = FcFileBaseName (cache_file, file);
1039         if (FcPatternGetInteger (font, FC_INDEX, 0, &id) != FcResultMatch)
1040             goto bail3;
1041         if (FcDebug () & FC_DBG_CACHEV)
1042             printf (" write file \"%s\"\n", base);
1043         if (!FcCacheWriteString (f, base))
1044             goto bail3;
1045         if (PUTC (' ', f) == EOF)
1046             goto bail3;
1047         if (!FcCacheWriteInt (f, id))
1048             goto bail3;
1049         if (PUTC (' ', f) == EOF)
1050             goto bail3;
1051         name = FcNameUnparse (font);
1052         if (!name)
1053             goto bail3;
1054         ret = FcCacheWriteString (f, name);
1055         FcStrFree (name);
1056         if (!ret)
1057             goto bail3;
1058         if (PUTC ('\n', f) == EOF)
1059             goto bail3;
1060     }
1061     
1062     FcStrListDone (list);
1063
1064     if (fclose (f) == EOF)
1065         goto bail1;
1066     
1067     FcStrFree (cache_file);
1068
1069     if (FcDebug () & FC_DBG_CACHE)
1070         printf (" cache written\n");
1071     return FcTrue;
1072     
1073 bail3:
1074     FcStrListDone (list);
1075 bail2:
1076     fclose (f);
1077 bail1:
1078     unlink ((char *) cache_file);
1079     FcStrFree (cache_file);
1080 bail0:
1081     return FcFalse;
1082 }