1 #include "common.h"
2 
3 #include <stdlib.h>
4 #include <string.h>
5 
6 #include "image.h"
7 
8 /* attach a string key'd data and/or int value to an image that cna be */
9 /* looked up later by its string key */
10 __EXPORT__ void
__imlib_AttachTag(ImlibImage * im,const char * key,int val,void * data,ImlibDataDestructorFunction destructor)11 __imlib_AttachTag(ImlibImage * im, const char *key, int val, void *data,
12                   ImlibDataDestructorFunction destructor)
13 {
14    ImlibImageTag      *t;
15 
16    /* no string key? abort */
17    if (!key)
18       return;
19 
20    /* if a tag of that name already exists - remove it and free it */
21    if ((t = __imlib_RemoveTag(im, key)))
22       __imlib_FreeTag(im, t);
23    /* allocate the struct */
24    t = malloc(sizeof(ImlibImageTag));
25    /* fill it int */
26    t->key = strdup(key);
27    t->val = val;
28    t->data = data;
29    t->destructor = destructor;
30    t->next = im->tags;
31    /* prepend it to the list of tags */
32    im->tags = t;
33 }
34 
35 /* look up a tage by its key on the image it was attached to */
36 __EXPORT__ ImlibImageTag *
__imlib_GetTag(const ImlibImage * im,const char * key)37 __imlib_GetTag(const ImlibImage * im, const char *key)
38 {
39    ImlibImageTag      *t;
40 
41    t = im->tags;
42    while (t)
43      {
44         if (!strcmp(t->key, key))
45            return t;
46         t = t->next;
47      }
48    /* no tag found - return NULL */
49    return NULL;
50 }
51 
52 /* remove a tag by looking it up by its key and removing it from */
53 /* the list of keys */
54 ImlibImageTag      *
__imlib_RemoveTag(ImlibImage * im,const char * key)55 __imlib_RemoveTag(ImlibImage * im, const char *key)
56 {
57    ImlibImageTag      *t, *tt;
58 
59    tt = NULL;
60    t = im->tags;
61    while (t)
62      {
63         if (!strcmp(t->key, key))
64           {
65              if (tt)
66                 tt->next = t->next;
67              else
68                 im->tags = t->next;
69              return t;
70           }
71         tt = t;
72         t = t->next;
73      }
74    /* no tag found - NULL */
75    return NULL;
76 }
77 
78 /* free the data struct for the tag and if a destructor function was */
79 /* provided call it on the data member */
80 void
__imlib_FreeTag(ImlibImage * im,ImlibImageTag * t)81 __imlib_FreeTag(ImlibImage * im, ImlibImageTag * t)
82 {
83    free(t->key);
84    if (t->destructor)
85       t->destructor(im, t->data);
86    free(t);
87 }
88 
89 /* free all the tags attached to an image */
90 void
__imlib_FreeAllTags(ImlibImage * im)91 __imlib_FreeAllTags(ImlibImage * im)
92 {
93    ImlibImageTag      *t, *tt;
94 
95    t = im->tags;
96    while (t)
97      {
98         tt = t;
99         t = t->next;
100         __imlib_FreeTag(im, tt);
101      }
102 }
103