1 /* 2 * Minimal command line editing 3 * Copyright (c) 2010, Jouni Malinen <j (at) 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 17 static char cmdbuf[CMD_BUF_LEN]; 18 static int cmdbuf_pos = 0; 19 20 static void *edit_cb_ctx; 21 static void (*edit_cmd_cb)(void *ctx, char *cmd); 22 static void (*edit_eof_cb)(void *ctx); 23 24 25 static 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 57 int 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 74 void 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 81 void edit_clear_line(void) 82 { 83 } 84 85 86 void edit_redraw(void) 87 { 88 cmdbuf[cmdbuf_pos] = '\0'; 89 printf("\r> %s", cmdbuf); 90 } 91