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