Updated copiright notice.
[bertos.git] / 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  * \version $Id$
67  *
68  * \author Giovanni Bajo <rasky@develer.com>
69  */
70
71 /*#*
72  *#* $Log$
73  *#* Revision 1.2  2006/07/19 12:56:28  bernie
74  *#* Convert to new Doxygen style.
75  *#*
76  *#* Revision 1.1  2006/06/01 12:27:39  marco
77  *#* Added utilities for protocols
78  *#*
79  *#*/
80
81 #include "readline.h"
82
83 #include <cfg/compiler.h>
84 #include <cfg/debug.h>
85
86 #include <stdio.h>
87
88
89 /// Enable compilation of the unit test code
90 #define DEBUG_UNIT_TEST       0
91
92 /// Enable dump of the history after each line
93 #define DEBUG_DUMP_HISTORY    0
94
95
96 /** Special keys (escape sequences converted to a single code) */
97 enum RL_KEYS {
98         SPECIAL_KEYS = 0x1000,
99
100         /*
101          * Three byte keys:
102          * #################
103          * UpArrow:     0x1B 0x5B 0X41
104          * DownArrow:   0x1B 0x5B 0X42
105          * RightArrow:  0x1B 0x5B 0x43
106          * LeftArrow:   0x1b 0x5B 0x44
107          * Beak(Pause): 0x1b 0x5B 0x50
108         */
109         KEY_UP_ARROW,
110         KEY_DOWN_ARROW,
111         KEY_LEFT_ARROW,
112         KEY_RIGHT_ARROW,
113         KEY_PAUSE,
114
115         /*
116          * Four byte keys:
117          * ################
118          * F1:          0x1b 0x5B 0x5B 0x41
119          * F2:          0x1b 0x5B 0x5B 0x42
120          * F3:          0x1b 0x5B 0x5B 0x43
121          * F4:          0x1b 0x5B 0x5B 0x44
122          * F5:          0x1b 0x5B 0x5B 0x45
123          * Ins:         0x1b 0x5B 0x32 0x7E
124          * Home:        0x1b 0x5B 0x31 0x7E
125          * PgUp:        0x1b 0x5B 0x35 0x7E
126          * Del:         0x1b 0x5B 0x33 0x7E
127          * End:         0x1b 0x5B 0x34 0x7E
128          * PgDn:        0x1b 0x5B 0x36 0x7E
129          */
130         KEY_F1, KEY_F2, KEY_F3, KEY_F4, KEY_F5,
131         KEY_INS, KEY_HOME, KEY_PGUP, KEY_DEL, KEY_END, KEY_PGDN,
132
133         /*
134          * Five byte keys:
135          * ################
136          * F6:          0x1b 0x5B 0x31 0x37 0x7E
137          * F7:          0x1b 0x5B 0x31 0x38 0x7E
138          * F8:          0x1b 0x5B 0x31 0x39 0x7E
139          * F9:          0x1b 0x5B 0x32 0x30 0x7E
140          * F10:         0x1b 0x5B 0x32 0x31 0x7E
141          * F11:         0x1b 0x5B 0x32 0x33 0x7E
142          * F12:         0x1b 0x5B 0x32 0x34 0x7E
143          */
144         KEY_F6, KEY_F7, KEY_F8, KEY_F9,
145         KEY_F10, KEY_F11, KEY_F12,
146 };
147
148 /** Check if \a c is a separator between words.
149  *  \note Parameter \a c is evaluated multiple times
150  */
151 #define IS_WORD_SEPARATOR(c) ((c) == ' ' || (c) == '\0')
152
153 /// Write the string \a txt to the IO output (without any kind of termination)
154 INLINE void rl_puts(const struct RLContext* ctx, const char* txt)
155 {
156         if (!ctx->put)
157                 return;
158
159         while (*txt)
160                 ctx->put(*txt++, ctx->put_param);
161 }
162
163 /// Write character \a ch to the IO output.
164 INLINE void rl_putc(const struct RLContext* ctx, char ch)
165 {
166         if (ctx->put)
167                 ctx->put(ch, ctx->put_param);
168 }
169
170 /** Read a character from the IO into \a ch. This function also takes
171  *  care of converting the ANSI escape sequences into one of the codes
172  *  defined in \c RL_KEYS.
173  */
174 static bool rl_getc(const struct RLContext* ctx, int* ch)
175 {
176         int c = ctx->get(ctx->get_param);
177         if (c == EOF)
178                 return false;
179
180         if (c == 0x1B)
181         {
182                 // Unknown ESC sequence. Ignore it and read
183                 //  return next character.
184                 if (ctx->get(ctx->get_param) != 0x5B)
185                         return rl_getc(ctx, ch);
186
187                 /* To be added:
188                         * Home:        0x1b 0x5B 0x31 0x7E
189                         * F6:          0x1b 0x5B 0x31 0x37 0x7E
190                         * F7:          0x1b 0x5B 0x31 0x38 0x7E
191                         * F8:          0x1b 0x5B 0x31 0x39 0x7E
192                         * Ins:         0x1b 0x5B 0x32 0x7E
193                         * F9:          0x1b 0x5B 0x32 0x30 0x7E
194                         * F10:         0x1b 0x5B 0x32 0x31 0x7E
195                         * F11:         0x1b 0x5B 0x32 0x33 0x7E
196                         * F12:         0x1b 0x5B 0x32 0x34 0x7E
197                         * Del:         0x1b 0x5B 0x33 0x7E
198                         * End:         0x1b 0x5B 0x34 0x7E
199                         * PgUp:        0x1b 0x5B 0x35 0x7E
200                         * PgDn:        0x1b 0x5B 0x36 0x7E
201                 */
202
203                 c = ctx->get(ctx->get_param);
204                 switch (c)
205                 {
206                 case 0x41: c = KEY_UP_ARROW; break;
207                 case 0x42: c = KEY_DOWN_ARROW; break;
208                 case 0x43: c = KEY_RIGHT_ARROW; break;
209                 case 0x44: c = KEY_LEFT_ARROW; break;
210                 case 0x50: c = KEY_PAUSE; break;
211                 case 0x5B:
212                         c = ctx->get(ctx->get_param);
213                         switch (c)
214                         {
215                         case 0x41: c = KEY_F1; break;
216                         case 0x42: c = KEY_F2; break;
217                         case 0x43: c = KEY_F3; break;
218                         case 0x44: c = KEY_F4; break;
219                         case 0x45: c = KEY_F5; break;
220                         default: return rl_getc(ctx, ch);
221                         }
222                         break;
223                 default: return rl_getc(ctx, ch);
224                 }
225         }
226
227         *ch = c;
228         return true;
229 }
230
231 INLINE void beep(struct RLContext* ctx)
232 {
233         rl_putc(ctx, '\a');
234 }
235
236 static bool pop_history(struct RLContext* ctx, int total_len)
237 {
238         // Compute the length of the first command (including terminator).
239         int len = strlen(ctx->real_history+1)+1;
240
241         // (the first byte of the history should always be 0)
242         ASSERT(ctx->real_history[0] == '\0');
243
244         // If it is the only one in the history, do nothing
245         if (len == total_len)
246                 return false;
247
248         // Overwrite the first command with the second one
249         memmove(ctx->real_history, ctx->real_history+len, HISTORY_SIZE-len);
250
251         // Move back the ctx->buffer pointer so that all the indices are still valid
252         ctx->history -= len;
253
254         return true;
255 }
256
257 /// Check if index \a i points to the begin of the history.
258 INLINE bool is_history_begin(struct RLContext* ctx, int i)
259 { return ctx->history + i == ctx->real_history; }
260
261 /// Check if index \a i points to the (exclusive) end of history
262 INLINE bool is_history_end(struct RLContext* ctx, int i)
263 { return ctx->history + i == ctx->real_history + HISTORY_SIZE; }
264
265 /// Check if index \a i points to the (exclusive) end of history, or somewhere past the end.
266 INLINE bool is_history_past_end(struct RLContext* ctx, int i)
267 { return ctx->history + i >= ctx->real_history + HISTORY_SIZE; }
268
269 /** Insert \a num_chars characters from \a ch into the history buffer at the
270  *  position indicated by \a curpos. If needed, remove old history to make room.
271  *  Returns true if everything was successful, false if there was no room to
272  *  add the characters.
273  *  \note \a num_chars can be 0, in which case we just make sure the line is
274  *  correctly zero-terminated (ASCIIZ format).
275  */
276 static bool insert_chars(struct RLContext* ctx, size_t *curpos, const char* ch, int num_chars)
277 {
278         ASSERT(!is_history_past_end(ctx, *curpos));
279
280         while (is_history_past_end(ctx, *curpos+num_chars+1))
281         {
282                 if (!pop_history(ctx, *curpos))
283                         return false;
284         }
285
286         while (num_chars--)
287                 ctx->history[++(*curpos)] = *ch++;
288
289         ASSERT(!is_history_past_end(ctx, *curpos + 1));
290         ctx->history[*curpos+1] = '\0';
291         return true;
292 }
293
294 /// Insert a single character \a ch into the buffer (with the same semantic of \c insert_chars())
295 static bool insert_char(struct RLContext* ctx, size_t *curpos, char ch)
296 {
297         return insert_chars(ctx, curpos, &ch, 1);
298 }
299
300 #if DEBUG_DUMP_HISTORY
301 /// Dump the internal history of a context (used only for debug purposes)
302 static void dump_history(struct RLContext* ctx)
303 {
304         int k;
305         char buf[8];
306         ASSERT(ctx->real_history[0] == '\0');
307         rl_puts(ctx, "History dump:");
308         rl_puts(ctx, "\r\n");
309         for (k = 1;
310              ctx->real_history + k != ctx->history + ctx->history_pos + 1;
311              k += strlen(&ctx->real_history[k]) + 1)
312         {
313                 rl_puts(ctx, &ctx->real_history[k]);
314                 rl_puts(ctx, "\r\n");
315         }
316
317         sprintf(buf, "%d\r\n", ctx->history_pos + (ctx->history - ctx->real_history));
318         rl_puts(ctx, buf);
319 }
320 #endif /* DEBUG_DUMP_HISTORY */
321
322 /// Complete the current word. Return false if no unambiguous completion was found
323 static bool complete_word(struct RLContext *ctx, size_t *curpos)
324 {
325         const char* completed_word;
326         size_t wstart;
327
328         // If the current character is a separator,
329         //  there is nothing to complete
330         wstart = *curpos;
331         if (IS_WORD_SEPARATOR(ctx->history[wstart]))
332         {
333                 beep(ctx);
334                 return false;
335         }
336
337         // Find the separator before the current word
338         do
339                 --wstart;
340         while (!IS_WORD_SEPARATOR(ctx->history[wstart]));
341
342         // Complete the word through the hook
343         completed_word = ctx->match(ctx->match_param, ctx->history + wstart + 1, *curpos - wstart);
344         if (!completed_word)
345                 return false;
346
347         // Move back the terminal cursor to the separator
348         while (*curpos != wstart)
349         {
350                 rl_putc(ctx, '\b');
351                 --*curpos;
352         }
353
354         // Insert the completed command
355         insert_chars(ctx, curpos, completed_word, strlen(completed_word));
356         rl_puts(ctx, completed_word);
357         insert_char(ctx, curpos, ' ');
358         rl_putc(ctx, ' ');
359
360         return true;
361 }
362
363 void rl_refresh(struct RLContext* ctx)
364 {
365         rl_puts(ctx, "\r\n");
366         if (ctx->prompt)
367                 rl_puts(ctx, ctx->prompt);
368         rl_puts(ctx, ctx->history + ctx->history_pos + 1);
369 }
370
371 const char* rl_readline(struct RLContext* ctx)
372 {
373         size_t i = ctx->history_pos;
374
375         if (ctx->prompt)
376                 rl_puts(ctx, ctx->prompt);
377
378         insert_chars(ctx, &i, NULL, 0);
379
380         while (1)
381         {
382                 char ch;
383                 int c;
384
385                 ASSERT(ctx->history - ctx->real_history + i < HISTORY_SIZE);
386
387                 if (!rl_getc(ctx, &c))
388                         return NULL;
389
390                 // Just ignore special keys for now
391                 if (c > SPECIAL_KEYS)
392                         continue;
393
394                 if (c == '\t')
395                 {
396                         // Ask the match hook if available
397                         if (!ctx->match)
398                                 return false;
399
400                         complete_word(ctx, &i);
401                         continue;
402                 }
403
404                 if (c == '\r' || c == '\n')
405                 {
406                         rl_puts(ctx, "\r\n");
407                         break;
408                 }
409
410                 // Backspace cancels a character, or it is ignored if at
411                 //  the start of the line
412                 if (c == '\b')
413                 {
414                         if (ctx->history[i] != '\0')
415                         {
416                                 --i;
417                                 rl_puts(ctx, "\b \b");
418                         }
419                         continue;
420                 }
421
422                 // Add a character to the buffer, if possible
423                 ch = (char)c;
424                 ASSERT2(ch == c, "a special key was not properly handled");
425                 if (insert_chars(ctx, &i, &ch, 1))
426                         rl_putc(ctx, ch);
427                 else
428                         beep(ctx);
429         }
430
431         ctx->history_pos = i+1;
432         while (ctx->history[i] != '\0')
433                 --i;
434
435         // Do not store empty lines in the history
436         if (i == ctx->history_pos - 1)
437                 ctx->history_pos -= 1;
438
439 #if DEBUG_DUMP_HISTORY
440         dump_history(ctx);
441 #endif
442
443         // Since the current pointer now points to the separator, we need
444         //  to return the first character
445         return &ctx->history[i+1];
446 }
447
448
449 #if DEBUG_UNIT_TEST
450
451 /** Perform the unit test for the readline library */
452 void rl_test(void);
453
454 #if HISTORY_SIZE != 32
455         #error This test needs HISTORY_SIZE to be set at 32
456 #endif
457
458 static struct RLContext test_ctx;
459
460 static char* test_getc_ptr;
461 static int test_getc(void* data)
462 {
463         return *test_getc_ptr++;
464 }
465
466 /** Perform a readline test. The function pipes the characters from \a input_buffer
467  *  through the I/O to \c rl_readline(). After the whole string is sent, \c do_test()
468  *  checks if the current history within the context match \a expected_history.
469  */
470 static bool do_test(char* input_buffer, char* expected_history)
471 {
472         rl_init_ctx(&test_ctx);
473         rl_sethook_get(&test_ctx, test_getc, NULL);
474
475         test_getc_ptr = input_buffer;
476         while (*test_getc_ptr)
477                 rl_readline(&test_ctx);
478
479         if (memcmp(test_ctx.real_history, expected_history, HISTORY_SIZE) != 0)
480         {
481                 ASSERT2(0, "history compare failed");
482                 return false;
483         }
484
485         return true;
486 }
487
488 void rl_test(void)
489 {
490         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";
491         char test1_hist[HISTORY_SIZE] = "\0l\0m\0n\0o\0p\0q\0r\0s\0t\0u\0v\0w\0x\0y\0z";
492
493         if (!do_test(test1_in, test1_hist))
494                 return;
495
496         kprintf("rl_test successful\n");
497 }
498
499 #endif /* DEBUG_UNIT_TEST */
500