Update preset.
[bertos.git] / bertos / mware / readline.c
1 /**
2  * \file
3  * <!--
4  * This file is part of BeRTOS.
5  *
6  * Bertos is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation; either version 2 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software
18  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
19  *
20  * As a special exception, you may use this file as part of a free software
21  * library without restriction.  Specifically, if other files instantiate
22  * templates or use macros or inline functions from this file, or you compile
23  * this file and link it with other files to produce an executable, this
24  * file does not by itself cause the resulting executable to be covered by
25  * the GNU General Public License.  This exception does not however
26  * invalidate any other reasons why the executable file might be covered by
27  * the GNU General Public License.
28  *
29  * Copyright 2004 Develer S.r.l. (http://www.develer.com/)
30  * Copyright 2004 Giovanni Bajo
31  * All Rights Reserved.
32  * -->
33  *
34  * \brief Line editing support with history
35  *
36  * Rationale for basic implementation choices:
37  *
38  * \li The history is implemented storing consecutive ASCIIZ strings within an array of memory. When
39  * the history is full, the first (oldest) line is cancelled and the whole buffer is memmoved to
40  * overwrite it and make room. while this is is obviously not the fastest algorithm (which would
41  * require the use of a circular buffer) it is surely good enough for this module, which does not
42  * aim at fast performances (line editing does not require to be blazingly fast).
43  *
44  * \li The first character in the history is always \c \\0, and it is used as a guard. By 'wasting' it
45  * in this way, the code actually gets much simpler in that we remove many checks when moving
46  * backward (\c i>0 and similar).
47  *
48  * \li While editing, the current index points to the position of the buffer which contains the
49  * last character typed in (exactly like a stack pointer). This also allows to simplify calculations
50  * and to make easier using the last byte of history.
51  *
52  * \li While editing, the current line is always kept null-terminated. This is important because
53  * if the user press ENTER, we must have room to add a \c \\0 to terminate the line. If the line
54  * is as long as the whole history buffer, there would not be space for it. By always keeping the
55  * \c \\0 at the end, we properly ensure this without making index checks harder.
56  *
57  * \li When removing a line from the history (see \c pop_history()), instead of updating all the
58  * indices we have around, we move backward the pointer to the history we use. This way, we don't
59  * have to update anything. This means that we keep two pointers to the history: \c real_history
60  * always points to the physical start, while \c history is the adjusted pointer (that is
61  * dereference to read/write to it).
62  *
63  * \todo Use up/down to move through history  The history line will be copied to the current line,
64  * making sure there is room for it.
65  *
66  * \author Giovanni Bajo <rasky@develer.com>
67  */
68
69
70 #include "readline.h"
71
72 #include <cfg/compiler.h>
73 #include <cfg/debug.h>
74
75 #include <stdio.h>
76
77 /// Enable compilation of the unit test code
78 #define DEBUG_UNIT_TEST       0
79
80 /// Enable dump of the history after each line
81 #define DEBUG_DUMP_HISTORY    0
82
83
84 /** Special keys (escape sequences converted to a single code) */
85 enum RL_KEYS {
86         SPECIAL_KEYS = 0x1000,
87
88         /*
89          * Three byte keys:
90          * #################
91          * UpArrow:     0x1B 0x5B 0X41
92          * DownArrow:   0x1B 0x5B 0X42
93          * RightArrow:  0x1B 0x5B 0x43
94          * LeftArrow:   0x1b 0x5B 0x44
95          * Beak(Pause): 0x1b 0x5B 0x50
96         */
97         KEY_UP_ARROW,
98         KEY_DOWN_ARROW,
99         KEY_LEFT_ARROW,
100         KEY_RIGHT_ARROW,
101         KEY_PAUSE,
102
103         /*
104          * Four byte keys:
105          * ################
106          * F1:          0x1b 0x5B 0x5B 0x41
107          * F2:          0x1b 0x5B 0x5B 0x42
108          * F3:          0x1b 0x5B 0x5B 0x43
109          * F4:          0x1b 0x5B 0x5B 0x44
110          * F5:          0x1b 0x5B 0x5B 0x45
111          * Ins:         0x1b 0x5B 0x32 0x7E
112          * Home:        0x1b 0x5B 0x31 0x7E
113          * PgUp:        0x1b 0x5B 0x35 0x7E
114          * Del:         0x1b 0x5B 0x33 0x7E
115          * End:         0x1b 0x5B 0x34 0x7E
116          * PgDn:        0x1b 0x5B 0x36 0x7E
117          */
118         KEY_F1, KEY_F2, KEY_F3, KEY_F4, KEY_F5,
119         KEY_INS, KEY_HOME, KEY_PGUP, KEY_DEL, KEY_END, KEY_PGDN,
120
121         /*
122          * Five byte keys:
123          * ################
124          * F6:          0x1b 0x5B 0x31 0x37 0x7E
125          * F7:          0x1b 0x5B 0x31 0x38 0x7E
126          * F8:          0x1b 0x5B 0x31 0x39 0x7E
127          * F9:          0x1b 0x5B 0x32 0x30 0x7E
128          * F10:         0x1b 0x5B 0x32 0x31 0x7E
129          * F11:         0x1b 0x5B 0x32 0x33 0x7E
130          * F12:         0x1b 0x5B 0x32 0x34 0x7E
131          */
132         KEY_F6, KEY_F7, KEY_F8, KEY_F9,
133         KEY_F10, KEY_F11, KEY_F12,
134 };
135
136 /** Check if \a c is a separator between words.
137  *  \note Parameter \a c is evaluated multiple times
138  */
139 #define IS_WORD_SEPARATOR(c) ((c) == ' ' || (c) == '\0')
140
141 /// Write the string \a txt to the IO output (without any kind of termination)
142 INLINE void rl_puts(const struct RLContext* ctx, const char* txt)
143 {
144         if (!ctx->put)
145                 return;
146
147         while (*txt)
148                 ctx->put(*txt++, ctx->put_param);
149 }
150
151 /// Write character \a ch to the IO output.
152 INLINE void rl_putc(const struct RLContext* ctx, char ch)
153 {
154         if (ctx->put)
155                 ctx->put(ch, ctx->put_param);
156 }
157
158 /** Read a character from the IO into \a ch. This function also takes
159  *  care of converting the ANSI escape sequences into one of the codes
160  *  defined in \c RL_KEYS.
161  */
162 static bool rl_getc(const struct RLContext* ctx, int* ch)
163 {
164         int c = ctx->get(ctx->get_param);
165
166         if (c == EOF)
167         {
168                 if (ctx->clear)
169                         ctx->clear(ctx->clear_param);
170
171                 return false;
172         }
173
174         if (c == 0x1B)
175         {
176                 // Unknown ESC sequence. Ignore it and read
177                 //  return next character.
178                 if (ctx->get(ctx->get_param) != 0x5B)
179                         return rl_getc(ctx, ch);
180
181                 /* To be added:
182                         * Home:        0x1b 0x5B 0x31 0x7E
183                         * F6:          0x1b 0x5B 0x31 0x37 0x7E
184                         * F7:          0x1b 0x5B 0x31 0x38 0x7E
185                         * F8:          0x1b 0x5B 0x31 0x39 0x7E
186                         * Ins:         0x1b 0x5B 0x32 0x7E
187                         * F9:          0x1b 0x5B 0x32 0x30 0x7E
188                         * F10:         0x1b 0x5B 0x32 0x31 0x7E
189                         * F11:         0x1b 0x5B 0x32 0x33 0x7E
190                         * F12:         0x1b 0x5B 0x32 0x34 0x7E
191                         * Del:         0x1b 0x5B 0x33 0x7E
192                         * End:         0x1b 0x5B 0x34 0x7E
193                         * PgUp:        0x1b 0x5B 0x35 0x7E
194                         * PgDn:        0x1b 0x5B 0x36 0x7E
195                 */
196
197                 c = ctx->get(ctx->get_param);
198                 switch (c)
199                 {
200                 case 0x41: c = KEY_UP_ARROW; break;
201                 case 0x42: c = KEY_DOWN_ARROW; break;
202                 case 0x43: c = KEY_RIGHT_ARROW; break;
203                 case 0x44: c = KEY_LEFT_ARROW; break;
204                 case 0x50: c = KEY_PAUSE; break;
205                 case 0x5B:
206                         c = ctx->get(ctx->get_param);
207                         switch (c)
208                         {
209                         case 0x41: c = KEY_F1; break;
210                         case 0x42: c = KEY_F2; break;
211                         case 0x43: c = KEY_F3; break;
212                         case 0x44: c = KEY_F4; break;
213                         case 0x45: c = KEY_F5; break;
214                         default: return rl_getc(ctx, ch);
215                         }
216                         break;
217                 default: return rl_getc(ctx, ch);
218                 }
219         }
220
221         *ch = c;
222         return true;
223 }
224
225 INLINE void beep(struct RLContext* ctx)
226 {
227         rl_putc(ctx, '\a');
228 }
229
230 static bool pop_history(struct RLContext* ctx, int total_len)
231 {
232         // Compute the length of the first command (including terminator).
233         int len = strlen(ctx->real_history+1)+1;
234
235         // (the first byte of the history should always be 0)
236         ASSERT(ctx->real_history[0] == '\0');
237
238         // If it is the only one in the history, do nothing
239         if (len == total_len)
240                 return false;
241
242         // Overwrite the first command with the second one
243         memmove(ctx->real_history, ctx->real_history+len, HISTORY_SIZE-len);
244
245         // Move back the ctx->buffer pointer so that all the indices are still valid
246         ctx->history -= len;
247
248         return true;
249 }
250
251 /// Check if index \a i points to the begin of the history.
252 INLINE bool is_history_begin(struct RLContext* ctx, int i)
253 { return ctx->history + i == ctx->real_history; }
254
255 /// Check if index \a i points to the (exclusive) end of history
256 INLINE bool is_history_end(struct RLContext* ctx, int i)
257 { return ctx->history + i == ctx->real_history + HISTORY_SIZE; }
258
259 /// Check if index \a i points to the (exclusive) end of history, or somewhere past the end.
260 INLINE bool is_history_past_end(struct RLContext* ctx, int i)
261 { return ctx->history + i >= ctx->real_history + HISTORY_SIZE; }
262
263 /** Insert \a num_chars characters from \a ch into the history buffer at the
264  *  position indicated by \a curpos. If needed, remove old history to make room.
265  *  Returns true if everything was successful, false if there was no room to
266  *  add the characters.
267  *  \note \a num_chars can be 0, in which case we just make sure the line is
268  *  correctly zero-terminated (ASCIIZ format).
269  */
270 static bool insert_chars(struct RLContext* ctx, size_t *curpos, const char* ch, int num_chars)
271 {
272         ASSERT(!is_history_past_end(ctx, *curpos));
273
274         while (is_history_past_end(ctx, *curpos+num_chars+1))
275         {
276                 if (!pop_history(ctx, *curpos))
277                         return false;
278         }
279
280         while (num_chars--)
281                 ctx->history[++(*curpos)] = *ch++;
282
283         ASSERT(!is_history_past_end(ctx, *curpos + 1));
284         ctx->history[*curpos+1] = '\0';
285         return true;
286 }
287
288 /// Insert a single character \a ch into the buffer (with the same semantic of \c insert_chars())
289 static bool insert_char(struct RLContext* ctx, size_t *curpos, char ch)
290 {
291         return insert_chars(ctx, curpos, &ch, 1);
292 }
293
294 #if DEBUG_DUMP_HISTORY
295 /// Dump the internal history of a context (used only for debug purposes)
296 static void dump_history(struct RLContext* ctx)
297 {
298         int k;
299         char buf[8];
300         ASSERT(ctx->real_history[0] == '\0');
301         rl_puts(ctx, "History dump:");
302         rl_puts(ctx, "\r\n");
303         for (k = 1;
304              ctx->real_history + k != ctx->history + ctx->history_pos + 1;
305              k += strlen(&ctx->real_history[k]) + 1)
306         {
307                 rl_puts(ctx, &ctx->real_history[k]);
308                 rl_puts(ctx, "\r\n");
309         }
310
311         sprintf(buf, "%d\r\n", ctx->history_pos + (ctx->history - ctx->real_history));
312         rl_puts(ctx, buf);
313 }
314 #endif /* DEBUG_DUMP_HISTORY */
315
316 /// Complete the current word. Return false if no unambiguous completion was found
317 static bool complete_word(struct RLContext *ctx, size_t *curpos)
318 {
319         const char* completed_word;
320         size_t wstart;
321
322         // If the current character is a separator,
323         //  there is nothing to complete
324         wstart = *curpos;
325         if (IS_WORD_SEPARATOR(ctx->history[wstart]))
326         {
327                 beep(ctx);
328                 return false;
329         }
330
331         // Find the separator before the current word
332         do
333                 --wstart;
334         while (!IS_WORD_SEPARATOR(ctx->history[wstart]));
335
336         // Complete the word through the hook
337         completed_word = ctx->match(ctx->match_param, ctx->history + wstart + 1, *curpos - wstart);
338         if (!completed_word)
339                 return false;
340
341         // Move back the terminal cursor to the separator
342         while (*curpos != wstart)
343         {
344                 rl_putc(ctx, '\b');
345                 --*curpos;
346         }
347
348         // Insert the completed command
349         insert_chars(ctx, curpos, completed_word, strlen(completed_word));
350         rl_puts(ctx, completed_word);
351         insert_char(ctx, curpos, ' ');
352         rl_putc(ctx, ' ');
353
354         return true;
355 }
356
357 void rl_refresh(struct RLContext* ctx)
358 {
359         rl_puts(ctx, "\r\n");
360         if (ctx->prompt)
361                 rl_puts(ctx, ctx->prompt);
362         rl_puts(ctx, ctx->history + ctx->history_pos + 1);
363 }
364
365 const char* rl_readline(struct RLContext* ctx)
366 {
367         while (1)
368         {
369                 char ch;
370                 int c;
371
372                 ASSERT(ctx->history - ctx->real_history + ctx->line_pos < HISTORY_SIZE);
373
374                 if (!rl_getc(ctx, &c))
375                         return NULL;
376
377                 // Just ignore special keys for now
378                 if (c > SPECIAL_KEYS)
379                         continue;
380
381                 if (c == '\t')
382                 {
383                         // Ask the match hook if available
384                         if (!ctx->match)
385                                 return NULL;
386
387                         complete_word(ctx, &ctx->line_pos);
388                         continue;
389                 }
390
391                 // Backspace cancels a character, or it is ignored if at
392                 //  the start of the line
393                 if (c == '\b')
394                 {
395                         if (ctx->history[ctx->line_pos] != '\0')
396                         {
397                                 --ctx->line_pos;
398                                 rl_puts(ctx, "\b \b");
399                         }
400                         continue;
401                 }
402
403                 if (c == '\r' || c == '\n')
404                 {
405                         rl_puts(ctx, "\r\n");
406                         break;
407                 }
408
409
410                 // Add a character to the buffer, if possible
411                 ch = (char)c;
412                 ASSERT2(ch == c, "a special key was not properly handled");
413                 if (insert_chars(ctx, &ctx->line_pos, &ch, 1))
414                         rl_putc(ctx, ch);
415                 else
416                         beep(ctx);
417         }
418
419         ctx->history_pos = ctx->line_pos + 1;
420         while (ctx->history[ctx->line_pos] != '\0')
421                 --ctx->line_pos;
422
423         // Do not store empty lines in the history
424         if (ctx->line_pos == ctx->history_pos - 1)
425                 ctx->history_pos -= 1;
426
427 #if DEBUG_DUMP_HISTORY
428         dump_history(ctx);
429 #endif
430
431         const char *buf = &ctx->history[ctx->line_pos + 1];
432
433         ctx->line_pos = ctx->history_pos;
434
435         if (ctx->prompt)
436                 rl_puts(ctx, ctx->prompt);
437
438         insert_chars(ctx, &ctx->line_pos, NULL, 0);
439
440         // Since the current pointer now points to the separator, we need
441         //  to return the first character
442         return buf;
443 }
444
445
446 #if DEBUG_UNIT_TEST
447
448 /** Perform the unit test for the readline library */
449 void rl_test(void);
450
451 #if HISTORY_SIZE != 32
452         #error This test needs HISTORY_SIZE to be set at 32
453 #endif
454
455 static struct RLContext test_ctx;
456
457 static char* test_getc_ptr;
458 static int test_getc(void* data)
459 {
460         return *test_getc_ptr++;
461 }
462
463 /** Perform a readline test. The function pipes the characters from \a input_buffer
464  *  through the I/O to \c rl_readline(). After the whole string is sent, \c do_test()
465  *  checks if the current history within the context match \a expected_history.
466  */
467 static bool do_test(char* input_buffer, char* expected_history)
468 {
469         rl_init_ctx(&test_ctx);
470         rl_sethook_get(&test_ctx, test_getc, NULL);
471
472         test_getc_ptr = input_buffer;
473         while (*test_getc_ptr)
474                 rl_readline(&test_ctx);
475
476         if (memcmp(test_ctx.real_history, expected_history, HISTORY_SIZE) != 0)
477         {
478                 ASSERT2(0, "history compare failed");
479                 return false;
480         }
481
482         return true;
483 }
484
485 void rl_test(void)
486 {
487         char* test1_in = "a\nb\nc\nd\ne\nf\ng\nh\ni\nj\nk\nl\nm\nn\no\np\nq\nr\ns\nt\nu\nv\nw\nx\ny\nz\n";
488         char test1_hist[HISTORY_SIZE] = "\0l\0m\0n\0o\0p\0q\0r\0s\0t\0u\0v\0w\0x\0y\0z";
489
490         if (!do_test(test1_in, test1_hist))
491                 return;
492
493         kprintf("rl_test successful\n");
494 }
495
496 #endif /* DEBUG_UNIT_TEST */
497