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"
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"
28 /// speed (pixels/s) the console closes
29 static const float FADE_SPEED = 1;
33 history_position(history.end()),
54 sq_release(scripting::global_vm, &vm_object);
59 Console::init_graphics()
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");
68 Console::flush(ConsoleStreamBuffer* buffer)
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);
75 outputBuffer.str(std::string());
84 vm = scripting::global_vm;
85 HSQUIRRELVM new_vm = sq_newthread(vm, 16);
87 throw scripting::SquirrelError(vm, "Couldn't create new VM thread for console");
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);
96 // create new roottable for thread
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");
102 sq_setroottable(new_vm);
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;
117 Console::execute_script(const std::string& command)
119 using namespace scripting;
123 SQInteger oldtop = sq_gettop(vm);
125 if(SQ_FAILED(sq_compilebuffer(vm, command.c_str(), command.length(),
127 throw SquirrelError(vm, "Couldn't compile command");
129 sq_pushroottable(vm);
130 if(SQ_FAILED(sq_call(vm, 1, SQTrue, SQTrue)))
131 throw SquirrelError(vm, "Problem while executing command");
133 if(sq_gettype(vm, -1) != OT_NULL)
134 addLines(squirrel2string(vm, -1));
135 } catch(std::exception& e) {
138 SQInteger newtop = sq_gettop(vm);
139 if(newtop < oldtop) {
140 log_fatal << "Script destroyed squirrel stack..." << std::endl;
142 sq_settop(vm, oldtop);
147 Console::input(char c)
149 inputBuffer.insert(inputBufferPosition, 1, c);
150 inputBufferPosition++;
156 if ((inputBufferPosition > 0) && (inputBuffer.length() > 0)) {
157 inputBuffer.erase(inputBufferPosition-1, 1);
158 inputBufferPosition--;
165 if (inputBufferPosition < (int)inputBuffer.length()) {
166 inputBuffer.erase(inputBufferPosition, 1);
173 addLines("> "+inputBuffer);
176 inputBufferPosition = 0;
180 Console::scroll(int numLines)
183 if (offset > 0) offset = 0;
187 Console::show_history(int offset)
189 while ((offset > 0) && (history_position != history.end())) {
193 while ((offset < 0) && (history_position != history.begin())) {
197 if (history_position == history.end()) {
199 inputBufferPosition = 0;
201 inputBuffer = *history_position;
202 inputBufferPosition = inputBuffer.length();
207 Console::move_cursor(int offset)
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();
216 // Helper functions for Console::autocomplete
217 // TODO: Fix rough documentation
220 void sq_insert_commands(std::list<std::string>& cmds, HSQUIRRELVM vm, std::string table_prefix, std::string search_prefix);
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);
228 sq_insert_command(std::list<std::string>& cmds, HSQUIRRELVM vm, std::string table_prefix, std::string search_prefix)
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;
234 switch (sq_gettype(vm, -1)) {
237 if (search_prefix.substr(0, key_string.length()) == key_string) {
239 sq_insert_commands(cmds, vm, key_string, search_prefix);
246 if (search_prefix.substr(0, key_string.length()) == key_string) {
247 sq_insert_commands(cmds, vm, key_string, search_prefix);
251 case OT_NATIVECLOSURE:
258 if (key_string.substr(0, search_prefix.length()) == search_prefix) {
259 cmds.push_back(key_string);
265 * calls sq_insert_command for all entries of table/class on top of stack
268 sq_insert_commands(std::list<std::string>& cmds, HSQUIRRELVM vm, std::string table_prefix, std::string search_prefix)
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
275 sq_pop(vm, 1); // pop iterator
279 // End of Console::autocomplete helper functions
282 Console::autocomplete()
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;
289 autocompleteFrom = 0;
291 std::string prefix = inputBuffer.substr(autocompleteFrom, inputBufferPosition - autocompleteFrom);
292 addLines("> "+prefix);
294 std::list<std::string> cmds;
298 // append all keys of the current root table to list
299 sq_pushroottable(vm); // push root table
301 // check all keys (and their children) for matches
302 sq_insert_commands(cmds, vm, "", prefix);
304 // cycle through parent(delegate) table
305 SQInteger oldtop = sq_gettop(vm);
306 if(SQ_FAILED(sq_getdelegate(vm, -1)) || oldtop == sq_gettop(vm)) {
309 sq_remove(vm, -2); // remove old table
311 sq_pop(vm, 1); // remove table
313 // depending on number of hits, show matches or autocomplete
314 if (cmds.empty()) 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());
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();
328 for (int n = commonPrefix.length(); n >= 1; n--) {
329 if (cmd.compare(0, n, commonPrefix) != 0) commonPrefix.resize(n-1); else break;
332 std::string replaceWith = commonPrefix;
333 inputBuffer.replace(autocompleteFrom, prefix.length(), replaceWith);
334 inputBufferPosition += (replaceWith.length() - prefix.length());
339 Console::addLines(std::string s)
341 std::istringstream iss(s);
343 while (std::getline(iss, line, '\n')) addLine(line);
347 Console::addLine(std::string s)
349 // output line to stderr
350 std::cerr << s << std::endl;
353 std::string overflow;
354 unsigned int line_count = 0;
356 lines.push_front(Font::wrap_to_chars(s, 99, &overflow));
359 } while (s.length() > 0);
361 // trim scrollback buffer
362 while (lines.size() >= 1000)
365 // increase console height if necessary
366 if ((stayOpen > 0) && (height < 64)) {
369 height += fontheight * line_count;
372 // reset console to full opacity
377 Console::parse(std::string s)
379 // make sure we actually have something to parse
380 if (s.length() == 0) return;
382 // add line to history
383 history.push_back(s);
384 history_position = history.end();
386 // split line into list of args
387 std::vector<std::string> args;
391 start = s.find_first_not_of(" ,", end);
392 end = s.find_first_of(" ,", start);
393 if (start == s.npos) break;
394 args.push_back(s.substr(start, end-start));
397 // command is args[0]
398 if (args.size() == 0) return;
399 std::string command = args.front();
400 args.erase(args.begin());
402 // ignore if it's an internal command
403 if (consoleCommand(command,args)) return;
407 } catch(std::exception& e) {
414 Console::consoleCommand(std::string /*command*/, std::vector<std::string> /*arguments*/)
428 if(!g_config->console_enabled)
434 SDL_EnableKeyRepeat(SDL_DEFAULT_REPEAT_DELAY, SDL_DEFAULT_REPEAT_INTERVAL);
451 // clear input buffer
453 inputBufferPosition = 0;
454 SDL_EnableKeyRepeat(0, SDL_DEFAULT_REPEAT_INTERVAL);
460 if (Console::hasFocus()) {
469 Console::update(float elapsed_time)
472 stayOpen -= elapsed_time;
475 } else if(!focused && height > 0) {
476 alpha -= elapsed_time * FADE_SPEED;
485 Console::draw(DrawingContext& context)
490 int layer = LAYER_GUI + 1;
492 context.push_transform();
493 context.set_alpha(alpha);
494 context.draw_surface(background2, Vector(SCREEN_WIDTH/2 - background->get_width()/2 - background->get_width() + backgroundOffset, height - background->get_height()), layer);
495 context.draw_surface(background2, Vector(SCREEN_WIDTH/2 - background->get_width()/2 + backgroundOffset, height - background->get_height()), layer);
496 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()) {
497 context.draw_surface(background, Vector(x, height - background->get_height()), layer);
499 backgroundOffset+=10;
500 if (backgroundOffset > (int)background->get_width()) backgroundOffset -= (int)background->get_width();
506 float py = height-4-1 * font->get_height();
507 context.draw_text(font, "> "+inputBuffer, Vector(4, py), ALIGN_LEFT, layer);
508 if (SDL_GetTicks() % 1000 < 750) {
509 int cursor_px = 2 + inputBufferPosition;
510 context.draw_text(font, "_", Vector(4 + (cursor_px * font->get_text_width("X")), py), ALIGN_LEFT, layer);
514 int skipLines = -offset;
515 for (std::list<std::string>::iterator i = lines.begin(); i != lines.end(); i++) {
516 if (skipLines-- > 0) continue;
518 float py = height - 4 - lineNo*font->get_height();
519 if (py < -font->get_height()) break;
520 context.draw_text(font, *i, Vector(4, py), ALIGN_LEFT, layer);
522 context.pop_transform();
525 Console* Console::instance = NULL;
526 int Console::inputBufferPosition = 0;
527 std::string Console::inputBuffer;
528 ConsoleStreamBuffer Console::outputBuffer;
529 std::ostream Console::output(&Console::outputBuffer);