Added line-editing functionality to console (issue 111)
[supertux.git] / src / console.cpp
1 //  $Id$
2 //
3 //  SuperTux - Console
4 //  Copyright (C) 2006 Christoph Sommer <christoph.sommer@2006.expires.deltadevelopment.de>
5 //
6 //  This program is free software; you can redistribute it and/or
7 //  modify it under the terms of the GNU General Public License
8 //  as published by the Free Software Foundation; either version 2
9 //  of the License, or (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., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
19 #include <config.h>
20
21 #include <iostream>
22 #include <SDL_timer.h>
23 #include <SDL_keyboard.h>
24 #include "console.hpp"
25 #include "video/drawing_context.hpp"
26 #include "video/surface.hpp"
27 #include "scripting/squirrel_error.hpp"
28 #include "scripting/squirrel_util.hpp"
29 #include "physfs/physfs_stream.hpp"
30 #include "player_status.hpp"
31 #include "main.hpp"
32 #include "log.hpp"
33 #include "resources.hpp"
34 #include "gameconfig.hpp"
35
36 /// speed (pixels/s) the console closes
37 static const float FADE_SPEED = 1;
38
39 Console::Console()
40   : history_position(history.end()), vm(NULL), backgroundOffset(0),
41     height(0), alpha(1.0), offset(0), focused(false), stayOpen(0) {
42   fontheight = 8;
43 }
44
45 Console::~Console()
46 {
47   if(vm != NULL) {
48     sq_release(Scripting::global_vm, &vm_object);
49   }
50 }
51
52 void
53 Console::init_graphics()
54 {
55   font.reset(new Font(Font::FIXED,
56                       "images/engine/fonts/andale12.png",
57                       "images/engine/fonts/andale12-shadow.png", 7, 14, 1));
58   fontheight = font->get_height();
59   background.reset(new Surface("images/engine/console.png"));
60   background2.reset(new Surface("images/engine/console2.png"));
61 }
62
63 void
64 Console::flush(ConsoleStreamBuffer* buffer)
65 {
66   if (buffer == &outputBuffer) {
67     std::string s = outputBuffer.str();
68     if ((s.length() > 0) && ((s[s.length()-1] == '\n') || (s[s.length()-1] == '\r'))) {
69       while ((s[s.length()-1] == '\n') || (s[s.length()-1] == '\r')) s.erase(s.length()-1);
70       addLines(s);
71       outputBuffer.str(std::string());
72     }
73   }
74 }
75
76 void
77 Console::ready_vm()
78 {
79   if(vm == NULL) {
80     vm = Scripting::global_vm;
81     HSQUIRRELVM new_vm = sq_newthread(vm, 16);
82     if(new_vm == NULL)
83       throw Scripting::SquirrelError(vm, "Couldn't create new VM thread for console");
84
85     // store reference to thread
86     sq_resetobject(&vm_object);
87     if(SQ_FAILED(sq_getstackobj(vm, -1, &vm_object)))
88       throw Scripting::SquirrelError(vm, "Couldn't get vm object for console");
89     sq_addref(vm, &vm_object);
90     sq_pop(vm, 1);
91
92     // create new roottable for thread
93     sq_newtable(new_vm);
94     sq_pushroottable(new_vm);
95     if(SQ_FAILED(sq_setdelegate(new_vm, -2)))
96       throw Scripting::SquirrelError(new_vm, "Couldn't set console_table delegate");
97
98     sq_setroottable(new_vm);
99
100     vm = new_vm;
101
102     try {
103       std::string filename = "scripts/console.nut";
104       IFileStream stream(filename);
105       Scripting::compile_and_run(vm, stream, filename);
106     } catch(std::exception& e) {
107       log_warning << "Couldn't load console.nut: " << e.what() << std::endl;
108     }
109   }
110 }
111
112 void
113 Console::execute_script(const std::string& command)
114 {
115   using namespace Scripting;
116
117   ready_vm();
118
119   SQInteger oldtop = sq_gettop(vm);
120   try {
121     if(SQ_FAILED(sq_compilebuffer(vm, command.c_str(), command.length(),
122                  "", SQTrue)))
123       throw SquirrelError(vm, "Couldn't compile command");
124
125     sq_pushroottable(vm);
126     if(SQ_FAILED(sq_call(vm, 1, SQTrue, SQTrue)))
127       throw SquirrelError(vm, "Problem while executing command");
128
129     if(sq_gettype(vm, -1) != OT_NULL)
130       addLines(squirrel2string(vm, -1));
131   } catch(std::exception& e) {
132     addLines(e.what());
133   }
134   SQInteger newtop = sq_gettop(vm);
135   if(newtop < oldtop) {
136     log_fatal << "Script destroyed squirrel stack..." << std::endl;
137   } else {
138     sq_settop(vm, oldtop);
139   }
140 }
141
142 void 
143 Console::input(char c)
144 {
145   inputBuffer.insert(inputBufferPosition, 1, c);
146   inputBufferPosition++;
147 }
148
149 void
150 Console::backspace()
151 {
152   if ((inputBufferPosition > 0) && (inputBuffer.length() > 0)) {
153     inputBuffer.erase(inputBufferPosition-1, 1);
154     inputBufferPosition--;
155   }
156 }
157
158 void
159 Console::eraseChar()
160 {
161   if (inputBufferPosition < (int)inputBuffer.length()) {
162     inputBuffer.erase(inputBufferPosition, 1);
163   }
164 }
165
166 void
167 Console::enter()
168 {
169   addLines("> "+inputBuffer);
170   parse(inputBuffer);
171   inputBuffer = "";
172   inputBufferPosition = 0;
173 }
174
175 void
176 Console::scroll(int numLines)
177 {
178   offset += numLines;
179   if (offset > 0) offset = 0;
180 }
181
182 void
183 Console::show_history(int offset)
184 {
185   while ((offset > 0) && (history_position != history.end())) {
186     history_position++;
187     offset--;
188   }
189   while ((offset < 0) && (history_position != history.begin())) {
190     history_position--;
191     offset++;
192   }
193   if (history_position == history.end()) {
194     inputBuffer = "";
195     inputBufferPosition = 0;
196   } else {
197     inputBuffer = *history_position;
198     inputBufferPosition = inputBuffer.length();
199   }
200 }
201
202 void 
203 Console::move_cursor(int offset)
204 {
205   if (offset == -65535) inputBufferPosition = 0;
206   if (offset == +65535) inputBufferPosition = inputBuffer.length();
207   inputBufferPosition+=offset;
208   if (inputBufferPosition < 0) inputBufferPosition = 0;
209   if (inputBufferPosition > (int)inputBuffer.length()) inputBufferPosition = inputBuffer.length();
210 }
211
212 // Helper functions for Console::autocomplete
213 // TODO: Fix rough documentation
214 namespace {
215
216 void sq_insert_commands(std::list<std::string>& cmds, HSQUIRRELVM vm, std::string table_prefix, std::string search_prefix);
217
218 /**
219  * Acts upon key,value on top of stack:
220  * Appends key (plus type-dependent suffix) to cmds if table_prefix+key starts with search_prefix;
221  * Calls sq_insert_commands if search_prefix starts with table_prefix+key (and value is a table/class/instance);
222  */
223 void
224 sq_insert_command(std::list<std::string>& cmds, HSQUIRRELVM vm, std::string table_prefix, std::string search_prefix)
225 {
226   const SQChar* key_chars;
227   if (SQ_FAILED(sq_getstring(vm, -2, &key_chars))) return;
228   std::string key_string = table_prefix + key_chars;
229
230   switch (sq_gettype(vm, -1)) {
231     case OT_INSTANCE:
232       key_string+=".";
233       if (search_prefix.substr(0, key_string.length()) == key_string) {
234         sq_getclass(vm, -1);
235         sq_insert_commands(cmds, vm, key_string, search_prefix);
236         sq_pop(vm, 1);
237       }
238       break;
239     case OT_TABLE:
240     case OT_CLASS:
241       key_string+=".";
242       if (search_prefix.substr(0, key_string.length()) == key_string) {
243         sq_insert_commands(cmds, vm, key_string, search_prefix);
244       }
245       break;
246     case OT_CLOSURE:
247     case OT_NATIVECLOSURE:
248       key_string+="()";
249       break;
250     default:
251       break;
252   }
253
254   if (key_string.substr(0, search_prefix.length()) == search_prefix) {
255     cmds.push_back(key_string);
256   }
257
258 }
259
260 /**
261  * calls sq_insert_command for all entries of table/class on top of stack
262  */
263 void
264 sq_insert_commands(std::list<std::string>& cmds, HSQUIRRELVM vm, std::string table_prefix, std::string search_prefix)
265 {
266   sq_pushnull(vm); // push iterator
267   while (SQ_SUCCEEDED(sq_next(vm,-2))) {
268     sq_insert_command(cmds, vm, table_prefix, search_prefix);
269     sq_pop(vm, 2); // pop key, val
270   }
271   sq_pop(vm, 1); // pop iterator
272 }
273
274
275 }
276 // End of Console::autocomplete helper functions
277
278 void
279 Console::autocomplete()
280 {
281   //int autocompleteFrom = inputBuffer.find_last_of(" ();+", inputBufferPosition);
282   int autocompleteFrom = inputBuffer.find_last_not_of("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_->.", inputBufferPosition);
283   if (autocompleteFrom != (int)std::string::npos) {
284     autocompleteFrom += 1;
285   } else {
286     autocompleteFrom = 0;
287   }
288   std::string prefix = inputBuffer.substr(autocompleteFrom, inputBufferPosition - autocompleteFrom);
289   addLines("> "+prefix);
290
291   std::list<std::string> cmds;
292
293   ready_vm();
294
295   // append all keys of the current root table to list
296   sq_pushroottable(vm); // push root table
297   while(true) {
298     // check all keys (and their children) for matches
299     sq_insert_commands(cmds, vm, "", prefix);
300
301     // cycle through parent(delegate) table
302     SQInteger oldtop = sq_gettop(vm);
303     if(SQ_FAILED(sq_getdelegate(vm, -1)) || oldtop == sq_gettop(vm)) {
304       break;
305     }
306     sq_remove(vm, -2); // remove old table
307   }
308   sq_pop(vm, 1); // remove table
309
310   // depending on number of hits, show matches or autocomplete
311   if (cmds.size() == 0) addLines("No known command starts with \""+prefix+"\"");
312   if (cmds.size() == 1) {
313     // one match: just replace input buffer with full command
314     std::string replaceWith = cmds.front();
315     inputBuffer.replace(autocompleteFrom, prefix.length(), replaceWith);
316     inputBufferPosition += (replaceWith.length() - prefix.length());
317   }
318   if (cmds.size() > 1) {
319     // multiple matches: show all matches and set input buffer to longest common prefix
320     std::string commonPrefix = cmds.front();
321     while (cmds.begin() != cmds.end()) {
322       std::string cmd = cmds.front();
323       cmds.pop_front();
324       addLines(cmd);
325       for (int n = commonPrefix.length(); n >= 1; n--) {
326         if (cmd.compare(0, n, commonPrefix) != 0) commonPrefix.resize(n-1); else break;
327       }
328     }
329     std::string replaceWith = commonPrefix;
330     inputBuffer.replace(autocompleteFrom, prefix.length(), replaceWith);
331     inputBufferPosition += (replaceWith.length() - prefix.length());
332   }
333 }
334
335 void
336 Console::addLines(std::string s)
337 {
338   std::istringstream iss(s);
339   std::string line;
340   while (std::getline(iss, line, '\n')) addLine(line);
341 }
342
343 void
344 Console::addLine(std::string s)
345 {
346   // output line to stderr
347   std::cerr << s << std::endl;
348
349   // wrap long lines
350   std::string overflow;
351   unsigned int line_count = 0;
352   do {
353     lines.push_front(Font::wrap_to_chars(s, 99, &overflow));
354     line_count++;
355     s = overflow;
356   } while (s.length() > 0);
357
358   // trim scrollback buffer
359   while (lines.size() >= 1000)
360     lines.pop_back();
361
362   // increase console height if necessary
363   if (height < 64) {
364     if(height < 4)
365       height = 4;
366     height += fontheight * line_count;
367   }
368
369   // reset console to full opacity
370   alpha = 1.0;
371
372   // increase time that console stays open
373   if(stayOpen < 6)
374     stayOpen += 1.5;
375 }
376
377 void
378 Console::parse(std::string s)
379 {
380   // make sure we actually have something to parse
381   if (s.length() == 0) return;
382
383   // add line to history
384   history.push_back(s);
385   history_position = history.end();
386
387   // split line into list of args
388   std::vector<std::string> args;
389   size_t start = 0;
390   size_t end = 0;
391   while (1) {
392     start = s.find_first_not_of(" ,", end);
393     end = s.find_first_of(" ,", start);
394     if (start == s.npos) break;
395     args.push_back(s.substr(start, end-start));
396   }
397
398   // command is args[0]
399   if (args.size() == 0) return;
400   std::string command = args.front();
401   args.erase(args.begin());
402
403   // ignore if it's an internal command
404   if (consoleCommand(command,args)) return;
405
406   try {
407     execute_script(s);
408   } catch(std::exception& e) {
409     addLines(e.what());
410   }
411
412 }
413
414 bool
415 Console::consoleCommand(std::string /*command*/, std::vector<std::string> /*arguments*/)
416 {
417   return false;
418 }
419
420 bool
421 Console::hasFocus()
422 {
423   return focused;
424 }
425
426 void
427 Console::show()
428 {
429   if(!config->console_enabled)
430     return;
431
432   focused = true;
433   height = 256;
434   alpha = 1.0;
435   SDL_EnableKeyRepeat(SDL_DEFAULT_REPEAT_DELAY, SDL_DEFAULT_REPEAT_INTERVAL);
436 }
437
438 void
439 Console::hide()
440 {
441   focused = false;
442   height = 0;
443   stayOpen = 0;
444
445   // clear input buffer
446   inputBuffer = "";
447   inputBufferPosition = 0;
448   SDL_EnableKeyRepeat(0, SDL_DEFAULT_REPEAT_INTERVAL);
449 }
450
451 void
452 Console::toggle()
453 {
454   if (Console::hasFocus()) {
455     Console::hide();
456   }
457   else {
458     Console::show();
459   }
460 }
461
462 void
463 Console::update(float elapsed_time)
464 {
465   if(stayOpen > 0) {
466     stayOpen -= elapsed_time;
467     if(stayOpen < 0)
468       stayOpen = 0;
469   } else if(!focused && height > 0) {
470     alpha -= elapsed_time * FADE_SPEED;
471     if(alpha < 0) {
472       alpha = 0;
473       height = 0;
474     }
475   }
476 }
477
478 void
479 Console::draw(DrawingContext& context)
480 {
481   if (height == 0)
482     return;
483
484   int layer = LAYER_GUI + 1;
485
486   context.push_transform();
487   context.set_alpha(alpha);
488   context.draw_surface(background2.get(), Vector(SCREEN_WIDTH/2 - background->get_width()/2 - background->get_width() + backgroundOffset, height - background->get_height()), layer);
489   context.draw_surface(background2.get(), Vector(SCREEN_WIDTH/2 - background->get_width()/2 + backgroundOffset, height - background->get_height()), layer);
490   context.draw_surface(background.get(), Vector(SCREEN_WIDTH/2 - background->get_width()/2, height - background->get_height()), layer);
491   backgroundOffset+=10;
492   if (backgroundOffset > (int)background->get_width()) backgroundOffset -= (int)background->get_width();
493
494   int lineNo = 0;
495
496   if (focused) {
497     lineNo++;
498     float py = height-4-1 * font->get_height();
499     context.draw_text(font.get(), "> "+inputBuffer, Vector(4, py), ALIGN_LEFT, layer);
500     if (SDL_GetTicks() % 1000 < 750) {
501       int cursor_px = 2 + inputBufferPosition;
502       context.draw_text(font.get(), "_", Vector(4 + (cursor_px * font->get_text_width("X")), py), ALIGN_LEFT, layer);
503     }
504   }
505
506   int skipLines = -offset;
507   for (std::list<std::string>::iterator i = lines.begin(); i != lines.end(); i++) {
508     if (skipLines-- > 0) continue;
509     lineNo++;
510     float py = height - 4 - lineNo*font->get_height();
511     if (py < -font->get_height()) break;
512     context.draw_text(font.get(), *i, Vector(4, py), ALIGN_LEFT, layer);
513   }
514   context.pop_transform();
515 }
516
517 Console* Console::instance = NULL;
518 int Console::inputBufferPosition = 0;
519 std::string Console::inputBuffer;
520 ConsoleStreamBuffer Console::outputBuffer;
521 std::ostream Console::output(&Console::outputBuffer);
522