1 /*
2  * Copyright (c) 2018 Nordic Semiconductor ASA
3  *
4  * SPDX-License-Identifier: Apache-2.0
5  */
6 
7 #include <ctype.h>
8 #include "shell_ops.h"
9 
10 #define CMD_CURSOR_LEN 8
z_shell_op_cursor_vert_move(const struct shell * sh,int32_t delta)11 void z_shell_op_cursor_vert_move(const struct shell *sh, int32_t delta)
12 {
13 	char dir = delta > 0 ? 'A' : 'B';
14 
15 	if (delta == 0) {
16 		return;
17 	}
18 
19 	if (delta < 0) {
20 		delta = -delta;
21 	}
22 
23 	Z_SHELL_VT100_CMD(sh, "\e[%d%c", delta, dir);
24 }
25 
z_shell_op_cursor_horiz_move(const struct shell * sh,int32_t delta)26 void z_shell_op_cursor_horiz_move(const struct shell *sh, int32_t delta)
27 {
28 	char dir = delta > 0 ? 'C' : 'D';
29 
30 	if (delta == 0) {
31 		return;
32 	}
33 
34 	if (delta < 0) {
35 		delta = -delta;
36 	}
37 
38 	Z_SHELL_VT100_CMD(sh, "\e[%d%c", delta, dir);
39 }
40 
41 /* Function returns true if command length is equal to multiplicity of terminal
42  * width.
43  */
full_line_cmd(const struct shell * sh)44 static inline bool full_line_cmd(const struct shell *sh)
45 {
46 	size_t line_length = sh->ctx->cmd_buff_len + z_shell_strlen(sh->ctx->prompt);
47 
48 	if (line_length == 0) {
49 		return false;
50 	}
51 
52 	return (line_length % sh->ctx->vt100_ctx.cons.terminal_wid == 0U);
53 }
54 
55 /* Function returns true if cursor is at beginning of an empty line. */
z_shell_cursor_in_empty_line(const struct shell * sh)56 bool z_shell_cursor_in_empty_line(const struct shell *sh)
57 {
58 	return (((sh->ctx->cmd_buff_pos * sh->ctx->cfg.flags.echo) +
59 		 z_shell_strlen(sh->ctx->prompt)) %
60 			sh->ctx->vt100_ctx.cons.terminal_wid ==
61 		0U);
62 }
63 
z_shell_op_cond_next_line(const struct shell * sh)64 void z_shell_op_cond_next_line(const struct shell *sh)
65 {
66 	if (z_shell_cursor_in_empty_line(sh) || full_line_cmd(sh)) {
67 		z_cursor_next_line_move(sh);
68 	}
69 }
70 
z_shell_op_cursor_position_synchronize(const struct shell * sh)71 void z_shell_op_cursor_position_synchronize(const struct shell *sh)
72 {
73 	struct shell_multiline_cons *cons = &sh->ctx->vt100_ctx.cons;
74 	bool last_line;
75 
76 	z_shell_multiline_data_calc(cons, sh->ctx->cmd_buff_pos,
77 				    sh->ctx->cmd_buff_len);
78 	last_line = (cons->cur_y == cons->cur_y_end);
79 
80 	/* In case cursor reaches the bottom line of a terminal, it will
81 	 * be moved to the next line.
82 	 */
83 	if (full_line_cmd(sh)) {
84 		z_cursor_next_line_move(sh);
85 	}
86 
87 	if (last_line) {
88 		z_shell_op_cursor_horiz_move(sh, cons->cur_x -
89 							       cons->cur_x_end);
90 	} else {
91 		z_shell_op_cursor_vert_move(sh, cons->cur_y_end - cons->cur_y);
92 		z_shell_op_cursor_horiz_move(sh, cons->cur_x -
93 							       cons->cur_x_end);
94 	}
95 }
96 
z_shell_op_cursor_move(const struct shell * sh,int16_t val)97 void z_shell_op_cursor_move(const struct shell *sh, int16_t val)
98 {
99 	struct shell_multiline_cons *cons = &sh->ctx->vt100_ctx.cons;
100 	uint16_t new_pos = sh->ctx->cmd_buff_pos + val;
101 	int32_t row_span;
102 	int32_t col_span;
103 
104 	z_shell_multiline_data_calc(cons, sh->ctx->cmd_buff_pos,
105 				    sh->ctx->cmd_buff_len);
106 
107 	/* Calculate the new cursor. */
108 	row_span = z_row_span_with_buffer_offsets_get(
109 						&sh->ctx->vt100_ctx.cons,
110 						sh->ctx->cmd_buff_pos,
111 						new_pos);
112 	col_span = z_column_span_with_buffer_offsets_get(
113 						&sh->ctx->vt100_ctx.cons,
114 						sh->ctx->cmd_buff_pos,
115 						new_pos);
116 
117 	z_shell_op_cursor_vert_move(sh, -row_span);
118 	z_shell_op_cursor_horiz_move(sh, col_span);
119 	sh->ctx->cmd_buff_pos = new_pos;
120 }
121 
shift_calc(const char * str,uint16_t pos,uint16_t len,int16_t sign)122 static uint16_t shift_calc(const char *str, uint16_t pos, uint16_t len, int16_t sign)
123 {
124 	bool found = false;
125 	uint16_t ret = 0U;
126 	uint16_t idx;
127 
128 	while (1) {
129 		idx = pos + ret * sign;
130 		if (((idx == 0U) && (sign < 0)) ||
131 		    ((idx == len) && (sign > 0))) {
132 			break;
133 		}
134 		if (isalnum((int)str[idx]) != 0) {
135 			found = true;
136 		} else {
137 			if (found) {
138 				break;
139 			}
140 		}
141 		ret++;
142 	}
143 
144 	return ret;
145 }
146 
z_shell_op_cursor_word_move(const struct shell * sh,int16_t val)147 void z_shell_op_cursor_word_move(const struct shell *sh, int16_t val)
148 {
149 	int16_t shift;
150 	int16_t sign;
151 
152 	if (val < 0) {
153 		val = -val;
154 		sign = -1;
155 	} else {
156 		sign = 1;
157 	}
158 
159 	while (val--) {
160 		shift = shift_calc(sh->ctx->cmd_buff,
161 				   sh->ctx->cmd_buff_pos,
162 				   sh->ctx->cmd_buff_len, sign);
163 		z_shell_op_cursor_move(sh, sign * shift);
164 	}
165 }
166 
z_shell_op_word_remove(const struct shell * sh)167 void z_shell_op_word_remove(const struct shell *sh)
168 {
169 	/* Line must not be empty and cursor must not be at 0 to continue. */
170 	if ((sh->ctx->cmd_buff_len == 0) ||
171 	    (sh->ctx->cmd_buff_pos == 0)) {
172 		return;
173 	}
174 
175 	char *str = &sh->ctx->cmd_buff[sh->ctx->cmd_buff_pos - 1];
176 	char *str_start = &sh->ctx->cmd_buff[0];
177 	uint16_t chars_to_delete;
178 
179 	/* Start at the current position. */
180 	chars_to_delete = 0U;
181 
182 	/* Look back for all spaces then for non-spaces. */
183 	while ((str >= str_start) && (*str == ' ')) {
184 		++chars_to_delete;
185 		--str;
186 	}
187 
188 	while ((str >= str_start) && (*str != ' ')) {
189 		++chars_to_delete;
190 		--str;
191 	}
192 
193 	/* Manage the buffer. */
194 	memmove(str + 1, str + 1 + chars_to_delete,
195 		sh->ctx->cmd_buff_len - chars_to_delete);
196 	sh->ctx->cmd_buff_len -= chars_to_delete;
197 	sh->ctx->cmd_buff[sh->ctx->cmd_buff_len] = '\0';
198 
199 	/* Update display. */
200 	z_shell_op_cursor_move(sh, -chars_to_delete);
201 	z_cursor_save(sh);
202 	z_shell_fprintf(sh, SHELL_NORMAL, "%s", str + 1);
203 	z_clear_eos(sh);
204 	z_cursor_restore(sh);
205 }
206 
z_shell_op_cursor_home_move(const struct shell * sh)207 void z_shell_op_cursor_home_move(const struct shell *sh)
208 {
209 	z_shell_op_cursor_move(sh, -sh->ctx->cmd_buff_pos);
210 }
211 
z_shell_op_cursor_end_move(const struct shell * sh)212 void z_shell_op_cursor_end_move(const struct shell *sh)
213 {
214 	z_shell_op_cursor_move(sh, sh->ctx->cmd_buff_len -
215 						sh->ctx->cmd_buff_pos);
216 }
217 
z_shell_op_left_arrow(const struct shell * sh)218 void z_shell_op_left_arrow(const struct shell *sh)
219 {
220 	if (sh->ctx->cmd_buff_pos > 0) {
221 		z_shell_op_cursor_move(sh, -1);
222 	}
223 }
224 
z_shell_op_right_arrow(const struct shell * sh)225 void z_shell_op_right_arrow(const struct shell *sh)
226 {
227 	if (sh->ctx->cmd_buff_pos < sh->ctx->cmd_buff_len) {
228 		z_shell_op_cursor_move(sh, 1);
229 	}
230 }
231 
reprint_from_cursor(const struct shell * sh,uint16_t diff,bool data_removed)232 static void reprint_from_cursor(const struct shell *sh, uint16_t diff,
233 				bool data_removed)
234 {
235 	/* Clear eos is needed only when newly printed command is shorter than
236 	 * previously printed command. This can happen when delete or backspace
237 	 * was called.
238 	 *
239 	 * Such condition is useful for Bluetooth devices to save number of
240 	 * bytes transmitted between terminal and device.
241 	 */
242 	if (data_removed) {
243 		z_clear_eos(sh);
244 	}
245 
246 	if (z_flag_obscure_get(sh)) {
247 		int len = strlen(&sh->ctx->cmd_buff[sh->ctx->cmd_buff_pos]);
248 
249 		while (len--) {
250 			z_shell_raw_fprintf(sh->fprintf_ctx, "*");
251 		}
252 	} else {
253 		z_shell_fprintf(sh, SHELL_NORMAL, "%s",
254 			      &sh->ctx->cmd_buff[sh->ctx->cmd_buff_pos]);
255 	}
256 	sh->ctx->cmd_buff_pos = sh->ctx->cmd_buff_len;
257 
258 	if (full_line_cmd(sh)) {
259 		if (((data_removed) && (diff > 0)) || (!data_removed)) {
260 			z_cursor_next_line_move(sh);
261 		}
262 	}
263 
264 	z_shell_op_cursor_move(sh, -diff);
265 }
266 
data_insert(const struct shell * sh,const char * data,uint16_t len)267 static void data_insert(const struct shell *sh, const char *data, uint16_t len)
268 {
269 	uint16_t after = sh->ctx->cmd_buff_len - sh->ctx->cmd_buff_pos;
270 	char *curr_pos = &sh->ctx->cmd_buff[sh->ctx->cmd_buff_pos];
271 
272 	if ((sh->ctx->cmd_buff_len + len) >= CONFIG_SHELL_CMD_BUFF_SIZE) {
273 		return;
274 	}
275 
276 	memmove(curr_pos + len, curr_pos, after);
277 	memcpy(curr_pos, data, len);
278 	sh->ctx->cmd_buff_len += len;
279 	sh->ctx->cmd_buff[sh->ctx->cmd_buff_len] = '\0';
280 
281 	if (!z_flag_echo_get(sh)) {
282 		sh->ctx->cmd_buff_pos += len;
283 		return;
284 	}
285 
286 	reprint_from_cursor(sh, after, false);
287 }
288 
char_replace(const struct shell * sh,char data)289 static void char_replace(const struct shell *sh, char data)
290 {
291 	sh->ctx->cmd_buff[sh->ctx->cmd_buff_pos++] = data;
292 
293 	if (!z_flag_echo_get(sh)) {
294 		return;
295 	}
296 	if (z_flag_obscure_get(sh)) {
297 		data = '*';
298 	}
299 
300 	z_shell_raw_fprintf(sh->fprintf_ctx, "%c", data);
301 	if (z_shell_cursor_in_empty_line(sh)) {
302 		z_cursor_next_line_move(sh);
303 	}
304 }
305 
z_shell_op_char_insert(const struct shell * sh,char data)306 void z_shell_op_char_insert(const struct shell *sh, char data)
307 {
308 	if (z_flag_insert_mode_get(sh) &&
309 	    (sh->ctx->cmd_buff_len != sh->ctx->cmd_buff_pos)) {
310 		char_replace(sh, data);
311 	} else {
312 		data_insert(sh, &data, 1);
313 	}
314 }
315 
z_shell_op_char_backspace(const struct shell * sh)316 void z_shell_op_char_backspace(const struct shell *sh)
317 {
318 	if ((sh->ctx->cmd_buff_len == 0) ||
319 	    (sh->ctx->cmd_buff_pos == 0)) {
320 		return;
321 	}
322 
323 	z_shell_op_cursor_move(sh, -1);
324 	z_shell_op_char_delete(sh);
325 }
326 
z_shell_op_char_delete(const struct shell * sh)327 void z_shell_op_char_delete(const struct shell *sh)
328 {
329 	uint16_t diff = sh->ctx->cmd_buff_len - sh->ctx->cmd_buff_pos;
330 	char *str = &sh->ctx->cmd_buff[sh->ctx->cmd_buff_pos];
331 
332 	if (diff == 0U) {
333 		return;
334 	}
335 
336 	memmove(str, str + 1, diff);
337 	--sh->ctx->cmd_buff_len;
338 	reprint_from_cursor(sh, --diff, true);
339 }
340 
z_shell_op_delete_from_cursor(const struct shell * sh)341 void z_shell_op_delete_from_cursor(const struct shell *sh)
342 {
343 	sh->ctx->cmd_buff_len = sh->ctx->cmd_buff_pos;
344 	sh->ctx->cmd_buff[sh->ctx->cmd_buff_pos] = '\0';
345 
346 	z_clear_eos(sh);
347 }
348 
z_shell_op_completion_insert(const struct shell * sh,const char * compl,uint16_t compl_len)349 void z_shell_op_completion_insert(const struct shell *sh,
350 				  const char *compl,
351 				  uint16_t compl_len)
352 {
353 	data_insert(sh, compl, compl_len);
354 }
355 
z_shell_cmd_line_erase(const struct shell * sh)356 void z_shell_cmd_line_erase(const struct shell *sh)
357 {
358 	z_shell_multiline_data_calc(&sh->ctx->vt100_ctx.cons,
359 				    sh->ctx->cmd_buff_pos,
360 				    sh->ctx->cmd_buff_len);
361 	z_shell_op_cursor_horiz_move(sh,
362 				   -(sh->ctx->vt100_ctx.cons.cur_x - 1));
363 	z_shell_op_cursor_vert_move(sh, sh->ctx->vt100_ctx.cons.cur_y - 1);
364 
365 	z_clear_eos(sh);
366 }
367 
print_prompt(const struct shell * sh)368 static void print_prompt(const struct shell *sh)
369 {
370 	z_shell_fprintf(sh, SHELL_INFO, "%s", sh->ctx->prompt);
371 }
372 
z_shell_print_cmd(const struct shell * sh)373 void z_shell_print_cmd(const struct shell *sh)
374 {
375 	int beg_offset = 0;
376 	int end_offset = 0;
377 	int cmd_width = z_shell_strlen(sh->ctx->cmd_buff);
378 	int adjust = sh->ctx->vt100_ctx.cons.name_len;
379 	char ch;
380 
381 	while (cmd_width > sh->ctx->vt100_ctx.cons.terminal_wid - adjust) {
382 		end_offset += sh->ctx->vt100_ctx.cons.terminal_wid - adjust;
383 		ch = sh->ctx->cmd_buff[end_offset];
384 		sh->ctx->cmd_buff[end_offset] = '\0';
385 
386 		z_shell_raw_fprintf(sh->fprintf_ctx, "%s\n",
387 				&sh->ctx->cmd_buff[beg_offset]);
388 
389 		sh->ctx->cmd_buff[end_offset] = ch;
390 		cmd_width -= (sh->ctx->vt100_ctx.cons.terminal_wid - adjust);
391 		beg_offset = end_offset;
392 		adjust = 0;
393 	}
394 	if (cmd_width > 0) {
395 		z_shell_raw_fprintf(sh->fprintf_ctx, "%s",
396 				&sh->ctx->cmd_buff[beg_offset]);
397 	}
398 }
399 
z_shell_print_prompt_and_cmd(const struct shell * sh)400 void z_shell_print_prompt_and_cmd(const struct shell *sh)
401 {
402 	print_prompt(sh);
403 
404 	if (z_flag_echo_get(sh)) {
405 		z_shell_print_cmd(sh);
406 		z_shell_op_cursor_position_synchronize(sh);
407 	}
408 }
409 
shell_pend_on_txdone(const struct shell * sh)410 static void shell_pend_on_txdone(const struct shell *sh)
411 {
412 	if (IS_ENABLED(CONFIG_MULTITHREADING) &&
413 	    (sh->ctx->state < SHELL_STATE_PANIC_MODE_ACTIVE)) {
414 		struct k_poll_event event;
415 
416 		k_poll_event_init(&event,
417 				  K_POLL_TYPE_SIGNAL,
418 				  K_POLL_MODE_NOTIFY_ONLY,
419 				  &sh->ctx->signals[SHELL_SIGNAL_TXDONE]);
420 		k_poll(&event, 1, K_FOREVER);
421 		k_poll_signal_reset(&sh->ctx->signals[SHELL_SIGNAL_TXDONE]);
422 	} else {
423 		/* Blocking wait in case of bare metal. */
424 		while (!z_flag_tx_rdy_get(sh)) {
425 		}
426 		z_flag_tx_rdy_set(sh, false);
427 	}
428 }
429 
z_shell_write(const struct shell * sh,const void * data,size_t length)430 void z_shell_write(const struct shell *sh, const void *data,
431 		 size_t length)
432 {
433 	__ASSERT_NO_MSG(sh && data);
434 
435 	size_t offset = 0;
436 	size_t tmp_cnt;
437 
438 	while (length) {
439 		int err = sh->iface->api->write(sh->iface,
440 				&((const uint8_t *) data)[offset], length,
441 				&tmp_cnt);
442 		(void)err;
443 		__ASSERT_NO_MSG(err == 0);
444 		__ASSERT_NO_MSG(length >= tmp_cnt);
445 		offset += tmp_cnt;
446 		length -= tmp_cnt;
447 		if (tmp_cnt == 0 &&
448 		    (sh->ctx->state != SHELL_STATE_PANIC_MODE_ACTIVE)) {
449 			shell_pend_on_txdone(sh);
450 		}
451 	}
452 }
453 
454 /* Function shall be only used by the fprintf module. */
z_shell_print_stream(const void * user_ctx,const char * data,size_t len)455 void z_shell_print_stream(const void *user_ctx, const char *data, size_t len)
456 {
457 	z_shell_write((const struct shell *) user_ctx, data, len);
458 }
459 
vt100_bgcolor_set(const struct shell * sh,enum shell_vt100_color bgcolor)460 static void vt100_bgcolor_set(const struct shell *sh,
461 			      enum shell_vt100_color bgcolor)
462 {
463 	if (!IS_ENABLED(CONFIG_SHELL_VT100_COLORS)) {
464 		return;
465 	}
466 
467 	if (bgcolor >= VT100_COLOR_END) {
468 		return;
469 	}
470 
471 	if ((bgcolor == SHELL_NORMAL) ||
472 	    (sh->ctx->vt100_ctx.col.bgcol == bgcolor)) {
473 		return;
474 	}
475 
476 	sh->ctx->vt100_ctx.col.bgcol = bgcolor;
477 	Z_SHELL_VT100_CMD(sh, "\e[403%dm", bgcolor);
478 }
479 
z_shell_vt100_color_set(const struct shell * sh,enum shell_vt100_color color)480 void z_shell_vt100_color_set(const struct shell *sh,
481 			     enum shell_vt100_color color)
482 {
483 	if (!IS_ENABLED(CONFIG_SHELL_VT100_COLORS)) {
484 		return;
485 	}
486 
487 	if (color >= VT100_COLOR_END) {
488 		return;
489 	}
490 
491 	if (sh->ctx->vt100_ctx.col.col == color) {
492 		return;
493 	}
494 
495 	sh->ctx->vt100_ctx.col.col = color;
496 
497 	if (color != SHELL_NORMAL) {
498 		Z_SHELL_VT100_CMD(sh, "\e[1;3%dm", color);
499 	} else {
500 		Z_SHELL_VT100_CMD(sh, SHELL_VT100_MODESOFF);
501 	}
502 }
503 
z_shell_vt100_colors_restore(const struct shell * sh,const struct shell_vt100_colors * color)504 void z_shell_vt100_colors_restore(const struct shell *sh,
505 				  const struct shell_vt100_colors *color)
506 {
507 	if (!IS_ENABLED(CONFIG_SHELL_VT100_COLORS)) {
508 		return;
509 	}
510 
511 	z_shell_vt100_color_set(sh, color->col);
512 	vt100_bgcolor_set(sh, color->bgcol);
513 }
514 
z_shell_vfprintf(const struct shell * sh,enum shell_vt100_color color,const char * fmt,va_list args)515 void z_shell_vfprintf(const struct shell *sh, enum shell_vt100_color color,
516 		      const char *fmt, va_list args)
517 {
518 	if (IS_ENABLED(CONFIG_SHELL_VT100_COLORS) &&
519 	    z_flag_use_colors_get(sh)	  &&
520 	    (color != sh->ctx->vt100_ctx.col.col)) {
521 		struct shell_vt100_colors col;
522 
523 		z_shell_vt100_colors_store(sh, &col);
524 		z_shell_vt100_color_set(sh, color);
525 
526 		z_shell_fprintf_fmt(sh->fprintf_ctx, fmt, args);
527 
528 		z_shell_vt100_colors_restore(sh, &col);
529 	} else {
530 		z_shell_fprintf_fmt(sh->fprintf_ctx, fmt, args);
531 	}
532 }
533 
z_shell_fprintf(const struct shell * sh,enum shell_vt100_color color,const char * fmt,...)534 void z_shell_fprintf(const struct shell *sh,
535 		     enum shell_vt100_color color,
536 		     const char *fmt, ...)
537 {
538 	__ASSERT_NO_MSG(sh);
539 	__ASSERT_NO_MSG(sh->ctx);
540 	__ASSERT_NO_MSG(sh->fprintf_ctx);
541 	__ASSERT_NO_MSG(fmt);
542 	__ASSERT(z_flag_sync_mode_get(sh) || !k_is_in_isr(),
543 		 "Thread context required.");
544 
545 	va_list args;
546 
547 	va_start(args, fmt);
548 	z_shell_vfprintf(sh, color, fmt, args);
549 	va_end(args);
550 }
551 
z_shell_backend_rx_buffer_flush(const struct shell * sh)552 void z_shell_backend_rx_buffer_flush(const struct shell *sh)
553 {
554 	__ASSERT_NO_MSG(sh);
555 
556 	int32_t max_iterations = 1000;
557 	uint8_t buf[64];
558 	size_t count = 0;
559 	int err;
560 
561 	do {
562 		err = sh->iface->api->read(sh->iface, buf, sizeof(buf), &count);
563 	} while (count != 0 && err == 0 && --max_iterations > 0);
564 }
565