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