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