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