- Avoid some expensive SDL_GetTicks() calls
[supertux.git] / src / console.cpp
1 //  $Id$
2 //
3 //  SuperTux - Console
4 //  Copyright (C) 2006 Christoph Sommer <christoph.sommer@2006.expires.deltadevelopment.de>
5 //
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.
10 //
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.
15 //
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.
19 #include <config.h>
20
21 #include <iostream>
22 #include "console.hpp"
23 #include "video/drawing_context.hpp"
24 #include "video/surface.hpp"
25 #include "scripting/squirrel_error.hpp"
26 #include "scripting/squirrel_util.hpp"
27 #include "physfs/physfs_stream.hpp"
28 #include "player_status.hpp"
29 #include "main.hpp"
30 #include "log.hpp"
31 #include "resources.hpp"
32
33 /// speed (pixels/s) the console closes
34 static const float FADE_SPEED = 1;
35
36 Console::Console()
37   : vm(NULL), backgroundOffset(0), height(0), alpha(1.0), offset(0),
38     focused(false), stayOpen(0)
39 {
40   fontheight = 8;
41 }
42
43 Console::~Console() 
44 {
45   if(vm != NULL) {
46     sq_release(Scripting::global_vm, &vm_object);
47   }
48 }
49
50 void
51 Console::init_graphics()
52 {
53   font.reset(new Font("images/engine/fonts/white-small.png",
54                       "images/engine/fonts/shadow-small.png", 8, 9, 1));
55   fontheight = font->get_height();
56   background.reset(new Surface("images/engine/console.png"));
57   background2.reset(new Surface("images/engine/console2.png"));
58 }
59
60 void 
61 Console::flush(ConsoleStreamBuffer* buffer) 
62 {
63   if (buffer == &outputBuffer) {
64     std::string s = outputBuffer.str();
65     if ((s.length() > 0) && ((s[s.length()-1] == '\n') || (s[s.length()-1] == '\r'))) {
66       while ((s[s.length()-1] == '\n') || (s[s.length()-1] == '\r')) s.erase(s.length()-1);
67       addLine(s);
68       outputBuffer.str(std::string());
69     }
70   }
71   if (buffer == &inputBuffer) {
72     std::string s = inputBuffer.str();
73     if ((s.length() > 0) && ((s[s.length()-1] == '\n') || (s[s.length()-1] == '\r'))) {
74       while ((s[s.length()-1] == '\n') || (s[s.length()-1] == '\r')) s.erase(s.length()-1);
75       addLine("> "+s);
76       parse(s);
77       inputBuffer.str(std::string());
78     }
79   }
80 }
81
82 void
83 Console::execute_script(const std::string& command)
84 {
85   using namespace Scripting;
86
87   if(vm == NULL) {
88     vm = Scripting::global_vm;
89     HSQUIRRELVM new_vm = sq_newthread(vm, 16);
90     if(new_vm == NULL)
91       throw Scripting::SquirrelError(vm, "Couldn't create new VM thread for console");
92
93     // store reference to thread
94     sq_resetobject(&vm_object);
95     if(SQ_FAILED(sq_getstackobj(vm, -1, &vm_object)))
96       throw Scripting::SquirrelError(vm, "Couldn't get vm object for console");
97     sq_addref(vm, &vm_object);
98     sq_pop(vm, 1);
99     
100     // create new roottable for thread
101     sq_newtable(new_vm);
102     sq_pushroottable(new_vm);
103     if(SQ_FAILED(sq_setdelegate(new_vm, -2)))
104       throw Scripting::SquirrelError(new_vm, "Couldn't set console_table delegate");
105
106     sq_setroottable(new_vm);
107
108     vm = new_vm;
109     
110     try {
111       std::string filename = "scripts/console.nut";
112       IFileStream stream(filename);
113       Scripting::compile_and_run(vm, stream, filename);
114     } catch(std::exception& e) {
115       log_warning << "Couldn't load console.nut: " << e.what() << std::endl;
116     }
117   }
118     
119   int oldtop = sq_gettop(vm); 
120   try {
121     if(SQ_FAILED(sq_compilebuffer(vm, command.c_str(), command.length(),
122                  "", SQTrue)))
123       throw SquirrelError(vm, "Couldn't compile command");
124
125     sq_pushroottable(vm); 
126     if(SQ_FAILED(sq_call(vm, 1, SQTrue, SQTrue)))
127       throw SquirrelError(vm, "Problem while executing command");
128
129     if(sq_gettype(vm, -1) != OT_NULL)
130       addLine(squirrel2string(vm, -1));
131   } catch(std::exception& e) {
132     addLine(e.what());
133   }
134   int newtop = sq_gettop(vm);
135   if(newtop < oldtop) {
136     log_fatal << "Script destroyed squirrel stack..." << std::endl;
137   } else {
138     sq_settop(vm, oldtop);
139   }
140 }
141
142 void
143 Console::backspace()
144 {
145   std::string s = inputBuffer.str();
146   if (s.length() > 0) {
147     s.erase(s.length()-1);
148     inputBuffer.str(s);
149     inputBuffer.pubseekoff(0, std::ios_base::end, std::ios_base::out);
150   }
151 }
152
153 void
154 Console::scroll(int numLines)
155 {
156   offset += numLines;
157   if (offset > 0) offset = 0;
158 }
159
160 void
161 Console::autocomplete()
162 {
163   std::string cmdPart = inputBuffer.str();
164   addLine("> "+cmdPart);
165
166   std::string cmdList = "";
167   int cmdListLen = 0;
168   for (std::map<std::string, std::list<ConsoleCommandReceiver*> >::iterator i = commands.begin(); i != commands.end(); i++) {
169     std::string cmdKnown = i->first;
170     if (cmdKnown.substr(0, cmdPart.length()) == cmdPart) {
171       if (cmdListLen > 0) cmdList = cmdList + ", ";
172       cmdList = cmdList + cmdKnown;
173       cmdListLen++;
174     }
175   }
176   if (cmdListLen == 0) addLine("No known command starts with \""+cmdPart+"\"");
177   if (cmdListLen == 1) {
178     inputBuffer.str(cmdList);
179     inputBuffer.pubseekoff(0, std::ios_base::end, std::ios_base::out);
180   }
181   if (cmdListLen > 1) addLine(cmdList);
182 }
183
184 void 
185 Console::addLine(std::string s) 
186 {
187   std::cerr << s << std::endl;
188   while (s.length() > 99) {
189     lines.push_front(s.substr(0, 99-3)+"...");
190     s = "..."+s.substr(99-3);
191   }
192   lines.push_front(s);
193   
194   while (lines.size() >= 1000)
195     lines.pop_back();
196   
197   if (height < 64) {
198     if(height < 4)
199       height = 4;
200     height += fontheight;
201   }
202
203   alpha = 1.0;
204   if(stayOpen < 6)
205     stayOpen += 1.5;
206 }
207
208 void
209 Console::parse(std::string s) 
210 {
211   // make sure we actually have something to parse
212   if (s.length() == 0) return;
213         
214   // split line into list of args
215   std::vector<std::string> args;
216   size_t start = 0;
217   size_t end = 0;
218   while (1) {
219     start = s.find_first_not_of(" ,", end);
220     end = s.find_first_of(" ,", start);
221     if (start == s.npos) break;
222     args.push_back(s.substr(start, end-start));
223   }
224
225   // command is args[0]
226   if (args.size() == 0) return;
227   std::string command = args.front();
228   args.erase(args.begin());
229
230   // ignore if it's an internal command
231   if (consoleCommand(command,args)) return;
232
233   // look up registered ccr
234   std::map<std::string, std::list<ConsoleCommandReceiver*> >::iterator i = commands.find(command);
235   if ((i == commands.end()) || (i->second.size() == 0)) {
236     try {
237       execute_script(s);
238     } catch(std::exception& e) {
239       addLine(e.what());
240     }
241     return;
242   }
243
244   // send command to the most recently registered ccr
245   ConsoleCommandReceiver* ccr = i->second.front();
246   if (ccr->consoleCommand(command, args) != true) log_warning << "Sent command to registered ccr, but command was unhandled" << std::endl;
247 }
248
249 bool
250 Console::consoleCommand(std::string command, std::vector<std::string> arguments) 
251 {
252   if (command == "ccrs") {
253     if (arguments.size() != 1) {
254       log_info << "Usage: ccrs <command>" << std::endl;
255       return true;
256     }
257     std::map<std::string, std::list<ConsoleCommandReceiver*> >::iterator i = commands.find(arguments[0]);
258     if ((i == commands.end()) || (i->second.size() == 0)) {
259       log_info << "unknown command: \"" << arguments[0] << "\"" << std::endl;
260       return true;
261     }
262
263     std::ostringstream ccr_list;
264     std::list<ConsoleCommandReceiver*> &ccrs = i->second;
265     std::list<ConsoleCommandReceiver*>::iterator j;
266     for (j = ccrs.begin(); j != ccrs.end(); j++) {
267       if (j != ccrs.begin()) ccr_list << ", ";
268       ccr_list << "[" << *j << "]";
269     }
270
271     log_info << "registered ccrs for \"" << arguments[0] << "\": " << ccr_list.str() << std::endl;
272     return true;
273   }
274
275   return false;
276 }
277
278 bool
279 Console::hasFocus() 
280 {
281   return focused;
282 }
283
284 void
285 Console::show()
286 {
287   focused = true;
288   height = 256;
289   alpha = 1.0;
290 }
291
292 void 
293 Console::hide()
294 {
295   focused = false;
296   height = 0;
297   stayOpen = 0;
298
299   // clear input buffer
300   inputBuffer.str(std::string());
301 }
302
303 void 
304 Console::toggle()
305 {
306   if (Console::hasFocus()) {
307     Console::hide(); 
308   } 
309   else { 
310     Console::show();
311   }
312 }
313
314 void
315 Console::update(float elapsed_time)
316 {
317   if(stayOpen > 0) {
318     stayOpen -= elapsed_time;
319     if(stayOpen < 0)
320       stayOpen = 0;
321   } else if(!focused && height > 0) {
322     alpha -= elapsed_time * FADE_SPEED;
323     if(alpha < 0) {
324       alpha = 0;
325       height = 0;
326     }
327   }
328 }
329
330 void 
331 Console::draw(DrawingContext& context)
332 {
333   if (height == 0)
334     return;
335
336   int layer = LAYER_GUI + 1;
337
338   context.push_transform();
339   context.set_alpha(alpha);
340   context.draw_surface(background2.get(), Vector(SCREEN_WIDTH/2 - background->get_width()/2 - background->get_width() + backgroundOffset, height - background->get_height()), layer);
341   context.draw_surface(background2.get(), Vector(SCREEN_WIDTH/2 - background->get_width()/2 + backgroundOffset, height - background->get_height()), layer);
342   context.draw_surface(background.get(), Vector(SCREEN_WIDTH/2 - background->get_width()/2, height - background->get_height()), layer);
343   backgroundOffset+=10;
344   if (backgroundOffset > (int)background->get_width()) backgroundOffset -= (int)background->get_width();
345
346   int lineNo = 0;
347
348   if (focused) {
349     lineNo++;
350     float py = height-4-1*9;
351     context.draw_text(font.get(), "> "+inputBuffer.str()+"_", Vector(4, py), LEFT_ALLIGN, layer);
352   }
353
354   int skipLines = -offset;
355   for (std::list<std::string>::iterator i = lines.begin(); i != lines.end(); i++) {
356     if (skipLines-- > 0) continue;
357     lineNo++;
358     float py = height-4-lineNo*9;
359     if (py < -9) break;
360     context.draw_text(font.get(), *i, Vector(4, py), LEFT_ALLIGN, layer);
361   }
362
363   context.pop_transform();
364 }
365
366 void 
367 Console::registerCommand(std::string command, ConsoleCommandReceiver* ccr)
368 {
369   commands[command].push_front(ccr);
370 }
371
372 void 
373 Console::unregisterCommand(std::string command, ConsoleCommandReceiver* ccr)
374 {
375   std::map<std::string, std::list<ConsoleCommandReceiver*> >::iterator i = commands.find(command);
376   if ((i == commands.end()) || (i->second.size() == 0)) {
377     log_warning << "Command \"" << command << "\" not associated with a command receiver. Not dissociated." << std::endl;
378     return;
379   }
380   std::list<ConsoleCommandReceiver*>::iterator j = find(i->second.begin(), i->second.end(), ccr);
381   if (j == i->second.end()) {
382     log_warning << "Command \"" << command << "\" not associated with given command receiver. Not dissociated." << std::endl;
383     return;
384   }
385   i->second.erase(j);
386 }
387
388 void 
389 Console::unregisterCommands(ConsoleCommandReceiver* ccr)
390 {
391   for (std::map<std::string, std::list<ConsoleCommandReceiver*> >::iterator i = commands.begin(); i != commands.end(); i++) {
392     std::list<ConsoleCommandReceiver*> &ccrs = i->second;
393     std::list<ConsoleCommandReceiver*>::iterator j;
394     while ((j = find(ccrs.begin(), ccrs.end(), ccr)) != ccrs.end()) {
395       ccrs.erase(j);
396     }
397   }
398 }
399
400 Console* Console::instance = NULL;
401 ConsoleStreamBuffer Console::inputBuffer;
402 ConsoleStreamBuffer Console::outputBuffer;
403 std::ostream Console::input(&Console::inputBuffer);
404 std::ostream Console::output(&Console::outputBuffer);
405