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());
74 if (buffer == &inputBuffer) {
75 std::string s = inputBuffer.str();
76 if ((s.length() > 0) && ((s[s.length()-1] == '\n') || (s[s.length()-1] == '\r'))) {
77 while ((s[s.length()-1] == '\n') || (s[s.length()-1] == '\r')) s.erase(s.length()-1);
87 vm = Scripting::global_vm;
88 HSQUIRRELVM new_vm = sq_newthread(vm, 16);
90 throw Scripting::SquirrelError(vm, "Couldn't create new VM thread for console");
92 // store reference to thread
93 sq_resetobject(&vm_object);
94 if(SQ_FAILED(sq_getstackobj(vm, -1, &vm_object)))
95 throw Scripting::SquirrelError(vm, "Couldn't get vm object for console");
96 sq_addref(vm, &vm_object);
99 // create new roottable for thread
101 sq_pushroottable(new_vm);
102 if(SQ_FAILED(sq_setdelegate(new_vm, -2)))
103 throw Scripting::SquirrelError(new_vm, "Couldn't set console_table delegate");
105 sq_setroottable(new_vm);
110 std::string filename = "scripts/console.nut";
111 IFileStream stream(filename);
112 Scripting::compile_and_run(vm, stream, filename);
113 } catch(std::exception& e) {
114 log_warning << "Couldn't load console.nut: " << e.what() << std::endl;
120 Console::execute_script(const std::string& command)
122 using namespace Scripting;
126 SQInteger oldtop = sq_gettop(vm);
128 if(SQ_FAILED(sq_compilebuffer(vm, command.c_str(), command.length(),
130 throw SquirrelError(vm, "Couldn't compile command");
132 sq_pushroottable(vm);
133 if(SQ_FAILED(sq_call(vm, 1, SQTrue, SQTrue)))
134 throw SquirrelError(vm, "Problem while executing command");
136 if(sq_gettype(vm, -1) != OT_NULL)
137 addLines(squirrel2string(vm, -1));
138 } catch(std::exception& e) {
141 SQInteger newtop = sq_gettop(vm);
142 if(newtop < oldtop) {
143 log_fatal << "Script destroyed squirrel stack..." << std::endl;
145 sq_settop(vm, oldtop);
152 std::string s = inputBuffer.str();
153 if (s.length() > 0) {
154 s.erase(s.length()-1);
156 inputBuffer.pubseekoff(0, std::ios_base::end, std::ios_base::out);
163 std::string s = inputBuffer.str();
166 inputBuffer.str(std::string());
170 Console::scroll(int numLines)
173 if (offset > 0) offset = 0;
177 Console::show_history(int offset)
179 while ((offset > 0) && (history_position != history.end())) {
183 while ((offset < 0) && (history_position != history.begin())) {
187 if (history_position == history.end()) {
188 inputBuffer.str(std::string());
190 inputBuffer.str(*history_position);
191 inputBuffer.pubseekoff(0, std::ios_base::end, std::ios_base::out);
196 Console::move_cursor(int offset)
198 if (offset == -65535) inputBuffer.pubseekoff(0, std::ios_base::beg, std::ios_base::out);
199 if (offset == +65535) inputBuffer.pubseekoff(0, std::ios_base::end, std::ios_base::out);
200 inputBuffer.pubseekoff(offset, std::ios_base::cur, std::ios_base::out);
203 // Helper functions for Console::autocomplete
204 // TODO: Fix rough documentation
207 void sq_insert_commands(std::list<std::string>& cmds, HSQUIRRELVM vm, std::string table_prefix, std::string search_prefix);
210 * Acts upon key,value on top of stack:
211 * Appends key (plus type-dependent suffix) to cmds if table_prefix+key starts with search_prefix;
212 * Calls sq_insert_commands if search_prefix starts with table_prefix+key (and value is a table/class/instance);
215 sq_insert_command(std::list<std::string>& cmds, HSQUIRRELVM vm, std::string table_prefix, std::string search_prefix)
217 const SQChar* key_chars;
218 if (SQ_FAILED(sq_getstring(vm, -2, &key_chars))) return;
219 std::string key_string = table_prefix + key_chars;
221 switch (sq_gettype(vm, -1)) {
224 if (search_prefix.substr(0, key_string.length()) == key_string) {
226 sq_insert_commands(cmds, vm, key_string, search_prefix);
233 if (search_prefix.substr(0, key_string.length()) == key_string) {
234 sq_insert_commands(cmds, vm, key_string, search_prefix);
238 case OT_NATIVECLOSURE:
245 if (key_string.substr(0, search_prefix.length()) == search_prefix) {
246 cmds.push_back(key_string);
252 * calls sq_insert_command for all entries of table/class on top of stack
255 sq_insert_commands(std::list<std::string>& cmds, HSQUIRRELVM vm, std::string table_prefix, std::string search_prefix)
257 sq_pushnull(vm); // push iterator
258 while (SQ_SUCCEEDED(sq_next(vm,-2))) {
259 sq_insert_command(cmds, vm, table_prefix, search_prefix);
260 sq_pop(vm, 2); // pop key, val
262 sq_pop(vm, 1); // pop iterator
267 // End of Console::autocomplete helper functions
270 Console::autocomplete()
272 std::string prefix = inputBuffer.str();
273 addLines("> "+prefix);
275 std::list<std::string> cmds;
279 // append all keys of the current root table to list
280 sq_pushroottable(vm); // push root table
282 // check all keys (and their children) for matches
283 sq_insert_commands(cmds, vm, "", prefix);
285 // cycle through parent(delegate) table
286 SQInteger oldtop = sq_gettop(vm);
287 if(SQ_FAILED(sq_getdelegate(vm, -1)) || oldtop == sq_gettop(vm)) {
290 sq_remove(vm, -2); // remove old table
292 sq_pop(vm, 1); // remove table
294 // depending on number of hits, show matches or autocomplete
295 if (cmds.size() == 0) addLines("No known command starts with \""+prefix+"\"");
296 if (cmds.size() == 1) {
297 // one match: just replace input buffer with full command
298 inputBuffer.str(cmds.front());
299 inputBuffer.pubseekoff(0, std::ios_base::end, std::ios_base::out);
301 if (cmds.size() > 1) {
302 // multiple matches: show all matches and set input buffer to longest common prefix
303 std::string commonPrefix = cmds.front();
304 while (cmds.begin() != cmds.end()) {
305 std::string cmd = cmds.front();
308 for (int n = commonPrefix.length(); n >= 1; n--) {
309 if (cmd.compare(0, n, commonPrefix) != 0) commonPrefix.resize(n-1); else break;
312 inputBuffer.str(commonPrefix);
313 inputBuffer.pubseekoff(0, std::ios_base::end, std::ios_base::out);
318 Console::addLines(std::string s)
320 std::istringstream iss(s);
322 while (std::getline(iss, line, '\n')) addLine(line);
326 Console::addLine(std::string s)
328 // output line to stderr
329 std::cerr << s << std::endl;
332 std::string overflow;
333 unsigned int line_count = 0;
335 lines.push_front(Font::wrap_to_chars(s, 99, &overflow));
338 } while (s.length() > 0);
340 // trim scrollback buffer
341 while (lines.size() >= 1000)
344 // increase console height if necessary
348 height += fontheight * line_count;
351 // reset console to full opacity
354 // increase time that console stays open
360 Console::parse(std::string s)
362 // make sure we actually have something to parse
363 if (s.length() == 0) return;
365 // add line to history
366 history.push_back(s);
367 history_position = history.end();
369 // split line into list of args
370 std::vector<std::string> args;
374 start = s.find_first_not_of(" ,", end);
375 end = s.find_first_of(" ,", start);
376 if (start == s.npos) break;
377 args.push_back(s.substr(start, end-start));
380 // command is args[0]
381 if (args.size() == 0) return;
382 std::string command = args.front();
383 args.erase(args.begin());
385 // ignore if it's an internal command
386 if (consoleCommand(command,args)) return;
390 } catch(std::exception& e) {
397 Console::consoleCommand(std::string /*command*/, std::vector<std::string> /*arguments*/)
411 if(!config->console_enabled)
417 SDL_EnableKeyRepeat(SDL_DEFAULT_REPEAT_DELAY, SDL_DEFAULT_REPEAT_INTERVAL);
427 // clear input buffer
428 inputBuffer.str(std::string());
429 SDL_EnableKeyRepeat(0, SDL_DEFAULT_REPEAT_INTERVAL);
435 if (Console::hasFocus()) {
444 Console::update(float elapsed_time)
447 stayOpen -= elapsed_time;
450 } else if(!focused && height > 0) {
451 alpha -= elapsed_time * FADE_SPEED;
460 Console::draw(DrawingContext& context)
465 int layer = LAYER_GUI + 1;
467 context.push_transform();
468 context.set_alpha(alpha);
469 context.draw_surface(background2.get(), Vector(SCREEN_WIDTH/2 - background->get_width()/2 - background->get_width() + backgroundOffset, height - background->get_height()), layer);
470 context.draw_surface(background2.get(), Vector(SCREEN_WIDTH/2 - background->get_width()/2 + backgroundOffset, height - background->get_height()), layer);
471 context.draw_surface(background.get(), Vector(SCREEN_WIDTH/2 - background->get_width()/2, height - background->get_height()), layer);
472 backgroundOffset+=10;
473 if (backgroundOffset > (int)background->get_width()) backgroundOffset -= (int)background->get_width();
479 float py = height-4-1 * font->get_height();
480 context.draw_text(font.get(), "> "+inputBuffer.str(), Vector(4, py), ALIGN_LEFT, layer);
481 if (SDL_GetTicks() % 1000 < 750) {
482 int cursor_px = 2 + inputBuffer.pubseekoff(0, std::ios_base::cur, std::ios_base::out);
483 context.draw_text(font.get(), "_", Vector(4 + (cursor_px * font->get_text_width("X")), py), ALIGN_LEFT, layer);
487 int skipLines = -offset;
488 for (std::list<std::string>::iterator i = lines.begin(); i != lines.end(); i++) {
489 if (skipLines-- > 0) continue;
491 float py = height - 4 - lineNo*font->get_height();
492 if (py < -font->get_height()) break;
493 context.draw_text(font.get(), *i, Vector(4, py), ALIGN_LEFT, layer);
495 context.pop_transform();
498 Console* Console::instance = NULL;
499 ConsoleStreamBuffer Console::inputBuffer;
500 ConsoleStreamBuffer Console::outputBuffer;
501 std::ostream Console::input(&Console::inputBuffer);
502 std::ostream Console::output(&Console::outputBuffer);