This commit is contained in:
Arti Zirk 2016-12-01 14:41:42 +02:00
commit 6efb7921ff
5 changed files with 1173 additions and 0 deletions

165
lib/helius_microrl/LICENSE Executable file
View File

@ -0,0 +1,165 @@
GNU LESSER GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
This version of the GNU Lesser General Public License incorporates
the terms and conditions of version 3 of the GNU General Public
License, supplemented by the additional permissions listed below.
0. Additional Definitions.
As used herein, "this License" refers to version 3 of the GNU Lesser
General Public License, and the "GNU GPL" refers to version 3 of the GNU
General Public License.
"The Library" refers to a covered work governed by this License,
other than an Application or a Combined Work as defined below.
An "Application" is any work that makes use of an interface provided
by the Library, but which is not otherwise based on the Library.
Defining a subclass of a class defined by the Library is deemed a mode
of using an interface provided by the Library.
A "Combined Work" is a work produced by combining or linking an
Application with the Library. The particular version of the Library
with which the Combined Work was made is also called the "Linked
Version".
The "Minimal Corresponding Source" for a Combined Work means the
Corresponding Source for the Combined Work, excluding any source code
for portions of the Combined Work that, considered in isolation, are
based on the Application, and not on the Linked Version.
The "Corresponding Application Code" for a Combined Work means the
object code and/or source code for the Application, including any data
and utility programs needed for reproducing the Combined Work from the
Application, but excluding the System Libraries of the Combined Work.
1. Exception to Section 3 of the GNU GPL.
You may convey a covered work under sections 3 and 4 of this License
without being bound by section 3 of the GNU GPL.
2. Conveying Modified Versions.
If you modify a copy of the Library, and, in your modifications, a
facility refers to a function or data to be supplied by an Application
that uses the facility (other than as an argument passed when the
facility is invoked), then you may convey a copy of the modified
version:
a) under this License, provided that you make a good faith effort to
ensure that, in the event an Application does not supply the
function or data, the facility still operates, and performs
whatever part of its purpose remains meaningful, or
b) under the GNU GPL, with none of the additional permissions of
this License applicable to that copy.
3. Object Code Incorporating Material from Library Header Files.
The object code form of an Application may incorporate material from
a header file that is part of the Library. You may convey such object
code under terms of your choice, provided that, if the incorporated
material is not limited to numerical parameters, data structure
layouts and accessors, or small macros, inline functions and templates
(ten or fewer lines in length), you do both of the following:
a) Give prominent notice with each copy of the object code that the
Library is used in it and that the Library and its use are
covered by this License.
b) Accompany the object code with a copy of the GNU GPL and this license
document.
4. Combined Works.
You may convey a Combined Work under terms of your choice that,
taken together, effectively do not restrict modification of the
portions of the Library contained in the Combined Work and reverse
engineering for debugging such modifications, if you also do each of
the following:
a) Give prominent notice with each copy of the Combined Work that
the Library is used in it and that the Library and its use are
covered by this License.
b) Accompany the Combined Work with a copy of the GNU GPL and this license
document.
c) For a Combined Work that displays copyright notices during
execution, include the copyright notice for the Library among
these notices, as well as a reference directing the user to the
copies of the GNU GPL and this license document.
d) Do one of the following:
0) Convey the Minimal Corresponding Source under the terms of this
License, and the Corresponding Application Code in a form
suitable for, and under terms that permit, the user to
recombine or relink the Application with a modified version of
the Linked Version to produce a modified Combined Work, in the
manner specified by section 6 of the GNU GPL for conveying
Corresponding Source.
1) Use a suitable shared library mechanism for linking with the
Library. A suitable mechanism is one that (a) uses at run time
a copy of the Library already present on the user's computer
system, and (b) will operate properly with a modified version
of the Library that is interface-compatible with the Linked
Version.
e) Provide Installation Information, but only if you would otherwise
be required to provide such information under section 6 of the
GNU GPL, and only to the extent that such information is
necessary to install and execute a modified version of the
Combined Work produced by recombining or relinking the
Application with a modified version of the Linked Version. (If
you use option 4d0, the Installation Information must accompany
the Minimal Corresponding Source and Corresponding Application
Code. If you use option 4d1, you must provide the Installation
Information in the manner specified by section 6 of the GNU GPL
for conveying Corresponding Source.)
5. Combined Libraries.
You may place library facilities that are a work based on the
Library side by side in a single library together with other library
facilities that are not Applications and are not covered by this
License, and convey such a combined library under terms of your
choice, if you do both of the following:
a) Accompany the combined library with a copy of the same work based
on the Library, uncombined with any other library facilities,
conveyed under the terms of this License.
b) Give prominent notice with the combined library that part of it
is a work based on the Library, and explaining where to find the
accompanying uncombined form of the same work.
6. Revised Versions of the GNU Lesser General Public License.
The Free Software Foundation may publish revised and/or new versions
of the GNU Lesser General Public License from time to time. Such new
versions will be similar in spirit to the present version, but may
differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the
Library as you received it specifies that a certain numbered version
of the GNU Lesser General Public License "or any later version"
applies to it, you have the option of following the terms and
conditions either of that published version or of any later version
published by the Free Software Foundation. If the Library as you
received it does not specify a version number of the GNU Lesser
General Public License, you may choose any version of the GNU Lesser
General Public License ever published by the Free Software Foundation.
If the Library as you received it specifies that a proxy can decide
whether future versions of the GNU Lesser General Public License shall
apply, that proxy's public statement of acceptance of any version is
permanent authorization for you to choose that version for the
Library.

103
lib/helius_microrl/README Executable file
View File

@ -0,0 +1,103 @@
microrl - micro read line library for small and embedded devices with basic VT100 support.
1. DESCRIPTION
Microrl library is designed to help implement command line interface in small and embedded devices. Main goal is to write compact, small memory consuming but powerful interfaces, with support navigation through command line with cursor, HOME, END keys, hot key like Ctrl+U and other, history and completion feature.
2. FEATURE
** config.h file
- Turn on/off feature for add functional/decrease memory via config files.
** hot keys support
- backspace, cursor arrow, HOME, END keys
- Ctrl+U (cut line from cursor to begin)
- Ctrl+K (cut line from cursor to end)
- Ctrl+A (like HOME)
- Ctrl+E (like END)
- Ctrl+H (like backspace)
- Ctrl+B (like cursor arrow left)
- Ctrl+F (like cursor arrow right)
- Ctrl+P (like cursor arrow up)
- Ctrl+N (like cursor arrow down)
- Ctrl+C (call 'sigint' callback, only for embedded system)
** history
- Static ring buffer history for memory saving. Number of commands saved to history depends from commands length and buffer size (defined in config)
** completion
- via completion callback
3. SRC STRUCTURE
src/ - library source
microrl.c - microrl routines
microrl.h - lib interface and data type
config.h - customisation config-file
examples/ - library usage examples
avr_misc/ - avr specific routines for avr example
unix_misc/ - unix specific routines for desktop example
example.c - common part of example, for build demonstrating example for various platform
example_misc.h - interface to platform specific routines for example build (avr, unix)
Makefile - unix example build (gcc)
Makefile.avr - avr example build (avr-gcc)
4. INSTALL
Requirements: C compiler with support for C99 standard (GNU GCC, Keil, IAR) with standard C library (libc, uClibc or other compatible). Also you have to implement several routines in your own code for library to work.
NOTE: need add -std=gnu99 arg for gcc
For embed lib to you project, you need to do few simple steps:
a) Include microrl.h file to you project.
b) Create 'microrl_t' object, and call 'microrl_init' func, with print callback pointer. Print callback pointer is pointer to function that call by library if it's need to put text to terminal. Text string always is null terminated.
For example on linux PC print callback may be:
// print callback for microrl library
void print (char * str)
{
fprintf (stdout, "%s", str);
}
c) Call 'microrl_set_execute_callback' with pointer to you routine, what will be called if user press enter in terminal. Execute callback give a 'argc', 'argv' parametrs, like 'main' func in application. All token in 'argv' is null terminated. So you can simply walk through argv and handle commands.
d) If you want completion support if user press TAB key, call 'microrl_set_complete_callback' and set you callback. It also give 'argc' and 'argv' arguments, so iterate through it and return set of complete variants.
e) Look at 'config.h' file, for tune library for you requiring.
f) Now you just call 'microrl_insert_char' on each char received from input stream (usart, network, etc).
Example of code:
//*****************************************************************************
int main (int argc, char ** argv)
{
// create microrl object and pointer on it
microrl_t rl;
microrl_t * prl = &rl;
// call init with ptr to microrl instance and print callback
microrl_init (prl, print);
// set callback for execute
microrl_set_execute_callback (prl, execute);
// set callback for completion (optionally)
microrl_set_complete_callback (prl, complet);
// set callback for ctrl+c handling (optionally)
microrl_set_sigint_callback (prl, sigint);
while (1) {
// put received char from stdin to microrl lib
char ch = get_char ();
microrl_insert_char (prl, ch);
}
return 0;
}
See examples library usage.
Author: Eugene Samoylov aka Helius (ghelius@gmail.com)
01.09.2011

104
lib/helius_microrl/config.h Executable file
View File

@ -0,0 +1,104 @@
/*
Microrl library config files
Autor: Eugene Samoylov aka Helius (ghelius@gmail.com)
*/
#ifndef _MICRORL_CONFIG_H_
#define _MICRORL_CONFIG_H_
#define MICRORL_LIB_VER "1.5.1"
/*********** CONFIG SECTION **************/
/*
Command line length, define cmdline buffer size. Set max number of chars + 1,
because last byte of buffer need to contain '\0' - NULL terminator, and
not use for storing inputed char.
If user input chars more then it parametrs-1, chars not added to command line.*/
#define _COMMAND_LINE_LEN (1+100) // for 32 chars
/*
Command token number, define max token it command line, if number of token
typed in command line exceed this value, then prints message about it and
command line not to be parced and 'execute' callback will not calls.
Token is word separate by white space, for example 3 token line:
"IRin> set mode test" */
#define _COMMAND_TOKEN_NMB 8
/*
Define you prompt string here. You can use colors escape code, for highlight you prompt,
for example this prompt will green color (if you terminal supports color)*/
//#define _PROMPT_DEFAULT "\033[32mIRin >\033[0m " // green color
//#define _PROMPT_DEFAULT "IRin > "
#define _PROMPT_DEFAULT ">"
/*
Define prompt text (without ESC sequence, only text) prompt length, it needs because if you use
ESC sequence, it's not possible detect only text length*/
#define _PROMPT_LEN 1
/*Define it, if you wanna use completion functional, also set completion callback in you code,
now if user press TAB calls 'copmlitetion' callback. If you no need it, you can just set
NULL to callback ptr and do not use it, but for memory saving tune,
if you are not going to use it - disable this define.*/
//#define _USE_COMPLETE
/*Define it, if you wanna use history. It s work's like bash history, and
set stored value to cmdline, if UP and DOWN key pressed. Using history add
memory consuming, depends from _RING_HISTORY_LEN parametr */
//#define _USE_HISTORY
/*
History ring buffer length, define static buffer size.
For saving memory, each entered cmdline store to history in ring buffer,
so we can not say, how many line we can store, it depends from cmdline len,
but memory using more effective. We not prefer dinamic memory allocation for
small and embedded devices. Overhead is 2 char on each saved line*/
//#define _RING_HISTORY_LEN 64
/*
Enable Handling terminal ESC sequence. If disabling, then cursor arrow, HOME, END will not work,
use Ctrl+A(B,F,P,N,A,E,H,K,U,C) see README, but decrease code memory.*/
//#define _USE_ESC_SEQ
/*
Use snprintf from you standard complier library, but it gives some overhead.
If not defined, use my own u16int_to_str variant, it's save about 800 byte of code size
on AVR (avr-gcc build).
Try to build with and without, and compare total code size for tune library.
*/
#define _USE_LIBC_STDIO
/*
Enable 'interrupt signal' callback, if user press Ctrl+C */
//#define _USE_CTLR_C
/*
Print prompt at 'microrl_init', if enable, prompt will print at startup,
otherwise first prompt will print after first press Enter in terminal
NOTE!: Enable it, if you call 'microrl_init' after your communication subsystem
already initialize and ready to print message */
#define _ENABLE_INIT_PROMPT
/*
New line symbol */
#define _ENDL_CR
#if defined(_ENDL_CR)
#define ENDL "\r"
#elif defined(_ENDL_CRLF)
#define ENDL "\r\n"
#elif defined(_ENDL_LF)
#define ENDL "\n"
#elif defined(_ENDL_LFCR)
#define ENDL "\n\r"
#else
#error "You must define new line symbol."
#endif
/********** END CONFIG SECTION ************/
#if _RING_HISTORY_LEN > 256
#error "This history implementation (ring buffer with 1 byte iterator) allow 256 byte buffer size maximum"
#endif
#endif

684
lib/helius_microrl/microrl.c Executable file
View File

@ -0,0 +1,684 @@
/*
Author: Samoylov Eugene aka Helius (ghelius@gmail.com)
BUGS and TODO:
-- add echo_off feature
-- rewrite history for use more than 256 byte buffer
*/
#include <string.h>
#include <ctype.h>
#include <stdlib.h>
#include "microrl.h"
#ifdef _USE_LIBC_STDIO
#include <stdio.h>
#endif
//#define DBG(...) fprintf(stderr, "\033[33m");fprintf(stderr,__VA_ARGS__);fprintf(stderr,"\033[0m");
char * prompt_default = _PROMPT_DEFAULT;
#ifdef _USE_HISTORY
#ifdef _HISTORY_DEBUG
//*****************************************************************************
// print buffer content on screen
static void print_hist (ring_history_t * pThis)
{
printf ("\n");
for (int i = 0; i < _RING_HISTORY_LEN; i++) {
if (i == pThis->begin)
printf ("b");
else
printf (" ");
}
printf ("\n");
for (int i = 0; i < _RING_HISTORY_LEN; i++) {
if (isalpha(pThis->ring_buf[i]))
printf ("%c", pThis->ring_buf[i]);
else
printf ("%d", pThis->ring_buf[i]);
}
printf ("\n");
for (int i = 0; i < _RING_HISTORY_LEN; i++) {
if (i == pThis->end)
printf ("e");
else
printf (" ");
}
printf ("\n");
}
#endif
//*****************************************************************************
// remove older message from ring buffer
static void hist_erase_older (ring_history_t * pThis)
{
int new_pos = pThis->begin + pThis->ring_buf [pThis->begin] + 1;
if (new_pos >= _RING_HISTORY_LEN)
new_pos = new_pos - _RING_HISTORY_LEN;
pThis->begin = new_pos;
}
//*****************************************************************************
// check space for new line, remove older while not space
static int hist_is_space_for_new (ring_history_t * pThis, int len)
{
if (pThis->ring_buf [pThis->begin] == 0)
return true;
if (pThis->end >= pThis->begin) {
if (_RING_HISTORY_LEN - pThis->end + pThis->begin - 1 > len)
return true;
} else {
if (pThis->begin - pThis->end - 1> len)
return true;
}
return false;
}
//*****************************************************************************
// put line to ring buffer
static void hist_save_line (ring_history_t * pThis, char * line, int len)
{
if (len > _RING_HISTORY_LEN - 2)
return;
while (!hist_is_space_for_new (pThis, len)) {
hist_erase_older (pThis);
}
// if it's first line
if (pThis->ring_buf [pThis->begin] == 0)
pThis->ring_buf [pThis->begin] = len;
// store line
if (len < _RING_HISTORY_LEN-pThis->end-1)
memcpy (pThis->ring_buf + pThis->end + 1, line, len);
else {
int part_len = _RING_HISTORY_LEN-pThis->end-1;
memcpy (pThis->ring_buf + pThis->end + 1, line, part_len);
memcpy (pThis->ring_buf, line + part_len, len - part_len);
}
pThis->ring_buf [pThis->end] = len;
pThis->end = pThis->end + len + 1;
if (pThis->end >= _RING_HISTORY_LEN)
pThis->end -= _RING_HISTORY_LEN;
pThis->ring_buf [pThis->end] = 0;
pThis->cur = 0;
#ifdef _HISTORY_DEBUG
print_hist (pThis);
#endif
}
//*****************************************************************************
// copy saved line to 'line' and return size of line
static int hist_restore_line (ring_history_t * pThis, char * line, int dir)
{
int cnt = 0;
// count history record
int header = pThis->begin;
while (pThis->ring_buf [header] != 0) {
header += pThis->ring_buf [header] + 1;
if (header >= _RING_HISTORY_LEN)
header -= _RING_HISTORY_LEN;
cnt++;
}
if (dir == _HIST_UP) {
if (cnt >= pThis->cur) {
int header = pThis->begin;
int j = 0;
// found record for 'pThis->cur' index
while ((pThis->ring_buf [header] != 0) && (cnt - j -1 != pThis->cur)) {
header += pThis->ring_buf [header] + 1;
if (header >= _RING_HISTORY_LEN)
header -= _RING_HISTORY_LEN;
j++;
}
if (pThis->ring_buf[header]) {
pThis->cur++;
// obtain saved line
if (pThis->ring_buf [header] + header < _RING_HISTORY_LEN) {
memset (line, 0, _COMMAND_LINE_LEN);
memcpy (line, pThis->ring_buf + header + 1, pThis->ring_buf[header]);
} else {
int part0 = _RING_HISTORY_LEN - header - 1;
memset (line, 0, _COMMAND_LINE_LEN);
memcpy (line, pThis->ring_buf + header + 1, part0);
memcpy (line + part0, pThis->ring_buf, pThis->ring_buf[header] - part0);
}
return pThis->ring_buf[header];
}
}
} else {
if (pThis->cur > 0) {
pThis->cur--;
int header = pThis->begin;
int j = 0;
while ((pThis->ring_buf [header] != 0) && (cnt - j != pThis->cur)) {
header += pThis->ring_buf [header] + 1;
if (header >= _RING_HISTORY_LEN)
header -= _RING_HISTORY_LEN;
j++;
}
if (pThis->ring_buf [header] + header < _RING_HISTORY_LEN) {
memcpy (line, pThis->ring_buf + header + 1, pThis->ring_buf[header]);
} else {
int part0 = _RING_HISTORY_LEN - header - 1;
memcpy (line, pThis->ring_buf + header + 1, part0);
memcpy (line + part0, pThis->ring_buf, pThis->ring_buf[header] - part0);
}
return pThis->ring_buf[header];
} else {
/* empty line */
return 0;
}
}
return -1;
}
#endif
//*****************************************************************************
// split cmdline to tkn array and return nmb of token
static int split (microrl_t * pThis, int limit, char const ** tkn_arr)
{
int i = 0;
int ind = 0;
while (1) {
// go to the first whitespace (zerro for us)
while ((pThis->cmdline [ind] == '\0') && (ind < limit)) {
ind++;
}
if (!(ind < limit)) return i;
tkn_arr[i++] = pThis->cmdline + ind;
if (i >= _COMMAND_TOKEN_NMB) {
return -1;
}
// go to the first NOT whitespace (not zerro for us)
while ((pThis->cmdline [ind] != '\0') && (ind < limit)) {
ind++;
}
if (!(ind < limit)) return i;
}
return i;
}
//*****************************************************************************
inline static void print_prompt (microrl_t * pThis)
{
pThis->print (pThis->prompt_str);
}
//*****************************************************************************
inline static void terminal_backspace (microrl_t * pThis)
{
pThis->print ("\033[D \033[D");
}
//*****************************************************************************
inline static void terminal_newline (microrl_t * pThis)
{
pThis->print (ENDL);
}
#ifndef _USE_LIBC_STDIO
//*****************************************************************************
// convert 16 bit value to string
// 0 value not supported!!! just make empty string
// Returns pointer to a buffer tail
static char *u16bit_to_str (unsigned int nmb, char * buf)
{
char tmp_str [6] = {0,};
int i = 0, j;
if (nmb <= 0xFFFF) {
while (nmb > 0) {
tmp_str[i++] = (nmb % 10) + '0';
nmb /=10;
}
for (j = 0; j < i; ++j)
*(buf++) = tmp_str [i-j-1];
}
*buf = '\0';
return buf;
}
#endif
//*****************************************************************************
// set cursor at position from begin cmdline (after prompt) + offset
static void terminal_move_cursor (microrl_t * pThis, int offset)
{
char str[16] = {0,};
#ifdef _USE_LIBC_STDIO
if (offset > 0) {
snprintf (str, 16, "\033[%dC", offset);
} else if (offset < 0) {
snprintf (str, 16, "\033[%dD", -(offset));
}
#else
char *endstr;
strcpy (str, "\033[");
if (offset > 0) {
endstr = u16bit_to_str (offset, str+2);
strcpy (endstr, "C");
} else if (offset < 0) {
endstr = u16bit_to_str (-(offset), str+2);
strcpy (endstr, "D");
} else
return;
#endif
pThis->print (str);
}
//*****************************************************************************
static void terminal_reset_cursor (microrl_t * pThis)
{
char str[16];
#ifdef _USE_LIBC_STDIO
snprintf (str, 16, "\033[%dD\033[%dC", \
_COMMAND_LINE_LEN + _PROMPT_LEN + 2, _PROMPT_LEN);
#else
char *endstr;
strcpy (str, "\033[");
endstr = u16bit_to_str ( _COMMAND_LINE_LEN + _PROMPT_LEN + 2,str+2);
strcpy (endstr, "D\033["); endstr += 3;
endstr = u16bit_to_str (_PROMPT_LEN, endstr);
strcpy (endstr, "C");
#endif
pThis->print (str);
}
//*****************************************************************************
// print cmdline to screen, replace '\0' to wihitespace
static void terminal_print_line (microrl_t * pThis, int pos, int cursor)
{
pThis->print ("\033[K"); // delete all from cursor to end
char nch [] = {0,0};
int i;
for (i = pos; i < pThis->cmdlen; i++) {
nch [0] = pThis->cmdline [i];
if (nch[0] == '\0')
nch[0] = ' ';
pThis->print (nch);
}
terminal_reset_cursor (pThis);
terminal_move_cursor (pThis, cursor);
}
//*****************************************************************************
void microrl_init (microrl_t * pThis, void (*print) (const char *))
{
memset(pThis->cmdline, 0, _COMMAND_LINE_LEN);
#ifdef _USE_HISTORY
memset(pThis->ring_hist.ring_buf, 0, _RING_HISTORY_LEN);
pThis->ring_hist.begin = 0;
pThis->ring_hist.end = 0;
pThis->ring_hist.cur = 0;
#endif
pThis->cmdlen =0;
pThis->cursor = 0;
pThis->execute = NULL;
pThis->get_completion = NULL;
#ifdef _USE_CTLR_C
pThis->sigint = NULL;
#endif
pThis->prompt_str = prompt_default;
pThis->print = print;
#ifdef _ENABLE_INIT_PROMPT
print_prompt (pThis);
#endif
}
//*****************************************************************************
void microrl_set_complete_callback (microrl_t * pThis, char ** (*get_completion)(int, const char* const*))
{
pThis->get_completion = get_completion;
}
//*****************************************************************************
void microrl_set_execute_callback (microrl_t * pThis, int (*execute)(int, const char* const*))
{
pThis->execute = execute;
}
#ifdef _USE_CTLR_C
//*****************************************************************************
void microrl_set_sigint_callback (microrl_t * pThis, void (*sigintf)(void))
{
pThis->sigint = sigintf;
}
#endif
#ifdef _USE_ESC_SEQ
static void hist_search (microrl_t * pThis, int dir)
{
int len = hist_restore_line (&pThis->ring_hist, pThis->cmdline, dir);
if (len >= 0) {
pThis->cursor = pThis->cmdlen = len;
terminal_reset_cursor (pThis);
terminal_print_line (pThis, 0, pThis->cursor);
}
}
//*****************************************************************************
// handling escape sequences
static int escape_process (microrl_t * pThis, char ch)
{
if (ch == '[') {
pThis->escape_seq = _ESC_BRACKET;
return 0;
} else if (pThis->escape_seq == _ESC_BRACKET) {
if (ch == 'A') {
#ifdef _USE_HISTORY
hist_search (pThis, _HIST_UP);
#endif
return 1;
} else if (ch == 'B') {
#ifdef _USE_HISTORY
hist_search (pThis, _HIST_DOWN);
#endif
return 1;
} else if (ch == 'C') {
if (pThis->cursor < pThis->cmdlen) {
terminal_move_cursor (pThis, 1);
pThis->cursor++;
}
return 1;
} else if (ch == 'D') {
if (pThis->cursor > 0) {
terminal_move_cursor (pThis, -1);
pThis->cursor--;
}
return 1;
} else if (ch == '7') {
pThis->escape_seq = _ESC_HOME;
return 0;
} else if (ch == '8') {
pThis->escape_seq = _ESC_END;
return 0;
}
} else if (ch == '~') {
if (pThis->escape_seq == _ESC_HOME) {
terminal_reset_cursor (pThis);
pThis->cursor = 0;
return 1;
} else if (pThis->escape_seq == _ESC_END) {
terminal_move_cursor (pThis, pThis->cmdlen-pThis->cursor);
pThis->cursor = pThis->cmdlen;
return 1;
}
}
/* unknown escape sequence, stop */
return 1;
}
#endif
//*****************************************************************************
// insert len char of text at cursor position
static int microrl_insert_text (microrl_t * pThis, char * text, int len)
{
int i;
if (pThis->cmdlen + len < _COMMAND_LINE_LEN) {
memmove (pThis->cmdline + pThis->cursor + len,
pThis->cmdline + pThis->cursor,
pThis->cmdlen - pThis->cursor);
for (i = 0; i < len; i++) {
pThis->cmdline [pThis->cursor + i] = text [i];
if (pThis->cmdline [pThis->cursor + i] == ' ') {
pThis->cmdline [pThis->cursor + i] = 0;
}
}
pThis->cursor += len;
pThis->cmdlen += len;
pThis->cmdline [pThis->cmdlen] = '\0';
return true;
}
return false;
}
//*****************************************************************************
// remove one char at cursor
static void microrl_backspace (microrl_t * pThis)
{
if (pThis->cursor > 0) {
terminal_backspace (pThis);
memmove (pThis->cmdline + pThis->cursor-1,
pThis->cmdline + pThis->cursor,
pThis->cmdlen-pThis->cursor+1);
pThis->cursor--;
pThis->cmdline [pThis->cmdlen] = '\0';
pThis->cmdlen--;
}
}
#ifdef _USE_COMPLETE
//*****************************************************************************
static int common_len (char ** arr)
{
unsigned int i;
unsigned int j;
char *shortest = arr[0];
unsigned int shortlen = strlen(shortest);
for (i = 0; arr[i] != NULL; ++i)
if (strlen(arr[i]) < shortlen) {
shortest = arr[i];
shortlen = strlen(shortest);
}
for (i = 0; i < shortlen; ++i)
for (j = 0; arr[j] != 0; ++j)
if (shortest[i] != arr[j][i])
return i;
return i;
}
//*****************************************************************************
static void microrl_get_complite (microrl_t * pThis)
{
char const * tkn_arr[_COMMAND_TOKEN_NMB];
char ** compl_token;
if (pThis->get_completion == NULL) // callback was not set
return;
int status = split (pThis, pThis->cursor, tkn_arr);
if (pThis->cmdline[pThis->cursor-1] == '\0')
tkn_arr[status++] = "";
compl_token = pThis->get_completion (status, tkn_arr);
if (compl_token[0] != NULL) {
int i = 0;
int len;
if (compl_token[1] == NULL) {
len = strlen (compl_token[0]);
} else {
len = common_len (compl_token);
terminal_newline (pThis);
while (compl_token [i] != NULL) {
pThis->print (compl_token[i]);
pThis->print (" ");
i++;
}
terminal_newline (pThis);
print_prompt (pThis);
}
if (len) {
microrl_insert_text (pThis, compl_token[0] + strlen(tkn_arr[status-1]),
len - strlen(tkn_arr[status-1]));
if (compl_token[1] == NULL)
microrl_insert_text (pThis, " ", 1);
}
terminal_reset_cursor (pThis);
terminal_print_line (pThis, 0, pThis->cursor);
}
}
#endif
//*****************************************************************************
void new_line_handler(microrl_t * pThis){
char const * tkn_arr [_COMMAND_TOKEN_NMB];
int status;
terminal_newline (pThis);
#ifdef _USE_HISTORY
if (pThis->cmdlen > 0)
hist_save_line (&pThis->ring_hist, pThis->cmdline, pThis->cmdlen);
#endif
status = split (pThis, pThis->cmdlen, tkn_arr);
if (status == -1){
// pThis->print ("ERROR: Max token amount exseed\n");
pThis->print ("ERROR:too many tokens");
pThis->print (ENDL);
}
if ((status > 0) && (pThis->execute != NULL))
pThis->execute (status, tkn_arr);
print_prompt (pThis);
pThis->cmdlen = 0;
pThis->cursor = 0;
memset(pThis->cmdline, 0, _COMMAND_LINE_LEN);
#ifdef _USE_HISTORY
pThis->ring_hist.cur = 0;
#endif
}
//*****************************************************************************
void microrl_insert_char (microrl_t * pThis, int ch)
{
#ifdef _USE_ESC_SEQ
if (pThis->escape) {
if (escape_process(pThis, ch))
pThis->escape = 0;
} else {
#endif
switch (ch) {
//-----------------------------------------------------
#ifdef _ENDL_CR
case KEY_CR:
new_line_handler(pThis);
break;
case KEY_LF:
break;
#elif defined(_ENDL_CRLF)
case KEY_CR:
pThis->tmpch = KEY_CR;
break;
case KEY_LF:
if (pThis->tmpch == KEY_CR)
new_line_handler(pThis);
break;
#elif defined(_ENDL_LFCR)
case KEY_LF:
pThis->tmpch = KEY_LF;
break;
case KEY_CR:
if (pThis->tmpch == KEY_LF)
new_line_handler(pThis);
break;
#else
case KEY_CR:
break;
case KEY_LF:
new_line_handler(pThis);
break;
#endif
//-----------------------------------------------------
#ifdef _USE_COMPLETE
case KEY_HT:
microrl_get_complite (pThis);
break;
#endif
//-----------------------------------------------------
case KEY_ESC:
#ifdef _USE_ESC_SEQ
pThis->escape = 1;
#endif
break;
//-----------------------------------------------------
case KEY_NAK: // ^U
while (pThis->cursor > 0) {
microrl_backspace (pThis);
}
terminal_print_line (pThis, 0, pThis->cursor);
break;
//-----------------------------------------------------
case KEY_VT: // ^K
pThis->print ("\033[K");
pThis->cmdlen = pThis->cursor;
break;
//-----------------------------------------------------
case KEY_ENQ: // ^E
terminal_move_cursor (pThis, pThis->cmdlen-pThis->cursor);
pThis->cursor = pThis->cmdlen;
break;
//-----------------------------------------------------
case KEY_SOH: // ^A
terminal_reset_cursor (pThis);
pThis->cursor = 0;
break;
//-----------------------------------------------------
case KEY_ACK: // ^F
if (pThis->cursor < pThis->cmdlen) {
terminal_move_cursor (pThis, 1);
pThis->cursor++;
}
break;
//-----------------------------------------------------
case KEY_STX: // ^B
if (pThis->cursor) {
terminal_move_cursor (pThis, -1);
pThis->cursor--;
}
break;
//-----------------------------------------------------
case KEY_DLE: //^P
#ifdef _USE_HISTORY
hist_search (pThis, _HIST_UP);
#endif
break;
//-----------------------------------------------------
case KEY_SO: //^N
#ifdef _USE_HISTORY
hist_search (pThis, _HIST_DOWN);
#endif
break;
//-----------------------------------------------------
case KEY_DEL: // Backspace
case KEY_BS: // ^U
microrl_backspace (pThis);
terminal_print_line (pThis, pThis->cursor, pThis->cursor);
break;
#ifdef _USE_CTLR_C
case KEY_ETX:
if (pThis->sigint != NULL)
pThis->sigint();
break;
#endif
//-----------------------------------------------------
default:
if (((ch == ' ') && (pThis->cmdlen == 0)) || IS_CONTROL_CHAR(ch))
break;
if (microrl_insert_text (pThis, (char*)&ch, 1))
terminal_print_line (pThis, pThis->cursor-1, pThis->cursor);
break;
}
#ifdef _USE_ESC_SEQ
}
#endif
}

117
lib/helius_microrl/microrl.h Executable file
View File

@ -0,0 +1,117 @@
#ifndef _MICRORL_H_
#define _MICRORL_H_
#include "config.h"
#define true 1
#define false 0
/* define the Key codes */
#define KEY_NUL 0 /**< ^@ Null character */
#define KEY_SOH 1 /**< ^A Start of heading, = console interrupt */
#define KEY_STX 2 /**< ^B Start of text, maintenance mode on HP console */
#define KEY_ETX 3 /**< ^C End of text */
#define KEY_EOT 4 /**< ^D End of transmission, not the same as ETB */
#define KEY_ENQ 5 /**< ^E Enquiry, goes with ACK; old HP flow control */
#define KEY_ACK 6 /**< ^F Acknowledge, clears ENQ logon hand */
#define KEY_BEL 7 /**< ^G Bell, rings the bell... */
#define KEY_BS 8 /**< ^H Backspace, works on HP terminals/computers */
#define KEY_HT 9 /**< ^I Horizontal tab, move to next tab stop */
#define KEY_LF 10 /**< ^J Line Feed */
#define KEY_VT 11 /**< ^K Vertical tab */
#define KEY_FF 12 /**< ^L Form Feed, page eject */
#define KEY_CR 13 /**< ^M Carriage Return*/
#define KEY_SO 14 /**< ^N Shift Out, alternate character set */
#define KEY_SI 15 /**< ^O Shift In, resume defaultn character set */
#define KEY_DLE 16 /**< ^P Data link escape */
#define KEY_DC1 17 /**< ^Q XON, with XOFF to pause listings; "okay to send". */
#define KEY_DC2 18 /**< ^R Device control 2, block-mode flow control */
#define KEY_DC3 19 /**< ^S XOFF, with XON is TERM=18 flow control */
#define KEY_DC4 20 /**< ^T Device control 4 */
#define KEY_NAK 21 /**< ^U Negative acknowledge */
#define KEY_SYN 22 /**< ^V Synchronous idle */
#define KEY_ETB 23 /**< ^W End transmission block, not the same as EOT */
#define KEY_CAN 24 /**< ^X Cancel line, MPE echoes !!! */
#define KEY_EM 25 /**< ^Y End of medium, Control-Y interrupt */
#define KEY_SUB 26 /**< ^Z Substitute */
#define KEY_ESC 27 /**< ^[ Escape, next character is not echoed */
#define KEY_FS 28 /**< ^\ File separator */
#define KEY_GS 29 /**< ^] Group separator */
#define KEY_RS 30 /**< ^^ Record separator, block-mode terminator */
#define KEY_US 31 /**< ^_ Unit separator */
#define KEY_DEL 127 /**< Delete (not a real control character...) */
#define IS_CONTROL_CHAR(x) ((x)<=31)
// direction of history navigation
#define _HIST_UP 0
#define _HIST_DOWN 1
// esc seq internal codes
#define _ESC_BRACKET 1
#define _ESC_HOME 2
#define _ESC_END 3
#ifdef _USE_HISTORY
// history struct, contain internal variable
// history store in static ring buffer for memory saving
typedef struct {
char ring_buf [_RING_HISTORY_LEN];
int begin;
int end;
int cur;
} ring_history_t;
#endif
// microrl struct, contain internal library data
typedef struct {
#ifdef _USE_ESC_SEQ
char escape_seq;
char escape;
#endif
#if (defined(_ENDL_CRLF) || defined(_ENDL_LFCR))
char tmpch;
#endif
#ifdef _USE_HISTORY
ring_history_t ring_hist; // history object
#endif
char * prompt_str; // pointer to prompt string
char cmdline [_COMMAND_LINE_LEN]; // cmdline buffer
int cmdlen; // last position in command line
int cursor; // input cursor
int (*execute) (int argc, const char * const * argv ); // ptr to 'execute' callback
char ** (*get_completion) (int argc, const char * const * argv ); // ptr to 'completion' callback
void (*print) (const char *); // ptr to 'print' callback
#ifdef _USE_CTLR_C
void (*sigint) (void);
#endif
} microrl_t;
// init internal data, calls once at start up
void microrl_init (microrl_t * pThis, void (*print)(const char*));
// set echo mode (true/false), using for disabling echo for password input
// echo mode will enabled after user press Enter.
void microrl_set_echo (int);
// set pointer to callback complition func, that called when user press 'Tab'
// callback func description:
// param: argc - argument count, argv - pointer array to token string
// must return NULL-terminated string, contain complite variant splitted by 'Whitespace'
// If complite token found, it's must contain only one token to be complitted
// Empty string if complite not found, and multiple string if there are some token
void microrl_set_complete_callback (microrl_t * pThis, char ** (*get_completion)(int, const char* const*));
// pointer to callback func, that called when user press 'Enter'
// execute func param: argc - argument count, argv - pointer array to token string
void microrl_set_execute_callback (microrl_t * pThis, int (*execute)(int, const char* const*));
// set callback for Ctrl+C terminal signal
#ifdef _USE_CTLR_C
void microrl_set_sigint_callback (microrl_t * pThis, void (*sigintf)(void));
#endif
// insert char to cmdline (for example call in usart RX interrupt)
void microrl_insert_char (microrl_t * pThis, int ch);
#endif