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