Major rewrite of scripting support:
[supertux.git] / src / console.cpp
1 //  $Id: worldmap.cpp 3209 2006-04-02 22:19:22Z sommer $
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 "player_status.hpp"
28 #include "script_manager.hpp"
29 #include "main.hpp"
30 #include "resources.hpp"
31
32 namespace {
33   int ticks; // TODO: use a clock?
34 }
35
36 Console::Console()
37 {
38   background = new Surface("images/engine/console.png");
39   background2 = new Surface("images/engine/console2.png");
40 }
41
42 Console::~Console() 
43 {
44   delete background;
45   delete background2;
46 }
47
48 void 
49 Console::flush(ConsoleStreamBuffer* buffer) 
50 {
51   if (buffer == &outputBuffer) {
52     std::string s = outputBuffer.str();
53     if ((s.length() > 0) && ((s[s.length()-1] == '\n') || (s[s.length()-1] == '\r'))) {
54       while ((s[s.length()-1] == '\n') || (s[s.length()-1] == '\r')) s.erase(s.length()-1);
55       addLine(s);
56       outputBuffer.str(std::string());
57     }
58   }
59   if (buffer == &inputBuffer) {
60     std::string s = inputBuffer.str();
61     if ((s.length() > 0) && ((s[s.length()-1] == '\n') || (s[s.length()-1] == '\r'))) {
62       while ((s[s.length()-1] == '\n') || (s[s.length()-1] == '\r')) s.erase(s.length()-1);
63       addLine("> "+s);
64       parse(s);
65       inputBuffer.str(std::string());
66     }
67   }
68 }
69
70 void
71 Console::execute_script(const std::string& command)
72 {
73   using namespace Scripting;
74
75   HSQUIRRELVM vm = script_manager->get_global_vm();
76
77   if(command == "")
78     return;
79   
80   int oldtop = sq_gettop(vm); 
81   try {
82     if(SQ_FAILED(sq_compilebuffer(vm, command.c_str(), command.length(),
83                  "", SQTrue)))
84       throw SquirrelError(vm, "Couldn't compile command");
85
86     sq_pushroottable(vm);
87     if(SQ_FAILED(sq_call(vm, 1, SQTrue)))
88       throw SquirrelError(vm, "Problem while executing command");
89
90     if(sq_gettype(vm, -1) != OT_NULL)
91       addLine(squirrel2string(vm, -1));
92   } catch(std::exception& e) {
93     addLine(e.what());
94   }
95   int newtop = sq_gettop(vm);
96   if(newtop < oldtop) {
97     msg_fatal << "Script destroyed squirrel stack..." << std::endl;
98   } else {
99     sq_settop(vm, oldtop);
100   }
101 }
102
103 void
104 Console::backspace()
105 {
106   std::string s = inputBuffer.str();
107   if (s.length() > 0) {
108     s.erase(s.length()-1);
109     inputBuffer.str(s);
110     inputBuffer.pubseekoff(0, std::ios_base::end, std::ios_base::out);
111   }
112 }
113
114 void
115 Console::scroll(int numLines)
116 {
117   offset += numLines;
118   if (offset > 0) offset = 0;
119 }
120
121 void
122 Console::autocomplete()
123 {
124   std::string cmdPart = inputBuffer.str();
125   addLine("> "+cmdPart);
126
127   std::string cmdList = "";
128   int cmdListLen = 0;
129   for (std::map<std::string, std::list<ConsoleCommandReceiver*> >::iterator i = commands.begin(); i != commands.end(); i++) {
130     std::string cmdKnown = i->first;
131     if (cmdKnown.substr(0, cmdPart.length()) == cmdPart) {
132       if (cmdListLen > 0) cmdList = cmdList + ", ";
133       cmdList = cmdList + cmdKnown;
134       cmdListLen++;
135     }
136   }
137   if (cmdListLen == 0) addLine("No known command starts with \""+cmdPart+"\"");
138   if (cmdListLen == 1) {
139     inputBuffer.str(cmdList);
140     inputBuffer.pubseekoff(0, std::ios_base::end, std::ios_base::out);
141   }
142   if (cmdListLen > 1) addLine(cmdList);
143 }
144
145 void 
146 Console::addLine(std::string s) 
147 {
148   std::cerr << s << std::endl;
149   while (s.length() > 99) {
150     lines.push_front(s.substr(0, 99-3)+"...");
151     s = "..."+s.substr(99-3);
152   }
153   lines.push_front(s);
154   while (lines.size() >= 65535) lines.pop_back();
155   if (height < 64) {
156     if (height < 4+9) height=4+9;
157     height+=9;
158   }
159   ticks=60;
160 }
161
162 void
163 Console::parse(std::string s) 
164 {
165   // make sure we actually have something to parse
166   if (s.length() == 0) return;
167         
168   // split line into list of args
169   std::vector<std::string> args;
170   size_t start = 0;
171   size_t end = 0;
172   while (1) {
173     start = s.find_first_not_of(" ,", end);
174     end = s.find_first_of(" ,", start);
175     if (start == s.npos) break;
176     args.push_back(s.substr(start, end-start));
177   }
178
179   // command is args[0]
180   std::string command = args.front();
181   args.erase(args.begin());
182
183   // ignore if it's an internal command
184   if (consoleCommand(command,args)) return;
185
186   // look up registered ccr
187   std::map<std::string, std::list<ConsoleCommandReceiver*> >::iterator i = commands.find(command);
188   if ((i == commands.end()) || (i->second.size() == 0)) {
189     try {
190       execute_script(s);
191     } catch(std::exception& e) {
192       addLine(e.what());
193     }
194     return;
195   }
196
197   // send command to the most recently registered ccr
198   ConsoleCommandReceiver* ccr = i->second.front();
199   if (ccr->consoleCommand(command, args) != true) msg_warning << "Sent command to registered ccr, but command was unhandled" << std::endl;
200 }
201
202 bool
203 Console::consoleCommand(std::string command, std::vector<std::string> arguments) 
204 {
205   if (command == "ccrs") {
206     if (arguments.size() != 1) {
207       msg_info << "Usage: ccrs <command>" << std::endl;
208       return true;
209     }
210     std::map<std::string, std::list<ConsoleCommandReceiver*> >::iterator i = commands.find(arguments[0]);
211     if ((i == commands.end()) || (i->second.size() == 0)) {
212       msg_info << "unknown command: \"" << arguments[0] << "\"" << std::endl;
213       return true;
214     }
215
216     std::ostringstream ccr_list;
217     std::list<ConsoleCommandReceiver*> &ccrs = i->second;
218     std::list<ConsoleCommandReceiver*>::iterator j;
219     for (j = ccrs.begin(); j != ccrs.end(); j++) {
220       if (j != ccrs.begin()) ccr_list << ", ";
221       ccr_list << "[" << *j << "]";
222     }
223
224     msg_info << "registered ccrs for \"" << arguments[0] << "\": " << ccr_list.str() << std::endl;
225     return true;
226   }
227
228   return false;
229 }
230
231 bool
232 Console::hasFocus() 
233 {
234   return focused;
235 }
236
237 void
238 Console::show()
239 {
240   focused = true;
241   height = 256;
242 }
243
244 void 
245 Console::hide()
246 {
247   focused = false;
248   height = 0;
249
250   // clear input buffer
251   inputBuffer.str(std::string());
252 }
253
254 void 
255 Console::toggle()
256 {
257   if (Console::hasFocus()) {
258     Console::hide(); 
259   } 
260   else { 
261     Console::show();
262   }
263 }
264
265 void 
266 Console::draw(DrawingContext& context)
267 {
268   if (height == 0) return;
269   if (!focused) {
270     if (ticks-- < 0) {
271       height-=10;
272       ticks=0;
273       if (height < 0) height=0;
274     }
275     if (height == 0) return;
276   }
277
278   context.draw_surface(background2, Vector(SCREEN_WIDTH/2 - background->get_width()/2 - background->get_width() + backgroundOffset, height - background->get_height()), LAYER_FOREGROUND1+1);
279   context.draw_surface(background2, Vector(SCREEN_WIDTH/2 - background->get_width()/2 + backgroundOffset, height - background->get_height()), LAYER_FOREGROUND1+1);
280   context.draw_surface(background, Vector(SCREEN_WIDTH/2 - background->get_width()/2, height - background->get_height()), LAYER_FOREGROUND1+1);
281   backgroundOffset+=10;
282   if (backgroundOffset > (int)background->get_width()) backgroundOffset -= (int)background->get_width();
283
284   int lineNo = 0;
285
286   if (focused) {
287     lineNo++;
288     float py = height-4-1*9;
289     context.draw_text(white_small_text, "> "+inputBuffer.str()+"_", Vector(4, py), LEFT_ALLIGN, LAYER_FOREGROUND1+1);
290   }
291
292   int skipLines = -offset;
293   for (std::list<std::string>::iterator i = lines.begin(); i != lines.end(); i++) {
294     if (skipLines-- > 0) continue;
295     lineNo++;
296     float py = height-4-lineNo*9;
297     if (py < -9) break;
298     context.draw_text(white_small_text, *i, Vector(4, py), LEFT_ALLIGN, LAYER_FOREGROUND1+1);
299   }
300 }
301
302 void 
303 Console::registerCommand(std::string command, ConsoleCommandReceiver* ccr)
304 {
305   commands[command].push_front(ccr);
306 }
307
308 void 
309 Console::unregisterCommand(std::string command, ConsoleCommandReceiver* ccr)
310 {
311   std::map<std::string, std::list<ConsoleCommandReceiver*> >::iterator i = commands.find(command);
312   if ((i == commands.end()) || (i->second.size() == 0)) {
313     msg_warning << "Command \"" << command << "\" not associated with a command receiver. Not dissociated." << std::endl;
314     return;
315   }
316   std::list<ConsoleCommandReceiver*>::iterator j = find(i->second.begin(), i->second.end(), ccr);
317   if (j == i->second.end()) {
318     msg_warning << "Command \"" << command << "\" not associated with given command receiver. Not dissociated." << std::endl;
319     return;
320   }
321   i->second.erase(j);
322 }
323
324 void 
325 Console::unregisterCommands(ConsoleCommandReceiver* ccr)
326 {
327   for (std::map<std::string, std::list<ConsoleCommandReceiver*> >::iterator i = commands.begin(); i != commands.end(); i++) {
328     std::list<ConsoleCommandReceiver*> &ccrs = i->second;
329     std::list<ConsoleCommandReceiver*>::iterator j;
330     while ((j = find(ccrs.begin(), ccrs.end(), ccr)) != ccrs.end()) {
331       ccrs.erase(j);
332     }
333   }
334 }
335
336 int Console::height = 0;
337 bool Console::focused = false;
338 std::list<std::string> Console::lines;
339 std::map<std::string, std::list<ConsoleCommandReceiver*> > Console::commands;
340 ConsoleStreamBuffer Console::inputBuffer;
341 ConsoleStreamBuffer Console::outputBuffer;
342 std::ostream Console::input(&Console::inputBuffer);
343 std::ostream Console::output(&Console::outputBuffer);
344 int Console::offset = 0;
345 int Console::backgroundOffset = 0;
346