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