blob: 0e3637cbb5ef1cbcb1df8178af4dacd078ae3b97 [file] [log] [blame]
Dmitry Shmidt8d520ff2011-05-09 14:06:53 -07001/*
2 * Minimal command line editing
3 * Copyright (c) 2010, Jouni Malinen <j@w1.fi>
4 *
Dmitry Shmidtc5ec7f52012-03-06 16:33:24 -08005 * This software may be distributed under the terms of the BSD license.
6 * See README for more details.
Dmitry Shmidt8d520ff2011-05-09 14:06:53 -07007 */
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;
19
20static void *edit_cb_ctx;
21static void (*edit_cmd_cb)(void *ctx, char *cmd);
22static void (*edit_eof_cb)(void *ctx);
23
24
25static void edit_read_char(int sock, void *eloop_ctx, void *sock_ctx)
26{
27 int c;
28 unsigned char buf[1];
29 int res;
30
31 res = read(sock, buf, 1);
32 if (res < 0)
33 perror("read");
34 if (res <= 0) {
35 edit_eof_cb(edit_cb_ctx);
36 return;
37 }
38 c = buf[0];
39
40 if (c == '\r' || c == '\n') {
41 cmdbuf[cmdbuf_pos] = '\0';
42 cmdbuf_pos = 0;
43 edit_cmd_cb(edit_cb_ctx, cmdbuf);
44 printf("> ");
45 fflush(stdout);
46 return;
47 }
48
49 if (c >= 32 && c <= 255) {
50 if (cmdbuf_pos < (int) sizeof(cmdbuf) - 1) {
51 cmdbuf[cmdbuf_pos++] = c;
52 }
53 }
54}
55
56
57int edit_init(void (*cmd_cb)(void *ctx, char *cmd),
58 void (*eof_cb)(void *ctx),
59 char ** (*completion_cb)(void *ctx, const char *cmd, int pos),
60 void *ctx, const char *history_file)
61{
62 edit_cb_ctx = ctx;
63 edit_cmd_cb = cmd_cb;
64 edit_eof_cb = eof_cb;
65 eloop_register_read_sock(STDIN_FILENO, edit_read_char, NULL, NULL);
66
67 printf("> ");
68 fflush(stdout);
69
70 return 0;
71}
72
73
74void edit_deinit(const char *history_file,
75 int (*filter_cb)(void *ctx, const char *cmd))
76{
77 eloop_unregister_read_sock(STDIN_FILENO);
78}
79
80
81void edit_clear_line(void)
82{
83}
84
85
86void edit_redraw(void)
87{
88 cmdbuf[cmdbuf_pos] = '\0';
89 printf("\r> %s", cmdbuf);
90}