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,"fonts/andale12.stf",1));
57 fontheight = font->get_height();
58 background.reset(new Surface("images/engine/console.png"));
59 background2.reset(new Surface("images/engine/console2.png"));
63 Console::flush(ConsoleStreamBuffer* buffer)
65 if (buffer == &outputBuffer) {
66 std::string s = outputBuffer.str();
67 if ((s.length() > 0) && ((s[s.length()-1] == '\n') || (s[s.length()-1] == '\r'))) {
68 while ((s[s.length()-1] == '\n') || (s[s.length()-1] == '\r')) s.erase(s.length()-1);
70 outputBuffer.str(std::string());
79 vm = Scripting::global_vm;
80 HSQUIRRELVM new_vm = sq_newthread(vm, 16);
82 throw Scripting::SquirrelError(vm, "Couldn't create new VM thread for console");
84 // store reference to thread
85 sq_resetobject(&vm_object);
86 if(SQ_FAILED(sq_getstackobj(vm, -1, &vm_object)))
87 throw Scripting::SquirrelError(vm, "Couldn't get vm object for console");
88 sq_addref(vm, &vm_object);
91 // create new roottable for thread
93 sq_pushroottable(new_vm);
94 if(SQ_FAILED(sq_setdelegate(new_vm, -2)))
95 throw Scripting::SquirrelError(new_vm, "Couldn't set console_table delegate");
97 sq_setroottable(new_vm);
102 std::string filename = "scripts/console.nut";
103 IFileStream stream(filename);
104 Scripting::compile_and_run(vm, stream, filename);
105 } catch(std::exception& e) {
106 log_warning << "Couldn't load console.nut: " << e.what() << std::endl;
112 Console::execute_script(const std::string& command)
114 using namespace Scripting;
118 SQInteger oldtop = sq_gettop(vm);
120 if(SQ_FAILED(sq_compilebuffer(vm, command.c_str(), command.length(),
122 throw SquirrelError(vm, "Couldn't compile command");
124 sq_pushroottable(vm);
125 if(SQ_FAILED(sq_call(vm, 1, SQTrue, SQTrue)))
126 throw SquirrelError(vm, "Problem while executing command");
128 if(sq_gettype(vm, -1) != OT_NULL)
129 addLines(squirrel2string(vm, -1));
130 } catch(std::exception& e) {
133 SQInteger newtop = sq_gettop(vm);
134 if(newtop < oldtop) {
135 log_fatal << "Script destroyed squirrel stack..." << std::endl;
137 sq_settop(vm, oldtop);
142 Console::input(char c)
144 inputBuffer.insert(inputBufferPosition, 1, c);
145 inputBufferPosition++;
151 if ((inputBufferPosition > 0) && (inputBuffer.length() > 0)) {
152 inputBuffer.erase(inputBufferPosition-1, 1);
153 inputBufferPosition--;
160 if (inputBufferPosition < (int)inputBuffer.length()) {
161 inputBuffer.erase(inputBufferPosition, 1);
168 addLines("> "+inputBuffer);
171 inputBufferPosition = 0;
175 Console::scroll(int numLines)
178 if (offset > 0) offset = 0;
182 Console::show_history(int offset)
184 while ((offset > 0) && (history_position != history.end())) {
188 while ((offset < 0) && (history_position != history.begin())) {
192 if (history_position == history.end()) {
194 inputBufferPosition = 0;
196 inputBuffer = *history_position;
197 inputBufferPosition = inputBuffer.length();
202 Console::move_cursor(int offset)
204 if (offset == -65535) inputBufferPosition = 0;
205 if (offset == +65535) inputBufferPosition = inputBuffer.length();
206 inputBufferPosition+=offset;
207 if (inputBufferPosition < 0) inputBufferPosition = 0;
208 if (inputBufferPosition > (int)inputBuffer.length()) inputBufferPosition = inputBuffer.length();
211 // Helper functions for Console::autocomplete
212 // TODO: Fix rough documentation
215 void sq_insert_commands(std::list<std::string>& cmds, HSQUIRRELVM vm, std::string table_prefix, std::string search_prefix);
218 * Acts upon key,value on top of stack:
219 * Appends key (plus type-dependent suffix) to cmds if table_prefix+key starts with search_prefix;
220 * Calls sq_insert_commands if search_prefix starts with table_prefix+key (and value is a table/class/instance);
223 sq_insert_command(std::list<std::string>& cmds, HSQUIRRELVM vm, std::string table_prefix, std::string search_prefix)
225 const SQChar* key_chars;
226 if (SQ_FAILED(sq_getstring(vm, -2, &key_chars))) return;
227 std::string key_string = table_prefix + key_chars;
229 switch (sq_gettype(vm, -1)) {
232 if (search_prefix.substr(0, key_string.length()) == key_string) {
234 sq_insert_commands(cmds, vm, key_string, search_prefix);
241 if (search_prefix.substr(0, key_string.length()) == key_string) {
242 sq_insert_commands(cmds, vm, key_string, search_prefix);
246 case OT_NATIVECLOSURE:
253 if (key_string.substr(0, search_prefix.length()) == search_prefix) {
254 cmds.push_back(key_string);
260 * calls sq_insert_command for all entries of table/class on top of stack
263 sq_insert_commands(std::list<std::string>& cmds, HSQUIRRELVM vm, std::string table_prefix, std::string search_prefix)
265 sq_pushnull(vm); // push iterator
266 while (SQ_SUCCEEDED(sq_next(vm,-2))) {
267 sq_insert_command(cmds, vm, table_prefix, search_prefix);
268 sq_pop(vm, 2); // pop key, val
270 sq_pop(vm, 1); // pop iterator
275 // End of Console::autocomplete helper functions
278 Console::autocomplete()
280 //int autocompleteFrom = inputBuffer.find_last_of(" ();+", inputBufferPosition);
281 int autocompleteFrom = inputBuffer.find_last_not_of("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_->.", inputBufferPosition);
282 if (autocompleteFrom != (int)std::string::npos) {
283 autocompleteFrom += 1;
285 autocompleteFrom = 0;
287 std::string prefix = inputBuffer.substr(autocompleteFrom, inputBufferPosition - autocompleteFrom);
288 addLines("> "+prefix);
290 std::list<std::string> cmds;
294 // append all keys of the current root table to list
295 sq_pushroottable(vm); // push root table
297 // check all keys (and their children) for matches
298 sq_insert_commands(cmds, vm, "", prefix);
300 // cycle through parent(delegate) table
301 SQInteger oldtop = sq_gettop(vm);
302 if(SQ_FAILED(sq_getdelegate(vm, -1)) || oldtop == sq_gettop(vm)) {
305 sq_remove(vm, -2); // remove old table
307 sq_pop(vm, 1); // remove table
309 // depending on number of hits, show matches or autocomplete
310 if (cmds.size() == 0) addLines("No known command starts with \""+prefix+"\"");
311 if (cmds.size() == 1) {
312 // one match: just replace input buffer with full command
313 std::string replaceWith = cmds.front();
314 inputBuffer.replace(autocompleteFrom, prefix.length(), replaceWith);
315 inputBufferPosition += (replaceWith.length() - prefix.length());
317 if (cmds.size() > 1) {
318 // multiple matches: show all matches and set input buffer to longest common prefix
319 std::string commonPrefix = cmds.front();
320 while (cmds.begin() != cmds.end()) {
321 std::string cmd = cmds.front();
324 for (int n = commonPrefix.length(); n >= 1; n--) {
325 if (cmd.compare(0, n, commonPrefix) != 0) commonPrefix.resize(n-1); else break;
328 std::string replaceWith = commonPrefix;
329 inputBuffer.replace(autocompleteFrom, prefix.length(), replaceWith);
330 inputBufferPosition += (replaceWith.length() - prefix.length());
335 Console::addLines(std::string s)
337 std::istringstream iss(s);
339 while (std::getline(iss, line, '\n')) addLine(line);
343 Console::addLine(std::string s)
345 // output line to stderr
346 std::cerr << s << std::endl;
349 std::string overflow;
350 unsigned int line_count = 0;
352 lines.push_front(Font::wrap_to_chars(s, 99, &overflow));
355 } while (s.length() > 0);
357 // trim scrollback buffer
358 while (lines.size() >= 1000)
361 // increase console height if necessary
365 height += fontheight * line_count;
368 // reset console to full opacity
371 // increase time that console stays open
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(!config->console_enabled)
434 SDL_EnableKeyRepeat(SDL_DEFAULT_REPEAT_DELAY, SDL_DEFAULT_REPEAT_INTERVAL);
444 // clear input buffer
446 inputBufferPosition = 0;
447 SDL_EnableKeyRepeat(0, SDL_DEFAULT_REPEAT_INTERVAL);
453 if (Console::hasFocus()) {
462 Console::update(float elapsed_time)
465 stayOpen -= elapsed_time;
468 } else if(!focused && height > 0) {
469 alpha -= elapsed_time * FADE_SPEED;
478 Console::draw(DrawingContext& context)
483 int layer = LAYER_GUI + 1;
485 context.push_transform();
486 context.set_alpha(alpha);
487 context.draw_surface(background2.get(), Vector(SCREEN_WIDTH/2 - background->get_width()/2 - background->get_width() + backgroundOffset, height - background->get_height()), layer);
488 context.draw_surface(background2.get(), Vector(SCREEN_WIDTH/2 - background->get_width()/2 + backgroundOffset, height - background->get_height()), layer);
489 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()) {
490 context.draw_surface(background.get(), Vector(x, height - background->get_height()), layer);
492 backgroundOffset+=10;
493 if (backgroundOffset > (int)background->get_width()) backgroundOffset -= (int)background->get_width();
499 float py = height-4-1 * font->get_height();
500 context.draw_text(font.get(), "> "+inputBuffer, Vector(4, py), ALIGN_LEFT, layer);
501 if (SDL_GetTicks() % 1000 < 750) {
502 int cursor_px = 2 + inputBufferPosition;
503 context.draw_text(font.get(), "_", Vector(4 + (cursor_px * font->get_text_width("X")), py), ALIGN_LEFT, layer);
507 int skipLines = -offset;
508 for (std::list<std::string>::iterator i = lines.begin(); i != lines.end(); i++) {
509 if (skipLines-- > 0) continue;
511 float py = height - 4 - lineNo*font->get_height();
512 if (py < -font->get_height()) break;
513 context.draw_text(font.get(), *i, Vector(4, py), ALIGN_LEFT, layer);
515 context.pop_transform();
518 Console* Console::instance = NULL;
519 int Console::inputBufferPosition = 0;
520 std::string Console::inputBuffer;
521 ConsoleStreamBuffer Console::outputBuffer;
522 std::ostream Console::output(&Console::outputBuffer);