8 #include <sys/select.h>
10 #include "color_reader.h"
16 static int byte_from_hex(const char* s
, unsigned char* out
) {
17 static const char hex
[] = "0123456789abcdef";
18 char* h1
= strchr(hex
, s
[0]);
19 char* h2
= strchr(hex
, s
[1]);
20 if(!h1
|| !h2
) return 1;
21 *out
= ((h1
- hex
) << 4) | (h2
- hex
);
25 int color_reader_init(struct color_reader
*cr
) {
26 if(-1==(cr
->fd
= open("/dev/tty", O_RDWR
|O_CLOEXEC
))) return 1;
27 if(-1==tcgetattr(cr
->fd
, &cr
->t
)) goto err
;
28 struct termios
new = cr
->t
;
30 new.c_oflag
&= ~OPOST
;
31 new.c_lflag
&= ~(ISIG
| ICANON
| ECHO
| XCASE
);
34 if(-1==tcsetattr(cr
->fd
, TCSAFLUSH
, &new)) goto err
;
42 int color_reader_get_color(struct color_reader
*cr
, int colnr
, rgb_t
*out
) {
47 dprintf(cr
->fd
, "\x1b]4;%d;?\x1b\x5c", colnr
);
49 FD_SET(cr
->fd
, &reed
);
50 while(select(cr
->fd
+1, &reed
, 0, 0, 0)<=0);
51 for(l
=0,p
=buf
;l
<sizeof(buf
);l
++,p
++) {
53 if(1==(rd
=read(cr
->fd
, p
, 1))) continue;
58 if(memcmp(p
,"\x1b]4;",4)) return 4;
60 while(l
>4 && memcmp(p
,"rgb:",4)) p
++,l
--;
63 if(byte_from_hex(p
, &out
->r
)) return 6;
65 if(byte_from_hex(p
, &out
->g
)) return 7;
67 if(byte_from_hex(p
, &out
->b
)) return 8;
70 int color_reader_close(struct color_reader
*cr
) {
72 if(tcsetattr(cr
->fd
, TCSAFLUSH
, &cr
->t
)==-1) err
=1;