Browse code

Extract ANSI CSI SGR calls into tty.c

John Hawthorn authored on 04/08/2014 07:08:10
Showing 3 changed files

  • fzy.c index ad294bb..f1f1659 100644
  • tty.c index 4f434b5..387ea6f 100644
  • tty.h index 82ab0ac..aa59d2e 100644
... ...
@@ -106,17 +106,20 @@ void draw_match(tty_t *tty, const char *choice, int selected){
106 106
 
107 107
 	match_positions(search, choice, &positions[0]);
108 108
 
109
+	if(selected)
110
+		tty_setinvert(tty);
111
+
109 112
 	for(size_t i = 0, p = 0; choice[i] != '\0'; i++){
110 113
 		if(positions[p] == i){
111
-			fprintf(tty->fout, "%c%c33m", 0x1b, '[');
114
+			tty_setfg(tty, 3);
112 115
 			p++;
113 116
 		}else{
114
-			fprintf(tty->fout, "%c%c39;49m", 0x1b, '[');
117
+			tty_setfg(tty, 9);
115 118
 		}
116 119
 		fprintf(tty->fout, "%c", choice[i]);
117 120
 	}
118 121
 	fprintf(tty->fout, "\n");
119
-	fprintf(tty->fout, "%c%c0m", 0x1b, '[');
122
+	tty_setnormal(tty);
120 123
 }
121 124
 
122 125
 void draw(tty_t *tty){
... ...
@@ -125,8 +128,6 @@ void draw(tty_t *tty){
125 128
 	clear(tty);
126 129
 	fprintf(tty->fout, "%s%s\n", prompt, search);
127 130
 	for(size_t i = 0; line < NUMLINES && i < choices_available; i++){
128
-		if(i == current_selection)
129
-			fprintf(tty->fout, "%c%c7m", 0x1b, '[');
130 131
 		draw_match(tty, choices[choices_sorted[i]], i == current_selection);
131 132
 		line++;
132 133
 	}
... ...
@@ -20,6 +20,8 @@ void tty_init(tty_t *tty){
20 20
 	new_termios.c_lflag &= ~(ICANON | ECHO);
21 21
 
22 22
 	tcsetattr(tty->fdin, TCSANOW, &new_termios);
23
+
24
+	tty_setnormal(tty);
23 25
 }
24 26
 
25 27
 char tty_getchar(tty_t *tty){
... ...
@@ -36,3 +38,23 @@ char tty_getchar(tty_t *tty){
36 38
 	}
37 39
 }
38 40
 
41
+static void tty_sgr(tty_t *tty, int code){
42
+	fprintf(tty->fout, "%c%c%im", 0x1b, '[', code);
43
+}
44
+
45
+void tty_setfg(tty_t *tty, int fg){
46
+	if(tty->fgcolor != fg){
47
+		tty_sgr(tty, 30 + fg);
48
+		tty->fgcolor = fg;
49
+	}
50
+}
51
+
52
+void tty_setinvert(tty_t *tty){
53
+	tty_sgr(tty, 7);
54
+}
55
+
56
+void tty_setnormal(tty_t *tty){
57
+	tty_sgr(tty, 0);
58
+	tty->fgcolor = 9;
59
+}
60
+
... ...
@@ -7,10 +7,16 @@ typedef struct{
7 7
 	int fdin;
8 8
 	FILE *fout;
9 9
 	struct termios original_termios;
10
+	int fgcolor;
10 11
 } tty_t;
11 12
 
12 13
 void tty_reset(tty_t *tty);
13 14
 void tty_init(tty_t *tty);
14 15
 char tty_getchar(tty_t *tty);
15 16
 
17
+void tty_setfg(tty_t *tty, int fg);
18
+void tty_setinvert(tty_t *tty);
19
+void tty_setnormal(tty_t *tty);
20
+
21
+
16 22
 #endif