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