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.
22 #include <SDL_timer.h>
23 #include <SDL_keyboard.h>
24 #include "console.hpp"
25 #include "video/drawing_context.hpp"
26 #include "video/surface.hpp"
27 #include "scripting/squirrel_error.hpp"
28 #include "scripting/squirrel_util.hpp"
29 #include "physfs/physfs_stream.hpp"
30 #include "player_status.hpp"
33 #include "resources.hpp"
34 #include "gameconfig.hpp"
36 /// speed (pixels/s) the console closes
37 static const float FADE_SPEED = 1;
40 : history_position(history.end()), vm(NULL), backgroundOffset(0),
41 height(0), alpha(1.0), offset(0), focused(false), stayOpen(0) {
48 sq_release(Scripting::global_vm, &vm_object);
53 Console::init_graphics()
55 font.reset(new Font(Font::FIXED,
56 "images/engine/fonts/andale12.png",
57 "images/engine/fonts/andale12-shadow.png", 7, 14, 1));
58 fontheight = font->get_height();
59 background.reset(new Surface("images/engine/console.png"));
60 background2.reset(new Surface("images/engine/console2.png"));
64 Console::flush(ConsoleStreamBuffer* buffer)
66 if (buffer == &outputBuffer) {
67 std::string s = outputBuffer.str();
68 if ((s.length() > 0) && ((s[s.length()-1] == '\n') || (s[s.length()-1] == '\r'))) {
69 while ((s[s.length()-1] == '\n') || (s[s.length()-1] == '\r')) s.erase(s.length()-1);
71 outputBuffer.str(std::string());
80 vm = Scripting::global_vm;
81 HSQUIRRELVM new_vm = sq_newthread(vm, 16);
83 throw Scripting::SquirrelError(vm, "Couldn't create new VM thread for console");
85 // store reference to thread
86 sq_resetobject(&vm_object);
87 if(SQ_FAILED(sq_getstackobj(vm, -1, &vm_object)))
88 throw Scripting::SquirrelError(vm, "Couldn't get vm object for console");
89 sq_addref(vm, &vm_object);
92 // create new roottable for thread
94 sq_pushroottable(new_vm);
95 if(SQ_FAILED(sq_setdelegate(new_vm, -2)))
96 throw Scripting::SquirrelError(new_vm, "Couldn't set console_table delegate");
98 sq_setroottable(new_vm);
103 std::string filename = "scripts/console.nut";
104 IFileStream stream(filename);
105 Scripting::compile_and_run(vm, stream, filename);
106 } catch(std::exception& e) {
107 log_warning << "Couldn't load console.nut: " << e.what() << std::endl;
113 Console::execute_script(const std::string& command)
115 using namespace Scripting;
119 SQInteger oldtop = sq_gettop(vm);
121 if(SQ_FAILED(sq_compilebuffer(vm, command.c_str(), command.length(),
123 throw SquirrelError(vm, "Couldn't compile command");
125 sq_pushroottable(vm);
126 if(SQ_FAILED(sq_call(vm, 1, SQTrue, SQTrue)))
127 throw SquirrelError(vm, "Problem while executing command");
129 if(sq_gettype(vm, -1) != OT_NULL)
130 addLines(squirrel2string(vm, -1));
131 } catch(std::exception& e) {
134 SQInteger newtop = sq_gettop(vm);
135 if(newtop < oldtop) {
136 log_fatal << "Script destroyed squirrel stack..." << std::endl;
138 sq_settop(vm, oldtop);
143 Console::input(char c)
145 inputBuffer.insert(inputBufferPosition, 1, c);
146 inputBufferPosition++;
152 if ((inputBufferPosition > 0) && (inputBuffer.length() > 0)) {
153 inputBuffer.erase(inputBufferPosition-1, 1);
154 inputBufferPosition--;
161 if (inputBufferPosition < (int)inputBuffer.length()) {
162 inputBuffer.erase(inputBufferPosition, 1);
169 addLines("> "+inputBuffer);
172 inputBufferPosition = 0;
176 Console::scroll(int numLines)
179 if (offset > 0) offset = 0;
183 Console::show_history(int offset)
185 while ((offset > 0) && (history_position != history.end())) {
189 while ((offset < 0) && (history_position != history.begin())) {
193 if (history_position == history.end()) {
195 inputBufferPosition = 0;
197 inputBuffer = *history_position;
198 inputBufferPosition = inputBuffer.length();
203 Console::move_cursor(int offset)
205 if (offset == -65535) inputBufferPosition = 0;
206 if (offset == +65535) inputBufferPosition = inputBuffer.length();
207 inputBufferPosition+=offset;
208 if (inputBufferPosition < 0) inputBufferPosition = 0;
209 if (inputBufferPosition > (int)inputBuffer.length()) inputBufferPosition = inputBuffer.length();
212 // Helper functions for Console::autocomplete
213 // TODO: Fix rough documentation
216 void sq_insert_commands(std::list<std::string>& cmds, HSQUIRRELVM vm, std::string table_prefix, std::string search_prefix);
219 * Acts upon key,value on top of stack:
220 * Appends key (plus type-dependent suffix) to cmds if table_prefix+key starts with search_prefix;
221 * Calls sq_insert_commands if search_prefix starts with table_prefix+key (and value is a table/class/instance);
224 sq_insert_command(std::list<std::string>& cmds, HSQUIRRELVM vm, std::string table_prefix, std::string search_prefix)
226 const SQChar* key_chars;
227 if (SQ_FAILED(sq_getstring(vm, -2, &key_chars))) return;
228 std::string key_string = table_prefix + key_chars;
230 switch (sq_gettype(vm, -1)) {
233 if (search_prefix.substr(0, key_string.length()) == key_string) {
235 sq_insert_commands(cmds, vm, key_string, search_prefix);
242 if (search_prefix.substr(0, key_string.length()) == key_string) {
243 sq_insert_commands(cmds, vm, key_string, search_prefix);
247 case OT_NATIVECLOSURE:
254 if (key_string.substr(0, search_prefix.length()) == search_prefix) {
255 cmds.push_back(key_string);
261 * calls sq_insert_command for all entries of table/class on top of stack
264 sq_insert_commands(std::list<std::string>& cmds, HSQUIRRELVM vm, std::string table_prefix, std::string search_prefix)
266 sq_pushnull(vm); // push iterator
267 while (SQ_SUCCEEDED(sq_next(vm,-2))) {
268 sq_insert_command(cmds, vm, table_prefix, search_prefix);
269 sq_pop(vm, 2); // pop key, val
271 sq_pop(vm, 1); // pop iterator
276 // End of Console::autocomplete helper functions
279 Console::autocomplete()
281 //int autocompleteFrom = inputBuffer.find_last_of(" ();+", inputBufferPosition);
282 int autocompleteFrom = inputBuffer.find_last_not_of("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_->.", inputBufferPosition);
283 if (autocompleteFrom != (int)std::string::npos) {
284 autocompleteFrom += 1;
286 autocompleteFrom = 0;
288 std::string prefix = inputBuffer.substr(autocompleteFrom, inputBufferPosition - autocompleteFrom);
289 addLines("> "+prefix);
291 std::list<std::string> cmds;
295 // append all keys of the current root table to list
296 sq_pushroottable(vm); // push root table
298 // check all keys (and their children) for matches
299 sq_insert_commands(cmds, vm, "", prefix);
301 // cycle through parent(delegate) table
302 SQInteger oldtop = sq_gettop(vm);
303 if(SQ_FAILED(sq_getdelegate(vm, -1)) || oldtop == sq_gettop(vm)) {
306 sq_remove(vm, -2); // remove old table
308 sq_pop(vm, 1); // remove table
310 // depending on number of hits, show matches or autocomplete
311 if (cmds.size() == 0) addLines("No known command starts with \""+prefix+"\"");
312 if (cmds.size() == 1) {
313 // one match: just replace input buffer with full command
314 std::string replaceWith = cmds.front();
315 inputBuffer.replace(autocompleteFrom, prefix.length(), replaceWith);
316 inputBufferPosition += (replaceWith.length() - prefix.length());
318 if (cmds.size() > 1) {
319 // multiple matches: show all matches and set input buffer to longest common prefix
320 std::string commonPrefix = cmds.front();
321 while (cmds.begin() != cmds.end()) {
322 std::string cmd = cmds.front();
325 for (int n = commonPrefix.length(); n >= 1; n--) {
326 if (cmd.compare(0, n, commonPrefix) != 0) commonPrefix.resize(n-1); else break;
329 std::string replaceWith = commonPrefix;
330 inputBuffer.replace(autocompleteFrom, prefix.length(), replaceWith);
331 inputBufferPosition += (replaceWith.length() - prefix.length());
336 Console::addLines(std::string s)
338 std::istringstream iss(s);
340 while (std::getline(iss, line, '\n')) addLine(line);
344 Console::addLine(std::string s)
346 // output line to stderr
347 std::cerr << s << std::endl;
350 std::string overflow;
351 unsigned int line_count = 0;
353 lines.push_front(Font::wrap_to_chars(s, 99, &overflow));
356 } while (s.length() > 0);
358 // trim scrollback buffer
359 while (lines.size() >= 1000)
362 // increase console height if necessary
366 height += fontheight * line_count;
369 // reset console to full opacity
372 // increase time that console stays open
378 Console::parse(std::string s)
380 // make sure we actually have something to parse
381 if (s.length() == 0) return;
383 // add line to history
384 history.push_back(s);
385 history_position = history.end();
387 // split line into list of args
388 std::vector<std::string> args;
392 start = s.find_first_not_of(" ,", end);
393 end = s.find_first_of(" ,", start);
394 if (start == s.npos) break;
395 args.push_back(s.substr(start, end-start));
398 // command is args[0]
399 if (args.size() == 0) return;
400 std::string command = args.front();
401 args.erase(args.begin());
403 // ignore if it's an internal command
404 if (consoleCommand(command,args)) return;
408 } catch(std::exception& e) {
415 Console::consoleCommand(std::string /*command*/, std::vector<std::string> /*arguments*/)
429 if(!config->console_enabled)
435 SDL_EnableKeyRepeat(SDL_DEFAULT_REPEAT_DELAY, SDL_DEFAULT_REPEAT_INTERVAL);
445 // clear input buffer
447 inputBufferPosition = 0;
448 SDL_EnableKeyRepeat(0, SDL_DEFAULT_REPEAT_INTERVAL);
454 if (Console::hasFocus()) {
463 Console::update(float elapsed_time)
466 stayOpen -= elapsed_time;
469 } else if(!focused && height > 0) {
470 alpha -= elapsed_time * FADE_SPEED;
479 Console::draw(DrawingContext& context)
484 int layer = LAYER_GUI + 1;
486 context.push_transform();
487 context.set_alpha(alpha);
488 context.draw_surface(background2.get(), Vector(SCREEN_WIDTH/2 - background->get_width()/2 - background->get_width() + backgroundOffset, height - background->get_height()), layer);
489 context.draw_surface(background2.get(), Vector(SCREEN_WIDTH/2 - background->get_width()/2 + backgroundOffset, height - background->get_height()), layer);
490 context.draw_surface(background.get(), Vector(SCREEN_WIDTH/2 - background->get_width()/2, height - background->get_height()), layer);
491 backgroundOffset+=10;
492 if (backgroundOffset > (int)background->get_width()) backgroundOffset -= (int)background->get_width();
498 float py = height-4-1 * font->get_height();
499 context.draw_text(font.get(), "> "+inputBuffer, Vector(4, py), ALIGN_LEFT, layer);
500 if (SDL_GetTicks() % 1000 < 750) {
501 int cursor_px = 2 + inputBufferPosition;
502 context.draw_text(font.get(), "_", Vector(4 + (cursor_px * font->get_text_width("X")), py), ALIGN_LEFT, layer);
506 int skipLines = -offset;
507 for (std::list<std::string>::iterator i = lines.begin(); i != lines.end(); i++) {
508 if (skipLines-- > 0) continue;
510 float py = height - 4 - lineNo*font->get_height();
511 if (py < -font->get_height()) break;
512 context.draw_text(font.get(), *i, Vector(4, py), ALIGN_LEFT, layer);
514 context.pop_transform();
517 Console* Console::instance = NULL;
518 int Console::inputBufferPosition = 0;
519 std::string Console::inputBuffer;
520 ConsoleStreamBuffer Console::outputBuffer;
521 std::ostream Console::output(&Console::outputBuffer);