• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
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
23 static char cmdbuf[CMD_BUF_LEN];
24 static int cmdbuf_pos = 0;
25 
26 static void *edit_cb_ctx;
27 static void (*edit_cmd_cb)(void *ctx, char *cmd);
28 static void (*edit_eof_cb)(void *ctx);
29 
30 
edit_read_char(int sock,void * eloop_ctx,void * sock_ctx)31 static 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 
edit_init(void (* cmd_cb)(void * ctx,char * cmd),void (* eof_cb)(void * ctx),char ** (* completion_cb)(void * ctx,const char * cmd,int pos),void * ctx,const char * history_file)63 int 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 
edit_deinit(const char * history_file,int (* filter_cb)(void * ctx,const char * cmd))80 void 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 
edit_clear_line(void)87 void edit_clear_line(void)
88 {
89 }
90 
91 
edit_redraw(void)92 void edit_redraw(void)
93 {
94 	cmdbuf[cmdbuf_pos] = '\0';
95 	printf("\r> %s", cmdbuf);
96 }
97