Merge tag 'upstream/1.2.0'
[psensor-pkg-debian.git] / src / lib / color.c
1 /*
2  * Copyright (C) 2010-2016 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 color_set(struct color *c, double r, double g, double b)
27 {
28         c->red = r;
29         c->green = g;
30         c->blue = b;
31 }
32
33 struct color *color_new(double r, double g, double b)
34 {
35         struct color *color;
36
37         color = malloc(sizeof(struct color));
38
39         color_set(color, r, g, b);
40
41         return color;
42 }
43
44 struct color *color_dup(struct color *color)
45 {
46         return color_new(color->red, color->green, color->blue);
47 }
48
49 int is_color(const char *str)
50 {
51         int n = strlen(str);
52         int i;
53
54         if (n != 13 || str[0] != '#')
55                 return 0;
56
57         for (i = 1; i < n; i++)
58                 if (isxdigit(str[i]) == 0)
59                         return 0;
60
61         return 1;
62 }
63
64 struct color *str_to_color(const char *str)
65 {
66         char tmp[5];
67         unsigned int red, green, blue;
68
69         if (!is_color(str))
70                 return NULL;
71
72         strncpy(tmp, str + 1, 4);
73         tmp[4] = '\0';
74         red = strtol(tmp, NULL, 16);
75
76         strncpy(tmp, str + 5, 4);
77         tmp[4] = '\0';
78         green = strtol(tmp, NULL, 16);
79
80         strncpy(tmp, str + 9, 4);
81         tmp[4] = '\0';
82         blue = strtol(tmp, NULL, 16);
83
84         return color_new(((double)red)/65535,
85                          ((double)green)/65535,
86                          ((double)blue)/65535);
87 }
88
89 char *color_to_str(const struct color *color)
90 {
91         char *str = malloc(1 + 12 + 1);
92
93         sprintf(str, "#%.4x%.4x%.4x",
94                 (int)(65535 * color->red),
95                 (int)(65535 * color->green),
96                 (int)(65535 * color->blue));
97
98         return str;
99 }