1 /**
2  * DinkC interactive console
3 
4  * Copyright (C) 2005, 2006  Dan Walma
5  * Copyright (C) 2008, 2009  Sylvain Beucler
6 
7  * This file is part of GNU FreeDink
8 
9  * GNU FreeDink is free software; you can redistribute it and/or
10  * modify it under the terms of the GNU General Public License as
11  * published by the Free Software Foundation; either version 3 of the
12  * License, or (at your option) any later version.
13 
14  * GNU FreeDink is distributed in the hope that it will be useful, but
15  * WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17  * General Public License for more details.
18 
19  * You should have received a copy of the GNU General Public License
20  * along with this program.  If not, see
21  * <http://www.gnu.org/licenses/>.
22  */
23 
24 #ifdef HAVE_CONFIG_H
25 #include <config.h>
26 #endif
27 
28 #include "dinkc_console.h"
29 
30 #include <string.h>
31 #include "str_util.h"
32 #include "dinkc.h"
33 
34 #define NB_LINES 20
35 #define MAX_LINE_LEN 254
36 
37 /* Console mode */
38 int console_active = 0;
39 
40 
41 /* Last 20 commands entered in the console */
42 static char history[NB_LINES][MAX_LINE_LEN+1];
43 
44 /* Current history index */
45 static int cur_line = 0;
46 
47 /* Result of the last evaluation */
48 static int console_return_value = 0;
49 
50 
dinkc_console_process_key(SDL_KeyboardEvent kev)51 void dinkc_console_process_key(SDL_KeyboardEvent kev)
52 {
53   if (kev.keysym.sym == SDLK_UP)
54     {
55       cur_line--;
56       /* Using (a+N)%N instead of a%N to avoid negative results */
57       cur_line = (cur_line + NB_LINES) % NB_LINES;
58     }
59   else if(kev.keysym.sym == SDLK_DOWN)
60     {
61       cur_line++;
62       cur_line %= NB_LINES;
63     }
64   else if (kev.keysym.sym == SDLK_BACKSPACE)
65     {
66       /* Delete last char */
67       int len = strlen(history[cur_line]);
68       if (len > 0)
69 	history[cur_line][len-1] = '\0';
70     }
71   else if (kev.keysym.sym == SDLK_ESCAPE)
72     {
73       console_active = 0;
74     }
75   else if (kev.keysym.unicode == SDLK_RETURN)
76     {
77       /* Try to parse the string */
78       console_return_value = dinkc_execute_one_liner(history[cur_line]);
79 
80       /* Go the next line */
81       cur_line++;
82       cur_line %= NB_LINES;
83       int len = strlen(history[cur_line]);
84       if (len > 0)
85 	history[cur_line][0] = '\0';
86     }
87   else if (kev.keysym.unicode != 0)
88     {
89       /* Append character to the current line */
90       if (strlen(history[cur_line]) < MAX_LINE_LEN)
91 	strchar(history[cur_line], kev.keysym.unicode);
92     }
93 }
94 
dinkc_console_get_cur_line()95 char* dinkc_console_get_cur_line()
96 {
97   return history[cur_line];
98 }
99 
dinkc_console_get_last_retval()100 int dinkc_console_get_last_retval()
101 {
102   return console_return_value;
103 }
104