4 // Copyright (C) 2006 Christoph Sommer <christoph.sommer@2006.expires.deltadevelopment.de>
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.
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.
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.
23 #include <SDL_timer.h>
24 #include <SDL_keyboard.h>
25 #include "console.hpp"
26 #include "video/drawing_context.hpp"
27 #include "video/surface.hpp"
28 #include "scripting/squirrel_error.hpp"
29 #include "scripting/squirrel_util.hpp"
30 #include "physfs/physfs_stream.hpp"
31 #include "player_status.hpp"
34 #include "resources.hpp"
35 #include "gameconfig.hpp"
37 /// speed (pixels/s) the console closes
38 static const float FADE_SPEED = 1;
41 : history_position(history.end()), vm(NULL), backgroundOffset(0),
42 height(0), alpha(1.0), offset(0), focused(false), stayOpen(0) {
49 sq_release(Scripting::global_vm, &vm_object);
54 Console::init_graphics()
56 font.reset(new Font(Font::FIXED,
57 "images/engine/fonts/andale12.png",
58 "images/engine/fonts/andale12-shadow.png", 7, 14, 1));
59 fontheight = font->get_height();
60 background.reset(new Surface("images/engine/console.png"));
61 background2.reset(new Surface("images/engine/console2.png"));
65 Console::flush(ConsoleStreamBuffer* buffer)
67 if (buffer == &outputBuffer) {
68 std::string s = outputBuffer.str();
69 if ((s.length() > 0) && ((s[s.length()-1] == '\n') || (s[s.length()-1] == '\r'))) {
70 while ((s[s.length()-1] == '\n') || (s[s.length()-1] == '\r')) s.erase(s.length()-1);
72 outputBuffer.str(std::string());
81 vm = Scripting::global_vm;
82 HSQUIRRELVM new_vm = sq_newthread(vm, 16);
84 throw Scripting::SquirrelError(vm, "Couldn't create new VM thread for console");
86 // store reference to thread
87 sq_resetobject(&vm_object);
88 if(SQ_FAILED(sq_getstackobj(vm, -1, &vm_object)))
89 throw Scripting::SquirrelError(vm, "Couldn't get vm object for console");
90 sq_addref(vm, &vm_object);
93 // create new roottable for thread
95 sq_pushroottable(new_vm);
96 if(SQ_FAILED(sq_setdelegate(new_vm, -2)))
97 throw Scripting::SquirrelError(new_vm, "Couldn't set console_table delegate");
99 sq_setroottable(new_vm);
104 std::string filename = "scripts/console.nut";
105 IFileStream stream(filename);
106 Scripting::compile_and_run(vm, stream, filename);
107 } catch(std::exception& e) {
108 log_warning << "Couldn't load console.nut: " << e.what() << std::endl;
114 Console::execute_script(const std::string& command)
116 using namespace Scripting;
120 SQInteger oldtop = sq_gettop(vm);
122 if(SQ_FAILED(sq_compilebuffer(vm, command.c_str(), command.length(),
124 throw SquirrelError(vm, "Couldn't compile command");
126 sq_pushroottable(vm);
127 if(SQ_FAILED(sq_call(vm, 1, SQTrue, SQTrue)))
128 throw SquirrelError(vm, "Problem while executing command");
130 if(sq_gettype(vm, -1) != OT_NULL)
131 addLines(squirrel2string(vm, -1));
132 } catch(std::exception& e) {
135 SQInteger newtop = sq_gettop(vm);
136 if(newtop < oldtop) {
137 log_fatal << "Script destroyed squirrel stack..." << std::endl;
139 sq_settop(vm, oldtop);
144 Console::input(char c)
146 inputBuffer.insert(inputBufferPosition, 1, c);
147 inputBufferPosition++;
153 if ((inputBufferPosition > 0) && (inputBuffer.length() > 0)) {
154 inputBuffer.erase(inputBufferPosition-1, 1);
155 inputBufferPosition--;
162 if (inputBufferPosition < (int)inputBuffer.length()) {
163 inputBuffer.erase(inputBufferPosition, 1);
170 addLines("> "+inputBuffer);
173 inputBufferPosition = 0;
177 Console::scroll(int numLines)
180 if (offset > 0) offset = 0;
184 Console::show_history(int offset)
186 while ((offset > 0) && (history_position != history.end())) {
190 while ((offset < 0) && (history_position != history.begin())) {
194 if (history_position == history.end()) {
196 inputBufferPosition = 0;
198 inputBuffer = *history_position;
199 inputBufferPosition = inputBuffer.length();
204 Console::move_cursor(int offset)
206 if (offset == -65535) inputBufferPosition = 0;
207 if (offset == +65535) inputBufferPosition = inputBuffer.length();
208 inputBufferPosition+=offset;
209 if (inputBufferPosition < 0) inputBufferPosition = 0;
210 if (inputBufferPosition > (int)inputBuffer.length()) inputBufferPosition = inputBuffer.length();
213 // Helper functions for Console::autocomplete
214 // TODO: Fix rough documentation
217 void sq_insert_commands(std::list<std::string>& cmds, HSQUIRRELVM vm, std::string table_prefix, std::string search_prefix);
220 * Acts upon key,value on top of stack:
221 * Appends key (plus type-dependent suffix) to cmds if table_prefix+key starts with search_prefix;
222 * Calls sq_insert_commands if search_prefix starts with table_prefix+key (and value is a table/class/instance);
225 sq_insert_command(std::list<std::string>& cmds, HSQUIRRELVM vm, std::string table_prefix, std::string search_prefix)
227 const SQChar* key_chars;
228 if (SQ_FAILED(sq_getstring(vm, -2, &key_chars))) return;
229 std::string key_string = table_prefix + key_chars;
231 switch (sq_gettype(vm, -1)) {
234 if (search_prefix.substr(0, key_string.length()) == key_string) {
236 sq_insert_commands(cmds, vm, key_string, search_prefix);
243 if (search_prefix.substr(0, key_string.length()) == key_string) {
244 sq_insert_commands(cmds, vm, key_string, search_prefix);
248 case OT_NATIVECLOSURE:
255 if (key_string.substr(0, search_prefix.length()) == search_prefix) {
256 cmds.push_back(key_string);
262 * calls sq_insert_command for all entries of table/class on top of stack
265 sq_insert_commands(std::list<std::string>& cmds, HSQUIRRELVM vm, std::string table_prefix, std::string search_prefix)
267 sq_pushnull(vm); // push iterator
268 while (SQ_SUCCEEDED(sq_next(vm,-2))) {
269 sq_insert_command(cmds, vm, table_prefix, search_prefix);
270 sq_pop(vm, 2); // pop key, val
272 sq_pop(vm, 1); // pop iterator
277 // End of Console::autocomplete helper functions
280 Console::autocomplete()
282 //int autocompleteFrom = inputBuffer.find_last_of(" ();+", inputBufferPosition);
283 int autocompleteFrom = inputBuffer.find_last_not_of("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_->.", inputBufferPosition);
284 if (autocompleteFrom != (int)std::string::npos) {
285 autocompleteFrom += 1;
287 autocompleteFrom = 0;
289 std::string prefix = inputBuffer.substr(autocompleteFrom, inputBufferPosition - autocompleteFrom);
290 addLines("> "+prefix);
292 std::list<std::string> cmds;
296 // append all keys of the current root table to list
297 sq_pushroottable(vm); // push root table
299 // check all keys (and their children) for matches
300 sq_insert_commands(cmds, vm, "", prefix);
302 // cycle through parent(delegate) table
303 SQInteger oldtop = sq_gettop(vm);
304 if(SQ_FAILED(sq_getdelegate(vm, -1)) || oldtop == sq_gettop(vm)) {
307 sq_remove(vm, -2); // remove old table
309 sq_pop(vm, 1); // remove table
311 // depending on number of hits, show matches or autocomplete
312 if (cmds.size() == 0) addLines("No known command starts with \""+prefix+"\"");
313 if (cmds.size() == 1) {
314 // one match: just replace input buffer with full command
315 std::string replaceWith = cmds.front();
316 inputBuffer.replace(autocompleteFrom, prefix.length(), replaceWith);
317 inputBufferPosition += (replaceWith.length() - prefix.length());
319 if (cmds.size() > 1) {
320 // multiple matches: show all matches and set input buffer to longest common prefix
321 std::string commonPrefix = cmds.front();
322 while (cmds.begin() != cmds.end()) {
323 std::string cmd = cmds.front();
326 for (int n = commonPrefix.length(); n >= 1; n--) {
327 if (cmd.compare(0, n, commonPrefix) != 0) commonPrefix.resize(n-1); else break;
330 std::string replaceWith = commonPrefix;
331 inputBuffer.replace(autocompleteFrom, prefix.length(), replaceWith);
332 inputBufferPosition += (replaceWith.length() - prefix.length());
337 Console::addLines(std::string s)
339 std::istringstream iss(s);
341 while (std::getline(iss, line, '\n')) addLine(line);
345 Console::addLine(std::string s)
347 // output line to stderr
348 std::cerr << s << std::endl;
351 std::string overflow;
352 unsigned int line_count = 0;
354 lines.push_front(Font::wrap_to_chars(s, 99, &overflow));
357 } while (s.length() > 0);
359 // trim scrollback buffer
360 while (lines.size() >= 1000)
363 // increase console height if necessary
367 height += fontheight * line_count;
370 // reset console to full opacity
373 // increase time that console stays open
379 Console::parse(std::string s)
381 // make sure we actually have something to parse
382 if (s.length() == 0) return;
384 // add line to history
385 history.push_back(s);
386 history_position = history.end();
388 // split line into list of args
389 std::vector<std::string> args;
393 start = s.find_first_not_of(" ,", end);
394 end = s.find_first_of(" ,", start);
395 if (start == s.npos) break;
396 args.push_back(s.substr(start, end-start));
399 // command is args[0]
400 if (args.size() == 0) return;
401 std::string command = args.front();
402 args.erase(args.begin());
404 // ignore if it's an internal command
405 if (consoleCommand(command,args)) return;
409 } catch(std::exception& e) {
416 Console::consoleCommand(std::string /*command*/, std::vector<std::string> /*arguments*/)
430 if(!config->console_enabled)
436 SDL_EnableKeyRepeat(SDL_DEFAULT_REPEAT_DELAY, SDL_DEFAULT_REPEAT_INTERVAL);
446 // clear input buffer
448 inputBufferPosition = 0;
449 SDL_EnableKeyRepeat(0, SDL_DEFAULT_REPEAT_INTERVAL);
455 if (Console::hasFocus()) {
464 Console::update(float elapsed_time)
467 stayOpen -= elapsed_time;
470 } else if(!focused && height > 0) {
471 alpha -= elapsed_time * FADE_SPEED;
480 Console::draw(DrawingContext& context)
485 int layer = LAYER_GUI + 1;
487 context.push_transform();
488 context.set_alpha(alpha);
489 context.draw_surface(background2.get(), Vector(SCREEN_WIDTH/2 - background->get_width()/2 - background->get_width() + backgroundOffset, height - background->get_height()), layer);
490 context.draw_surface(background2.get(), Vector(SCREEN_WIDTH/2 - background->get_width()/2 + backgroundOffset, height - background->get_height()), layer);
491 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()) {
492 context.draw_surface(background.get(), Vector(x, height - background->get_height()), layer);
494 backgroundOffset+=10;
495 if (backgroundOffset > (int)background->get_width()) backgroundOffset -= (int)background->get_width();
501 float py = height-4-1 * font->get_height();
502 context.draw_text(font.get(), "> "+inputBuffer, Vector(4, py), ALIGN_LEFT, layer);
503 if (SDL_GetTicks() % 1000 < 750) {
504 int cursor_px = 2 + inputBufferPosition;
505 context.draw_text(font.get(), "_", Vector(4 + (cursor_px * font->get_text_width("X")), py), ALIGN_LEFT, layer);
509 int skipLines = -offset;
510 for (std::list<std::string>::iterator i = lines.begin(); i != lines.end(); i++) {
511 if (skipLines-- > 0) continue;
513 float py = height - 4 - lineNo*font->get_height();
514 if (py < -font->get_height()) break;
515 context.draw_text(font.get(), *i, Vector(4, py), ALIGN_LEFT, layer);
517 context.pop_transform();
520 Console* Console::instance = NULL;
521 int Console::inputBufferPosition = 0;
522 std::string Console::inputBuffer;
523 ConsoleStreamBuffer Console::outputBuffer;
524 std::ostream Console::output(&Console::outputBuffer);