src/supertux/console.cpp

Go to the documentation of this file.
00001 //  SuperTux - Console
00002 //  Copyright (C) 2006 Christoph Sommer <christoph.sommer@2006.expires.deltadevelopment.de>
00003 //
00004 //  This program is free software: you can redistribute it and/or modify
00005 //  it under the terms of the GNU General Public License as published by
00006 //  the Free Software Foundation, either version 3 of the License, or
00007 //  (at your option) any later version.
00008 //
00009 //  This program is distributed in the hope that it will be useful,
00010 //  but WITHOUT ANY WARRANTY; without even the implied warranty of
00011 //  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
00012 //  GNU General Public License for more details.
00013 //
00014 //  You should have received a copy of the GNU General Public License
00015 //  along with this program.  If not, see <http://www.gnu.org/licenses/>.
00016 
00017 #include "supertux/console.hpp"
00018 
00019 #include <math.h>
00020 #include <iostream>
00021 
00022 #include "physfs/ifile_stream.hpp"
00023 #include "scripting/squirrel_util.hpp"
00024 #include "supertux/gameconfig.hpp"
00025 #include "supertux/globals.hpp"
00026 #include "video/drawing_context.hpp"
00027 
00029 static const float FADE_SPEED = 1;
00030 
00031 Console::Console() :
00032   history(),
00033   history_position(history.end()), 
00034   lines(),
00035   background(),
00036   background2(),
00037   vm(NULL), 
00038   vm_object(),
00039   backgroundOffset(0),
00040   height(0),
00041   alpha(1.0), 
00042   offset(0), 
00043   focused(false), 
00044   font(),
00045   fontheight(),
00046   stayOpen(0) 
00047 {
00048   fontheight = 8;
00049 }
00050 
00051 Console::~Console()
00052 {
00053   if(vm != NULL) {
00054     sq_release(scripting::global_vm, &vm_object);
00055   }
00056 }
00057 
00058 void
00059 Console::init_graphics()
00060 {
00061   font.reset(new Font(Font::FIXED,"fonts/andale12.stf",1));
00062   fontheight = font->get_height();
00063   background = Surface::create("images/engine/console.png");
00064   background2 = Surface::create("images/engine/console2.png");
00065 }
00066 
00067 void
00068 Console::flush(ConsoleStreamBuffer* buffer)
00069 {
00070   if (buffer == &outputBuffer) {
00071     std::string s = outputBuffer.str();
00072     if ((s.length() > 0) && ((s[s.length()-1] == '\n') || (s[s.length()-1] == '\r'))) {
00073       while ((s[s.length()-1] == '\n') || (s[s.length()-1] == '\r')) s.erase(s.length()-1);
00074       addLines(s);
00075       outputBuffer.str(std::string());
00076     }
00077   }
00078 }
00079 
00080 void
00081 Console::ready_vm()
00082 {
00083   if(vm == NULL) {
00084     vm = scripting::global_vm;
00085     HSQUIRRELVM new_vm = sq_newthread(vm, 16);
00086     if(new_vm == NULL)
00087       throw scripting::SquirrelError(vm, "Couldn't create new VM thread for console");
00088 
00089     // store reference to thread
00090     sq_resetobject(&vm_object);
00091     if(SQ_FAILED(sq_getstackobj(vm, -1, &vm_object)))
00092       throw scripting::SquirrelError(vm, "Couldn't get vm object for console");
00093     sq_addref(vm, &vm_object);
00094     sq_pop(vm, 1);
00095 
00096     // create new roottable for thread
00097     sq_newtable(new_vm);
00098     sq_pushroottable(new_vm);
00099     if(SQ_FAILED(sq_setdelegate(new_vm, -2)))
00100       throw scripting::SquirrelError(new_vm, "Couldn't set console_table delegate");
00101 
00102     sq_setroottable(new_vm);
00103 
00104     vm = new_vm;
00105 
00106     try {
00107       std::string filename = "scripts/console.nut";
00108       IFileStream stream(filename);
00109       scripting::compile_and_run(vm, stream, filename);
00110     } catch(std::exception& e) {
00111       log_warning << "Couldn't load console.nut: " << e.what() << std::endl;
00112     }
00113   }
00114 }
00115 
00116 void
00117 Console::execute_script(const std::string& command)
00118 {
00119   using namespace scripting;
00120 
00121   ready_vm();
00122 
00123   SQInteger oldtop = sq_gettop(vm);
00124   try {
00125     if(SQ_FAILED(sq_compilebuffer(vm, command.c_str(), command.length(),
00126                                   "", SQTrue)))
00127       throw SquirrelError(vm, "Couldn't compile command");
00128 
00129     sq_pushroottable(vm);
00130     if(SQ_FAILED(sq_call(vm, 1, SQTrue, SQTrue)))
00131       throw SquirrelError(vm, "Problem while executing command");
00132 
00133     if(sq_gettype(vm, -1) != OT_NULL)
00134       addLines(squirrel2string(vm, -1));
00135   } catch(std::exception& e) {
00136     addLines(e.what());
00137   }
00138   SQInteger newtop = sq_gettop(vm);
00139   if(newtop < oldtop) {
00140     log_fatal << "Script destroyed squirrel stack..." << std::endl;
00141   } else {
00142     sq_settop(vm, oldtop);
00143   }
00144 }
00145 
00146 void 
00147 Console::input(char c)
00148 {
00149   inputBuffer.insert(inputBufferPosition, 1, c);
00150   inputBufferPosition++;
00151 }
00152 
00153 void
00154 Console::backspace()
00155 {
00156   if ((inputBufferPosition > 0) && (inputBuffer.length() > 0)) {
00157     inputBuffer.erase(inputBufferPosition-1, 1);
00158     inputBufferPosition--;
00159   }
00160 }
00161 
00162 void
00163 Console::eraseChar()
00164 {
00165   if (inputBufferPosition < (int)inputBuffer.length()) {
00166     inputBuffer.erase(inputBufferPosition, 1);
00167   }
00168 }
00169 
00170 void
00171 Console::enter()
00172 {
00173   addLines("> "+inputBuffer);
00174   parse(inputBuffer);
00175   inputBuffer = "";
00176   inputBufferPosition = 0;
00177 }
00178 
00179 void
00180 Console::scroll(int numLines)
00181 {
00182   offset += numLines;
00183   if (offset > 0) offset = 0;
00184 }
00185 
00186 void
00187 Console::show_history(int offset)
00188 {
00189   while ((offset > 0) && (history_position != history.end())) {
00190     history_position++;
00191     offset--;
00192   }
00193   while ((offset < 0) && (history_position != history.begin())) {
00194     history_position--;
00195     offset++;
00196   }
00197   if (history_position == history.end()) {
00198     inputBuffer = "";
00199     inputBufferPosition = 0;
00200   } else {
00201     inputBuffer = *history_position;
00202     inputBufferPosition = inputBuffer.length();
00203   }
00204 }
00205 
00206 void 
00207 Console::move_cursor(int offset)
00208 {
00209   if (offset == -65535) inputBufferPosition = 0;
00210   if (offset == +65535) inputBufferPosition = inputBuffer.length();
00211   inputBufferPosition+=offset;
00212   if (inputBufferPosition < 0) inputBufferPosition = 0;
00213   if (inputBufferPosition > (int)inputBuffer.length()) inputBufferPosition = inputBuffer.length();
00214 }
00215 
00216 // Helper functions for Console::autocomplete
00217 // TODO: Fix rough documentation
00218 namespace {
00219 
00220 void sq_insert_commands(std::list<std::string>& cmds, HSQUIRRELVM vm, std::string table_prefix, std::string search_prefix);
00221 
00227 void
00228 sq_insert_command(std::list<std::string>& cmds, HSQUIRRELVM vm, std::string table_prefix, std::string search_prefix)
00229 {
00230   const SQChar* key_chars;
00231   if (SQ_FAILED(sq_getstring(vm, -2, &key_chars))) return;
00232   std::string key_string = table_prefix + key_chars;
00233 
00234   switch (sq_gettype(vm, -1)) {
00235     case OT_INSTANCE:
00236       key_string+=".";
00237       if (search_prefix.substr(0, key_string.length()) == key_string) {
00238         sq_getclass(vm, -1);
00239         sq_insert_commands(cmds, vm, key_string, search_prefix);
00240         sq_pop(vm, 1);
00241       }
00242       break;
00243     case OT_TABLE:
00244     case OT_CLASS:
00245       key_string+=".";
00246       if (search_prefix.substr(0, key_string.length()) == key_string) {
00247         sq_insert_commands(cmds, vm, key_string, search_prefix);
00248       }
00249       break;
00250     case OT_CLOSURE:
00251     case OT_NATIVECLOSURE:
00252       key_string+="()";
00253       break;
00254     default:
00255       break;
00256   }
00257 
00258   if (key_string.substr(0, search_prefix.length()) == search_prefix) {
00259     cmds.push_back(key_string);
00260   }
00261 
00262 }
00263 
00267 void
00268 sq_insert_commands(std::list<std::string>& cmds, HSQUIRRELVM vm, std::string table_prefix, std::string search_prefix)
00269 {
00270   sq_pushnull(vm); // push iterator
00271   while (SQ_SUCCEEDED(sq_next(vm,-2))) {
00272     sq_insert_command(cmds, vm, table_prefix, search_prefix);
00273     sq_pop(vm, 2); // pop key, val
00274   }
00275   sq_pop(vm, 1); // pop iterator
00276 }
00277 
00278 }
00279 // End of Console::autocomplete helper functions
00280 
00281 void
00282 Console::autocomplete()
00283 {
00284   //int autocompleteFrom = inputBuffer.find_last_of(" ();+", inputBufferPosition);
00285   int autocompleteFrom = inputBuffer.find_last_not_of("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_->.", inputBufferPosition);
00286   if (autocompleteFrom != (int)std::string::npos) {
00287     autocompleteFrom += 1;
00288   } else {
00289     autocompleteFrom = 0;
00290   }
00291   std::string prefix = inputBuffer.substr(autocompleteFrom, inputBufferPosition - autocompleteFrom);
00292   addLines("> "+prefix);
00293 
00294   std::list<std::string> cmds;
00295 
00296   ready_vm();
00297 
00298   // append all keys of the current root table to list
00299   sq_pushroottable(vm); // push root table
00300   while(true) {
00301     // check all keys (and their children) for matches
00302     sq_insert_commands(cmds, vm, "", prefix);
00303 
00304     // cycle through parent(delegate) table
00305     SQInteger oldtop = sq_gettop(vm);
00306     if(SQ_FAILED(sq_getdelegate(vm, -1)) || oldtop == sq_gettop(vm)) {
00307       break;
00308     }
00309     sq_remove(vm, -2); // remove old table
00310   }
00311   sq_pop(vm, 1); // remove table
00312 
00313   // depending on number of hits, show matches or autocomplete
00314   if (cmds.size() == 0) addLines("No known command starts with \""+prefix+"\"");
00315   if (cmds.size() == 1) {
00316     // one match: just replace input buffer with full command
00317     std::string replaceWith = cmds.front();
00318     inputBuffer.replace(autocompleteFrom, prefix.length(), replaceWith);
00319     inputBufferPosition += (replaceWith.length() - prefix.length());
00320   }
00321   if (cmds.size() > 1) {
00322     // multiple matches: show all matches and set input buffer to longest common prefix
00323     std::string commonPrefix = cmds.front();
00324     while (cmds.begin() != cmds.end()) {
00325       std::string cmd = cmds.front();
00326       cmds.pop_front();
00327       addLines(cmd);
00328       for (int n = commonPrefix.length(); n >= 1; n--) {
00329         if (cmd.compare(0, n, commonPrefix) != 0) commonPrefix.resize(n-1); else break;
00330       }
00331     }
00332     std::string replaceWith = commonPrefix;
00333     inputBuffer.replace(autocompleteFrom, prefix.length(), replaceWith);
00334     inputBufferPosition += (replaceWith.length() - prefix.length());
00335   }
00336 }
00337 
00338 void
00339 Console::addLines(std::string s)
00340 {
00341   std::istringstream iss(s);
00342   std::string line;
00343   while (std::getline(iss, line, '\n')) addLine(line);
00344 }
00345 
00346 void
00347 Console::addLine(std::string s)
00348 {
00349   // output line to stderr
00350   std::cerr << s << std::endl;
00351 
00352   // wrap long lines
00353   std::string overflow;
00354   unsigned int line_count = 0;
00355   do {
00356     lines.push_front(Font::wrap_to_chars(s, 99, &overflow));
00357     line_count++;
00358     s = overflow;
00359   } while (s.length() > 0);
00360 
00361   // trim scrollback buffer
00362   while (lines.size() >= 1000)
00363     lines.pop_back();
00364 
00365   // increase console height if necessary
00366   if ((stayOpen > 0) && (height < 64)) {
00367     if(height < 4)
00368       height = 4;
00369     height += fontheight * line_count;
00370   }
00371 
00372   // reset console to full opacity
00373   alpha = 1.0;
00374 }
00375 
00376 void
00377 Console::parse(std::string s)
00378 {
00379   // make sure we actually have something to parse
00380   if (s.length() == 0) return;
00381 
00382   // add line to history
00383   history.push_back(s);
00384   history_position = history.end();
00385 
00386   // split line into list of args
00387   std::vector<std::string> args;
00388   size_t start = 0;
00389   size_t end = 0;
00390   while (1) {
00391     start = s.find_first_not_of(" ,", end);
00392     end = s.find_first_of(" ,", start);
00393     if (start == s.npos) break;
00394     args.push_back(s.substr(start, end-start));
00395   }
00396 
00397   // command is args[0]
00398   if (args.size() == 0) return;
00399   std::string command = args.front();
00400   args.erase(args.begin());
00401 
00402   // ignore if it's an internal command
00403   if (consoleCommand(command,args)) return;
00404 
00405   try {
00406     execute_script(s);
00407   } catch(std::exception& e) {
00408     addLines(e.what());
00409   }
00410 
00411 }
00412 
00413 bool
00414 Console::consoleCommand(std::string /*command*/, std::vector<std::string> /*arguments*/)
00415 {
00416   return false;
00417 }
00418 
00419 bool
00420 Console::hasFocus()
00421 {
00422   return focused;
00423 }
00424 
00425 void
00426 Console::show()
00427 {
00428   if(!g_config->console_enabled)
00429     return;
00430 
00431   focused = true;
00432   height = 256;
00433   alpha = 1.0;
00434   SDL_EnableKeyRepeat(SDL_DEFAULT_REPEAT_DELAY, SDL_DEFAULT_REPEAT_INTERVAL);
00435 }
00436 
00437 void
00438 Console::open()
00439 {
00440   if(stayOpen < 2)
00441     stayOpen += 1.5;
00442 }
00443 
00444 void
00445 Console::hide()
00446 {
00447   focused = false;
00448   height = 0;
00449   stayOpen = 0;
00450 
00451   // clear input buffer
00452   inputBuffer = "";
00453   inputBufferPosition = 0;
00454   SDL_EnableKeyRepeat(0, SDL_DEFAULT_REPEAT_INTERVAL);
00455 }
00456 
00457 void
00458 Console::toggle()
00459 {
00460   if (Console::hasFocus()) {
00461     Console::hide();
00462   }
00463   else {
00464     Console::show();
00465   }
00466 }
00467 
00468 void
00469 Console::update(float elapsed_time)
00470 {
00471   if(stayOpen > 0) {
00472     stayOpen -= elapsed_time;
00473     if(stayOpen < 0)
00474       stayOpen = 0;
00475   } else if(!focused && height > 0) {
00476     alpha -= elapsed_time * FADE_SPEED;
00477     if(alpha < 0) {
00478       alpha = 0;
00479       height = 0;
00480     }
00481   }
00482 }
00483 
00484 void
00485 Console::draw(DrawingContext& context)
00486 {
00487   if (height == 0)
00488     return;
00489 
00490   int layer = LAYER_GUI + 1;
00491 
00492   context.push_transform();
00493   context.set_alpha(alpha);
00494   context.draw_surface(background2, Vector(SCREEN_WIDTH/2 - background->get_width()/2 - background->get_width() + backgroundOffset, height - background->get_height()), layer);
00495   context.draw_surface(background2, Vector(SCREEN_WIDTH/2 - background->get_width()/2 + backgroundOffset, height - background->get_height()), layer);
00496   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()) {
00497     context.draw_surface(background, Vector(x, height - background->get_height()), layer);
00498   }
00499   backgroundOffset+=10;
00500   if (backgroundOffset > (int)background->get_width()) backgroundOffset -= (int)background->get_width();
00501 
00502   int lineNo = 0;
00503 
00504   if (focused) {
00505     lineNo++;
00506     float py = height-4-1 * font->get_height();
00507     context.draw_text(font, "> "+inputBuffer, Vector(4, py), ALIGN_LEFT, layer);
00508     if (SDL_GetTicks() % 1000 < 750) {
00509       int cursor_px = 2 + inputBufferPosition;
00510       context.draw_text(font, "_", Vector(4 + (cursor_px * font->get_text_width("X")), py), ALIGN_LEFT, layer);
00511     }
00512   }
00513 
00514   int skipLines = -offset;
00515   for (std::list<std::string>::iterator i = lines.begin(); i != lines.end(); i++) {
00516     if (skipLines-- > 0) continue;
00517     lineNo++;
00518     float py = height - 4 - lineNo*font->get_height();
00519     if (py < -font->get_height()) break;
00520     context.draw_text(font, *i, Vector(4, py), ALIGN_LEFT, layer);
00521   }
00522   context.pop_transform();
00523 }
00524 
00525 Console* Console::instance = NULL;
00526 int Console::inputBufferPosition = 0;
00527 std::string Console::inputBuffer;
00528 ConsoleStreamBuffer Console::outputBuffer;
00529 std::ostream Console::output(&Console::outputBuffer);
00530 
00531 /* EOF */

Generated on Mon Jun 9 03:38:22 2014 for SuperTux by  doxygen 1.5.1