]> git.lizzy.rs Git - minetest.git/blob - src/guiFormSpecMenu.cpp
4751978d7d3c63bead655a24e8bd7cd20a2839e7
[minetest.git] / src / guiFormSpecMenu.cpp
1 /*
2 Minetest
3 Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com>
4
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU Lesser General Public License as published by
7 the Free Software Foundation; either version 2.1 of the License, or
8 (at your option) any later version.
9
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 GNU Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public License along
16 with this program; if not, write to the Free Software Foundation, Inc.,
17 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18 */
19
20
21 #include <cstdlib>
22 #include <algorithm>
23 #include <iterator>
24 #include <sstream>
25 #include <limits>
26 #include "guiFormSpecMenu.h"
27 #include "guiTable.h"
28 #include "constants.h"
29 #include "gamedef.h"
30 #include "keycode.h"
31 #include "strfnd.h"
32 #include <IGUICheckBox.h>
33 #include <IGUIEditBox.h>
34 #include <IGUIButton.h>
35 #include <IGUIStaticText.h>
36 #include <IGUIFont.h>
37 #include <IGUITabControl.h>
38 #include <IGUIComboBox.h>
39 #include "log.h"
40 #include "tile.h" // ITextureSource
41 #include "hud.h" // drawItemStack
42 #include "hex.h"
43 #include "util/string.h"
44 #include "util/numeric.h"
45 #include "filesys.h"
46 #include "gettime.h"
47 #include "gettext.h"
48
49 #define MY_CHECKPOS(a,b)                                                                                                        \
50         if (v_pos.size() != 2) {                                                                                                \
51                 errorstream<< "Invalid pos for element " << a << "specified: \""        \
52                         << parts[b] << "\"" << std::endl;                                                               \
53                         return;                                                                                                                 \
54         }
55
56 #define MY_CHECKGEOM(a,b)                                                                                                       \
57         if (v_geom.size() != 2) {                                                                                               \
58                 errorstream<< "Invalid pos for element " << a << "specified: \""        \
59                         << parts[b] << "\"" << std::endl;                                                               \
60                         return;                                                                                                                 \
61         }
62
63
64 /*
65         GUIFormSpecMenu
66 */
67
68 GUIFormSpecMenu::GUIFormSpecMenu(irr::IrrlichtDevice* dev,
69                 gui::IGUIElement* parent, s32 id, IMenuManager *menumgr,
70                 InventoryManager *invmgr, IGameDef *gamedef,
71                 ISimpleTextureSource *tsrc) :
72         GUIModalMenu(dev->getGUIEnvironment(), parent, id, menumgr),
73         m_device(dev),
74         m_invmgr(invmgr),
75         m_gamedef(gamedef),
76         m_tsrc(tsrc),
77         m_form_src(NULL),
78         m_text_dst(NULL),
79         m_selected_item(NULL),
80         m_selected_amount(0),
81         m_selected_dragging(false),
82         m_tooltip_element(NULL),
83         m_allowclose(true),
84         m_lock(false)
85 {
86         current_keys_pending.key_down = false;
87         current_keys_pending.key_up = false;
88         current_keys_pending.key_enter = false;
89         current_keys_pending.key_escape = false;
90
91 }
92
93 GUIFormSpecMenu::~GUIFormSpecMenu()
94 {
95         removeChildren();
96
97         delete m_selected_item;
98         delete m_form_src;
99         delete m_text_dst;
100 }
101
102 void GUIFormSpecMenu::removeChildren()
103 {
104         const core::list<gui::IGUIElement*> &children = getChildren();
105         core::list<gui::IGUIElement*> children_copy;
106         for(core::list<gui::IGUIElement*>::ConstIterator
107                         i = children.begin(); i != children.end(); i++)
108         {
109                 children_copy.push_back(*i);
110         }
111         for(core::list<gui::IGUIElement*>::Iterator
112                         i = children_copy.begin();
113                         i != children_copy.end(); i++)
114         {
115                 (*i)->remove();
116         }
117         /*{
118                 gui::IGUIElement *e = getElementFromId(256);
119                 if(e != NULL)
120                         e->remove();
121         }*/
122
123         if(m_tooltip_element)
124         {
125                 m_tooltip_element->remove();
126                 m_tooltip_element->drop();
127                 m_tooltip_element = NULL;
128         }
129
130 }
131
132 void GUIFormSpecMenu::setInitialFocus()
133 {
134         // Set initial focus according to following order of precedence:
135         // 1. first empty editbox
136         // 2. first editbox
137         // 3. first table
138         // 4. last button
139         // 5. first focusable (not statictext, not tabheader)
140         // 6. first child element
141
142         core::list<gui::IGUIElement*> children = getChildren();
143
144         // in case "children" contains any NULL elements, remove them
145         for (core::list<gui::IGUIElement*>::Iterator it = children.begin();
146                         it != children.end();) {
147                 if (*it)
148                         ++it;
149                 else
150                         it = children.erase(it);
151         }
152
153         // 1. first empty editbox
154         for (core::list<gui::IGUIElement*>::Iterator it = children.begin();
155                         it != children.end(); ++it) {
156                 if ((*it)->getType() == gui::EGUIET_EDIT_BOX
157                                 && (*it)->getText()[0] == 0) {
158                         Environment->setFocus(*it);
159                         return;
160                 }
161         }
162
163         // 2. first editbox
164         for (core::list<gui::IGUIElement*>::Iterator it = children.begin();
165                         it != children.end(); ++it) {
166                 if ((*it)->getType() == gui::EGUIET_EDIT_BOX) {
167                         Environment->setFocus(*it);
168                         return;
169                 }
170         }
171
172         // 3. first table
173         for (core::list<gui::IGUIElement*>::Iterator it = children.begin();
174                         it != children.end(); ++it) {
175                 if ((*it)->getTypeName() == std::string("GUITable")) {
176                         Environment->setFocus(*it);
177                         return;
178                 }
179         }
180
181         // 4. last button
182         for (core::list<gui::IGUIElement*>::Iterator it = children.getLast();
183                         it != children.end(); --it) {
184                 if ((*it)->getType() == gui::EGUIET_BUTTON) {
185                         Environment->setFocus(*it);
186                         return;
187                 }
188         }
189
190         // 5. first focusable (not statictext, not tabheader)
191         for (core::list<gui::IGUIElement*>::Iterator it = children.begin();
192                         it != children.end(); ++it) {
193                 if ((*it)->getType() != gui::EGUIET_STATIC_TEXT &&
194                                 (*it)->getType() != gui::EGUIET_TAB_CONTROL) {
195                         Environment->setFocus(*it);
196                         return;
197                 }
198         }
199
200         // 6. first child element
201         if (children.empty())
202                 Environment->setFocus(this);
203         else
204                 Environment->setFocus(*(children.begin()));
205 }
206
207 GUITable* GUIFormSpecMenu::getTable(std::wstring tablename)
208 {
209         for (u32 i = 0; i < m_tables.size(); ++i) {
210                 if (tablename == m_tables[i].first.fname)
211                         return m_tables[i].second;
212         }
213         return 0;
214 }
215
216 std::vector<std::string> split(const std::string &s, char delim) {
217         std::vector<std::string> tokens;
218
219         std::string current = "";
220         bool last_was_escape = false;
221         for(unsigned int i=0; i < s.size(); i++) {
222                 if (last_was_escape) {
223                         current += '\\';
224                         current += s.c_str()[i];
225                         last_was_escape = false;
226                 }
227                 else {
228                         if (s.c_str()[i] == delim) {
229                                 tokens.push_back(current);
230                                 current = "";
231                                 last_was_escape = false;
232                         }
233                         else if (s.c_str()[i] == '\\'){
234                                 last_was_escape = true;
235                         }
236                         else {
237                                 current += s.c_str()[i];
238                                 last_was_escape = false;
239                         }
240                 }
241         }
242         //push last element
243         tokens.push_back(current);
244
245         return tokens;
246 }
247
248 void GUIFormSpecMenu::parseSize(parserData* data,std::string element)
249 {
250         std::vector<std::string> parts = split(element,',');
251
252         if ((parts.size() == 2) || parts.size() == 3) {
253                 v2f invsize;
254
255                 if (parts[1].find(';') != std::string::npos)
256                         parts[1] = parts[1].substr(0,parts[1].find(';'));
257
258                 invsize.X = stof(parts[0]);
259                 invsize.Y = stof(parts[1]);
260
261                 lockSize(false);
262                 if (parts.size() == 3) {
263                         if (parts[2] == "true") {
264                                 lockSize(true,v2u32(800,600));
265                         }
266                 }
267
268                 if (m_lock) {
269                         v2u32 current_screensize = m_device->getVideoDriver()->getScreenSize();
270                         v2u32 delta = current_screensize - m_lockscreensize;
271
272                         if (current_screensize.Y > m_lockscreensize.Y)
273                                 delta.Y /= 2;
274                         else
275                                 delta.Y = 0;
276
277                         if (current_screensize.X > m_lockscreensize.X)
278                                 delta.X /= 2;
279                         else
280                                 delta.X = 0;
281
282                         offset = v2s32(delta.X,delta.Y);
283
284                         data->screensize = m_lockscreensize;
285                 }
286                 else {
287                         offset = v2s32(0,0);
288                 }
289
290                 padding = v2s32(data->screensize.Y/40, data->screensize.Y/40);
291                 spacing = v2s32(data->screensize.Y/12, data->screensize.Y/13);
292                 imgsize = v2s32(data->screensize.Y/15, data->screensize.Y/15);
293                 data->size = v2s32(
294                         padding.X*2+spacing.X*(invsize.X-1.0)+imgsize.X,
295                         padding.Y*2+spacing.Y*(invsize.Y-1.0)+imgsize.Y + (data->helptext_h-5)
296                 );
297                 data->rect = core::rect<s32>(
298                                 data->screensize.X/2 - data->size.X/2 + offset.X,
299                                 data->screensize.Y/2 - data->size.Y/2 + offset.Y,
300                                 data->screensize.X/2 + data->size.X/2 + offset.X,
301                                 data->screensize.Y/2 + data->size.Y/2 + offset.Y
302                 );
303
304                 DesiredRect = data->rect;
305                 recalculateAbsolutePosition(false);
306                 data->basepos = getBasePos();
307                 data->bp_set = 2;
308                 return;
309         }
310         errorstream<< "Invalid size element (" << parts.size() << "): '" << element << "'"  << std::endl;
311 }
312
313 void GUIFormSpecMenu::parseList(parserData* data,std::string element)
314 {
315         if (m_gamedef == 0) {
316                 errorstream<<"WARNING: invalid use of 'list' with m_gamedef==0"<<std::endl;
317                 return;
318         }
319
320         std::vector<std::string> parts = split(element,';');
321
322         if ((parts.size() == 4) || (parts.size() == 5)) {
323                 std::string location = parts[0];
324                 std::string listname = parts[1];
325                 std::vector<std::string> v_pos  = split(parts[2],',');
326                 std::vector<std::string> v_geom = split(parts[3],',');
327                 std::string startindex = "";
328                 if (parts.size() == 5)
329                         startindex = parts[4];
330
331                 MY_CHECKPOS("list",2);
332                 MY_CHECKGEOM("list",3);
333
334                 InventoryLocation loc;
335
336                 if(location == "context" || location == "current_name")
337                         loc = m_current_inventory_location;
338                 else
339                         loc.deSerialize(location);
340
341                 v2s32 pos = padding + AbsoluteRect.UpperLeftCorner;
342                 pos.X += stof(v_pos[0]) * (float)spacing.X;
343                 pos.Y += stof(v_pos[1]) * (float)spacing.Y;
344
345                 v2s32 geom;
346                 geom.X = stoi(v_geom[0]);
347                 geom.Y = stoi(v_geom[1]);
348
349                 s32 start_i = 0;
350                 if(startindex != "")
351                         start_i = stoi(startindex);
352
353                 if (geom.X < 0 || geom.Y < 0 || start_i < 0) {
354                         errorstream<< "Invalid list element: '" << element << "'"  << std::endl;
355                         return;
356                 }
357
358                 if(data->bp_set != 2)
359                         errorstream<<"WARNING: invalid use of list without a size[] element"<<std::endl;
360                 m_inventorylists.push_back(ListDrawSpec(loc, listname, pos, geom, start_i));
361                 return;
362         }
363         errorstream<< "Invalid list element(" << parts.size() << "): '" << element << "'"  << std::endl;
364 }
365
366 void GUIFormSpecMenu::parseCheckbox(parserData* data,std::string element)
367 {
368         std::vector<std::string> parts = split(element,';');
369
370         if ((parts.size() == 3) || (parts.size() == 4)) {
371                 std::vector<std::string> v_pos = split(parts[0],',');
372                 std::string name = parts[1];
373                 std::string label = parts[2];
374                 std::string selected = "";
375
376                 if (parts.size() == 4)
377                         selected = parts[3];
378
379                 MY_CHECKPOS("checkbox",0);
380
381                 v2s32 pos = padding;
382                 pos.X += stof(v_pos[0]) * (float) spacing.X;
383                 pos.Y += stof(v_pos[1]) * (float) spacing.Y;
384
385                 core::rect<s32> rect = core::rect<s32>(pos.X, pos.Y+((imgsize.Y/2)-15), pos.X+300, pos.Y+((imgsize.Y/2)+15));
386
387                 bool fselected = false;
388
389                 if (selected == "true")
390                         fselected = true;
391
392                 std::wstring wlabel = narrow_to_wide(label.c_str());
393
394                 FieldSpec spec = FieldSpec(
395                                 narrow_to_wide(name.c_str()),
396                                 L"",
397                                 wlabel,
398                                 258+m_fields.size()
399                         );
400
401                 spec.ftype = f_CheckBox;
402                 spec.flabel = wlabel; //Needed for displaying text on MSVC
403                 gui::IGUICheckBox* e = Environment->addCheckBox(fselected, rect, this,
404                                         spec.fid, spec.flabel.c_str());
405
406                 if (spec.fname == data->focused_fieldname) {
407                         Environment->setFocus(e);
408                 }
409
410                 m_checkboxes.push_back(std::pair<FieldSpec,gui::IGUICheckBox*>(spec,e));
411                 m_fields.push_back(spec);
412                 return;
413         }
414         errorstream<< "Invalid checkbox element(" << parts.size() << "): '" << element << "'"  << std::endl;
415 }
416
417 void GUIFormSpecMenu::parseImage(parserData* data,std::string element)
418 {
419         std::vector<std::string> parts = split(element,';');
420
421         if (parts.size() == 3) {
422                 std::vector<std::string> v_pos = split(parts[0],',');
423                 std::vector<std::string> v_geom = split(parts[1],',');
424                 std::string name = unescape_string(parts[2]);
425
426                 MY_CHECKPOS("image",0);
427                 MY_CHECKGEOM("image",1);
428
429                 v2s32 pos = padding + AbsoluteRect.UpperLeftCorner;
430                 pos.X += stof(v_pos[0]) * (float) spacing.X;
431                 pos.Y += stof(v_pos[1]) * (float) spacing.Y;
432
433                 v2s32 geom;
434                 geom.X = stof(v_geom[0]) * (float)imgsize.X;
435                 geom.Y = stof(v_geom[1]) * (float)imgsize.Y;
436
437                 if(data->bp_set != 2)
438                         errorstream<<"WARNING: invalid use of image without a size[] element"<<std::endl;
439                 m_images.push_back(ImageDrawSpec(name, pos, geom));
440                 return;
441         }
442
443         if (parts.size() == 2) {
444                 std::vector<std::string> v_pos = split(parts[0],',');
445                 std::string name = unescape_string(parts[1]);
446
447                 MY_CHECKPOS("image",0);
448
449                 v2s32 pos = padding + AbsoluteRect.UpperLeftCorner;
450                 pos.X += stof(v_pos[0]) * (float) spacing.X;
451                 pos.Y += stof(v_pos[1]) * (float) spacing.Y;
452
453                 if(data->bp_set != 2)
454                         errorstream<<"WARNING: invalid use of image without a size[] element"<<std::endl;
455                 m_images.push_back(ImageDrawSpec(name, pos));
456                 return;
457         }
458         errorstream<< "Invalid image element(" << parts.size() << "): '" << element << "'"  << std::endl;
459 }
460
461 void GUIFormSpecMenu::parseItemImage(parserData* data,std::string element)
462 {
463         std::vector<std::string> parts = split(element,';');
464
465         if (parts.size() == 3) {
466                 std::vector<std::string> v_pos = split(parts[0],',');
467                 std::vector<std::string> v_geom = split(parts[1],',');
468                 std::string name = parts[2];
469
470                 MY_CHECKPOS("itemimage",0);
471                 MY_CHECKGEOM("itemimage",1);
472
473                 v2s32 pos = padding + AbsoluteRect.UpperLeftCorner;
474                 pos.X += stof(v_pos[0]) * (float) spacing.X;
475                 pos.Y += stof(v_pos[1]) * (float) spacing.Y;
476
477                 v2s32 geom;
478                 geom.X = stoi(v_geom[0]) * (float)imgsize.X;
479                 geom.Y = stoi(v_geom[1]) * (float)imgsize.Y;
480
481                 if(data->bp_set != 2)
482                         errorstream<<"WARNING: invalid use of item_image without a size[] element"<<std::endl;
483                 m_itemimages.push_back(ImageDrawSpec(name, pos, geom));
484                 return;
485         }
486         errorstream<< "Invalid ItemImage element(" << parts.size() << "): '" << element << "'"  << std::endl;
487 }
488
489 void GUIFormSpecMenu::parseButton(parserData* data,std::string element,
490                 std::string type)
491 {
492         std::vector<std::string> parts = split(element,';');
493
494         if (parts.size() == 4) {
495                 std::vector<std::string> v_pos = split(parts[0],',');
496                 std::vector<std::string> v_geom = split(parts[1],',');
497                 std::string name = parts[2];
498                 std::string label = parts[3];
499
500                 MY_CHECKPOS("button",0);
501                 MY_CHECKGEOM("button",1);
502
503                 v2s32 pos = padding;
504                 pos.X += stof(v_pos[0]) * (float)spacing.X;
505                 pos.Y += stof(v_pos[1]) * (float)spacing.Y;
506
507                 v2s32 geom;
508                 geom.X = (stof(v_geom[0]) * (float)spacing.X)-(spacing.X-imgsize.X);
509                 pos.Y += (stof(v_geom[1]) * (float)imgsize.Y)/2;
510
511                 core::rect<s32> rect = core::rect<s32>(pos.X, pos.Y-15, pos.X+geom.X, pos.Y+15);
512
513                 if(data->bp_set != 2)
514                         errorstream<<"WARNING: invalid use of button without a size[] element"<<std::endl;
515
516                 label = unescape_string(label);
517
518                 std::wstring wlabel = narrow_to_wide(label.c_str());
519
520                 FieldSpec spec = FieldSpec(
521                         narrow_to_wide(name.c_str()),
522                         wlabel,
523                         L"",
524                         258+m_fields.size()
525                 );
526                 spec.ftype = f_Button;
527                 if(type == "button_exit")
528                         spec.is_exit = true;
529
530                 gui::IGUIButton* e = Environment->addButton(rect, this, spec.fid,
531                                 spec.flabel.c_str());
532
533                 if (spec.fname == data->focused_fieldname) {
534                         Environment->setFocus(e);
535                 }
536
537                 m_fields.push_back(spec);
538                 return;
539         }
540         errorstream<< "Invalid button element(" << parts.size() << "): '" << element << "'"  << std::endl;
541 }
542
543 void GUIFormSpecMenu::parseBackground(parserData* data,std::string element)
544 {
545         std::vector<std::string> parts = split(element,';');
546
547         if ((parts.size() == 3) || (parts.size() == 4)) {
548                 std::vector<std::string> v_pos = split(parts[0],',');
549                 std::vector<std::string> v_geom = split(parts[1],',');
550                 std::string name = unescape_string(parts[2]);
551
552                 MY_CHECKPOS("background",0);
553                 MY_CHECKGEOM("background",1);
554
555                 v2s32 pos = padding + AbsoluteRect.UpperLeftCorner;
556                 pos.X += stof(v_pos[0]) * (float)spacing.X - ((float)spacing.X-(float)imgsize.X)/2;
557                 pos.Y += stof(v_pos[1]) * (float)spacing.Y - ((float)spacing.Y-(float)imgsize.Y)/2;
558
559                 v2s32 geom;
560                 geom.X = stof(v_geom[0]) * (float)spacing.X;
561                 geom.Y = stof(v_geom[1]) * (float)spacing.Y;
562
563                 if (parts.size() == 4) {
564                         m_clipbackground = is_yes(parts[3]);
565                         if (m_clipbackground) {
566                                 pos.X = stoi(v_pos[0]); //acts as offset
567                                 pos.Y = stoi(v_pos[1]); //acts as offset
568                         }
569                 }
570
571                 if(data->bp_set != 2)
572                         errorstream<<"WARNING: invalid use of background without a size[] element"<<std::endl;
573                 m_backgrounds.push_back(ImageDrawSpec(name, pos, geom));
574                 return;
575         }
576         errorstream<< "Invalid background element(" << parts.size() << "): '" << element << "'"  << std::endl;
577 }
578
579 void GUIFormSpecMenu::parseTableOptions(parserData* data,std::string element)
580 {
581         std::vector<std::string> parts = split(element,';');
582
583         data->table_options.clear();
584         for (size_t i = 0; i < parts.size(); ++i) {
585                 // Parse table option
586                 std::string opt = unescape_string(parts[i]);
587                 data->table_options.push_back(GUITable::splitOption(opt));
588         }
589 }
590
591 void GUIFormSpecMenu::parseTableColumns(parserData* data,std::string element)
592 {
593         std::vector<std::string> parts = split(element,';');
594
595         data->table_columns.clear();
596         for (size_t i = 0; i < parts.size(); ++i) {
597                 std::vector<std::string> col_parts = split(parts[i],',');
598                 GUITable::TableColumn column;
599                 // Parse column type
600                 if (!col_parts.empty())
601                         column.type = col_parts[0];
602                 // Parse column options
603                 for (size_t j = 1; j < col_parts.size(); ++j) {
604                         std::string opt = unescape_string(col_parts[j]);
605                         column.options.push_back(GUITable::splitOption(opt));
606                 }
607                 data->table_columns.push_back(column);
608         }
609 }
610
611 void GUIFormSpecMenu::parseTable(parserData* data,std::string element)
612 {
613         std::vector<std::string> parts = split(element,';');
614
615         if ((parts.size() == 4) || (parts.size() == 5)) {
616                 std::vector<std::string> v_pos = split(parts[0],',');
617                 std::vector<std::string> v_geom = split(parts[1],',');
618                 std::string name = parts[2];
619                 std::vector<std::string> items = split(parts[3],',');
620                 std::string str_initial_selection = "";
621                 std::string str_transparent = "false";
622
623                 if (parts.size() >= 5)
624                         str_initial_selection = parts[4];
625
626                 MY_CHECKPOS("table",0);
627                 MY_CHECKGEOM("table",1);
628
629                 v2s32 pos = padding;
630                 pos.X += stof(v_pos[0]) * (float)spacing.X;
631                 pos.Y += stof(v_pos[1]) * (float)spacing.Y;
632
633                 v2s32 geom;
634                 geom.X = stof(v_geom[0]) * (float)spacing.X;
635                 geom.Y = stof(v_geom[1]) * (float)spacing.Y;
636
637
638                 core::rect<s32> rect = core::rect<s32>(pos.X, pos.Y, pos.X+geom.X, pos.Y+geom.Y);
639
640                 std::wstring fname_w = narrow_to_wide(name.c_str());
641
642                 FieldSpec spec = FieldSpec(
643                         fname_w,
644                         L"",
645                         L"",
646                         258+m_fields.size()
647                 );
648
649                 spec.ftype = f_Table;
650
651                 for (unsigned int i = 0; i < items.size(); ++i) {
652                         items[i] = unescape_string(items[i]);
653                 }
654
655                 //now really show table
656                 GUITable *e = new GUITable(Environment, this, spec.fid, rect,
657                                 m_tsrc);
658                 e->drop();  // IGUIElement maintains the remaining reference
659
660                 if (spec.fname == data->focused_fieldname) {
661                         Environment->setFocus(e);
662                 }
663
664                 e->setTable(data->table_options, data->table_columns, items);
665
666                 if (data->table_dyndata.find(fname_w) != data->table_dyndata.end()) {
667                         e->setDynamicData(data->table_dyndata[fname_w]);
668                 }
669
670                 if ((str_initial_selection != "") &&
671                                 (str_initial_selection != "0"))
672                         e->setSelected(stoi(str_initial_selection.c_str()));
673
674                 m_tables.push_back(std::pair<FieldSpec,GUITable*>(spec, e));
675                 m_fields.push_back(spec);
676                 return;
677         }
678         errorstream<< "Invalid table element(" << parts.size() << "): '" << element << "'"  << std::endl;
679 }
680
681 void GUIFormSpecMenu::parseTextList(parserData* data,std::string element)
682 {
683         std::vector<std::string> parts = split(element,';');
684
685         if ((parts.size() == 4) || (parts.size() == 5) || (parts.size() == 6)) {
686                 std::vector<std::string> v_pos = split(parts[0],',');
687                 std::vector<std::string> v_geom = split(parts[1],',');
688                 std::string name = parts[2];
689                 std::vector<std::string> items = split(parts[3],',');
690                 std::string str_initial_selection = "";
691                 std::string str_transparent = "false";
692
693                 if (parts.size() >= 5)
694                         str_initial_selection = parts[4];
695
696                 if (parts.size() >= 6)
697                         str_transparent = parts[5];
698
699                 MY_CHECKPOS("textlist",0);
700                 MY_CHECKGEOM("textlist",1);
701
702                 v2s32 pos = padding;
703                 pos.X += stof(v_pos[0]) * (float)spacing.X;
704                 pos.Y += stof(v_pos[1]) * (float)spacing.Y;
705
706                 v2s32 geom;
707                 geom.X = stof(v_geom[0]) * (float)spacing.X;
708                 geom.Y = stof(v_geom[1]) * (float)spacing.Y;
709
710
711                 core::rect<s32> rect = core::rect<s32>(pos.X, pos.Y, pos.X+geom.X, pos.Y+geom.Y);
712
713                 std::wstring fname_w = narrow_to_wide(name.c_str());
714
715                 FieldSpec spec = FieldSpec(
716                         fname_w,
717                         L"",
718                         L"",
719                         258+m_fields.size()
720                 );
721
722                 spec.ftype = f_Table;
723
724                 for (unsigned int i = 0; i < items.size(); ++i) {
725                         items[i] = unescape_string(items[i]);
726                 }
727
728                 //now really show list
729                 GUITable *e = new GUITable(Environment, this, spec.fid, rect,
730                                 m_tsrc);
731                 e->drop();  // IGUIElement maintains the remaining reference
732
733                 if (spec.fname == data->focused_fieldname) {
734                         Environment->setFocus(e);
735                 }
736
737                 e->setTextList(items, is_yes(str_transparent));
738
739                 if (data->table_dyndata.find(fname_w) != data->table_dyndata.end()) {
740                         e->setDynamicData(data->table_dyndata[fname_w]);
741                 }
742
743                 if ((str_initial_selection != "") &&
744                                 (str_initial_selection != "0"))
745                         e->setSelected(stoi(str_initial_selection.c_str()));
746
747                 m_tables.push_back(std::pair<FieldSpec,GUITable*>(spec, e));
748                 m_fields.push_back(spec);
749                 return;
750         }
751         errorstream<< "Invalid textlist element(" << parts.size() << "): '" << element << "'"  << std::endl;
752 }
753
754
755 void GUIFormSpecMenu::parseDropDown(parserData* data,std::string element)
756 {
757         std::vector<std::string> parts = split(element,';');
758
759         if (parts.size() == 5) {
760                 std::vector<std::string> v_pos = split(parts[0],',');
761                 std::string name = parts[2];
762                 std::vector<std::string> items = split(parts[3],',');
763                 std::string str_initial_selection = "";
764                 str_initial_selection = parts[4];
765
766                 MY_CHECKPOS("dropdown",0);
767
768                 v2s32 pos = padding;
769                 pos.X += stof(v_pos[0]) * (float)spacing.X;
770                 pos.Y += stof(v_pos[1]) * (float)spacing.Y;
771
772                 s32 width = stof(parts[1]) * (float)spacing.Y;
773
774                 core::rect<s32> rect = core::rect<s32>(pos.X, pos.Y, pos.X+width, pos.Y+30);
775
776                 std::wstring fname_w = narrow_to_wide(name.c_str());
777
778                 FieldSpec spec = FieldSpec(
779                         fname_w,
780                         L"",
781                         L"",
782                         258+m_fields.size()
783                 );
784
785                 spec.ftype = f_DropDown;
786                 spec.send = true;
787
788                 //now really show list
789                 gui::IGUIComboBox *e = Environment->addComboBox(rect, this,spec.fid);
790
791                 if (spec.fname == data->focused_fieldname) {
792                         Environment->setFocus(e);
793                 }
794
795                 for (unsigned int i=0; i < items.size(); i++) {
796                         e->addItem(narrow_to_wide(items[i]).c_str());
797                 }
798
799                 if (str_initial_selection != "")
800                         e->setSelected(stoi(str_initial_selection.c_str())-1);
801
802                 m_fields.push_back(spec);
803                 return;
804         }
805         errorstream << "Invalid dropdown element(" << parts.size() << "): '"
806                                 << element << "'"  << std::endl;
807 }
808
809 void GUIFormSpecMenu::parsePwdField(parserData* data,std::string element)
810 {
811         std::vector<std::string> parts = split(element,';');
812
813         if (parts.size() == 4) {
814                 std::vector<std::string> v_pos = split(parts[0],',');
815                 std::vector<std::string> v_geom = split(parts[1],',');
816                 std::string name = parts[2];
817                 std::string label = parts[3];
818
819                 MY_CHECKPOS("pwdfield",0);
820                 MY_CHECKGEOM("pwdfield",1);
821
822                 v2s32 pos;
823                 pos.X += stof(v_pos[0]) * (float)spacing.X;
824                 pos.Y += stof(v_pos[1]) * (float)spacing.Y;
825
826                 v2s32 geom;
827                 geom.X = (stof(v_geom[0]) * (float)spacing.X)-(spacing.X-imgsize.X);
828
829                 pos.Y += (stof(v_geom[1]) * (float)imgsize.Y)/2;
830                 pos.Y -= 15;
831                 geom.Y = 30;
832
833                 core::rect<s32> rect = core::rect<s32>(pos.X, pos.Y, pos.X+geom.X, pos.Y+geom.Y);
834
835                 label = unescape_string(label);
836
837                 std::wstring wlabel = narrow_to_wide(label.c_str());
838
839                 FieldSpec spec = FieldSpec(
840                         narrow_to_wide(name.c_str()),
841                         wlabel,
842                         L"",
843                         258+m_fields.size()
844                         );
845
846                 spec.send = true;
847                 gui::IGUIEditBox * e = Environment->addEditBox(0, rect, true, this, spec.fid);
848
849                 if (spec.fname == data->focused_fieldname) {
850                         Environment->setFocus(e);
851                 }
852
853                 if (label.length() >= 1)
854                 {
855                         rect.UpperLeftCorner.Y -= 15;
856                         rect.LowerRightCorner.Y = rect.UpperLeftCorner.Y + 15;
857                         Environment->addStaticText(spec.flabel.c_str(), rect, false, true, this, 0);
858                 }
859
860                 e->setPasswordBox(true,L'*');
861
862                 irr::SEvent evt;
863                 evt.EventType            = EET_KEY_INPUT_EVENT;
864                 evt.KeyInput.Key         = KEY_END;
865                 evt.KeyInput.Char        = 0;
866                 evt.KeyInput.Control     = 0;
867                 evt.KeyInput.Shift       = 0;
868                 evt.KeyInput.PressedDown = true;
869                 e->OnEvent(evt);
870                 m_fields.push_back(spec);
871                 return;
872         }
873         errorstream<< "Invalid pwdfield element(" << parts.size() << "): '" << element << "'"  << std::endl;
874 }
875
876 void GUIFormSpecMenu::parseSimpleField(parserData* data,
877                 std::vector<std::string> &parts)
878 {
879         std::string name = parts[0];
880         std::string label = parts[1];
881         std::string default_val = parts[2];
882
883         core::rect<s32> rect;
884
885         if(!data->bp_set)
886         {
887                 rect = core::rect<s32>(
888                         data->screensize.X/2 - 580/2,
889                         data->screensize.Y/2 - 300/2,
890                         data->screensize.X/2 + 580/2,
891                         data->screensize.Y/2 + 300/2
892                 );
893                 DesiredRect = rect;
894                 recalculateAbsolutePosition(false);
895                 data->basepos = getBasePos();
896                 data->bp_set = 1;
897         }
898         else if(data->bp_set == 2)
899                 errorstream<<"WARNING: invalid use of unpositioned \"field\" in inventory"<<std::endl;
900
901         v2s32 pos = padding + AbsoluteRect.UpperLeftCorner;
902         pos.Y = ((m_fields.size()+2)*60);
903         v2s32 size = DesiredRect.getSize();
904
905         rect = core::rect<s32>(size.X/2-150, pos.Y, (size.X/2-150)+300, pos.Y+30);
906
907
908         if(m_form_src)
909                 default_val = m_form_src->resolveText(default_val);
910
911         default_val = unescape_string(default_val);
912         label = unescape_string(label);
913
914         std::wstring wlabel = narrow_to_wide(label.c_str());
915
916         FieldSpec spec = FieldSpec(
917                 narrow_to_wide(name.c_str()),
918                 wlabel,
919                 narrow_to_wide(default_val.c_str()),
920                 258+m_fields.size()
921         );
922
923         if (name == "")
924         {
925                 // spec field id to 0, this stops submit searching for a value that isn't there
926                 Environment->addStaticText(spec.flabel.c_str(), rect, false, true, this, spec.fid);
927         }
928         else
929         {
930                 spec.send = true;
931                 gui::IGUIEditBox *e = Environment->addEditBox(spec.fdefault.c_str(), rect, true, this, spec.fid);
932
933                 if (spec.fname == data->focused_fieldname) {
934                         Environment->setFocus(e);
935                 }
936
937                 irr::SEvent evt;
938                 evt.EventType            = EET_KEY_INPUT_EVENT;
939                 evt.KeyInput.Key         = KEY_END;
940                 evt.KeyInput.Char        = 0;
941                 evt.KeyInput.Control     = 0;
942                 evt.KeyInput.Shift       = 0;
943                 evt.KeyInput.PressedDown = true;
944                 e->OnEvent(evt);
945
946                 if (label.length() >= 1)
947                 {
948                         rect.UpperLeftCorner.Y -= 15;
949                         rect.LowerRightCorner.Y = rect.UpperLeftCorner.Y + 15;
950                         Environment->addStaticText(spec.flabel.c_str(), rect, false, true, this, 0);
951                 }
952         }
953
954         m_fields.push_back(spec);
955 }
956
957 void GUIFormSpecMenu::parseTextArea(parserData* data,
958                 std::vector<std::string>& parts,std::string type)
959 {
960
961         std::vector<std::string> v_pos = split(parts[0],',');
962         std::vector<std::string> v_geom = split(parts[1],',');
963         std::string name = parts[2];
964         std::string label = parts[3];
965         std::string default_val = parts[4];
966
967         MY_CHECKPOS(type,0);
968         MY_CHECKGEOM(type,1);
969
970         v2s32 pos;
971         pos.X = stof(v_pos[0]) * (float) spacing.X;
972         pos.Y = stof(v_pos[1]) * (float) spacing.Y;
973
974         v2s32 geom;
975
976         geom.X = (stof(v_geom[0]) * (float)spacing.X)-(spacing.X-imgsize.X);
977
978         if (type == "textarea")
979         {
980                 geom.Y = (stof(v_geom[1]) * (float)imgsize.Y) - (spacing.Y-imgsize.Y);
981                 pos.Y += 15;
982         }
983         else
984         {
985                 pos.Y += (stof(v_geom[1]) * (float)imgsize.Y)/2;
986                 pos.Y -= 15;
987                 geom.Y = 30;
988         }
989
990         core::rect<s32> rect = core::rect<s32>(pos.X, pos.Y, pos.X+geom.X, pos.Y+geom.Y);
991
992         if(data->bp_set != 2)
993                 errorstream<<"WARNING: invalid use of positioned "<<type<<" without a size[] element"<<std::endl;
994
995         if(m_form_src)
996                 default_val = m_form_src->resolveText(default_val);
997
998
999         default_val = unescape_string(default_val);
1000         label = unescape_string(label);
1001
1002         std::wstring wlabel = narrow_to_wide(label.c_str());
1003
1004         FieldSpec spec = FieldSpec(
1005                 narrow_to_wide(name.c_str()),
1006                 wlabel,
1007                 narrow_to_wide(default_val.c_str()),
1008                 258+m_fields.size()
1009         );
1010
1011         if (name == "")
1012         {
1013                 // spec field id to 0, this stops submit searching for a value that isn't there
1014                 Environment->addStaticText(spec.flabel.c_str(), rect, false, true, this, spec.fid);
1015         }
1016         else
1017         {
1018                 spec.send = true;
1019                 gui::IGUIEditBox *e = Environment->addEditBox(spec.fdefault.c_str(), rect, true, this, spec.fid);
1020
1021                 if (spec.fname == data->focused_fieldname) {
1022                         Environment->setFocus(e);
1023                 }
1024
1025                 if (type == "textarea")
1026                 {
1027                         e->setMultiLine(true);
1028                         e->setTextAlignment(gui::EGUIA_UPPERLEFT, gui::EGUIA_UPPERLEFT);
1029                 } else {
1030                         irr::SEvent evt;
1031                         evt.EventType            = EET_KEY_INPUT_EVENT;
1032                         evt.KeyInput.Key         = KEY_END;
1033                         evt.KeyInput.Char        = 0;
1034                         evt.KeyInput.Control     = 0;
1035                         evt.KeyInput.Shift       = 0;
1036                         evt.KeyInput.PressedDown = true;
1037                         e->OnEvent(evt);
1038                 }
1039
1040                 if (label.length() >= 1)
1041                 {
1042                         rect.UpperLeftCorner.Y -= 15;
1043                         rect.LowerRightCorner.Y = rect.UpperLeftCorner.Y + 15;
1044                         Environment->addStaticText(spec.flabel.c_str(), rect, false, true, this, 0);
1045                 }
1046         }
1047         m_fields.push_back(spec);
1048 }
1049
1050 void GUIFormSpecMenu::parseField(parserData* data,std::string element,
1051                 std::string type)
1052 {
1053         std::vector<std::string> parts = split(element,';');
1054
1055         if (parts.size() == 3) {
1056                 parseSimpleField(data,parts);
1057                 return;
1058         }
1059
1060         if (parts.size() == 5) {
1061                 parseTextArea(data,parts,type);
1062                 return;
1063         }
1064         errorstream<< "Invalid field element(" << parts.size() << "): '" << element << "'"  << std::endl;
1065 }
1066
1067 void GUIFormSpecMenu::parseLabel(parserData* data,std::string element)
1068 {
1069         std::vector<std::string> parts = split(element,';');
1070
1071         if (parts.size() == 2) {
1072                 std::vector<std::string> v_pos = split(parts[0],',');
1073                 std::string text = parts[1];
1074
1075                 MY_CHECKPOS("label",0);
1076
1077                 v2s32 pos = padding;
1078                 pos.X += stof(v_pos[0]) * (float)spacing.X;
1079                 pos.Y += stof(v_pos[1]) * (float)spacing.Y;
1080
1081                 core::rect<s32> rect = core::rect<s32>(pos.X, pos.Y+((imgsize.Y/2)-15), pos.X+300, pos.Y+((imgsize.Y/2)+15));
1082
1083                 if(data->bp_set != 2)
1084                         errorstream<<"WARNING: invalid use of label without a size[] element"<<std::endl;
1085
1086                 text = unescape_string(text);
1087
1088                 std::wstring wlabel = narrow_to_wide(text.c_str());
1089
1090                 FieldSpec spec = FieldSpec(
1091                         L"",
1092                         wlabel,
1093                         L"",
1094                         258+m_fields.size()
1095                 );
1096                 Environment->addStaticText(spec.flabel.c_str(), rect, false, true, this, spec.fid);
1097                 m_fields.push_back(spec);
1098                 return;
1099         }
1100         errorstream<< "Invalid label element(" << parts.size() << "): '" << element << "'"  << std::endl;
1101 }
1102
1103 void GUIFormSpecMenu::parseVertLabel(parserData* data,std::string element)
1104 {
1105         std::vector<std::string> parts = split(element,';');
1106
1107         if (parts.size() == 2) {
1108                 std::vector<std::string> v_pos = split(parts[0],',');
1109                 std::wstring text = narrow_to_wide(unescape_string(parts[1]));
1110
1111                 MY_CHECKPOS("vertlabel",1);
1112
1113                 v2s32 pos = padding;
1114                 pos.X += stof(v_pos[0]) * (float)spacing.X;
1115                 pos.Y += stof(v_pos[1]) * (float)spacing.Y;
1116
1117                 core::rect<s32> rect = core::rect<s32>(pos.X, pos.Y+((imgsize.Y/2)-15), pos.X+15, pos.Y+300);
1118
1119                 if(data->bp_set != 2)
1120                         errorstream<<"WARNING: invalid use of label without a size[] element"<<std::endl;
1121
1122                 std::wstring label = L"";
1123
1124                 for (unsigned int i=0; i < text.length(); i++) {
1125                         label += text[i];
1126                         label += L"\n";
1127                 }
1128
1129                 FieldSpec spec = FieldSpec(
1130                         L"",
1131                         label,
1132                         L"",
1133                         258+m_fields.size()
1134                 );
1135                 gui::IGUIStaticText *t =
1136                                 Environment->addStaticText(spec.flabel.c_str(), rect, false, true, this, spec.fid);
1137                 t->setTextAlignment(gui::EGUIA_CENTER, gui::EGUIA_CENTER);
1138                 m_fields.push_back(spec);
1139                 return;
1140         }
1141         errorstream<< "Invalid vertlabel element(" << parts.size() << "): '" << element << "'"  << std::endl;
1142 }
1143
1144 void GUIFormSpecMenu::parseImageButton(parserData* data,std::string element,
1145                 std::string type)
1146 {
1147         std::vector<std::string> parts = split(element,';');
1148
1149         if ((parts.size() == 5) || (parts.size() == 7) || (parts.size() == 8)) {
1150                 std::vector<std::string> v_pos = split(parts[0],',');
1151                 std::vector<std::string> v_geom = split(parts[1],',');
1152                 std::string image_name = parts[2];
1153                 std::string name = parts[3];
1154                 std::string label = parts[4];
1155
1156                 MY_CHECKPOS("imagebutton",0);
1157                 MY_CHECKGEOM("imagebutton",1);
1158
1159                 v2s32 pos = padding;
1160                 pos.X += stof(v_pos[0]) * (float)spacing.X;
1161                 pos.Y += stof(v_pos[1]) * (float)spacing.Y;
1162                 v2s32 geom;
1163                 geom.X = (stof(v_geom[0]) * (float)spacing.X)-(spacing.X-imgsize.X);
1164                 geom.Y = (stof(v_geom[1]) * (float)spacing.Y)-(spacing.Y-imgsize.Y);
1165
1166                 bool noclip = false;
1167                 bool drawborder = true;
1168
1169                 if ((parts.size() >= 7)) {
1170                         if (parts[5] == "true")
1171                                 noclip = true;
1172
1173                         if (parts[6] == "false")
1174                                 drawborder = false;
1175                 }
1176                 
1177                 std::string pressed_image_name = "";
1178                 
1179                 if ((parts.size() == 8)) {
1180                         pressed_image_name = parts[7];
1181                 }
1182
1183                 core::rect<s32> rect = core::rect<s32>(pos.X, pos.Y, pos.X+geom.X, pos.Y+geom.Y);
1184
1185                 if(data->bp_set != 2)
1186                         errorstream<<"WARNING: invalid use of image_button without a size[] element"<<std::endl;
1187
1188                 image_name = unescape_string(image_name);
1189                 pressed_image_name = unescape_string(pressed_image_name);
1190                 label = unescape_string(label);
1191
1192                 std::wstring wlabel = narrow_to_wide(label.c_str());
1193
1194                 FieldSpec spec = FieldSpec(
1195                         narrow_to_wide(name.c_str()),
1196                         wlabel,
1197                         narrow_to_wide(image_name.c_str()),
1198                         258+m_fields.size()
1199                 );
1200                 spec.ftype = f_Button;
1201                 if(type == "image_button_exit")
1202                         spec.is_exit = true;
1203
1204                 video::ITexture *texture = 0;
1205                 video::ITexture *pressed_texture = 0;
1206                 texture = m_tsrc->getTexture(image_name);
1207                 if (parts.size() == 8)
1208                         pressed_texture = m_tsrc->getTexture(pressed_image_name);
1209                 else
1210                         pressed_texture = texture;
1211
1212                 gui::IGUIButton *e = Environment->addButton(rect, this, spec.fid, spec.flabel.c_str());
1213
1214                 if (spec.fname == data->focused_fieldname) {
1215                         Environment->setFocus(e);
1216                 }
1217
1218                 e->setUseAlphaChannel(true);
1219                 e->setImage(texture);
1220                 e->setPressedImage(pressed_texture);
1221                 e->setScaleImage(true);
1222                 e->setNotClipped(noclip);
1223                 e->setDrawBorder(drawborder);
1224
1225                 m_fields.push_back(spec);
1226                 return;
1227         }
1228
1229         errorstream<< "Invalid imagebutton element(" << parts.size() << "): '" << element << "'"  << std::endl;
1230 }
1231
1232 void GUIFormSpecMenu::parseTabHeader(parserData* data,std::string element)
1233 {
1234         std::vector<std::string> parts = split(element,';');
1235
1236         if ((parts.size() == 4) || (parts.size() == 6)) {
1237                 std::vector<std::string> v_pos = split(parts[0],',');
1238                 std::string name = parts[1];
1239                 std::vector<std::string> buttons = split(parts[2],',');
1240                 std::string str_index = parts[3];
1241                 bool show_background = true;
1242                 bool show_border = true;
1243                 int tab_index = stoi(str_index) -1;
1244
1245                 MY_CHECKPOS("tabheader",0);
1246
1247                 if (parts.size() == 6) {
1248                         if (parts[4] == "true")
1249                                 show_background = false;
1250                         if (parts[5] == "false")
1251                                 show_border = false;
1252                 }
1253
1254                 FieldSpec spec = FieldSpec(
1255                         narrow_to_wide(name.c_str()),
1256                         L"",
1257                         L"",
1258                         258+m_fields.size()
1259                 );
1260
1261                 spec.ftype = f_TabHeader;
1262
1263                 v2s32 pos = padding;
1264                 pos.X += stof(v_pos[0]) * (float)spacing.X;
1265                 pos.Y += stof(v_pos[1]) * (float)spacing.Y;
1266                 v2s32 geom;
1267                 geom.X = data->screensize.Y;
1268                 geom.Y = 30;
1269
1270                 core::rect<s32> rect = core::rect<s32>(pos.X, pos.Y, pos.X+geom.X, pos.Y+geom.Y);
1271
1272                 gui::IGUITabControl *e = Environment->addTabControl(rect,this,show_background,show_border,spec.fid);
1273
1274                 if (spec.fname == data->focused_fieldname) {
1275                         Environment->setFocus(e);
1276                 }
1277
1278                 e->setNotClipped(true);
1279
1280                 for (unsigned int i=0; i< buttons.size(); i++) {
1281                         wchar_t* wbutton = 0;
1282
1283                         std::wstring wlabel = narrow_to_wide(buttons[i]); //Needed for displaying text on windows
1284                         wbutton = (wchar_t*) wlabel.c_str();
1285
1286                         e->addTab(wbutton,-1);
1287                 }
1288
1289                 if ((tab_index >= 0) &&
1290                                 (buttons.size() < INT_MAX) &&
1291                                 (tab_index < (int) buttons.size()))
1292                         e->setActiveTab(tab_index);
1293
1294                 m_fields.push_back(spec);
1295                 return;
1296         }
1297         errorstream<< "Invalid TabHeader element(" << parts.size() << "): '" << element << "'"  << std::endl;
1298 }
1299
1300 void GUIFormSpecMenu::parseItemImageButton(parserData* data,std::string element)
1301 {
1302
1303         if (m_gamedef == 0) {
1304                 errorstream<<"WARNING: invalid use of item_image_button with m_gamedef==0"<<std::endl;
1305                 return;
1306         }
1307
1308         std::vector<std::string> parts = split(element,';');
1309
1310         if (parts.size() == 5) {
1311                 std::vector<std::string> v_pos = split(parts[0],',');
1312                 std::vector<std::string> v_geom = split(parts[1],',');
1313                 std::string item_name = parts[2];
1314                 std::string name = parts[3];
1315                 std::string label = parts[4];
1316
1317                 MY_CHECKPOS("itemimagebutton",0);
1318                 MY_CHECKGEOM("itemimagebutton",1);
1319
1320                 v2s32 pos = padding;
1321                 pos.X += stof(v_pos[0]) * (float)spacing.X;
1322                 pos.Y += stof(v_pos[1]) * (float)spacing.Y;
1323                 v2s32 geom;
1324                 geom.X = (stof(v_geom[0]) * (float)spacing.X)-(spacing.X-imgsize.X);
1325                 geom.Y = (stof(v_geom[1]) * (float)spacing.Y)-(spacing.Y-imgsize.Y);
1326
1327                 core::rect<s32> rect = core::rect<s32>(pos.X, pos.Y, pos.X+geom.X, pos.Y+geom.Y);
1328
1329                 if(data->bp_set != 2)
1330                         errorstream<<"WARNING: invalid use of item_image_button without a size[] element"<<std::endl;
1331
1332                 IItemDefManager *idef = m_gamedef->idef();
1333                 ItemStack item;
1334                 item.deSerialize(item_name, idef);
1335                 video::ITexture *texture = idef->getInventoryTexture(item.getDefinition(idef).name, m_gamedef);
1336                 std::string tooltip = item.getDefinition(idef).description;
1337
1338                 label = unescape_string(label);
1339                 FieldSpec spec = FieldSpec(
1340                         narrow_to_wide(name.c_str()),
1341                         narrow_to_wide(label.c_str()),
1342                         narrow_to_wide(item_name.c_str()),
1343                         258+m_fields.size()
1344                 );
1345
1346                 gui::IGUIButton *e = Environment->addButton(rect, this, spec.fid, spec.flabel.c_str());
1347
1348                 if (spec.fname == data->focused_fieldname) {
1349                         Environment->setFocus(e);
1350                 }
1351
1352                 e->setUseAlphaChannel(true);
1353                 e->setImage(texture);
1354                 e->setPressedImage(texture);
1355                 e->setScaleImage(true);
1356                 spec.ftype = f_Button;
1357                 rect+=data->basepos-padding;
1358                 spec.rect=rect;
1359                 if (tooltip!="")
1360                         spec.tooltip=tooltip;
1361                 m_fields.push_back(spec);
1362                 return;
1363         }
1364         errorstream<< "Invalid ItemImagebutton element(" << parts.size() << "): '" << element << "'"  << std::endl;
1365 }
1366
1367 void GUIFormSpecMenu::parseBox(parserData* data,std::string element)
1368 {
1369         std::vector<std::string> parts = split(element,';');
1370
1371         if (parts.size() == 3) {
1372                 std::vector<std::string> v_pos = split(parts[0],',');
1373                 std::vector<std::string> v_geom = split(parts[1],',');
1374
1375                 MY_CHECKPOS("box",0);
1376                 MY_CHECKGEOM("box",1);
1377
1378                 v2s32 pos = padding + AbsoluteRect.UpperLeftCorner;
1379                 pos.X += stof(v_pos[0]) * (float) spacing.X;
1380                 pos.Y += stof(v_pos[1]) * (float) spacing.Y;
1381
1382                 v2s32 geom;
1383                 geom.X = stof(v_geom[0]) * (float)spacing.X;
1384                 geom.Y = stof(v_geom[1]) * (float)spacing.Y;
1385
1386                 video::SColor tmp_color;
1387
1388                 if (parseColor(parts[2], tmp_color, false)) {
1389                         BoxDrawSpec spec(pos, geom, tmp_color);
1390
1391                         m_boxes.push_back(spec);
1392                 }
1393                 else {
1394                         errorstream<< "Invalid Box element(" << parts.size() << "): '" << element << "'  INVALID COLOR"  << std::endl;
1395                 }
1396                 return;
1397         }
1398         errorstream<< "Invalid Box element(" << parts.size() << "): '" << element << "'"  << std::endl;
1399 }
1400
1401 void GUIFormSpecMenu::parseBackgroundColor(parserData* data,std::string element)
1402 {
1403         std::vector<std::string> parts = split(element,';');
1404
1405         if ((parts.size() == 1) || (parts.size() == 2)) {
1406                 parseColor(parts[0],m_bgcolor,false);
1407
1408                 if (parts.size() == 2) {
1409                         std::string fullscreen = parts[1];
1410                         m_bgfullscreen = is_yes(fullscreen);
1411                 }
1412                 return;
1413         }
1414         errorstream<< "Invalid bgcolor element(" << parts.size() << "): '" << element << "'"  << std::endl;
1415 }
1416
1417 void GUIFormSpecMenu::parseListColors(parserData* data,std::string element)
1418 {
1419         std::vector<std::string> parts = split(element,';');
1420
1421         if ((parts.size() == 2) || (parts.size() == 3) || (parts.size() == 5)) {
1422                 parseColor(parts[0], m_slotbg_n, false);
1423                 parseColor(parts[1], m_slotbg_h, false);
1424                 
1425                 if (parts.size() >= 3) {
1426                         if (parseColor(parts[2], m_slotbordercolor, false)) {
1427                                 m_slotborder = true;
1428                         }
1429                 }
1430                 if (parts.size() == 5) {
1431                         video::SColor tmp_color;
1432
1433                         if (parseColor(parts[3], tmp_color, false))
1434                                 m_tooltip_element->setBackgroundColor(tmp_color);
1435                         if (parseColor(parts[4], tmp_color, false))
1436                                 m_tooltip_element->setOverrideColor(tmp_color);
1437                 }
1438                 return;
1439         }
1440         errorstream<< "Invalid listcolors element(" << parts.size() << "): '" << element << "'"  << std::endl;
1441 }
1442
1443 void GUIFormSpecMenu::parseElement(parserData* data,std::string element)
1444 {
1445         //some prechecks
1446         if (element == "")
1447                 return;
1448
1449         std::vector<std::string> parts = split(element,'[');
1450
1451         // ugly workaround to keep compatibility
1452         if (parts.size() > 2) {
1453                 if (trim(parts[0]) == "image") {
1454                         for (unsigned int i=2;i< parts.size(); i++) {
1455                                 parts[1] += "[" + parts[i];
1456                         }
1457                 }
1458                 else { return; }
1459         }
1460
1461         if (parts.size() < 2) {
1462                 return;
1463         }
1464
1465         std::string type = trim(parts[0]);
1466         std::string description = trim(parts[1]);
1467
1468         if ((type == "size") || (type == "invsize")){
1469                 parseSize(data,description);
1470                 return;
1471         }
1472
1473         if (type == "list") {
1474                 parseList(data,description);
1475                 return;
1476         }
1477
1478         if (type == "checkbox") {
1479                 parseCheckbox(data,description);
1480                 return;
1481         }
1482
1483         if (type == "image") {
1484                 parseImage(data,description);
1485                 return;
1486         }
1487
1488         if (type == "item_image") {
1489                 parseItemImage(data,description);
1490                 return;
1491         }
1492
1493         if ((type == "button") || (type == "button_exit")) {
1494                 parseButton(data,description,type);
1495                 return;
1496         }
1497
1498         if (type == "background") {
1499                 parseBackground(data,description);
1500                 return;
1501         }
1502
1503         if (type == "tableoptions"){
1504                 parseTableOptions(data,description);
1505                 return;
1506         }
1507
1508         if (type == "tablecolumns"){
1509                 parseTableColumns(data,description);
1510                 return;
1511         }
1512
1513         if (type == "table"){
1514                 parseTable(data,description);
1515                 return;
1516         }
1517
1518         if (type == "textlist"){
1519                 parseTextList(data,description);
1520                 return;
1521         }
1522
1523         if (type == "dropdown"){
1524                 parseDropDown(data,description);
1525                 return;
1526         }
1527
1528         if (type == "pwdfield") {
1529                 parsePwdField(data,description);
1530                 return;
1531         }
1532
1533         if ((type == "field") || (type == "textarea")){
1534                 parseField(data,description,type);
1535                 return;
1536         }
1537
1538         if (type == "label") {
1539                 parseLabel(data,description);
1540                 return;
1541         }
1542
1543         if (type == "vertlabel") {
1544                 parseVertLabel(data,description);
1545                 return;
1546         }
1547
1548         if (type == "item_image_button") {
1549                 parseItemImageButton(data,description);
1550                 return;
1551         }
1552
1553         if ((type == "image_button") || (type == "image_button_exit")) {
1554                 parseImageButton(data,description,type);
1555                 return;
1556         }
1557
1558         if (type == "tabheader") {
1559                 parseTabHeader(data,description);
1560                 return;
1561         }
1562
1563         if (type == "box") {
1564                 parseBox(data,description);
1565                 return;
1566         }
1567
1568         if (type == "bgcolor") {
1569                 parseBackgroundColor(data,description);
1570                 return;
1571         }
1572
1573         if (type == "listcolors") {
1574                 parseListColors(data,description);
1575                 return;
1576         }
1577
1578         // Ignore others
1579         infostream
1580                 << "Unknown DrawSpec: type="<<type<<", data=\""<<description<<"\""
1581                 <<std::endl;
1582 }
1583
1584
1585
1586 void GUIFormSpecMenu::regenerateGui(v2u32 screensize)
1587 {
1588         parserData mydata;
1589
1590         //preserve tables
1591         for (u32 i = 0; i < m_tables.size(); ++i) {
1592                 std::wstring tablename = m_tables[i].first.fname;
1593                 GUITable *table = m_tables[i].second;
1594                 mydata.table_dyndata[tablename] = table->getDynamicData();
1595         }
1596
1597         //preserve focus
1598         gui::IGUIElement *focused_element = Environment->getFocus();
1599         if (focused_element && focused_element->getParent() == this) {
1600                 s32 focused_id = focused_element->getID();
1601                 if (focused_id > 257) {
1602                         for (u32 i=0; i<m_fields.size(); i++) {
1603                                 if (m_fields[i].fid == focused_id) {
1604                                         mydata.focused_fieldname =
1605                                                 m_fields[i].fname;
1606                                         break;
1607                                 }
1608                         }
1609                 }
1610         }
1611
1612         // Remove children
1613         removeChildren();
1614
1615         mydata.size= v2s32(100,100);
1616         mydata.helptext_h = 15;
1617         mydata.screensize = screensize;
1618
1619         // Base position of contents of form
1620         mydata.basepos = getBasePos();
1621
1622         // State of basepos, 0 = not set, 1= set by formspec, 2 = set by size[] element
1623         // Used to adjust form size automatically if needed
1624         // A proceed button is added if there is no size[] element
1625         mydata.bp_set = 0;
1626
1627         
1628         /* Convert m_init_draw_spec to m_inventorylists */
1629         
1630         m_inventorylists.clear();
1631         m_images.clear();
1632         m_backgrounds.clear();
1633         m_itemimages.clear();
1634         m_tables.clear();
1635         m_checkboxes.clear();
1636         m_fields.clear();
1637         m_boxes.clear();
1638
1639         // Set default values (fits old formspec values)
1640         m_bgcolor = video::SColor(140,0,0,0);
1641         m_bgfullscreen = false;
1642
1643         m_slotbg_n = video::SColor(255,128,128,128);
1644         m_slotbg_h = video::SColor(255,192,192,192);
1645
1646         m_slotbordercolor = video::SColor(200,0,0,0);
1647         m_slotborder = false;
1648
1649         m_clipbackground = false;
1650         // Add tooltip
1651         {
1652                 // Note: parent != this so that the tooltip isn't clipped by the menu rectangle
1653                 m_tooltip_element = Environment->addStaticText(L"",core::rect<s32>(0,0,110,18));
1654                 m_tooltip_element->enableOverrideColor(true);
1655                 m_tooltip_element->setBackgroundColor(video::SColor(255,110,130,60));
1656                 m_tooltip_element->setDrawBackground(true);
1657                 m_tooltip_element->setDrawBorder(true);
1658                 m_tooltip_element->setOverrideColor(video::SColor(255,255,255,255));
1659                 m_tooltip_element->setTextAlignment(gui::EGUIA_CENTER, gui::EGUIA_CENTER);
1660                 m_tooltip_element->setWordWrap(false);
1661                 //we're not parent so no autograb for this one!
1662                 m_tooltip_element->grab();
1663         }
1664
1665
1666         std::vector<std::string> elements = split(m_formspec_string,']');
1667         for (unsigned int i=0;i< elements.size();i++) {
1668                 parseElement(&mydata,elements[i]);
1669         }
1670
1671         // If there's fields, add a Proceed button
1672         if (m_fields.size() && mydata.bp_set != 2)
1673         {
1674                 // if the size wasn't set by an invsize[] or size[] adjust it now to fit all the fields
1675                 mydata.rect = core::rect<s32>(
1676                                 mydata.screensize.X/2 - 580/2,
1677                                 mydata.screensize.Y/2 - 300/2,
1678                                 mydata.screensize.X/2 + 580/2,
1679                                 mydata.screensize.Y/2 + 240/2+(m_fields.size()*60)
1680                 );
1681                 DesiredRect = mydata.rect;
1682                 recalculateAbsolutePosition(false);
1683                 mydata.basepos = getBasePos();
1684
1685                 {
1686                         v2s32 pos = mydata.basepos;
1687                         pos.Y = ((m_fields.size()+2)*60);
1688
1689                         v2s32 size = DesiredRect.getSize();
1690                         mydata.rect = core::rect<s32>(size.X/2-70, pos.Y, (size.X/2-70)+140, pos.Y+30);
1691                         wchar_t* text = wgettext("Proceed");
1692                         Environment->addButton(mydata.rect, this, 257, text);
1693                         delete[] text;
1694                 }
1695
1696         }
1697
1698         //set initial focus if parser didn't set it
1699         focused_element = Environment->getFocus();
1700         if (!focused_element
1701                         || !isMyChild(focused_element)
1702                         || focused_element->getType() == gui::EGUIET_TAB_CONTROL)
1703                 setInitialFocus();
1704 }
1705
1706 GUIFormSpecMenu::ItemSpec GUIFormSpecMenu::getItemAtPos(v2s32 p) const
1707 {
1708         core::rect<s32> imgrect(0,0,imgsize.X,imgsize.Y);
1709         
1710         for(u32 i=0; i<m_inventorylists.size(); i++)
1711         {
1712                 const ListDrawSpec &s = m_inventorylists[i];
1713
1714                 for(s32 i=0; i<s.geom.X*s.geom.Y; i++)
1715                 {
1716                         s32 item_i = i + s.start_item_i;
1717                         s32 x = (i%s.geom.X) * spacing.X;
1718                         s32 y = (i/s.geom.X) * spacing.Y;
1719                         v2s32 p0(x,y);
1720                         core::rect<s32> rect = imgrect + s.pos + p0;
1721                         if(rect.isPointInside(p))
1722                         {
1723                                 return ItemSpec(s.inventoryloc, s.listname, item_i);
1724                         }
1725                 }
1726         }
1727
1728         return ItemSpec(InventoryLocation(), "", -1);
1729 }
1730
1731 void GUIFormSpecMenu::drawList(const ListDrawSpec &s, int phase)
1732 {
1733         video::IVideoDriver* driver = Environment->getVideoDriver();
1734
1735         // Get font
1736         gui::IGUIFont *font = NULL;
1737         gui::IGUISkin* skin = Environment->getSkin();
1738         if (skin)
1739                 font = skin->getFont();
1740         
1741         Inventory *inv = m_invmgr->getInventory(s.inventoryloc);
1742         if(!inv){
1743                 infostream<<"GUIFormSpecMenu::drawList(): WARNING: "
1744                                 <<"The inventory location "
1745                                 <<"\""<<s.inventoryloc.dump()<<"\" doesn't exist"
1746                                 <<std::endl;
1747                 return;
1748         }
1749         InventoryList *ilist = inv->getList(s.listname);
1750         if(!ilist){
1751                 infostream<<"GUIFormSpecMenu::drawList(): WARNING: "
1752                                 <<"The inventory list \""<<s.listname<<"\" @ \""
1753                                 <<s.inventoryloc.dump()<<"\" doesn't exist"
1754                                 <<std::endl;
1755                 return;
1756         }
1757         
1758         core::rect<s32> imgrect(0,0,imgsize.X,imgsize.Y);
1759         
1760         for(s32 i=0; i<s.geom.X*s.geom.Y; i++)
1761         {
1762                 s32 item_i = i + s.start_item_i;
1763                 if(item_i >= (s32) ilist->getSize())
1764                         break;
1765                 s32 x = (i%s.geom.X) * spacing.X;
1766                 s32 y = (i/s.geom.X) * spacing.Y;
1767                 v2s32 p(x,y);
1768                 core::rect<s32> rect = imgrect + s.pos + p;
1769                 ItemStack item;
1770                 if(ilist)
1771                         item = ilist->getItem(item_i);
1772
1773                 bool selected = m_selected_item
1774                         && m_invmgr->getInventory(m_selected_item->inventoryloc) == inv
1775                         && m_selected_item->listname == s.listname
1776                         && m_selected_item->i == item_i;
1777                 bool hovering = rect.isPointInside(m_pointer);
1778
1779                 if(phase == 0)
1780                 {
1781                         if(hovering)
1782                                 driver->draw2DRectangle(m_slotbg_h, rect, &AbsoluteClippingRect);
1783                         else
1784                                 driver->draw2DRectangle(m_slotbg_n, rect, &AbsoluteClippingRect);
1785                 }
1786
1787                 //Draw inv slot borders
1788                 if (m_slotborder) {
1789                         s32 x1 = rect.UpperLeftCorner.X;
1790                         s32 y1 = rect.UpperLeftCorner.Y;
1791                         s32 x2 = rect.LowerRightCorner.X;
1792                         s32 y2 = rect.LowerRightCorner.Y;
1793                         s32 border = 1;
1794                         driver->draw2DRectangle(m_slotbordercolor,
1795                                 core::rect<s32>(v2s32(x1 - border, y1 - border),
1796                                                                 v2s32(x2 + border, y1)), NULL);
1797                         driver->draw2DRectangle(m_slotbordercolor,
1798                                 core::rect<s32>(v2s32(x1 - border, y2),
1799                                                                 v2s32(x2 + border, y2 + border)), NULL);
1800                         driver->draw2DRectangle(m_slotbordercolor,
1801                                 core::rect<s32>(v2s32(x1 - border, y1),
1802                                                                 v2s32(x1, y2)), NULL);
1803                         driver->draw2DRectangle(m_slotbordercolor,
1804                                 core::rect<s32>(v2s32(x2, y1),
1805                                                                 v2s32(x2 + border, y2)), NULL);
1806                 }
1807
1808                 if(phase == 1)
1809                 {
1810                         // Draw item stack
1811                         if(selected)
1812                         {
1813                                 item.takeItem(m_selected_amount);
1814                         }
1815                         if(!item.empty())
1816                         {
1817                                 drawItemStack(driver, font, item,
1818                                                 rect, &AbsoluteClippingRect, m_gamedef);
1819                         }
1820
1821                         // Draw tooltip
1822                         std::string tooltip_text = "";
1823                         if(hovering && !m_selected_item)
1824                                 tooltip_text = item.getDefinition(m_gamedef->idef()).description;
1825                         if(tooltip_text != "")
1826                         {
1827                                 m_tooltip_element->setVisible(true);
1828                                 this->bringToFront(m_tooltip_element);
1829                                 m_tooltip_element->setText(narrow_to_wide(tooltip_text).c_str());
1830                                 s32 tooltip_x = m_pointer.X + 15;
1831                                 s32 tooltip_y = m_pointer.Y + 15;
1832                                 s32 tooltip_width = m_tooltip_element->getTextWidth() + 15;
1833                                 s32 tooltip_height = m_tooltip_element->getTextHeight() + 5;
1834                                 m_tooltip_element->setRelativePosition(core::rect<s32>(
1835                                                 core::position2d<s32>(tooltip_x, tooltip_y),
1836                                                 core::dimension2d<s32>(tooltip_width, tooltip_height)));
1837                         }
1838                 }
1839         }
1840 }
1841
1842 void GUIFormSpecMenu::drawSelectedItem()
1843 {
1844         if(!m_selected_item)
1845                 return;
1846
1847         video::IVideoDriver* driver = Environment->getVideoDriver();
1848
1849         // Get font
1850         gui::IGUIFont *font = NULL;
1851         gui::IGUISkin* skin = Environment->getSkin();
1852         if (skin)
1853                 font = skin->getFont();
1854         
1855         Inventory *inv = m_invmgr->getInventory(m_selected_item->inventoryloc);
1856         assert(inv);
1857         InventoryList *list = inv->getList(m_selected_item->listname);
1858         assert(list);
1859         ItemStack stack = list->getItem(m_selected_item->i);
1860         stack.count = m_selected_amount;
1861
1862         core::rect<s32> imgrect(0,0,imgsize.X,imgsize.Y);
1863         core::rect<s32> rect = imgrect + (m_pointer - imgrect.getCenter());
1864         drawItemStack(driver, font, stack, rect, NULL, m_gamedef);
1865 }
1866
1867 void GUIFormSpecMenu::drawMenu()
1868 {
1869         if(m_form_src){
1870                 std::string newform = m_form_src->getForm();
1871                 if(newform != m_formspec_string){
1872                         m_formspec_string = newform;
1873                         regenerateGui(m_screensize_old);
1874                 }
1875         }
1876
1877         m_pointer = m_device->getCursorControl()->getPosition();
1878
1879         updateSelectedItem();
1880
1881         gui::IGUISkin* skin = Environment->getSkin();
1882         if (!skin)
1883                 return;
1884         video::IVideoDriver* driver = Environment->getVideoDriver();
1885         
1886         v2u32 screenSize = driver->getScreenSize();
1887         core::rect<s32> allbg(0, 0, screenSize.X ,      screenSize.Y);
1888         if (m_bgfullscreen)
1889                 driver->draw2DRectangle(m_bgcolor, allbg, &allbg);
1890         else
1891                 driver->draw2DRectangle(m_bgcolor, AbsoluteRect, &AbsoluteClippingRect);
1892
1893         m_tooltip_element->setVisible(false);
1894
1895         /*
1896                 Draw backgrounds
1897         */
1898         for(u32 i=0; i<m_backgrounds.size(); i++)
1899         {
1900                 const ImageDrawSpec &spec = m_backgrounds[i];
1901                 video::ITexture *texture = m_tsrc->getTexture(spec.name);
1902
1903                 if (texture != 0) {
1904                         // Image size on screen
1905                         core::rect<s32> imgrect(0, 0, spec.geom.X, spec.geom.Y);
1906                         // Image rectangle on screen
1907                         core::rect<s32> rect = imgrect + spec.pos;
1908
1909                         if (m_clipbackground) {
1910                                 core::dimension2d<s32> absrec_size = AbsoluteRect.getSize();
1911                                 rect = core::rect<s32>(AbsoluteRect.UpperLeftCorner.X - spec.pos.X,
1912                                                                         AbsoluteRect.UpperLeftCorner.Y - spec.pos.Y,
1913                                                                         AbsoluteRect.UpperLeftCorner.X + absrec_size.Width + spec.pos.X,
1914                                                                         AbsoluteRect.UpperLeftCorner.Y + absrec_size.Height + spec.pos.Y);
1915                         }
1916
1917                         const video::SColor color(255,255,255,255);
1918                         const video::SColor colors[] = {color,color,color,color};
1919                         driver->draw2DImage(texture, rect,
1920                                 core::rect<s32>(core::position2d<s32>(0,0),
1921                                                 core::dimension2di(texture->getOriginalSize())),
1922                                 NULL/*&AbsoluteClippingRect*/, colors, true);
1923                 }
1924                 else {
1925                         errorstream << "GUIFormSpecMenu::drawMenu() Draw backgrounds unable to load texture:" << std::endl;
1926                         errorstream << "\t" << spec.name << std::endl;
1927                 }
1928         }
1929         
1930         /*
1931                 Draw Boxes
1932         */
1933         for(u32 i=0; i<m_boxes.size(); i++)
1934         {
1935                 const BoxDrawSpec &spec = m_boxes[i];
1936
1937                 irr::video::SColor todraw = spec.color;
1938
1939                 todraw.setAlpha(140);
1940
1941                 core::rect<s32> rect(spec.pos.X,spec.pos.Y,
1942                                                         spec.pos.X + spec.geom.X,spec.pos.Y + spec.geom.Y);
1943
1944                 driver->draw2DRectangle(todraw, rect, 0);
1945         }
1946         /*
1947                 Draw images
1948         */
1949         for(u32 i=0; i<m_images.size(); i++)
1950         {
1951                 const ImageDrawSpec &spec = m_images[i];
1952                 video::ITexture *texture = m_tsrc->getTexture(spec.name);
1953
1954                 if (texture != 0) {
1955                         const core::dimension2d<u32>& img_origsize = texture->getOriginalSize();
1956                         // Image size on screen
1957                         core::rect<s32> imgrect;
1958
1959                         if (spec.scale)
1960                                 imgrect = core::rect<s32>(0,0,spec.geom.X, spec.geom.Y);
1961                         else {
1962
1963                                 imgrect = core::rect<s32>(0,0,img_origsize.Width,img_origsize.Height);
1964                         }
1965                         // Image rectangle on screen
1966                         core::rect<s32> rect = imgrect + spec.pos;
1967                         const video::SColor color(255,255,255,255);
1968                         const video::SColor colors[] = {color,color,color,color};
1969                         driver->draw2DImage(texture, rect,
1970                                 core::rect<s32>(core::position2d<s32>(0,0),img_origsize),
1971                                 NULL/*&AbsoluteClippingRect*/, colors, true);
1972                 }
1973                 else {
1974                         errorstream << "GUIFormSpecMenu::drawMenu() Draw images unable to load texture:" << std::endl;
1975                         errorstream << "\t" << spec.name << std::endl;
1976                 }
1977         }
1978         
1979         /*
1980                 Draw item images
1981         */
1982         for(u32 i=0; i<m_itemimages.size(); i++)
1983         {
1984                 if (m_gamedef == 0)
1985                         break;
1986
1987                 const ImageDrawSpec &spec = m_itemimages[i];
1988                 IItemDefManager *idef = m_gamedef->idef();
1989                 ItemStack item;
1990                 item.deSerialize(spec.name, idef);
1991                 video::ITexture *texture = idef->getInventoryTexture(item.getDefinition(idef).name, m_gamedef);
1992                 // Image size on screen
1993                 core::rect<s32> imgrect(0, 0, spec.geom.X, spec.geom.Y);
1994                 // Image rectangle on screen
1995                 core::rect<s32> rect = imgrect + spec.pos;
1996                 const video::SColor color(255,255,255,255);
1997                 const video::SColor colors[] = {color,color,color,color};
1998                 driver->draw2DImage(texture, rect,
1999                         core::rect<s32>(core::position2d<s32>(0,0),
2000                                         core::dimension2di(texture->getOriginalSize())),
2001                         NULL/*&AbsoluteClippingRect*/, colors, true);
2002         }
2003         
2004         /*
2005                 Draw items
2006                 Phase 0: Item slot rectangles
2007                 Phase 1: Item images; prepare tooltip
2008         */
2009         int start_phase=0;
2010         for(int phase=start_phase; phase<=1; phase++)
2011         for(u32 i=0; i<m_inventorylists.size(); i++)
2012         {
2013                 drawList(m_inventorylists[i], phase);
2014         }
2015
2016         /*
2017                 Call base class
2018         */
2019         gui::IGUIElement::draw();
2020         
2021         /*
2022                 Draw fields/buttons tooltips
2023         */
2024         for(u32 i=0; i<m_fields.size(); i++)
2025         {
2026                 const FieldSpec &spec = m_fields[i];
2027                 if (spec.tooltip != "")
2028                 {
2029                         core::rect<s32> rect = spec.rect;
2030                         if (rect.isPointInside(m_pointer))
2031                         {
2032                                 m_tooltip_element->setVisible(true);
2033                                 this->bringToFront(m_tooltip_element);
2034                                 m_tooltip_element->setText(narrow_to_wide(spec.tooltip).c_str());
2035                                 s32 tooltip_x = m_pointer.X + 15;
2036                                 s32 tooltip_y = m_pointer.Y + 15;
2037                                 s32 tooltip_width = m_tooltip_element->getTextWidth() + 15;
2038                                 s32 tooltip_height = m_tooltip_element->getTextHeight() + 5;
2039                                 m_tooltip_element->setRelativePosition(core::rect<s32>(
2040                                 core::position2d<s32>(tooltip_x, tooltip_y),
2041                                 core::dimension2d<s32>(tooltip_width, tooltip_height)));
2042                         }
2043                 }
2044         }
2045         
2046         /*
2047                 Draw dragged item stack
2048         */
2049         drawSelectedItem();
2050 }
2051
2052 void GUIFormSpecMenu::updateSelectedItem()
2053 {
2054         // If the selected stack has become empty for some reason, deselect it.
2055         // If the selected stack has become inaccessible, deselect it.
2056         // If the selected stack has become smaller, adjust m_selected_amount.
2057         ItemStack selected = verifySelectedItem();
2058
2059         // WARNING: BLACK MAGIC
2060         // See if there is a stack suited for our current guess.
2061         // If such stack does not exist, clear the guess.
2062         if(m_selected_content_guess.name != "" &&
2063                         selected.name == m_selected_content_guess.name &&
2064                         selected.count == m_selected_content_guess.count){
2065                 // Selected item fits the guess. Skip the black magic.
2066         }
2067         else if(m_selected_content_guess.name != ""){
2068                 bool found = false;
2069                 for(u32 i=0; i<m_inventorylists.size() && !found; i++){
2070                         const ListDrawSpec &s = m_inventorylists[i];
2071                         Inventory *inv = m_invmgr->getInventory(s.inventoryloc);
2072                         if(!inv)
2073                                 continue;
2074                         InventoryList *list = inv->getList(s.listname);
2075                         if(!list)
2076                                 continue;
2077                         for(s32 i=0; i<s.geom.X*s.geom.Y && !found; i++){
2078                                 u32 item_i = i + s.start_item_i;
2079                                 if(item_i >= list->getSize())
2080                                         continue;
2081                                 ItemStack stack = list->getItem(item_i);
2082                                 if(stack.name == m_selected_content_guess.name &&
2083                                                 stack.count == m_selected_content_guess.count){
2084                                         found = true;
2085                                         infostream<<"Client: Changing selected content guess to "
2086                                                         <<s.inventoryloc.dump()<<" "<<s.listname
2087                                                         <<" "<<item_i<<std::endl;
2088                                         delete m_selected_item;
2089                                         m_selected_item = new ItemSpec(s.inventoryloc, s.listname, item_i);
2090                                         m_selected_amount = stack.count;
2091                                 }
2092                         }
2093                 }
2094                 if(!found){
2095                         infostream<<"Client: Discarding selected content guess: "
2096                                         <<m_selected_content_guess.getItemString()<<std::endl;
2097                         m_selected_content_guess.name = "";
2098                 }
2099         }
2100
2101         // If craftresult is nonempty and nothing else is selected, select it now.
2102         if(!m_selected_item)
2103         {
2104                 for(u32 i=0; i<m_inventorylists.size(); i++)
2105                 {
2106                         const ListDrawSpec &s = m_inventorylists[i];
2107                         if(s.listname == "craftpreview")
2108                         {
2109                                 Inventory *inv = m_invmgr->getInventory(s.inventoryloc);
2110                                 InventoryList *list = inv->getList("craftresult");
2111                                 if(list && list->getSize() >= 1 && !list->getItem(0).empty())
2112                                 {
2113                                         m_selected_item = new ItemSpec;
2114                                         m_selected_item->inventoryloc = s.inventoryloc;
2115                                         m_selected_item->listname = "craftresult";
2116                                         m_selected_item->i = 0;
2117                                         m_selected_amount = 0;
2118                                         m_selected_dragging = false;
2119                                         break;
2120                                 }
2121                         }
2122                 }
2123         }
2124
2125         // If craftresult is selected, keep the whole stack selected
2126         if(m_selected_item && m_selected_item->listname == "craftresult")
2127         {
2128                 m_selected_amount = verifySelectedItem().count;
2129         }
2130 }
2131
2132 ItemStack GUIFormSpecMenu::verifySelectedItem()
2133 {
2134         // If the selected stack has become empty for some reason, deselect it.
2135         // If the selected stack has become inaccessible, deselect it.
2136         // If the selected stack has become smaller, adjust m_selected_amount.
2137         // Return the selected stack.
2138
2139         if(m_selected_item)
2140         {
2141                 if(m_selected_item->isValid())
2142                 {
2143                         Inventory *inv = m_invmgr->getInventory(m_selected_item->inventoryloc);
2144                         if(inv)
2145                         {
2146                                 InventoryList *list = inv->getList(m_selected_item->listname);
2147                                 if(list && (u32) m_selected_item->i < list->getSize())
2148                                 {
2149                                         ItemStack stack = list->getItem(m_selected_item->i);
2150                                         if(m_selected_amount > stack.count)
2151                                                 m_selected_amount = stack.count;
2152                                         if(!stack.empty())
2153                                                 return stack;
2154                                 }
2155                         }
2156                 }
2157
2158                 // selection was not valid
2159                 delete m_selected_item;
2160                 m_selected_item = NULL;
2161                 m_selected_amount = 0;
2162                 m_selected_dragging = false;
2163         }
2164         return ItemStack();
2165 }
2166
2167 void GUIFormSpecMenu::acceptInput(FormspecQuitMode quitmode=quit_mode_no)
2168 {
2169         if(m_text_dst)
2170         {
2171                 std::map<std::string, std::string> fields;
2172
2173                 if (quitmode == quit_mode_accept) {
2174                         fields["quit"] = "true";
2175                 }
2176
2177                 if (quitmode == quit_mode_cancel) {
2178                         fields["quit"] = "true";
2179                         m_text_dst->gotText(fields);
2180                         return;
2181                 }
2182
2183                 if (current_keys_pending.key_down) {
2184                         fields["key_down"] = "true";
2185                         current_keys_pending.key_down = false;
2186                 }
2187
2188                 if (current_keys_pending.key_up) {
2189                         fields["key_up"] = "true";
2190                         current_keys_pending.key_up = false;
2191                 }
2192
2193                 if (current_keys_pending.key_enter) {
2194                         fields["key_enter"] = "true";
2195                         current_keys_pending.key_enter = false;
2196                 }
2197
2198                 if (current_keys_pending.key_escape) {
2199                         fields["key_escape"] = "true";
2200                         current_keys_pending.key_escape = false;
2201                 }
2202
2203                 for(u32 i=0; i<m_fields.size(); i++)
2204                 {
2205                         const FieldSpec &s = m_fields[i];
2206                         if(s.send)
2207                         {
2208                                 if(s.ftype == f_Button)
2209                                 {
2210                                         fields[wide_to_narrow(s.fname.c_str())] = wide_to_narrow(s.flabel.c_str());
2211                                 }
2212                                 else if(s.ftype == f_Table) {
2213                                         GUITable *table = getTable(s.fname);
2214                                         if (table) {
2215                                                 fields[wide_to_narrow(s.fname.c_str())]
2216                                                         = table->checkEvent();
2217                                         }
2218                                 }
2219                                 else if(s.ftype == f_DropDown) {
2220                                         // no dynamic cast possible due to some distributions shipped
2221                                         // without rtti support in irrlicht
2222                                         IGUIElement * element = getElementFromId(s.fid);
2223                                         gui::IGUIComboBox *e = NULL;
2224                                         if ((element) && (element->getType() == gui::EGUIET_COMBO_BOX)) {
2225                                                 e = static_cast<gui::IGUIComboBox*>(element);
2226                                         }
2227                                         s32 selected = e->getSelected();
2228                                         if (selected >= 0) {
2229                                                 fields[wide_to_narrow(s.fname.c_str())] =
2230                                                         wide_to_narrow(e->getItem(selected));
2231                                         }
2232                                 }
2233                                 else if (s.ftype == f_TabHeader) {
2234                                         // no dynamic cast possible due to some distributions shipped
2235                                         // without rtti support in irrlicht
2236                                         IGUIElement * element = getElementFromId(s.fid);
2237                                         gui::IGUITabControl *e = NULL;
2238                                         if ((element) && (element->getType() == gui::EGUIET_TAB_CONTROL)) {
2239                                                 e = static_cast<gui::IGUITabControl*>(element);
2240                                         }
2241
2242                                         if (e != 0) {
2243                                                 std::stringstream ss;
2244                                                 ss << (e->getActiveTab() +1);
2245                                                 fields[wide_to_narrow(s.fname.c_str())] = ss.str();
2246                                         }
2247                                 }
2248                                 else if (s.ftype == f_CheckBox) {
2249                                         // no dynamic cast possible due to some distributions shipped
2250                                         // without rtti support in irrlicht
2251                                         IGUIElement * element = getElementFromId(s.fid);
2252                                         gui::IGUICheckBox *e = NULL;
2253                                         if ((element) && (element->getType() == gui::EGUIET_CHECK_BOX)) {
2254                                                 e = static_cast<gui::IGUICheckBox*>(element);
2255                                         }
2256
2257                                         if (e != 0) {
2258                                                 if (e->isChecked())
2259                                                         fields[wide_to_narrow(s.fname.c_str())] = "true";
2260                                                 else
2261                                                         fields[wide_to_narrow(s.fname.c_str())] = "false";
2262                                         }
2263                                 }
2264                                 else
2265                                 {
2266                                         IGUIElement* e = getElementFromId(s.fid);
2267                                         if(e != NULL)
2268                                         {
2269                                                 fields[wide_to_narrow(s.fname.c_str())] = wide_to_narrow(e->getText());
2270                                         }
2271                                 }
2272                         }
2273                 }
2274
2275                 m_text_dst->gotText(fields);
2276         }
2277 }
2278
2279 bool GUIFormSpecMenu::preprocessEvent(const SEvent& event)
2280 {
2281         // Fix Esc/Return key being eaten by checkboxen and tables
2282         if(event.EventType==EET_KEY_INPUT_EVENT)
2283         {
2284                 KeyPress kp(event.KeyInput);
2285                 if (kp == EscapeKey || kp == getKeySetting("keymap_inventory")
2286                                 || event.KeyInput.Key==KEY_RETURN)
2287                 {
2288                         gui::IGUIElement *focused = Environment->getFocus();
2289                         if (focused && isMyChild(focused) &&
2290                                         (focused->getType() == gui::EGUIET_LIST_BOX ||
2291                                          focused->getType() == gui::EGUIET_CHECK_BOX)) {
2292                                 OnEvent(event);
2293                                 return true;
2294                         }
2295                 }
2296         }
2297         // Mouse wheel events: send to hovered element instead of focused
2298         if(event.EventType==EET_MOUSE_INPUT_EVENT
2299                         && event.MouseInput.Event == EMIE_MOUSE_WHEEL)
2300         {
2301                 s32 x = event.MouseInput.X;
2302                 s32 y = event.MouseInput.Y;
2303                 gui::IGUIElement *hovered =
2304                         Environment->getRootGUIElement()->getElementFromPoint(
2305                                 core::position2d<s32>(x, y));
2306                 if (hovered && isMyChild(hovered)) {
2307                         hovered->OnEvent(event);
2308                         return true;
2309                 }
2310         }
2311         return false;
2312 }
2313
2314 bool GUIFormSpecMenu::OnEvent(const SEvent& event)
2315 {
2316         if(event.EventType==EET_KEY_INPUT_EVENT)
2317         {
2318                 KeyPress kp(event.KeyInput);
2319                 if (event.KeyInput.PressedDown && (kp == EscapeKey ||
2320                         kp == getKeySetting("keymap_inventory")))
2321                 {
2322                         if (m_allowclose){
2323                                 doPause = false;
2324                                 acceptInput(quit_mode_cancel);
2325                                 quitMenu();
2326                         } else {
2327                                 m_text_dst->gotText(narrow_to_wide("MenuQuit"));
2328                         }
2329                         return true;
2330                 }
2331                 if (event.KeyInput.PressedDown &&
2332                         (event.KeyInput.Key==KEY_RETURN ||
2333                          event.KeyInput.Key==KEY_UP ||
2334                          event.KeyInput.Key==KEY_DOWN)
2335                         ) {
2336
2337
2338                         switch (event.KeyInput.Key) {
2339                                 case KEY_RETURN:
2340                                         current_keys_pending.key_enter = true;
2341                                         break;
2342                                 case KEY_UP:
2343                                         current_keys_pending.key_up = true;
2344                                         break;
2345                                 case KEY_DOWN:
2346                                         current_keys_pending.key_down = true;
2347                                         break;
2348                                 break;
2349                                 default:
2350                                         //can't happen at all!
2351                                         assert("reached a source line that can't ever been reached" == 0);
2352                                         break;
2353                         }
2354                         if (current_keys_pending.key_enter && m_allowclose) {
2355                                 acceptInput(quit_mode_accept);
2356                                 quitMenu();
2357                         }
2358                         else {
2359                                 acceptInput();
2360                         }
2361                         return true;
2362                 }
2363
2364         }
2365         if(event.EventType==EET_MOUSE_INPUT_EVENT
2366                         && event.MouseInput.Event != EMIE_MOUSE_MOVED)
2367         {
2368                 // Mouse event other than movement
2369
2370                 // Get selected item and hovered/clicked item (s)
2371
2372                 updateSelectedItem();
2373                 ItemSpec s = getItemAtPos(m_pointer);
2374
2375                 Inventory *inv_selected = NULL;
2376                 Inventory *inv_s = NULL;
2377
2378                 if(m_selected_item)
2379                 {
2380                         inv_selected = m_invmgr->getInventory(m_selected_item->inventoryloc);
2381                         assert(inv_selected);
2382                         assert(inv_selected->getList(m_selected_item->listname) != NULL);
2383                 }
2384
2385                 u32 s_count = 0;
2386
2387                 if(s.isValid())
2388                 do{ // breakable
2389                         inv_s = m_invmgr->getInventory(s.inventoryloc);
2390
2391                         if(!inv_s){
2392                                 errorstream<<"InventoryMenu: The selected inventory location "
2393                                                 <<"\""<<s.inventoryloc.dump()<<"\" doesn't exist"
2394                                                 <<std::endl;
2395                                 s.i = -1;  // make it invalid again
2396                                 break;
2397                         }
2398
2399                         InventoryList *list = inv_s->getList(s.listname);
2400                         if(list == NULL){
2401                                 verbosestream<<"InventoryMenu: The selected inventory list \""
2402                                                 <<s.listname<<"\" does not exist"<<std::endl;
2403                                 s.i = -1;  // make it invalid again
2404                                 break;
2405                         }
2406
2407                         if((u32)s.i >= list->getSize()){
2408                                 infostream<<"InventoryMenu: The selected inventory list \""
2409                                                 <<s.listname<<"\" is too small (i="<<s.i<<", size="
2410                                                 <<list->getSize()<<")"<<std::endl;
2411                                 s.i = -1;  // make it invalid again
2412                                 break;
2413                         }
2414
2415                         s_count = list->getItem(s.i).count;
2416                 }while(0);
2417
2418                 bool identical = (m_selected_item != NULL) && s.isValid() &&
2419                         (inv_selected == inv_s) &&
2420                         (m_selected_item->listname == s.listname) &&
2421                         (m_selected_item->i == s.i);
2422
2423                 // buttons: 0 = left, 1 = right, 2 = middle
2424                 // up/down: 0 = down (press), 1 = up (release), 2 = unknown event
2425                 int button = 0;
2426                 int updown = 2;
2427                 if(event.MouseInput.Event == EMIE_LMOUSE_PRESSED_DOWN)
2428                         { button = 0; updown = 0; }
2429                 else if(event.MouseInput.Event == EMIE_RMOUSE_PRESSED_DOWN)
2430                         { button = 1; updown = 0; }
2431                 else if(event.MouseInput.Event == EMIE_MMOUSE_PRESSED_DOWN)
2432                         { button = 2; updown = 0; }
2433                 else if(event.MouseInput.Event == EMIE_LMOUSE_LEFT_UP)
2434                         { button = 0; updown = 1; }
2435                 else if(event.MouseInput.Event == EMIE_RMOUSE_LEFT_UP)
2436                         { button = 1; updown = 1; }
2437                 else if(event.MouseInput.Event == EMIE_MMOUSE_LEFT_UP)
2438                         { button = 2; updown = 1; }
2439
2440                 // Set this number to a positive value to generate a move action
2441                 // from m_selected_item to s.
2442                 u32 move_amount = 0;
2443
2444                 // Set this number to a positive value to generate a drop action
2445                 // from m_selected_item.
2446                 u32 drop_amount = 0;
2447
2448                 // Set this number to a positive value to generate a craft action at s.
2449                 u32 craft_amount = 0;
2450
2451                 if(updown == 0)
2452                 {
2453                         // Some mouse button has been pressed
2454
2455                         //infostream<<"Mouse button "<<button<<" pressed at p=("
2456                         //      <<p.X<<","<<p.Y<<")"<<std::endl;
2457
2458                         m_selected_dragging = false;
2459
2460                         if(s.isValid() && s.listname == "craftpreview")
2461                         {
2462                                 // Craft preview has been clicked: craft
2463                                 craft_amount = (button == 2 ? 10 : 1);
2464                         }
2465                         else if(m_selected_item == NULL)
2466                         {
2467                                 if(s_count != 0)
2468                                 {
2469                                         // Non-empty stack has been clicked: select it
2470                                         m_selected_item = new ItemSpec(s);
2471
2472                                         if(button == 1)  // right
2473                                                 m_selected_amount = (s_count + 1) / 2;
2474                                         else if(button == 2)  // middle
2475                                                 m_selected_amount = MYMIN(s_count, 10);
2476                                         else  // left
2477                                                 m_selected_amount = s_count;
2478
2479                                         m_selected_dragging = true;
2480                                 }
2481                         }
2482                         else  // m_selected_item != NULL
2483                         {
2484                                 assert(m_selected_amount >= 1);
2485
2486                                 if(s.isValid())
2487                                 {
2488                                         // Clicked a slot: move
2489                                         if(button == 1)  // right
2490                                                 move_amount = 1;
2491                                         else if(button == 2)  // middle
2492                                                 move_amount = MYMIN(m_selected_amount, 10);
2493                                         else  // left
2494                                                 move_amount = m_selected_amount;
2495
2496                                         if(identical)
2497                                         {
2498                                                 if(move_amount >= m_selected_amount)
2499                                                         m_selected_amount = 0;
2500                                                 else
2501                                                         m_selected_amount -= move_amount;
2502                                                 move_amount = 0;
2503                                         }
2504                                 }
2505                                 else if (!getAbsoluteClippingRect().isPointInside(m_pointer))
2506                                 {
2507                                         // Clicked outside of the window: drop
2508                                         if(button == 1)  // right
2509                                                 drop_amount = 1;
2510                                         else if(button == 2)  // middle
2511                                                 drop_amount = MYMIN(m_selected_amount, 10);
2512                                         else  // left
2513                                                 drop_amount = m_selected_amount;
2514                                 }
2515                         }
2516                 }
2517                 else if(updown == 1)
2518                 {
2519                         // Some mouse button has been released
2520
2521                         //infostream<<"Mouse button "<<button<<" released at p=("
2522                         //      <<p.X<<","<<p.Y<<")"<<std::endl;
2523
2524                         if(m_selected_item != NULL && m_selected_dragging && s.isValid())
2525                         {
2526                                 if(!identical)
2527                                 {
2528                                         // Dragged to different slot: move all selected
2529                                         move_amount = m_selected_amount;
2530                                 }
2531                         }
2532                         else if(m_selected_item != NULL && m_selected_dragging &&
2533                                 !(getAbsoluteClippingRect().isPointInside(m_pointer)))
2534                         {
2535                                 // Dragged outside of window: drop all selected
2536                                 drop_amount = m_selected_amount;
2537                         }
2538
2539                         m_selected_dragging = false;
2540                 }
2541
2542                 // Possibly send inventory action to server
2543                 if(move_amount > 0)
2544                 {
2545                         // Send IACTION_MOVE
2546
2547                         assert(m_selected_item && m_selected_item->isValid());
2548                         assert(s.isValid());
2549
2550                         assert(inv_selected && inv_s);
2551                         InventoryList *list_from = inv_selected->getList(m_selected_item->listname);
2552                         InventoryList *list_to = inv_s->getList(s.listname);
2553                         assert(list_from && list_to);
2554                         ItemStack stack_from = list_from->getItem(m_selected_item->i);
2555                         ItemStack stack_to = list_to->getItem(s.i);
2556
2557                         // Check how many items can be moved
2558                         move_amount = stack_from.count = MYMIN(move_amount, stack_from.count);
2559                         ItemStack leftover = stack_to.addItem(stack_from, m_gamedef->idef());
2560                         // If source stack cannot be added to destination stack at all,
2561                         // they are swapped
2562                         if(leftover.count == stack_from.count && leftover.name == stack_from.name)
2563                         {
2564                                 m_selected_amount = stack_to.count;
2565                                 // In case the server doesn't directly swap them but instead
2566                                 // moves stack_to somewhere else, set this
2567                                 m_selected_content_guess = stack_to;
2568                                 m_selected_content_guess_inventory = s.inventoryloc;
2569                         }
2570                         // Source stack goes fully into destination stack
2571                         else if(leftover.empty())
2572                         {
2573                                 m_selected_amount -= move_amount;
2574                                 m_selected_content_guess = ItemStack(); // Clear
2575                         }
2576                         // Source stack goes partly into destination stack
2577                         else
2578                         {
2579                                 move_amount -= leftover.count;
2580                                 m_selected_amount -= move_amount;
2581                                 m_selected_content_guess = ItemStack(); // Clear
2582                         }
2583
2584                         infostream<<"Handing IACTION_MOVE to manager"<<std::endl;
2585                         IMoveAction *a = new IMoveAction();
2586                         a->count = move_amount;
2587                         a->from_inv = m_selected_item->inventoryloc;
2588                         a->from_list = m_selected_item->listname;
2589                         a->from_i = m_selected_item->i;
2590                         a->to_inv = s.inventoryloc;
2591                         a->to_list = s.listname;
2592                         a->to_i = s.i;
2593                         m_invmgr->inventoryAction(a);
2594                 }
2595                 else if(drop_amount > 0)
2596                 {
2597                         m_selected_content_guess = ItemStack(); // Clear
2598
2599                         // Send IACTION_DROP
2600
2601                         assert(m_selected_item && m_selected_item->isValid());
2602                         assert(inv_selected);
2603                         InventoryList *list_from = inv_selected->getList(m_selected_item->listname);
2604                         assert(list_from);
2605                         ItemStack stack_from = list_from->getItem(m_selected_item->i);
2606
2607                         // Check how many items can be dropped
2608                         drop_amount = stack_from.count = MYMIN(drop_amount, stack_from.count);
2609                         assert(drop_amount > 0 && drop_amount <= m_selected_amount);
2610                         m_selected_amount -= drop_amount;
2611
2612                         infostream<<"Handing IACTION_DROP to manager"<<std::endl;
2613                         IDropAction *a = new IDropAction();
2614                         a->count = drop_amount;
2615                         a->from_inv = m_selected_item->inventoryloc;
2616                         a->from_list = m_selected_item->listname;
2617                         a->from_i = m_selected_item->i;
2618                         m_invmgr->inventoryAction(a);
2619                 }
2620                 else if(craft_amount > 0)
2621                 {
2622                         m_selected_content_guess = ItemStack(); // Clear
2623
2624                         // Send IACTION_CRAFT
2625
2626                         assert(s.isValid());
2627                         assert(inv_s);
2628
2629                         infostream<<"Handing IACTION_CRAFT to manager"<<std::endl;
2630                         ICraftAction *a = new ICraftAction();
2631                         a->count = craft_amount;
2632                         a->craft_inv = s.inventoryloc;
2633                         m_invmgr->inventoryAction(a);
2634                 }
2635
2636                 // If m_selected_amount has been decreased to zero, deselect
2637                 if(m_selected_amount == 0)
2638                 {
2639                         delete m_selected_item;
2640                         m_selected_item = NULL;
2641                         m_selected_amount = 0;
2642                         m_selected_dragging = false;
2643                         m_selected_content_guess = ItemStack();
2644                 }
2645         }
2646         if(event.EventType==EET_GUI_EVENT)
2647         {
2648
2649                 if(event.GUIEvent.EventType==gui::EGET_TAB_CHANGED
2650                                                 && isVisible())
2651                 {
2652                         // find the element that was clicked
2653                         for(u32 i=0; i<m_fields.size(); i++)
2654                         {
2655                                 FieldSpec &s = m_fields[i];
2656                                 // if its a button, set the send field so
2657                                 // lua knows which button was pressed
2658                                 if ((s.ftype == f_TabHeader) && (s.fid == event.GUIEvent.Caller->getID()))
2659                                 {
2660                                         s.send = true;
2661                                         acceptInput();
2662                                         s.send = false;
2663                                         return true;
2664                                 }
2665                         }
2666                 }
2667                 if(event.GUIEvent.EventType==gui::EGET_ELEMENT_FOCUS_LOST
2668                                 && isVisible())
2669                 {
2670                         if(!canTakeFocus(event.GUIEvent.Element))
2671                         {
2672                                 infostream<<"GUIFormSpecMenu: Not allowing focus change."
2673                                                 <<std::endl;
2674                                 // Returning true disables focus change
2675                                 return true;
2676                         }
2677                 }
2678                 if((event.GUIEvent.EventType==gui::EGET_BUTTON_CLICKED) ||
2679                                 (event.GUIEvent.EventType==gui::EGET_CHECKBOX_CHANGED))
2680                 {
2681                         unsigned int btn_id = event.GUIEvent.Caller->getID();
2682
2683                         if (btn_id == 257) {
2684                                 if (m_allowclose) {
2685                                         acceptInput(quit_mode_accept);
2686                                         quitMenu();
2687                                 } else {
2688                                         acceptInput();
2689                                         m_text_dst->gotText(narrow_to_wide("ExitButton"));
2690                                 }
2691                                 // quitMenu deallocates menu
2692                                 return true;
2693                         }
2694
2695                         // find the element that was clicked
2696                         for(u32 i=0; i<m_fields.size(); i++)
2697                         {
2698                                 FieldSpec &s = m_fields[i];
2699                                 // if its a button, set the send field so
2700                                 // lua knows which button was pressed
2701                                 if (((s.ftype == f_Button) || (s.ftype == f_CheckBox)) &&
2702                                                 (s.fid == event.GUIEvent.Caller->getID()))
2703                                 {
2704                                         s.send = true;
2705                                         acceptInput();
2706                                         if(s.is_exit){
2707                                                 if (m_allowclose) {
2708                                                         acceptInput(quit_mode_accept);
2709                                                         quitMenu();
2710                                                 } else {
2711                                                         m_text_dst->gotText(narrow_to_wide("ExitButton"));
2712                                                 }
2713                                                 return true;
2714                                         }else{
2715                                                 s.send = false;
2716                                                 return true;
2717                                         }
2718                                 }
2719                         }
2720                 }
2721                 if(event.GUIEvent.EventType==gui::EGET_EDITBOX_ENTER)
2722                 {
2723                         if(event.GUIEvent.Caller->getID() > 257)
2724                         {
2725
2726                                 if (m_allowclose) {
2727                                         acceptInput(quit_mode_accept);
2728                                         quitMenu();
2729                                 }
2730                                 else {
2731                                         current_keys_pending.key_enter = true;
2732                                         acceptInput();
2733                                 }
2734                                 // quitMenu deallocates menu
2735                                 return true;
2736                         }
2737                 }
2738
2739                 if(event.GUIEvent.EventType==gui::EGET_TABLE_CHANGED)
2740                 {
2741                         int current_id = event.GUIEvent.Caller->getID();
2742                         if(current_id > 257)
2743                         {
2744                                 // find the element that was clicked
2745                                 for(u32 i=0; i<m_fields.size(); i++)
2746                                 {
2747                                         FieldSpec &s = m_fields[i];
2748                                         // if it's a table, set the send field
2749                                         // so lua knows which table was changed
2750                                         if ((s.ftype == f_Table) && (s.fid == current_id))
2751                                         {
2752                                                 s.send = true;
2753                                                 acceptInput();
2754                                                 s.send=false;
2755                                         }
2756                                 }
2757                                 return true;
2758                         }
2759                 }
2760         }
2761
2762         return Parent ? Parent->OnEvent(event) : false;
2763 }
2764
2765 bool GUIFormSpecMenu::parseColor(const std::string &value, video::SColor &color,
2766                 bool quiet)
2767 {
2768         const char *hexpattern = NULL;
2769         if (value[0] == '#') {
2770                 if (value.size() == 9)
2771                         hexpattern = "#RRGGBBAA";
2772                 else if (value.size() == 7)
2773                         hexpattern = "#RRGGBB";
2774                 else if (value.size() == 5)
2775                         hexpattern = "#RGBA";
2776                 else if (value.size() == 4)
2777                         hexpattern = "#RGB";
2778         }
2779
2780         if (hexpattern) {
2781                 assert(strlen(hexpattern) == value.size());
2782                 video::SColor outcolor(255, 255, 255, 255);
2783                 for (size_t pos = 0; pos < value.size(); ++pos) {
2784                         // '#' in the pattern means skip that character
2785                         if (hexpattern[pos] == '#')
2786                                 continue;
2787
2788                         // Else assume hexpattern[pos] is one of 'R' 'G' 'B' 'A'
2789                         // Read one or two digits, depending on hexpattern
2790                         unsigned char c1, c2;
2791                         if (hexpattern[pos+1] == hexpattern[pos]) {
2792                                 // Two digits, e.g. hexpattern == "#RRGGBB"
2793                                 if (!hex_digit_decode(value[pos], c1) ||
2794                                     !hex_digit_decode(value[pos+1], c2))
2795                                         goto fail;
2796                                 ++pos;
2797                         }
2798                         else {
2799                                 // One digit, e.g. hexpattern == "#RGB"
2800                                 if (!hex_digit_decode(value[pos], c1))
2801                                         goto fail;
2802                                 c2 = c1;
2803                         }
2804                         u32 colorpart = ((c1 & 0x0f) << 4) | (c2 & 0x0f);
2805
2806                         // Update outcolor with newly read color part
2807                         if (hexpattern[pos] == 'R')
2808                                 outcolor.setRed(colorpart);
2809                         else if (hexpattern[pos] == 'G')
2810                                 outcolor.setGreen(colorpart);
2811                         else if (hexpattern[pos] == 'B')
2812                                 outcolor.setBlue(colorpart);
2813                         else if (hexpattern[pos] == 'A')
2814                                 outcolor.setAlpha(colorpart);
2815                 }
2816
2817                 color = outcolor;
2818                 return true;
2819         }
2820
2821         // Optionally, named colors could be implemented here
2822
2823 fail:
2824         if (!quiet)
2825                 errorstream<<"Invalid color: \""<<value<<"\""<<std::endl;
2826         return false;
2827 }