edit_simple.c revision 61d9df3e62aaa0e87ad05452fcb95142159a17b6
1/*
2 * Minimal command line editing
3 * Copyright (c) 2010, Jouni Malinen <j@w1.fi>
4 *
5 * This software may be distributed under the terms of the BSD license.
6 * See README for more details.
7 */
8
9#include "includes.h"
10
11#include "common.h"
12#include "eloop.h"
13#include "edit.h"
14
15
16#define CMD_BUF_LEN 256
17static char cmdbuf[CMD_BUF_LEN];
18static int cmdbuf_pos = 0;
19static const char *ps2 = NULL;
20
21static void *edit_cb_ctx;
22static void (*edit_cmd_cb)(void *ctx, char *cmd);
23static void (*edit_eof_cb)(void *ctx);
24
25
26static void edit_read_char(int sock, void *eloop_ctx, void *sock_ctx)
27{
28	int c;
29	unsigned char buf[1];
30	int res;
31
32	res = read(sock, buf, 1);
33	if (res < 0)
34		perror("read");
35	if (res <= 0) {
36		edit_eof_cb(edit_cb_ctx);
37		return;
38	}
39	c = buf[0];
40
41	if (c == '\r' || c == '\n') {
42		cmdbuf[cmdbuf_pos] = '\0';
43		cmdbuf_pos = 0;
44		edit_cmd_cb(edit_cb_ctx, cmdbuf);
45		printf("%s> ", ps2 ? ps2 : "");
46		fflush(stdout);
47		return;
48	}
49
50	if (c >= 32 && c <= 255) {
51		if (cmdbuf_pos < (int) sizeof(cmdbuf) - 1) {
52			cmdbuf[cmdbuf_pos++] = c;
53		}
54	}
55}
56
57
58int edit_init(void (*cmd_cb)(void *ctx, char *cmd),
59	      void (*eof_cb)(void *ctx),
60	      char ** (*completion_cb)(void *ctx, const char *cmd, int pos),
61	      void *ctx, const char *history_file, const char *ps)
62{
63	edit_cb_ctx = ctx;
64	edit_cmd_cb = cmd_cb;
65	edit_eof_cb = eof_cb;
66	eloop_register_read_sock(STDIN_FILENO, edit_read_char, NULL, NULL);
67	ps2 = ps;
68
69	printf("%s> ", ps2 ? ps2 : "");
70	fflush(stdout);
71
72	return 0;
73}
74
75
76void edit_deinit(const char *history_file,
77		 int (*filter_cb)(void *ctx, const char *cmd))
78{
79	eloop_unregister_read_sock(STDIN_FILENO);
80}
81
82
83void edit_clear_line(void)
84{
85}
86
87
88void edit_redraw(void)
89{
90	cmdbuf[cmdbuf_pos] = '\0';
91	printf("\r> %s", cmdbuf);
92}
93