blob: 61fb24e23d55fb23d3f33a5ef348557f529e95f9 [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 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License version 2 as
7 * published by the Free Software Foundation.
8 *
9 * Alternatively, this software may be distributed under the terms of BSD
10 * license.
11 *
12 * See README and COPYING for more details.
13 */
14
15#include "includes.h"
16
17#include "common.h"
18#include "eloop.h"
19#include "edit.h"
20
21
22#define CMD_BUF_LEN 256
23static char cmdbuf[CMD_BUF_LEN];
24static int cmdbuf_pos = 0;
25
26static void *edit_cb_ctx;
27static void (*edit_cmd_cb)(void *ctx, char *cmd);
28static void (*edit_eof_cb)(void *ctx);
29
30
31static void edit_read_char(int sock, void *eloop_ctx, void *sock_ctx)
32{
33 int c;
34 unsigned char buf[1];
35 int res;
36
37 res = read(sock, buf, 1);
38 if (res < 0)
39 perror("read");
40 if (res <= 0) {
41 edit_eof_cb(edit_cb_ctx);
42 return;
43 }
44 c = buf[0];
45
46 if (c == '\r' || c == '\n') {
47 cmdbuf[cmdbuf_pos] = '\0';
48 cmdbuf_pos = 0;
49 edit_cmd_cb(edit_cb_ctx, cmdbuf);
50 printf("> ");
51 fflush(stdout);
52 return;
53 }
54
55 if (c >= 32 && c <= 255) {
56 if (cmdbuf_pos < (int) sizeof(cmdbuf) - 1) {
57 cmdbuf[cmdbuf_pos++] = c;
58 }
59 }
60}
61
62
63int edit_init(void (*cmd_cb)(void *ctx, char *cmd),
64 void (*eof_cb)(void *ctx),
65 char ** (*completion_cb)(void *ctx, const char *cmd, int pos),
66 void *ctx, const char *history_file)
67{
68 edit_cb_ctx = ctx;
69 edit_cmd_cb = cmd_cb;
70 edit_eof_cb = eof_cb;
71 eloop_register_read_sock(STDIN_FILENO, edit_read_char, NULL, NULL);
72
73 printf("> ");
74 fflush(stdout);
75
76 return 0;
77}
78
79
80void edit_deinit(const char *history_file,
81 int (*filter_cb)(void *ctx, const char *cmd))
82{
83 eloop_unregister_read_sock(STDIN_FILENO);
84}
85
86
87void edit_clear_line(void)
88{
89}
90
91
92void edit_redraw(void)
93{
94 cmdbuf[cmdbuf_pos] = '\0';
95 printf("\r> %s", cmdbuf);
96}