switched from wpitchoune@gmail.com to jeanfi@gmail.com (my usual email)
[psensor.git] / src / lib / color.c
1 /*
2     Copyright (C) 2010-2011 jeanfi@gmail.com
3
4     This program is free software; you can redistribute it and/or modify
5     it under the terms of the GNU General Public License as published by
6     the Free Software Foundation; either version 2 of the License, or
7     (at your option) any later version.
8
9     This program is distributed in the hope that it will be useful,
10     but WITHOUT ANY WARRANTY; without even the implied warranty of
11     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12     GNU General Public License for more details.
13
14     You should have received a copy of the GNU General Public License
15     along with this program; if not, write to the Free Software
16     Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
17     02110-1301 USA
18 */
19
20 #include <stdlib.h>
21 #include <stdio.h>
22 #include <ctype.h>
23 #include <string.h>
24
25 #include "color.h"
26
27 void
28 color_set(struct color *color,
29           unsigned int red, unsigned int green, unsigned int blue)
30 {
31         color->red = red;
32         color->green = green;
33         color->blue = blue;
34
35         color->f_red = ((double)color->red) / 65535;
36         color->f_green = ((double)color->green) / 65535;
37         color->f_blue = ((double)color->blue) / 65535;
38 }
39
40 struct color *color_new(unsigned int red, unsigned int green, unsigned int blue)
41 {
42         struct color *color = malloc(sizeof(struct color));
43
44         color_set(color, red, green, blue);
45
46         return color;
47 }
48
49 struct color *color_dup(struct color *color)
50 {
51         return color_new(color->red, color->green, color->blue);
52 }
53
54 int is_color(const char *str)
55 {
56         int n = strlen(str);
57         int i;
58
59         if (n != 13 || str[0] != '#')
60                 return 0;
61
62         for (i = 1; i < n; i++)
63                 if (isxdigit(str[i]) == 0)
64                         return 0;
65
66         return 1;
67 }
68
69 struct color *string_to_color(const char *str)
70 {
71         char tmp[5];
72         unsigned int red, green, blue;
73
74         if (!is_color(str))
75                 return NULL;
76
77         strncpy(tmp, str + 1, 4);
78         tmp[4] = '\0';
79         red = strtol(tmp, NULL, 16);
80
81         strncpy(tmp, str + 5, 4);
82         tmp[4] = '\0';
83         green = strtol(tmp, NULL, 16);
84
85         strncpy(tmp, str + 9, 4);
86         tmp[4] = '\0';
87         blue = strtol(tmp, NULL, 16);
88
89         return color_new(red, green, blue);
90 }
91
92 char *color_to_string(struct color *color)
93 {
94         char *str = malloc(1 + 12 + 1);
95
96         sprintf(str, "#%.4x%.4x%.4x", color->red, color->green, color->blue);
97
98         return str;
99 }