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