Browse code

Use tty_interface_t to communicate exit

John Hawthorn authored on 20/06/2016 06:40:44
Showing 1 changed files

... ...
@@ -87,10 +87,14 @@ static void draw(tty_interface_t *state) {
87 87
 	tty_flush(tty);
88 88
 }
89 89
 
90
-static void emit(tty_interface_t *state) {
91
-	choices_t *choices = state->choices;
90
+static void action_emit(tty_interface_t *state) {
91
+	/* Reset the tty as close as possible to the previous state */
92
+	clear(state);
93
+
94
+	/* ttyout should be flushed before outputting on stdout */
95
+	tty_close(state->tty);
92 96
 
93
-	const char *selection = choices_get(choices, choices->selection);
97
+	const char *selection = choices_get(state->choices, state->choices->selection);
94 98
 	if (selection) {
95 99
 		/* output the selected result */
96 100
 		printf("%s\n", selection);
... ...
@@ -98,6 +102,8 @@ static void emit(tty_interface_t *state) {
98 102
 		/* No match, output the query instead */
99 103
 		printf("%s\n", state->search);
100 104
 	}
105
+
106
+	state->exit = EXIT_SUCCESS;
101 107
 }
102 108
 
103 109
 #define KEY_CTRL(key) ((key) - ('@'))
... ...
@@ -109,6 +115,8 @@ void tty_interface_init(tty_interface_t *state, tty_t *tty, choices_t *choices,
109 115
 	state->choices = choices;
110 116
 	state->options = options;
111 117
 
118
+	state->exit = -1;
119
+
112 120
 	if (options->init_search)
113 121
 		strncpy(state->search, options->init_search, SEARCH_SIZE_MAX);
114 122
 }
... ...
@@ -120,7 +128,7 @@ int tty_interface_run(tty_interface_t *state) {
120 128
 
121 129
 	choices_search(choices, search);
122 130
 	char ch;
123
-	do {
131
+	while (state->exit < 0) {
124 132
 		draw(state);
125 133
 		ch = tty_getchar(tty);
126 134
 		size_t search_size = strlen(search);
... ...
@@ -154,17 +162,9 @@ int tty_interface_run(tty_interface_t *state) {
154 162
 		} else if (ch == KEY_CTRL('C') || ch == KEY_CTRL('D')) { /* ^C || ^D */
155 163
 			clear(state);
156 164
 			tty_close(tty);
157
-			exit(EXIT_FAILURE);
165
+			state->exit = EXIT_FAILURE;
158 166
 		} else if (ch == KEY_CTRL('M')) { /* CR */
159
-			clear(state);
160
-
161
-			/* ttyout should be flushed before outputting on stdout */
162
-			tty_close(tty);
163
-
164
-			emit(state);
165
-
166
-			/* Return to eventually exit successfully */
167
-			return 0;
167
+			action_emit(state);
168 168
 		} else if (ch == KEY_ESC) { /* ESC */
169 169
 			ch = tty_getchar(tty);
170 170
 			if (ch == '[' || ch == 'O') {
... ...
@@ -176,7 +176,7 @@ int tty_interface_run(tty_interface_t *state) {
176 176
 				}
177 177
 			}
178 178
 		}
179
-	} while (1);
179
+	}
180 180
 
181
-	return 0;
181
+	return state->exit;
182 182
 }