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