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