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