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