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