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