2 // Copyright (C) 2006 Christoph Sommer <christoph.sommer@2006.expires.deltadevelopment.de>
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.
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.
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/>.
17 #include "supertux/console.hpp"
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"
27 /// speed (pixels/s) the console closes
28 static const float FADE_SPEED = 1;
32 history_position(history.end()),
53 sq_release(Scripting::global_vm, &vm_object);
58 Console::init_graphics()
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"));
67 Console::flush(ConsoleStreamBuffer* buffer)
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);
74 outputBuffer.str(std::string());
83 vm = Scripting::global_vm;
84 HSQUIRRELVM new_vm = sq_newthread(vm, 16);
86 throw Scripting::SquirrelError(vm, "Couldn't create new VM thread for console");
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);
95 // create new roottable for thread
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");
101 sq_setroottable(new_vm);
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;
116 Console::execute_script(const std::string& command)
118 using namespace Scripting;
122 SQInteger oldtop = sq_gettop(vm);
124 if(SQ_FAILED(sq_compilebuffer(vm, command.c_str(), command.length(),
126 throw SquirrelError(vm, "Couldn't compile command");
128 sq_pushroottable(vm);
129 if(SQ_FAILED(sq_call(vm, 1, SQTrue, SQTrue)))
130 throw SquirrelError(vm, "Problem while executing command");
132 if(sq_gettype(vm, -1) != OT_NULL)
133 addLines(squirrel2string(vm, -1));
134 } catch(std::exception& e) {
137 SQInteger newtop = sq_gettop(vm);
138 if(newtop < oldtop) {
139 log_fatal << "Script destroyed squirrel stack..." << std::endl;
141 sq_settop(vm, oldtop);
146 Console::input(char c)
148 inputBuffer.insert(inputBufferPosition, 1, c);
149 inputBufferPosition++;
155 if ((inputBufferPosition > 0) && (inputBuffer.length() > 0)) {
156 inputBuffer.erase(inputBufferPosition-1, 1);
157 inputBufferPosition--;
164 if (inputBufferPosition < (int)inputBuffer.length()) {
165 inputBuffer.erase(inputBufferPosition, 1);
172 addLines("> "+inputBuffer);
175 inputBufferPosition = 0;
179 Console::scroll(int numLines)
182 if (offset > 0) offset = 0;
186 Console::show_history(int offset)
188 while ((offset > 0) && (history_position != history.end())) {
192 while ((offset < 0) && (history_position != history.begin())) {
196 if (history_position == history.end()) {
198 inputBufferPosition = 0;
200 inputBuffer = *history_position;
201 inputBufferPosition = inputBuffer.length();
206 Console::move_cursor(int offset)
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();
215 // Helper functions for Console::autocomplete
216 // TODO: Fix rough documentation
219 void sq_insert_commands(std::list<std::string>& cmds, HSQUIRRELVM vm, std::string table_prefix, std::string search_prefix);
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);
227 sq_insert_command(std::list<std::string>& cmds, HSQUIRRELVM vm, std::string table_prefix, std::string search_prefix)
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;
233 switch (sq_gettype(vm, -1)) {
236 if (search_prefix.substr(0, key_string.length()) == key_string) {
238 sq_insert_commands(cmds, vm, key_string, search_prefix);
245 if (search_prefix.substr(0, key_string.length()) == key_string) {
246 sq_insert_commands(cmds, vm, key_string, search_prefix);
250 case OT_NATIVECLOSURE:
257 if (key_string.substr(0, search_prefix.length()) == search_prefix) {
258 cmds.push_back(key_string);
264 * calls sq_insert_command for all entries of table/class on top of stack
267 sq_insert_commands(std::list<std::string>& cmds, HSQUIRRELVM vm, std::string table_prefix, std::string search_prefix)
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
274 sq_pop(vm, 1); // pop iterator
278 // End of Console::autocomplete helper functions
281 Console::autocomplete()
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;
288 autocompleteFrom = 0;
290 std::string prefix = inputBuffer.substr(autocompleteFrom, inputBufferPosition - autocompleteFrom);
291 addLines("> "+prefix);
293 std::list<std::string> cmds;
297 // append all keys of the current root table to list
298 sq_pushroottable(vm); // push root table
300 // check all keys (and their children) for matches
301 sq_insert_commands(cmds, vm, "", prefix);
303 // cycle through parent(delegate) table
304 SQInteger oldtop = sq_gettop(vm);
305 if(SQ_FAILED(sq_getdelegate(vm, -1)) || oldtop == sq_gettop(vm)) {
308 sq_remove(vm, -2); // remove old table
310 sq_pop(vm, 1); // remove table
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());
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();
327 for (int n = commonPrefix.length(); n >= 1; n--) {
328 if (cmd.compare(0, n, commonPrefix) != 0) commonPrefix.resize(n-1); else break;
331 std::string replaceWith = commonPrefix;
332 inputBuffer.replace(autocompleteFrom, prefix.length(), replaceWith);
333 inputBufferPosition += (replaceWith.length() - prefix.length());
338 Console::addLines(std::string s)
340 std::istringstream iss(s);
342 while (std::getline(iss, line, '\n')) addLine(line);
346 Console::addLine(std::string s)
348 // output line to stderr
349 std::cerr << s << std::endl;
352 std::string overflow;
353 unsigned int line_count = 0;
355 lines.push_front(Font::wrap_to_chars(s, 99, &overflow));
358 } while (s.length() > 0);
360 // trim scrollback buffer
361 while (lines.size() >= 1000)
364 // increase console height if necessary
368 height += fontheight * line_count;
371 // reset console to full opacity
374 // increase time that console stays open
380 Console::parse(std::string s)
382 // make sure we actually have something to parse
383 if (s.length() == 0) return;
385 // add line to history
386 history.push_back(s);
387 history_position = history.end();
389 // split line into list of args
390 std::vector<std::string> args;
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));
400 // command is args[0]
401 if (args.size() == 0) return;
402 std::string command = args.front();
403 args.erase(args.begin());
405 // ignore if it's an internal command
406 if (consoleCommand(command,args)) return;
410 } catch(std::exception& e) {
417 Console::consoleCommand(std::string /*command*/, std::vector<std::string> /*arguments*/)
431 if(!g_config->console_enabled)
437 SDL_EnableKeyRepeat(SDL_DEFAULT_REPEAT_DELAY, SDL_DEFAULT_REPEAT_INTERVAL);
447 // clear input buffer
449 inputBufferPosition = 0;
450 SDL_EnableKeyRepeat(0, SDL_DEFAULT_REPEAT_INTERVAL);
456 if (Console::hasFocus()) {
465 Console::update(float elapsed_time)
468 stayOpen -= elapsed_time;
471 } else if(!focused && height > 0) {
472 alpha -= elapsed_time * FADE_SPEED;
481 Console::draw(DrawingContext& context)
486 int layer = LAYER_GUI + 1;
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);
495 backgroundOffset+=10;
496 if (backgroundOffset > (int)background->get_width()) backgroundOffset -= (int)background->get_width();
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);
510 int skipLines = -offset;
511 for (std::list<std::string>::iterator i = lines.begin(); i != lines.end(); i++) {
512 if (skipLines-- > 0) continue;
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);
518 context.pop_transform();
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);