- renamed LEFT_ALLIGN to ALIGN_LEFT
[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(Font::FIXED,
54                       "images/engine/fonts/white-small.png",
55                       "images/engine/fonts/shadow-small.png", 8, 9, 1));
56   fontheight = font->get_height();
57   background.reset(new Surface("images/engine/console.png"));
58   background2.reset(new Surface("images/engine/console2.png"));
59 }
60
61 void
62 Console::flush(ConsoleStreamBuffer* buffer)
63 {
64   if (buffer == &outputBuffer) {
65     std::string s = outputBuffer.str();
66     if ((s.length() > 0) && ((s[s.length()-1] == '\n') || (s[s.length()-1] == '\r'))) {
67       while ((s[s.length()-1] == '\n') || (s[s.length()-1] == '\r')) s.erase(s.length()-1);
68       addLines(s);
69       outputBuffer.str(std::string());
70     }
71   }
72   if (buffer == &inputBuffer) {
73     std::string s = inputBuffer.str();
74     if ((s.length() > 0) && ((s[s.length()-1] == '\n') || (s[s.length()-1] == '\r'))) {
75       while ((s[s.length()-1] == '\n') || (s[s.length()-1] == '\r')) s.erase(s.length()-1);
76       addLines("> "+s);
77       parse(s);
78       inputBuffer.str(std::string());
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::scroll(int numLines)
162 {
163   offset += numLines;
164   if (offset > 0) offset = 0;
165 }
166
167 void
168 Console::show_history(int offset)
169 {
170   while ((offset > 0) && (history_position != history.end())) {
171     history_position++;
172     offset--;
173   }
174   while ((offset < 0) && (history_position != history.begin())) {
175     history_position--;
176     offset++;
177   }
178   if (history_position == history.end()) {
179     inputBuffer.str(std::string());
180   } else {
181     inputBuffer.str(*history_position);
182     inputBuffer.pubseekoff(0, std::ios_base::end, std::ios_base::out);
183   }
184 }
185
186 // Helper functions for Console::autocomplete
187 // TODO: Fix rough documentation
188 namespace {
189
190 void sq_insert_commands(std::list<std::string>& cmds, HSQUIRRELVM vm, std::string table_prefix, std::string search_prefix);
191
192 /**
193  * Acts upon key,value on top of stack:
194  * Appends key (plus type-dependent suffix) to cmds if table_prefix+key starts with search_prefix;
195  * Calls sq_insert_commands if search_prefix starts with table_prefix+key (and value is a table/class/instance);
196  */
197 void
198 sq_insert_command(std::list<std::string>& cmds, HSQUIRRELVM vm, std::string table_prefix, std::string search_prefix)
199 {
200   const SQChar* key_chars;
201   if (SQ_FAILED(sq_getstring(vm, -2, &key_chars))) return;
202   std::string key_string = table_prefix + key_chars;
203
204   switch (sq_gettype(vm, -1)) {
205     case OT_INSTANCE:
206       key_string+=".";
207       if (search_prefix.substr(0, key_string.length()) == key_string) {
208         sq_getclass(vm, -1);
209         sq_insert_commands(cmds, vm, key_string, search_prefix);
210         sq_pop(vm, 1);
211       }
212       break;
213     case OT_TABLE:
214     case OT_CLASS:
215       key_string+=".";
216       if (search_prefix.substr(0, key_string.length()) == key_string) {
217         sq_insert_commands(cmds, vm, key_string, search_prefix);
218       }
219       break;
220     case OT_CLOSURE:
221     case OT_NATIVECLOSURE:
222       key_string+="()";
223       break;
224     default:
225       break;
226   }
227
228   if (key_string.substr(0, search_prefix.length()) == search_prefix) {
229     cmds.push_back(key_string);
230   }
231
232 }
233
234 /**
235  * calls sq_insert_command for all entries of table/class on top of stack
236  */
237 void
238 sq_insert_commands(std::list<std::string>& cmds, HSQUIRRELVM vm, std::string table_prefix, std::string search_prefix)
239 {
240   sq_pushnull(vm); // push iterator
241   while (SQ_SUCCEEDED(sq_next(vm,-2))) {
242     sq_insert_command(cmds, vm, table_prefix, search_prefix);
243     sq_pop(vm, 2); // pop key, val
244   }
245   sq_pop(vm, 1); // pop iterator
246 }
247
248
249 }
250 // End of Console::autocomplete helper functions
251
252 void
253 Console::autocomplete()
254 {
255   std::string prefix = inputBuffer.str();
256   addLines("> "+prefix);
257
258   std::list<std::string> cmds;
259
260   ready_vm();
261
262   // append all keys of the current root table to list
263   sq_pushroottable(vm); // push root table
264   while(true) {
265     // check all keys (and their children) for matches
266     sq_insert_commands(cmds, vm, "", prefix);
267
268     // cycle through parent(delegate) table
269     SQInteger oldtop = sq_gettop(vm);
270     if(SQ_FAILED(sq_getdelegate(vm, -1)) || oldtop == sq_gettop(vm)) {
271       break;
272     }
273     sq_remove(vm, -2); // remove old table
274   }
275   sq_pop(vm, 1); // remove table
276
277   // depending on number of hits, show matches or autocomplete
278   if (cmds.size() == 0) addLines("No known command starts with \""+prefix+"\"");
279   if (cmds.size() == 1) {
280     // one match: just replace input buffer with full command
281     inputBuffer.str(cmds.front());
282     inputBuffer.pubseekoff(0, std::ios_base::end, std::ios_base::out);
283   }
284   if (cmds.size() > 1) {
285     // multiple matches: show all matches and set input buffer to longest common prefix
286     std::string commonPrefix = cmds.front();
287     while (cmds.begin() != cmds.end()) {
288       std::string cmd = cmds.front();
289       cmds.pop_front();
290       addLines(cmd);
291       for (int n = commonPrefix.length(); n >= 1; n--) {
292         if (cmd.compare(0, n, commonPrefix) != 0) commonPrefix.resize(n-1); else break;
293       }
294     }
295     inputBuffer.str(commonPrefix);
296     inputBuffer.pubseekoff(0, std::ios_base::end, std::ios_base::out);
297   }
298 }
299
300 void
301 Console::addLines(std::string s)
302 {
303   std::istringstream iss(s);
304   std::string line;
305   while (std::getline(iss, line, '\n')) addLine(line);
306 }
307
308 void
309 Console::addLine(std::string s)
310 {
311   // output line to stderr
312   std::cerr << s << std::endl;
313
314   // wrap long lines
315   std::string overflow;
316   do {
317     lines.push_front(Font::wrap_to_chars(s, 99, &overflow));
318     s = overflow;
319   } while (s.length() > 0);
320
321   // trim scrollback buffer
322   while (lines.size() >= 1000)
323     lines.pop_back();
324
325   // increase console height if necessary
326   if (height < 64) {
327     if(height < 4)
328       height = 4;
329     height += fontheight;
330   }
331
332   // reset console to full opacity
333   alpha = 1.0;
334
335   // increase time that console stays open
336   if(stayOpen < 6)
337     stayOpen += 1.5;
338 }
339
340 void
341 Console::parse(std::string s)
342 {
343   // make sure we actually have something to parse
344   if (s.length() == 0) return;
345
346   // add line to history
347   history.push_back(s);
348   history_position = history.end();
349
350   // split line into list of args
351   std::vector<std::string> args;
352   size_t start = 0;
353   size_t end = 0;
354   while (1) {
355     start = s.find_first_not_of(" ,", end);
356     end = s.find_first_of(" ,", start);
357     if (start == s.npos) break;
358     args.push_back(s.substr(start, end-start));
359   }
360
361   // command is args[0]
362   if (args.size() == 0) return;
363   std::string command = args.front();
364   args.erase(args.begin());
365
366   // ignore if it's an internal command
367   if (consoleCommand(command,args)) return;
368
369   try {
370     execute_script(s);
371   } catch(std::exception& e) {
372     addLines(e.what());
373   }
374
375 }
376
377 bool
378 Console::consoleCommand(std::string /*command*/, std::vector<std::string> /*arguments*/)
379 {
380   return false;
381 }
382
383 bool
384 Console::hasFocus()
385 {
386   return focused;
387 }
388
389 void
390 Console::show()
391 {
392   if(!config->console_enabled)
393     return;
394
395   focused = true;
396   height = 256;
397   alpha = 1.0;
398   SDL_EnableKeyRepeat(SDL_DEFAULT_REPEAT_DELAY, SDL_DEFAULT_REPEAT_INTERVAL);
399 }
400
401 void
402 Console::hide()
403 {
404   focused = false;
405   height = 0;
406   stayOpen = 0;
407
408   // clear input buffer
409   inputBuffer.str(std::string());
410   SDL_EnableKeyRepeat(0, SDL_DEFAULT_REPEAT_INTERVAL);
411 }
412
413 void
414 Console::toggle()
415 {
416   if (Console::hasFocus()) {
417     Console::hide();
418   }
419   else {
420     Console::show();
421   }
422 }
423
424 void
425 Console::update(float elapsed_time)
426 {
427   if(stayOpen > 0) {
428     stayOpen -= elapsed_time;
429     if(stayOpen < 0)
430       stayOpen = 0;
431   } else if(!focused && height > 0) {
432     alpha -= elapsed_time * FADE_SPEED;
433     if(alpha < 0) {
434       alpha = 0;
435       height = 0;
436     }
437   }
438 }
439
440 void
441 Console::draw(DrawingContext& context)
442 {
443   if (height == 0)
444     return;
445
446   int layer = LAYER_GUI + 1;
447
448   context.push_transform();
449   context.set_alpha(alpha);
450   context.draw_surface(background2.get(), Vector(SCREEN_WIDTH/2 - background->get_width()/2 - background->get_width() + backgroundOffset, height - background->get_height()), layer);
451   context.draw_surface(background2.get(), Vector(SCREEN_WIDTH/2 - background->get_width()/2 + backgroundOffset, height - background->get_height()), layer);
452   context.draw_surface(background.get(), Vector(SCREEN_WIDTH/2 - background->get_width()/2, height - background->get_height()), layer);
453   backgroundOffset+=10;
454   if (backgroundOffset > (int)background->get_width()) backgroundOffset -= (int)background->get_width();
455
456   int lineNo = 0;
457
458   if (focused) {
459     lineNo++;
460     float py = height-4-1*9;
461     context.draw_text(font.get(), "> "+inputBuffer.str()+"_", Vector(4, py), ALIGN_LEFT, layer);
462   }
463
464   int skipLines = -offset;
465   for (std::list<std::string>::iterator i = lines.begin(); i != lines.end(); i++) {
466     if (skipLines-- > 0) continue;
467     lineNo++;
468     float py = height-4-lineNo*9;
469     if (py < -9) break;
470     context.draw_text(font.get(), *i, Vector(4, py), ALIGN_LEFT, layer);
471   }
472   context.pop_transform();
473 }
474
475 Console* Console::instance = NULL;
476 ConsoleStreamBuffer Console::inputBuffer;
477 ConsoleStreamBuffer Console::outputBuffer;
478 std::ostream Console::input(&Console::inputBuffer);
479 std::ostream Console::output(&Console::outputBuffer);