]> git.lizzy.rs Git - dragonfireclient.git/blob - src/guiFormSpecMenu.cpp
Fix spaces float islands code
[dragonfireclient.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
725                 if (str_initial_selection != "")
726                         e->setSelected(stoi(str_initial_selection.c_str())-1);
727
728                 m_listboxes.push_back(std::pair<FieldSpec,gui::IGUIListBox*>(spec,e));
729                 m_fields.push_back(spec);
730                 return;
731         }
732         errorstream<< "Invalid textlist element(" << parts.size() << "): '" << element << "'"  << std::endl;
733 }
734
735
736 void GUIFormSpecMenu::parseDropDown(parserData* data,std::string element) {
737         std::vector<std::string> parts = split(element,';');
738
739         if (parts.size() == 5) {
740                 std::vector<std::string> v_pos = split(parts[0],',');
741                 std::string name = parts[2];
742                 std::vector<std::string> items = split(parts[3],',');
743                 std::string str_initial_selection = "";
744                 str_initial_selection = parts[4];
745
746                 MY_CHECKPOS("dropdown",0);
747
748                 v2s32 pos = padding;
749                 pos.X += stof(v_pos[0]) * (float)spacing.X;
750                 pos.Y += stof(v_pos[1]) * (float)spacing.Y;
751
752                 s32 width = stof(parts[1]) * (float)spacing.Y;
753
754                 core::rect<s32> rect = core::rect<s32>(pos.X, pos.Y, pos.X+width, pos.Y+30);
755
756                 std::wstring fname_w = narrow_to_wide(name.c_str());
757
758                 FieldSpec spec = FieldSpec(
759                         fname_w,
760                         L"",
761                         L"",
762                         258+m_fields.size()
763                 );
764
765                 spec.ftype = f_DropDown;
766                 spec.send = true;
767
768                 //now really show list
769                 gui::IGUIComboBox *e = Environment->addComboBox(rect, this,spec.fid);
770
771                 if (spec.fname == data->focused_fieldname) {
772                         Environment->setFocus(e);
773                 }
774
775                 for (unsigned int i=0; i < items.size(); i++) {
776                         e->addItem(narrow_to_wide(items[i]).c_str());
777                 }
778
779                 if (str_initial_selection != "")
780                         e->setSelected(stoi(str_initial_selection.c_str())-1);
781
782                 m_fields.push_back(spec);
783                 return;
784         }
785         errorstream << "Invalid dropdown element(" << parts.size() << "): '"
786                                 << element << "'"  << std::endl;
787 }
788
789 void GUIFormSpecMenu::parsePwdField(parserData* data,std::string element) {
790         std::vector<std::string> parts = split(element,';');
791
792         if (parts.size() == 4) {
793                 std::vector<std::string> v_pos = split(parts[0],',');
794                 std::vector<std::string> v_geom = split(parts[1],',');
795                 std::string name = parts[2];
796                 std::string label = parts[3];
797
798                 MY_CHECKPOS("pwdfield",0);
799                 MY_CHECKGEOM("pwdfield",1);
800
801                 v2s32 pos;
802                 pos.X += stof(v_pos[0]) * (float)spacing.X;
803                 pos.Y += stof(v_pos[1]) * (float)spacing.Y;
804
805                 v2s32 geom;
806                 geom.X = (stof(v_geom[0]) * (float)spacing.X)-(spacing.X-imgsize.X);
807
808                 pos.Y += (stof(v_geom[1]) * (float)imgsize.Y)/2;
809                 pos.Y -= 15;
810                 geom.Y = 30;
811
812                 core::rect<s32> rect = core::rect<s32>(pos.X, pos.Y, pos.X+geom.X, pos.Y+geom.Y);
813
814                 label = unescape_string(label);
815
816                 std::wstring wlabel = narrow_to_wide(label.c_str());
817
818                 FieldSpec spec = FieldSpec(
819                         narrow_to_wide(name.c_str()),
820                         wlabel,
821                         L"",
822                         258+m_fields.size()
823                         );
824
825                 spec.send = true;
826                 gui::IGUIEditBox * e = Environment->addEditBox(0, rect, true, this, spec.fid);
827
828                 if (spec.fname == data->focused_fieldname) {
829                         Environment->setFocus(e);
830                 }
831
832                 if (label.length() > 1)
833                 {
834                         rect.UpperLeftCorner.Y -= 15;
835                         rect.LowerRightCorner.Y = rect.UpperLeftCorner.Y + 15;
836                         Environment->addStaticText(spec.flabel.c_str(), rect, false, true, this, 0);
837                 }
838
839                 e->setPasswordBox(true,L'*');
840
841                 irr::SEvent evt;
842                 evt.EventType            = EET_KEY_INPUT_EVENT;
843                 evt.KeyInput.Key         = KEY_END;
844                 evt.KeyInput.Char        = 0;
845                 evt.KeyInput.Control     = 0;
846                 evt.KeyInput.Shift       = 0;
847                 evt.KeyInput.PressedDown = true;
848                 e->OnEvent(evt);
849                 m_fields.push_back(spec);
850                 return;
851         }
852         errorstream<< "Invalid pwdfield element(" << parts.size() << "): '" << element << "'"  << std::endl;
853 }
854
855 void GUIFormSpecMenu::parseSimpleField(parserData* data,std::vector<std::string> &parts) {
856         std::string name = parts[0];
857         std::string label = parts[1];
858         std::string default_val = parts[2];
859
860         core::rect<s32> rect;
861
862         if(!data->bp_set)
863         {
864                 rect = core::rect<s32>(
865                         data->screensize.X/2 - 580/2,
866                         data->screensize.Y/2 - 300/2,
867                         data->screensize.X/2 + 580/2,
868                         data->screensize.Y/2 + 300/2
869                 );
870                 DesiredRect = rect;
871                 recalculateAbsolutePosition(false);
872                 data->basepos = getBasePos();
873                 data->bp_set = 1;
874         }
875         else if(data->bp_set == 2)
876                 errorstream<<"WARNING: invalid use of unpositioned \"field\" in inventory"<<std::endl;
877
878         v2s32 pos = padding + AbsoluteRect.UpperLeftCorner;
879         pos.Y = ((m_fields.size()+2)*60);
880         v2s32 size = DesiredRect.getSize();
881
882         rect = core::rect<s32>(size.X/2-150, pos.Y, (size.X/2-150)+300, pos.Y+30);
883
884
885         if(m_form_src)
886                 default_val = m_form_src->resolveText(default_val);
887
888         default_val = unescape_string(default_val);
889         label = unescape_string(label);
890
891         std::wstring wlabel = narrow_to_wide(label.c_str());
892
893         FieldSpec spec = FieldSpec(
894                 narrow_to_wide(name.c_str()),
895                 wlabel,
896                 narrow_to_wide(default_val.c_str()),
897                 258+m_fields.size()
898         );
899
900         if (name == "")
901         {
902                 // spec field id to 0, this stops submit searching for a value that isn't there
903                 Environment->addStaticText(spec.flabel.c_str(), rect, false, true, this, spec.fid);
904         }
905         else
906         {
907                 spec.send = true;
908                 gui::IGUIEditBox *e = Environment->addEditBox(spec.fdefault.c_str(), rect, true, this, spec.fid);
909
910                 if (spec.fname == data->focused_fieldname) {
911                         Environment->setFocus(e);
912                 }
913
914                 irr::SEvent evt;
915                 evt.EventType            = EET_KEY_INPUT_EVENT;
916                 evt.KeyInput.Key         = KEY_END;
917                 evt.KeyInput.Char        = 0;
918                 evt.KeyInput.Control     = 0;
919                 evt.KeyInput.Shift       = 0;
920                 evt.KeyInput.PressedDown = true;
921                 e->OnEvent(evt);
922
923                 if (label.length() > 1)
924                 {
925                         rect.UpperLeftCorner.Y -= 15;
926                         rect.LowerRightCorner.Y = rect.UpperLeftCorner.Y + 15;
927                         Environment->addStaticText(spec.flabel.c_str(), rect, false, true, this, 0);
928                 }
929         }
930
931         m_fields.push_back(spec);
932 }
933
934 void GUIFormSpecMenu::parseTextArea(parserData* data,std::vector<std::string>& parts,std::string type) {
935
936         std::vector<std::string> v_pos = split(parts[0],',');
937         std::vector<std::string> v_geom = split(parts[1],',');
938         std::string name = parts[2];
939         std::string label = parts[3];
940         std::string default_val = parts[4];
941
942         MY_CHECKPOS(type,0);
943         MY_CHECKGEOM(type,1);
944
945         v2s32 pos;
946         pos.X = stof(v_pos[0]) * (float) spacing.X;
947         pos.Y = stof(v_pos[1]) * (float) spacing.Y;
948
949         v2s32 geom;
950
951         geom.X = (stof(v_geom[0]) * (float)spacing.X)-(spacing.X-imgsize.X);
952
953         if (type == "textarea")
954         {
955                 geom.Y = (stof(v_geom[1]) * (float)imgsize.Y) - (spacing.Y-imgsize.Y);
956                 pos.Y += 15;
957         }
958         else
959         {
960                 pos.Y += (stof(v_geom[1]) * (float)imgsize.Y)/2;
961                 pos.Y -= 15;
962                 geom.Y = 30;
963         }
964
965         core::rect<s32> rect = core::rect<s32>(pos.X, pos.Y, pos.X+geom.X, pos.Y+geom.Y);
966
967         if(data->bp_set != 2)
968                 errorstream<<"WARNING: invalid use of positioned "<<type<<" without a size[] element"<<std::endl;
969
970         if(m_form_src)
971                 default_val = m_form_src->resolveText(default_val);
972
973
974         default_val = unescape_string(default_val);
975         label = unescape_string(label);
976
977         std::wstring wlabel = narrow_to_wide(label.c_str());
978
979         FieldSpec spec = FieldSpec(
980                 narrow_to_wide(name.c_str()),
981                 wlabel,
982                 narrow_to_wide(default_val.c_str()),
983                 258+m_fields.size()
984         );
985
986         if (name == "")
987         {
988                 // spec field id to 0, this stops submit searching for a value that isn't there
989                 Environment->addStaticText(spec.flabel.c_str(), rect, false, true, this, spec.fid);
990         }
991         else
992         {
993                 spec.send = true;
994                 gui::IGUIEditBox *e = Environment->addEditBox(spec.fdefault.c_str(), rect, true, this, spec.fid);
995
996                 if (spec.fname == data->focused_fieldname) {
997                         Environment->setFocus(e);
998                 }
999
1000                 if (type == "textarea")
1001                 {
1002                         e->setMultiLine(true);
1003                         e->setTextAlignment(gui::EGUIA_UPPERLEFT, gui::EGUIA_UPPERLEFT);
1004                 } else {
1005                         irr::SEvent evt;
1006                         evt.EventType            = EET_KEY_INPUT_EVENT;
1007                         evt.KeyInput.Key         = KEY_END;
1008                         evt.KeyInput.Char        = 0;
1009                         evt.KeyInput.Control     = 0;
1010                         evt.KeyInput.Shift       = 0;
1011                         evt.KeyInput.PressedDown = true;
1012                         e->OnEvent(evt);
1013                 }
1014
1015                 if (label.length() > 1)
1016                 {
1017                         rect.UpperLeftCorner.Y -= 15;
1018                         rect.LowerRightCorner.Y = rect.UpperLeftCorner.Y + 15;
1019                         Environment->addStaticText(spec.flabel.c_str(), rect, false, true, this, 0);
1020                 }
1021         }
1022         m_fields.push_back(spec);
1023 }
1024
1025 void GUIFormSpecMenu::parseField(parserData* data,std::string element,std::string type) {
1026         std::vector<std::string> parts = split(element,';');
1027
1028         if (parts.size() == 3) {
1029                 parseSimpleField(data,parts);
1030                 return;
1031         }
1032
1033         if (parts.size() == 5) {
1034                 parseTextArea(data,parts,type);
1035                 return;
1036         }
1037         errorstream<< "Invalid field element(" << parts.size() << "): '" << element << "'"  << std::endl;
1038 }
1039
1040 void GUIFormSpecMenu::parseLabel(parserData* data,std::string element) {
1041         std::vector<std::string> parts = split(element,';');
1042
1043         if (parts.size() == 2) {
1044                 std::vector<std::string> v_pos = split(parts[0],',');
1045                 std::string text = parts[1];
1046
1047                 MY_CHECKPOS("label",0);
1048
1049                 v2s32 pos = padding;
1050                 pos.X += stof(v_pos[0]) * (float)spacing.X;
1051                 pos.Y += stof(v_pos[1]) * (float)spacing.Y;
1052
1053                 core::rect<s32> rect = core::rect<s32>(pos.X, pos.Y+((imgsize.Y/2)-15), pos.X+300, pos.Y+((imgsize.Y/2)+15));
1054
1055                 if(data->bp_set != 2)
1056                         errorstream<<"WARNING: invalid use of label without a size[] element"<<std::endl;
1057
1058                 text = unescape_string(text);
1059
1060                 std::wstring wlabel = narrow_to_wide(text.c_str());
1061
1062                 FieldSpec spec = FieldSpec(
1063                         L"",
1064                         wlabel,
1065                         L"",
1066                         258+m_fields.size()
1067                 );
1068                 Environment->addStaticText(spec.flabel.c_str(), rect, false, true, this, spec.fid);
1069                 m_fields.push_back(spec);
1070                 return;
1071         }
1072         errorstream<< "Invalid label element(" << parts.size() << "): '" << element << "'"  << std::endl;
1073 }
1074
1075 void GUIFormSpecMenu::parseVertLabel(parserData* data,std::string element) {
1076         std::vector<std::string> parts = split(element,';');
1077
1078         if (parts.size() == 2) {
1079                 std::vector<std::string> v_pos = split(parts[0],',');
1080                 std::wstring text = narrow_to_wide(unescape_string(parts[1]));
1081
1082                 MY_CHECKPOS("vertlabel",1);
1083
1084                 v2s32 pos = padding;
1085                 pos.X += stof(v_pos[0]) * (float)spacing.X;
1086                 pos.Y += stof(v_pos[1]) * (float)spacing.Y;
1087
1088                 core::rect<s32> rect = core::rect<s32>(pos.X, pos.Y+((imgsize.Y/2)-15), pos.X+15, pos.Y+300);
1089
1090                 if(data->bp_set != 2)
1091                         errorstream<<"WARNING: invalid use of label without a size[] element"<<std::endl;
1092
1093                 std::wstring label = L"";
1094
1095                 for (unsigned int i=0; i < text.length(); i++) {
1096                         label += text[i];
1097                         label += L"\n";
1098                 }
1099
1100                 FieldSpec spec = FieldSpec(
1101                         L"",
1102                         label,
1103                         L"",
1104                         258+m_fields.size()
1105                 );
1106                 gui::IGUIStaticText *t =
1107                                 Environment->addStaticText(spec.flabel.c_str(), rect, false, true, this, spec.fid);
1108                 t->setTextAlignment(gui::EGUIA_CENTER, gui::EGUIA_CENTER);
1109                 m_fields.push_back(spec);
1110                 return;
1111         }
1112         errorstream<< "Invalid vertlabel element(" << parts.size() << "): '" << element << "'"  << std::endl;
1113 }
1114
1115 void GUIFormSpecMenu::parseImageButton(parserData* data,std::string element,std::string type) {
1116         std::vector<std::string> parts = split(element,';');
1117
1118         if ((parts.size() == 5) || (parts.size() == 7) || (parts.size() == 8)) {
1119                 std::vector<std::string> v_pos = split(parts[0],',');
1120                 std::vector<std::string> v_geom = split(parts[1],',');
1121                 std::string image_name = parts[2];
1122                 std::string name = parts[3];
1123                 std::string label = parts[4];
1124
1125                 MY_CHECKPOS("imagebutton",0);
1126                 MY_CHECKGEOM("imagebutton",1);
1127
1128                 v2s32 pos = padding;
1129                 pos.X += stof(v_pos[0]) * (float)spacing.X;
1130                 pos.Y += stof(v_pos[1]) * (float)spacing.Y;
1131                 v2s32 geom;
1132                 geom.X = (stof(v_geom[0]) * (float)spacing.X)-(spacing.X-imgsize.X);
1133                 geom.Y = (stof(v_geom[1]) * (float)spacing.Y)-(spacing.Y-imgsize.Y);
1134
1135                 bool noclip = false;
1136                 bool drawborder = true;
1137
1138                 if ((parts.size() >= 7)) {
1139                         if (parts[5] == "true")
1140                                 noclip = true;
1141
1142                         if (parts[6] == "false")
1143                                 drawborder = false;
1144                 }
1145                 
1146                 std::string pressed_image_name = "";
1147                 
1148                 if ((parts.size() == 8)) {
1149                         pressed_image_name = parts[7];
1150                 }
1151
1152                 core::rect<s32> rect = core::rect<s32>(pos.X, pos.Y, pos.X+geom.X, pos.Y+geom.Y);
1153
1154                 if(data->bp_set != 2)
1155                         errorstream<<"WARNING: invalid use of image_button without a size[] element"<<std::endl;
1156
1157                 image_name = unescape_string(image_name);
1158                 pressed_image_name = unescape_string(pressed_image_name);
1159                 label = unescape_string(label);
1160
1161                 std::wstring wlabel = narrow_to_wide(label.c_str());
1162
1163                 FieldSpec spec = FieldSpec(
1164                         narrow_to_wide(name.c_str()),
1165                         wlabel,
1166                         narrow_to_wide(image_name.c_str()),
1167                         258+m_fields.size()
1168                 );
1169                 spec.ftype = f_Button;
1170                 if(type == "image_button_exit")
1171                         spec.is_exit = true;
1172
1173                 video::ITexture *texture = 0;
1174                 video::ITexture *pressed_texture = 0;
1175                 texture = m_tsrc->getTexture(image_name);
1176                 if (parts.size() == 8)
1177                         pressed_texture = m_tsrc->getTexture(pressed_image_name);
1178                 else
1179                         pressed_texture = texture;
1180
1181                 gui::IGUIButton *e = Environment->addButton(rect, this, spec.fid, spec.flabel.c_str());
1182
1183                 if (spec.fname == data->focused_fieldname) {
1184                         Environment->setFocus(e);
1185                 }
1186
1187                 e->setUseAlphaChannel(true);
1188                 e->setImage(texture);
1189                 e->setPressedImage(pressed_texture);
1190                 e->setScaleImage(true);
1191                 e->setNotClipped(noclip);
1192                 e->setDrawBorder(drawborder);
1193
1194                 m_fields.push_back(spec);
1195                 return;
1196         }
1197
1198         errorstream<< "Invalid imagebutton element(" << parts.size() << "): '" << element << "'"  << std::endl;
1199 }
1200
1201 void GUIFormSpecMenu::parseTabHeader(parserData* data,std::string element) {
1202         std::vector<std::string> parts = split(element,';');
1203
1204         if ((parts.size() == 4) || (parts.size() == 6)) {
1205                 std::vector<std::string> v_pos = split(parts[0],',');
1206                 std::string name = parts[1];
1207                 std::vector<std::string> buttons = split(parts[2],',');
1208                 std::string str_index = parts[3];
1209                 bool show_background = true;
1210                 bool show_border = true;
1211                 int tab_index = stoi(str_index) -1;
1212
1213                 MY_CHECKPOS("tabheader",0);
1214
1215                 if (parts.size() == 6) {
1216                         if (parts[4] == "true")
1217                                 show_background = false;
1218                         if (parts[5] == "false")
1219                                 show_border = false;
1220                 }
1221
1222                 FieldSpec spec = FieldSpec(
1223                         narrow_to_wide(name.c_str()),
1224                         L"",
1225                         L"",
1226                         258+m_fields.size()
1227                 );
1228
1229                 spec.ftype = f_TabHeader;
1230
1231                 v2s32 pos = padding;
1232                 pos.X += stof(v_pos[0]) * (float)spacing.X;
1233                 pos.Y += stof(v_pos[1]) * (float)spacing.Y;
1234                 v2s32 geom;
1235                 geom.X = data->screensize.Y;
1236                 geom.Y = 30;
1237
1238                 core::rect<s32> rect = core::rect<s32>(pos.X, pos.Y, pos.X+geom.X, pos.Y+geom.Y);
1239
1240                 gui::IGUITabControl *e = Environment->addTabControl(rect,this,show_background,show_border,spec.fid);
1241
1242                 if (spec.fname == data->focused_fieldname) {
1243                         Environment->setFocus(e);
1244                 }
1245
1246                 e->setNotClipped(true);
1247
1248                 for (unsigned int i=0; i< buttons.size(); i++) {
1249                         wchar_t* wbutton = 0;
1250
1251                         std::wstring wlabel = narrow_to_wide(buttons[i]); //Needed for displaying text on windows
1252                         wbutton = (wchar_t*) wlabel.c_str();
1253
1254                         e->addTab(wbutton,-1);
1255                 }
1256
1257                 if ((tab_index >= 0) &&
1258                                 (buttons.size() < INT_MAX) &&
1259                                 (tab_index < (int) buttons.size()))
1260                         e->setActiveTab(tab_index);
1261
1262                 m_fields.push_back(spec);
1263                 return;
1264         }
1265         errorstream<< "Invalid TabHeader element(" << parts.size() << "): '" << element << "'"  << std::endl;
1266 }
1267
1268 void GUIFormSpecMenu::parseItemImageButton(parserData* data,std::string element) {
1269
1270         if (m_gamedef == 0) {
1271                 errorstream<<"WARNING: invalid use of item_image_button with m_gamedef==0"<<std::endl;
1272                 return;
1273         }
1274
1275         std::vector<std::string> parts = split(element,';');
1276
1277         if (parts.size() == 5) {
1278                 std::vector<std::string> v_pos = split(parts[0],',');
1279                 std::vector<std::string> v_geom = split(parts[1],',');
1280                 std::string item_name = parts[2];
1281                 std::string name = parts[3];
1282                 std::string label = parts[4];
1283
1284                 MY_CHECKPOS("itemimagebutton",0);
1285                 MY_CHECKGEOM("itemimagebutton",1);
1286
1287                 v2s32 pos = padding;
1288                 pos.X += stof(v_pos[0]) * (float)spacing.X;
1289                 pos.Y += stof(v_pos[1]) * (float)spacing.Y;
1290                 v2s32 geom;
1291                 geom.X = (stof(v_geom[0]) * (float)spacing.X)-(spacing.X-imgsize.X);
1292                 geom.Y = (stof(v_geom[1]) * (float)spacing.Y)-(spacing.Y-imgsize.Y);
1293
1294                 core::rect<s32> rect = core::rect<s32>(pos.X, pos.Y, pos.X+geom.X, pos.Y+geom.Y);
1295
1296                 if(data->bp_set != 2)
1297                         errorstream<<"WARNING: invalid use of item_image_button without a size[] element"<<std::endl;
1298
1299                 IItemDefManager *idef = m_gamedef->idef();
1300                 ItemStack item;
1301                 item.deSerialize(item_name, idef);
1302                 video::ITexture *texture = idef->getInventoryTexture(item.getDefinition(idef).name, m_gamedef);
1303                 std::string tooltip = item.getDefinition(idef).description;
1304
1305                 label = unescape_string(label);
1306                 FieldSpec spec = FieldSpec(
1307                         narrow_to_wide(name.c_str()),
1308                         narrow_to_wide(label.c_str()),
1309                         narrow_to_wide(item_name.c_str()),
1310                         258+m_fields.size()
1311                 );
1312
1313                 gui::IGUIButton *e = Environment->addButton(rect, this, spec.fid, spec.flabel.c_str());
1314
1315                 if (spec.fname == data->focused_fieldname) {
1316                         Environment->setFocus(e);
1317                 }
1318
1319                 e->setUseAlphaChannel(true);
1320                 e->setImage(texture);
1321                 e->setPressedImage(texture);
1322                 e->setScaleImage(true);
1323                 spec.ftype = f_Button;
1324                 rect+=data->basepos-padding;
1325                 spec.rect=rect;
1326                 if (tooltip!="")
1327                         spec.tooltip=tooltip;
1328                 m_fields.push_back(spec);
1329                 return;
1330         }
1331         errorstream<< "Invalid ItemImagebutton element(" << parts.size() << "): '" << element << "'"  << std::endl;
1332 }
1333
1334 void GUIFormSpecMenu::parseBox(parserData* data,std::string element) {
1335         std::vector<std::string> parts = split(element,';');
1336
1337         if (parts.size() == 3) {
1338                 std::vector<std::string> v_pos = split(parts[0],',');
1339                 std::vector<std::string> v_geom = split(parts[1],',');
1340
1341                 MY_CHECKPOS("box",0);
1342                 MY_CHECKGEOM("box",1);
1343
1344                 v2s32 pos = padding + AbsoluteRect.UpperLeftCorner;
1345                 pos.X += stof(v_pos[0]) * (float) spacing.X;
1346                 pos.Y += stof(v_pos[1]) * (float) spacing.Y;
1347
1348                 v2s32 geom;
1349                 geom.X = stof(v_geom[0]) * (float)spacing.X;
1350                 geom.Y = stof(v_geom[1]) * (float)spacing.Y;
1351
1352                 video::SColor tmp_color;
1353
1354                 if (parseColor(parts[2], tmp_color, false)) {
1355                         BoxDrawSpec spec(pos, geom, tmp_color);
1356
1357                         m_boxes.push_back(spec);
1358                 }
1359                 else {
1360                         errorstream<< "Invalid Box element(" << parts.size() << "): '" << element << "'  INVALID COLOR"  << std::endl;
1361                 }
1362                 return;
1363         }
1364         errorstream<< "Invalid Box element(" << parts.size() << "): '" << element << "'"  << std::endl;
1365 }
1366
1367 void GUIFormSpecMenu::parseBackgroundColor(parserData* data,std::string element) {
1368         std::vector<std::string> parts = split(element,';');
1369
1370         if ((parts.size() == 1) || (parts.size() == 2)) {
1371                 parseColor(parts[0],m_bgcolor,false);
1372
1373                 if (parts.size() == 2) {
1374                         std::string fullscreen = parts[1];
1375                         m_bgfullscreen = is_yes(fullscreen);
1376                 }
1377                 return;
1378         }
1379         errorstream<< "Invalid bgcolor element(" << parts.size() << "): '" << element << "'"  << std::endl;
1380 }
1381
1382 void GUIFormSpecMenu::parseListColors(parserData* data,std::string element) {
1383         std::vector<std::string> parts = split(element,';');
1384
1385         if ((parts.size() == 2) || (parts.size() == 3) || (parts.size() == 5)) {
1386                 parseColor(parts[0], m_slotbg_n, false);
1387                 parseColor(parts[1], m_slotbg_h, false);
1388                 
1389                 if (parts.size() >= 3) {
1390                         if (parseColor(parts[2], m_slotbordercolor, false)) {
1391                                 m_slotborder = true;
1392                         }
1393                 }
1394                 if (parts.size() == 5) {
1395                         video::SColor tmp_color;
1396
1397                         if (parseColor(parts[3], tmp_color, false))
1398                                 m_tooltip_element->setBackgroundColor(tmp_color);
1399                         if (parseColor(parts[4], tmp_color, false))
1400                                 m_tooltip_element->setOverrideColor(tmp_color);
1401                 }
1402                 return;
1403         }
1404         errorstream<< "Invalid listcolors element(" << parts.size() << "): '" << element << "'"  << std::endl;
1405 }
1406
1407 void GUIFormSpecMenu::parseElement(parserData* data,std::string element) {
1408
1409         //some prechecks
1410         if (element == "")
1411                 return;
1412
1413         std::vector<std::string> parts = split(element,'[');
1414
1415         // ugly workaround to keep compatibility
1416         if (parts.size() > 2) {
1417                 if (trim(parts[0]) == "image") {
1418                         for (unsigned int i=2;i< parts.size(); i++) {
1419                                 parts[1] += "[" + parts[i];
1420                         }
1421                 }
1422                 else { return; }
1423         }
1424
1425         if (parts.size() < 2) {
1426                 return;
1427         }
1428
1429         std::string type = trim(parts[0]);
1430         std::string description = trim(parts[1]);
1431
1432         if ((type == "size") || (type == "invsize")){
1433                 parseSize(data,description);
1434                 return;
1435         }
1436
1437         if (type == "list") {
1438                 parseList(data,description);
1439                 return;
1440         }
1441
1442         if (type == "checkbox") {
1443                 parseCheckbox(data,description);
1444                 return;
1445         }
1446
1447         if (type == "image") {
1448                 parseImage(data,description);
1449                 return;
1450         }
1451
1452         if (type == "item_image") {
1453                 parseItemImage(data,description);
1454                 return;
1455         }
1456
1457         if ((type == "button") || (type == "button_exit")) {
1458                 parseButton(data,description,type);
1459                 return;
1460         }
1461
1462         if (type == "background") {
1463                 parseBackground(data,description);
1464                 return;
1465         }
1466
1467         if (type == "textlist"){
1468                 parseTextList(data,description);
1469                 return;
1470         }
1471
1472         if (type == "dropdown"){
1473                 parseDropDown(data,description);
1474                 return;
1475         }
1476
1477         if (type == "pwdfield") {
1478                 parsePwdField(data,description);
1479                 return;
1480         }
1481
1482         if ((type == "field") || (type == "textarea")){
1483                 parseField(data,description,type);
1484                 return;
1485         }
1486
1487         if (type == "label") {
1488                 parseLabel(data,description);
1489                 return;
1490         }
1491
1492         if (type == "vertlabel") {
1493                 parseVertLabel(data,description);
1494                 return;
1495         }
1496
1497         if (type == "item_image_button") {
1498                 parseItemImageButton(data,description);
1499                 return;
1500         }
1501
1502         if ((type == "image_button") || (type == "image_button_exit")) {
1503                 parseImageButton(data,description,type);
1504                 return;
1505         }
1506
1507         if (type == "tabheader") {
1508                 parseTabHeader(data,description);
1509                 return;
1510         }
1511
1512         if (type == "box") {
1513                 parseBox(data,description);
1514                 return;
1515         }
1516
1517         if (type == "bgcolor") {
1518                 parseBackgroundColor(data,description);
1519                 return;
1520         }
1521
1522         if (type == "listcolors") {
1523                 parseListColors(data,description);
1524                 return;
1525         }
1526
1527         // Ignore others
1528         infostream
1529                 << "Unknown DrawSpec: type="<<type<<", data=\""<<description<<"\""
1530                 <<std::endl;
1531 }
1532
1533
1534
1535 void GUIFormSpecMenu::regenerateGui(v2u32 screensize)
1536 {
1537         parserData mydata;
1538
1539         //preserve listboxes
1540         for (unsigned int i = 0; i < m_listboxes.size(); i++) {
1541                 std::wstring listboxname = m_listboxes[i].first.fname;
1542                 gui::IGUIListBox *listbox = m_listboxes[i].second;
1543
1544                 int selection = listbox->getSelected();
1545                 if (selection != -1) {
1546                         mydata.listbox_selections[listboxname] = selection;
1547                 }
1548
1549                 gui::IGUIScrollBar *scrollbar = getListboxScrollbar(listbox);
1550                 if (scrollbar) {
1551                         mydata.listbox_scroll[listboxname] = scrollbar->getPos();
1552                 }
1553         }
1554
1555         //preserve focus
1556         gui::IGUIElement *focused_element = Environment->getFocus();
1557         if (focused_element && focused_element->getParent() == this) {
1558                 s32 focused_id = focused_element->getID();
1559                 if (focused_id > 257) {
1560                         for (u32 i=0; i<m_fields.size(); i++) {
1561                                 if (m_fields[i].fid == focused_id) {
1562                                         mydata.focused_fieldname =
1563                                                 m_fields[i].fname;
1564                                         break;
1565                                 }
1566                         }
1567                 }
1568         }
1569
1570         // Remove children
1571         removeChildren();
1572
1573         mydata.size= v2s32(100,100);
1574         mydata.helptext_h = 15;
1575         mydata.screensize = screensize;
1576
1577         // Base position of contents of form
1578         mydata.basepos = getBasePos();
1579
1580         // State of basepos, 0 = not set, 1= set by formspec, 2 = set by size[] element
1581         // Used to adjust form size automatically if needed
1582         // A proceed button is added if there is no size[] element
1583         mydata.bp_set = 0;
1584
1585         
1586         /* Convert m_init_draw_spec to m_inventorylists */
1587         
1588         m_inventorylists.clear();
1589         m_images.clear();
1590         m_backgrounds.clear();
1591         m_itemimages.clear();
1592         m_listboxes.clear();
1593         m_checkboxes.clear();
1594         m_fields.clear();
1595         m_boxes.clear();
1596
1597         // Set default values (fits old formspec values)
1598         m_bgcolor = video::SColor(140,0,0,0);
1599         m_bgfullscreen = false;
1600
1601         m_slotbg_n = video::SColor(255,128,128,128);
1602         m_slotbg_h = video::SColor(255,192,192,192);
1603
1604         m_slotbordercolor = video::SColor(200,0,0,0);
1605         m_slotborder = false;
1606
1607         m_clipbackground = false;
1608         // Add tooltip
1609         {
1610                 // Note: parent != this so that the tooltip isn't clipped by the menu rectangle
1611                 m_tooltip_element = Environment->addStaticText(L"",core::rect<s32>(0,0,110,18));
1612                 m_tooltip_element->enableOverrideColor(true);
1613                 m_tooltip_element->setBackgroundColor(video::SColor(255,110,130,60));
1614                 m_tooltip_element->setDrawBackground(true);
1615                 m_tooltip_element->setDrawBorder(true);
1616                 m_tooltip_element->setOverrideColor(video::SColor(255,255,255,255));
1617                 m_tooltip_element->setTextAlignment(gui::EGUIA_CENTER, gui::EGUIA_CENTER);
1618                 m_tooltip_element->setWordWrap(false);
1619                 //we're not parent so no autograb for this one!
1620                 m_tooltip_element->grab();
1621         }
1622
1623
1624         std::vector<std::string> elements = split(m_formspec_string,']');
1625
1626         for (unsigned int i=0;i< elements.size();i++) {
1627                 parseElement(&mydata,elements[i]);
1628         }
1629
1630         // If there's fields, add a Proceed button
1631         if (m_fields.size() && mydata.bp_set != 2)
1632         {
1633                 // if the size wasn't set by an invsize[] or size[] adjust it now to fit all the fields
1634                 mydata.rect = core::rect<s32>(
1635                                 mydata.screensize.X/2 - 580/2,
1636                                 mydata.screensize.Y/2 - 300/2,
1637                                 mydata.screensize.X/2 + 580/2,
1638                                 mydata.screensize.Y/2 + 240/2+(m_fields.size()*60)
1639                 );
1640                 DesiredRect = mydata.rect;
1641                 recalculateAbsolutePosition(false);
1642                 mydata.basepos = getBasePos();
1643
1644                 changeCtype("");
1645                 {
1646                         v2s32 pos = mydata.basepos;
1647                         pos.Y = ((m_fields.size()+2)*60);
1648
1649                         v2s32 size = DesiredRect.getSize();
1650                         mydata.rect = core::rect<s32>(size.X/2-70, pos.Y, (size.X/2-70)+140, pos.Y+30);
1651                         wchar_t* text = wgettext("Proceed");
1652                         Environment->addButton(mydata.rect, this, 257, text);
1653                         delete[] text;
1654                 }
1655                 changeCtype("C");
1656         }
1657
1658         //set initial focus if parser didn't set it
1659         focused_element = Environment->getFocus();
1660         if (!focused_element
1661                         || !isMyChild(focused_element)
1662                         || focused_element->getType() == gui::EGUIET_TAB_CONTROL)
1663                 setInitialFocus();
1664 }
1665
1666 GUIFormSpecMenu::ItemSpec GUIFormSpecMenu::getItemAtPos(v2s32 p) const
1667 {
1668         core::rect<s32> imgrect(0,0,imgsize.X,imgsize.Y);
1669         
1670         for(u32 i=0; i<m_inventorylists.size(); i++)
1671         {
1672                 const ListDrawSpec &s = m_inventorylists[i];
1673
1674                 for(s32 i=0; i<s.geom.X*s.geom.Y; i++)
1675                 {
1676                         s32 item_i = i + s.start_item_i;
1677                         s32 x = (i%s.geom.X) * spacing.X;
1678                         s32 y = (i/s.geom.X) * spacing.Y;
1679                         v2s32 p0(x,y);
1680                         core::rect<s32> rect = imgrect + s.pos + p0;
1681                         if(rect.isPointInside(p))
1682                         {
1683                                 return ItemSpec(s.inventoryloc, s.listname, item_i);
1684                         }
1685                 }
1686         }
1687
1688         return ItemSpec(InventoryLocation(), "", -1);
1689 }
1690
1691 void GUIFormSpecMenu::drawList(const ListDrawSpec &s, int phase)
1692 {
1693         video::IVideoDriver* driver = Environment->getVideoDriver();
1694
1695         // Get font
1696         gui::IGUIFont *font = NULL;
1697         gui::IGUISkin* skin = Environment->getSkin();
1698         if (skin)
1699                 font = skin->getFont();
1700         
1701         Inventory *inv = m_invmgr->getInventory(s.inventoryloc);
1702         if(!inv){
1703                 infostream<<"GUIFormSpecMenu::drawList(): WARNING: "
1704                                 <<"The inventory location "
1705                                 <<"\""<<s.inventoryloc.dump()<<"\" doesn't exist"
1706                                 <<std::endl;
1707                 return;
1708         }
1709         InventoryList *ilist = inv->getList(s.listname);
1710         if(!ilist){
1711                 infostream<<"GUIFormSpecMenu::drawList(): WARNING: "
1712                                 <<"The inventory list \""<<s.listname<<"\" @ \""
1713                                 <<s.inventoryloc.dump()<<"\" doesn't exist"
1714                                 <<std::endl;
1715                 return;
1716         }
1717         
1718         core::rect<s32> imgrect(0,0,imgsize.X,imgsize.Y);
1719         
1720         for(s32 i=0; i<s.geom.X*s.geom.Y; i++)
1721         {
1722                 s32 item_i = i + s.start_item_i;
1723                 if(item_i >= (s32) ilist->getSize())
1724                         break;
1725                 s32 x = (i%s.geom.X) * spacing.X;
1726                 s32 y = (i/s.geom.X) * spacing.Y;
1727                 v2s32 p(x,y);
1728                 core::rect<s32> rect = imgrect + s.pos + p;
1729                 ItemStack item;
1730                 if(ilist)
1731                         item = ilist->getItem(item_i);
1732
1733                 bool selected = m_selected_item
1734                         && m_invmgr->getInventory(m_selected_item->inventoryloc) == inv
1735                         && m_selected_item->listname == s.listname
1736                         && m_selected_item->i == item_i;
1737                 bool hovering = rect.isPointInside(m_pointer);
1738
1739                 if(phase == 0)
1740                 {
1741                         if(hovering)
1742                                 driver->draw2DRectangle(m_slotbg_h, rect, &AbsoluteClippingRect);
1743                         else
1744                                 driver->draw2DRectangle(m_slotbg_n, rect, &AbsoluteClippingRect);
1745                 }
1746
1747                 //Draw inv slot borders
1748                 if (m_slotborder) {
1749                         s32 x1 = rect.UpperLeftCorner.X;
1750                         s32 y1 = rect.UpperLeftCorner.Y;
1751                         s32 x2 = rect.LowerRightCorner.X;
1752                         s32 y2 = rect.LowerRightCorner.Y;
1753                         s32 border = 1;
1754                         driver->draw2DRectangle(m_slotbordercolor,
1755                                 core::rect<s32>(v2s32(x1 - border, y1 - border),
1756                                                                 v2s32(x2 + border, y1)), NULL);
1757                         driver->draw2DRectangle(m_slotbordercolor,
1758                                 core::rect<s32>(v2s32(x1 - border, y2),
1759                                                                 v2s32(x2 + border, y2 + border)), NULL);
1760                         driver->draw2DRectangle(m_slotbordercolor,
1761                                 core::rect<s32>(v2s32(x1 - border, y1),
1762                                                                 v2s32(x1, y2)), NULL);
1763                         driver->draw2DRectangle(m_slotbordercolor,
1764                                 core::rect<s32>(v2s32(x2, y1),
1765                                                                 v2s32(x2 + border, y2)), NULL);
1766                 }
1767
1768                 if(phase == 1)
1769                 {
1770                         // Draw item stack
1771                         if(selected)
1772                         {
1773                                 item.takeItem(m_selected_amount);
1774                         }
1775                         if(!item.empty())
1776                         {
1777                                 drawItemStack(driver, font, item,
1778                                                 rect, &AbsoluteClippingRect, m_gamedef);
1779                         }
1780
1781                         // Draw tooltip
1782                         std::string tooltip_text = "";
1783                         if(hovering && !m_selected_item)
1784                                 tooltip_text = item.getDefinition(m_gamedef->idef()).description;
1785                         if(tooltip_text != "")
1786                         {
1787                                 m_tooltip_element->setVisible(true);
1788                                 this->bringToFront(m_tooltip_element);
1789                                 m_tooltip_element->setText(narrow_to_wide(tooltip_text).c_str());
1790                                 s32 tooltip_x = m_pointer.X + 15;
1791                                 s32 tooltip_y = m_pointer.Y + 15;
1792                                 s32 tooltip_width = m_tooltip_element->getTextWidth() + 15;
1793                                 s32 tooltip_height = m_tooltip_element->getTextHeight() + 5;
1794                                 m_tooltip_element->setRelativePosition(core::rect<s32>(
1795                                                 core::position2d<s32>(tooltip_x, tooltip_y),
1796                                                 core::dimension2d<s32>(tooltip_width, tooltip_height)));
1797                         }
1798                 }
1799         }
1800 }
1801
1802 void GUIFormSpecMenu::drawSelectedItem()
1803 {
1804         if(!m_selected_item)
1805                 return;
1806
1807         video::IVideoDriver* driver = Environment->getVideoDriver();
1808
1809         // Get font
1810         gui::IGUIFont *font = NULL;
1811         gui::IGUISkin* skin = Environment->getSkin();
1812         if (skin)
1813                 font = skin->getFont();
1814         
1815         Inventory *inv = m_invmgr->getInventory(m_selected_item->inventoryloc);
1816         assert(inv);
1817         InventoryList *list = inv->getList(m_selected_item->listname);
1818         assert(list);
1819         ItemStack stack = list->getItem(m_selected_item->i);
1820         stack.count = m_selected_amount;
1821
1822         core::rect<s32> imgrect(0,0,imgsize.X,imgsize.Y);
1823         core::rect<s32> rect = imgrect + (m_pointer - imgrect.getCenter());
1824         drawItemStack(driver, font, stack, rect, NULL, m_gamedef);
1825 }
1826
1827 void GUIFormSpecMenu::drawMenu()
1828 {
1829         if(m_form_src){
1830                 std::string newform = m_form_src->getForm();
1831                 if(newform != m_formspec_string){
1832                         m_formspec_string = newform;
1833                         regenerateGui(m_screensize_old);
1834                 }
1835         }
1836
1837         m_pointer = m_device->getCursorControl()->getPosition();
1838
1839         updateSelectedItem();
1840
1841         gui::IGUISkin* skin = Environment->getSkin();
1842         if (!skin)
1843                 return;
1844         video::IVideoDriver* driver = Environment->getVideoDriver();
1845         
1846         v2u32 screenSize = driver->getScreenSize();
1847         core::rect<s32> allbg(0, 0, screenSize.X ,      screenSize.Y);
1848         if (m_bgfullscreen) 
1849                 driver->draw2DRectangle(m_bgcolor, allbg, &allbg);
1850         else
1851                 driver->draw2DRectangle(m_bgcolor, AbsoluteRect, &AbsoluteClippingRect);
1852
1853         m_tooltip_element->setVisible(false);
1854
1855         /*
1856                 Draw backgrounds
1857         */
1858         for(u32 i=0; i<m_backgrounds.size(); i++)
1859         {
1860                 const ImageDrawSpec &spec = m_backgrounds[i];
1861                 video::ITexture *texture = m_tsrc->getTexture(spec.name);
1862
1863                 if (texture != 0) {
1864                         // Image size on screen
1865                         core::rect<s32> imgrect(0, 0, spec.geom.X, spec.geom.Y);
1866                         // Image rectangle on screen
1867                         core::rect<s32> rect = imgrect + spec.pos;
1868
1869                         if (m_clipbackground) {
1870                                 core::dimension2d<s32> absrec_size = AbsoluteRect.getSize();
1871                                 rect = core::rect<s32>(AbsoluteRect.UpperLeftCorner.X - spec.pos.X,
1872                                                                         AbsoluteRect.UpperLeftCorner.Y - spec.pos.Y,
1873                                                                         AbsoluteRect.UpperLeftCorner.X + absrec_size.Width + spec.pos.X*2,
1874                                                                         AbsoluteRect.UpperLeftCorner.Y + absrec_size.Height + spec.pos.Y*2);
1875                         }
1876
1877                         const video::SColor color(255,255,255,255);
1878                         const video::SColor colors[] = {color,color,color,color};
1879                         driver->draw2DImage(texture, rect,
1880                                 core::rect<s32>(core::position2d<s32>(0,0),
1881                                                 core::dimension2di(texture->getOriginalSize())),
1882                                 NULL/*&AbsoluteClippingRect*/, colors, true);
1883                 }
1884                 else {
1885                         errorstream << "GUIFormSpecMenu::drawMenu() Draw backgrounds unable to load texture:" << std::endl;
1886                         errorstream << "\t" << spec.name << std::endl;
1887                 }
1888         }
1889         
1890         /*
1891                 Draw Boxes
1892         */
1893         for(u32 i=0; i<m_boxes.size(); i++)
1894         {
1895                 const BoxDrawSpec &spec = m_boxes[i];
1896
1897                 irr::video::SColor todraw = spec.color;
1898
1899                 todraw.setAlpha(140);
1900
1901                 core::rect<s32> rect(spec.pos.X,spec.pos.Y,
1902                                                         spec.pos.X + spec.geom.X,spec.pos.Y + spec.geom.Y);
1903
1904                 driver->draw2DRectangle(todraw, rect, 0);
1905         }
1906         /*
1907                 Draw images
1908         */
1909         for(u32 i=0; i<m_images.size(); i++)
1910         {
1911                 const ImageDrawSpec &spec = m_images[i];
1912                 video::ITexture *texture = m_tsrc->getTexture(spec.name);
1913
1914                 if (texture != 0) {
1915                         const core::dimension2d<u32>& img_origsize = texture->getOriginalSize();
1916                         // Image size on screen
1917                         core::rect<s32> imgrect;
1918
1919                         if (spec.scale)
1920                                 imgrect = core::rect<s32>(0,0,spec.geom.X, spec.geom.Y);
1921                         else {
1922
1923                                 imgrect = core::rect<s32>(0,0,img_origsize.Width,img_origsize.Height);
1924                         }
1925                         // Image rectangle on screen
1926                         core::rect<s32> rect = imgrect + spec.pos;
1927                         const video::SColor color(255,255,255,255);
1928                         const video::SColor colors[] = {color,color,color,color};
1929                         driver->draw2DImage(texture, rect,
1930                                 core::rect<s32>(core::position2d<s32>(0,0),img_origsize),
1931                                 NULL/*&AbsoluteClippingRect*/, colors, true);
1932                 }
1933                 else {
1934                         errorstream << "GUIFormSpecMenu::drawMenu() Draw images unable to load texture:" << std::endl;
1935                         errorstream << "\t" << spec.name << std::endl;
1936                 }
1937         }
1938         
1939         /*
1940                 Draw item images
1941         */
1942         for(u32 i=0; i<m_itemimages.size(); i++)
1943         {
1944                 if (m_gamedef == 0)
1945                         break;
1946
1947                 const ImageDrawSpec &spec = m_itemimages[i];
1948                 IItemDefManager *idef = m_gamedef->idef();
1949                 ItemStack item;
1950                 item.deSerialize(spec.name, idef);
1951                 video::ITexture *texture = idef->getInventoryTexture(item.getDefinition(idef).name, m_gamedef);         
1952                 // Image size on screen
1953                 core::rect<s32> imgrect(0, 0, spec.geom.X, spec.geom.Y);
1954                 // Image rectangle on screen
1955                 core::rect<s32> rect = imgrect + spec.pos;
1956                 const video::SColor color(255,255,255,255);
1957                 const video::SColor colors[] = {color,color,color,color};
1958                 driver->draw2DImage(texture, rect,
1959                         core::rect<s32>(core::position2d<s32>(0,0),
1960                                         core::dimension2di(texture->getOriginalSize())),
1961                         NULL/*&AbsoluteClippingRect*/, colors, true);
1962         }
1963         
1964         /*
1965                 Draw items
1966                 Phase 0: Item slot rectangles
1967                 Phase 1: Item images; prepare tooltip
1968         */
1969         int start_phase=0;
1970         for(int phase=start_phase; phase<=1; phase++)
1971         for(u32 i=0; i<m_inventorylists.size(); i++)
1972         {
1973                 drawList(m_inventorylists[i], phase);
1974         }
1975
1976         /*
1977                 Call base class
1978         */
1979         gui::IGUIElement::draw();
1980         
1981         /*
1982                 Draw fields/buttons tooltips
1983         */
1984         for(u32 i=0; i<m_fields.size(); i++)
1985         {
1986                 const FieldSpec &spec = m_fields[i];
1987                 if (spec.tooltip != "")
1988                 {
1989                         core::rect<s32> rect = spec.rect;
1990                         if (rect.isPointInside(m_pointer)) 
1991                         {
1992                                 m_tooltip_element->setVisible(true);
1993                                 this->bringToFront(m_tooltip_element);
1994                                 m_tooltip_element->setText(narrow_to_wide(spec.tooltip).c_str());
1995                                 s32 tooltip_x = m_pointer.X + 15;
1996                                 s32 tooltip_y = m_pointer.Y + 15;
1997                                 s32 tooltip_width = m_tooltip_element->getTextWidth() + 15;
1998                                 s32 tooltip_height = m_tooltip_element->getTextHeight() + 5;
1999                                 m_tooltip_element->setRelativePosition(core::rect<s32>(
2000                                 core::position2d<s32>(tooltip_x, tooltip_y),
2001                                 core::dimension2d<s32>(tooltip_width, tooltip_height)));
2002                         }
2003                 }
2004         }
2005         
2006         /*
2007                 Draw dragged item stack
2008         */
2009         drawSelectedItem();
2010 }
2011
2012 void GUIFormSpecMenu::updateSelectedItem()
2013 {
2014         // If the selected stack has become empty for some reason, deselect it.
2015         // If the selected stack has become inaccessible, deselect it.
2016         // If the selected stack has become smaller, adjust m_selected_amount.
2017         ItemStack selected = verifySelectedItem();
2018
2019         // WARNING: BLACK MAGIC
2020         // See if there is a stack suited for our current guess.
2021         // If such stack does not exist, clear the guess.
2022         if(m_selected_content_guess.name != "" &&
2023                         selected.name == m_selected_content_guess.name &&
2024                         selected.count == m_selected_content_guess.count){
2025                 // Selected item fits the guess. Skip the black magic.
2026         }
2027         else if(m_selected_content_guess.name != ""){
2028                 bool found = false;
2029                 for(u32 i=0; i<m_inventorylists.size() && !found; i++){
2030                         const ListDrawSpec &s = m_inventorylists[i];
2031                         Inventory *inv = m_invmgr->getInventory(s.inventoryloc);
2032                         if(!inv)
2033                                 continue;
2034                         InventoryList *list = inv->getList(s.listname);
2035                         if(!list)
2036                                 continue;
2037                         for(s32 i=0; i<s.geom.X*s.geom.Y && !found; i++){
2038                                 u32 item_i = i + s.start_item_i;
2039                                 if(item_i >= list->getSize())
2040                                         continue;
2041                                 ItemStack stack = list->getItem(item_i);
2042                                 if(stack.name == m_selected_content_guess.name &&
2043                                                 stack.count == m_selected_content_guess.count){
2044                                         found = true;
2045                                         infostream<<"Client: Changing selected content guess to "
2046                                                         <<s.inventoryloc.dump()<<" "<<s.listname
2047                                                         <<" "<<item_i<<std::endl;
2048                                         delete m_selected_item;
2049                                         m_selected_item = new ItemSpec(s.inventoryloc, s.listname, item_i);
2050                                         m_selected_amount = stack.count;
2051                                 }
2052                         }
2053                 }
2054                 if(!found){
2055                         infostream<<"Client: Discarding selected content guess: "
2056                                         <<m_selected_content_guess.getItemString()<<std::endl;
2057                         m_selected_content_guess.name = "";
2058                 }
2059         }
2060
2061         // If craftresult is nonempty and nothing else is selected, select it now.
2062         if(!m_selected_item)
2063         {
2064                 for(u32 i=0; i<m_inventorylists.size(); i++)
2065                 {
2066                         const ListDrawSpec &s = m_inventorylists[i];
2067                         if(s.listname == "craftpreview")
2068                         {
2069                                 Inventory *inv = m_invmgr->getInventory(s.inventoryloc);
2070                                 InventoryList *list = inv->getList("craftresult");
2071                                 if(list && list->getSize() >= 1 && !list->getItem(0).empty())
2072                                 {
2073                                         m_selected_item = new ItemSpec;
2074                                         m_selected_item->inventoryloc = s.inventoryloc;
2075                                         m_selected_item->listname = "craftresult";
2076                                         m_selected_item->i = 0;
2077                                         m_selected_amount = 0;
2078                                         m_selected_dragging = false;
2079                                         break;
2080                                 }
2081                         }
2082                 }
2083         }
2084
2085         // If craftresult is selected, keep the whole stack selected
2086         if(m_selected_item && m_selected_item->listname == "craftresult")
2087         {
2088                 m_selected_amount = verifySelectedItem().count;
2089         }
2090 }
2091
2092 ItemStack GUIFormSpecMenu::verifySelectedItem()
2093 {
2094         // If the selected stack has become empty for some reason, deselect it.
2095         // If the selected stack has become inaccessible, deselect it.
2096         // If the selected stack has become smaller, adjust m_selected_amount.
2097         // Return the selected stack.
2098
2099         if(m_selected_item)
2100         {
2101                 if(m_selected_item->isValid())
2102                 {
2103                         Inventory *inv = m_invmgr->getInventory(m_selected_item->inventoryloc);
2104                         if(inv)
2105                         {
2106                                 InventoryList *list = inv->getList(m_selected_item->listname);
2107                                 if(list && (u32) m_selected_item->i < list->getSize())
2108                                 {
2109                                         ItemStack stack = list->getItem(m_selected_item->i);
2110                                         if(m_selected_amount > stack.count)
2111                                                 m_selected_amount = stack.count;
2112                                         if(!stack.empty())
2113                                                 return stack;
2114                                 }
2115                         }
2116                 }
2117
2118                 // selection was not valid
2119                 delete m_selected_item;
2120                 m_selected_item = NULL;
2121                 m_selected_amount = 0;
2122                 m_selected_dragging = false;
2123         }
2124         return ItemStack();
2125 }
2126
2127 void GUIFormSpecMenu::acceptInput(bool quit=false)
2128 {
2129         if(m_text_dst)
2130         {
2131                 std::map<std::string, std::string> fields;
2132
2133                 if (quit) {
2134                         fields["quit"] = "true";
2135                 }
2136
2137                 if (current_keys_pending.key_down) {
2138                         fields["key_down"] = "true";
2139                         current_keys_pending.key_down = false;
2140                 }
2141
2142                 if (current_keys_pending.key_up) {
2143                         fields["key_up"] = "true";
2144                         current_keys_pending.key_up = false;
2145                 }
2146
2147                 if (current_keys_pending.key_enter) {
2148                         fields["key_enter"] = "true";
2149                         current_keys_pending.key_enter = false;
2150                 }
2151
2152                 if (current_keys_pending.key_escape) {
2153                         fields["key_escape"] = "true";
2154                         current_keys_pending.key_escape = false;
2155                 }
2156
2157                 for(u32 i=0; i<m_fields.size(); i++)
2158                 {
2159                         const FieldSpec &s = m_fields[i];
2160                         if(s.send) 
2161                         {
2162                                 if(s.ftype == f_Button)
2163                                 {
2164                                         fields[wide_to_narrow(s.fname.c_str())] = wide_to_narrow(s.flabel.c_str());
2165                                 }
2166                                 else if(s.ftype == f_ListBox) {
2167                                         std::stringstream ss;
2168
2169                                         if (m_listbox_doubleclick) {
2170                                                 ss << "DCL:";
2171                                         }
2172                                         else {
2173                                                 ss << "CHG:";
2174                                         }
2175                                         ss << (getListboxIndex(wide_to_narrow(s.fname.c_str()))+1);
2176                                         fields[wide_to_narrow(s.fname.c_str())] = ss.str();
2177                                 }
2178                                 else if(s.ftype == f_DropDown) {
2179                                         // no dynamic cast possible due to some distributions shipped
2180                                         // without rtti support in irrlicht
2181                                         IGUIElement * element = getElementFromId(s.fid);
2182                                         gui::IGUIComboBox *e = NULL;
2183                                         if ((element) && (element->getType() == gui::EGUIET_COMBO_BOX)) {
2184                                                 e = static_cast<gui::IGUIComboBox*>(element);
2185                                         }
2186                                         fields[wide_to_narrow(s.fname.c_str())] =
2187                                                         wide_to_narrow(e->getItem(e->getSelected()));
2188                                 }
2189                                 else if (s.ftype == f_TabHeader) {
2190                                         // no dynamic cast possible due to some distributions shipped
2191                                         // without rtti support in irrlicht
2192                                         IGUIElement * element = getElementFromId(s.fid);
2193                                         gui::IGUITabControl *e = NULL;
2194                                         if ((element) && (element->getType() == gui::EGUIET_TAB_CONTROL)) {
2195                                                 e = static_cast<gui::IGUITabControl*>(element);
2196                                         }
2197
2198                                         if (e != 0) {
2199                                                 std::stringstream ss;
2200                                                 ss << (e->getActiveTab() +1);
2201                                                 fields[wide_to_narrow(s.fname.c_str())] = ss.str();
2202                                         }
2203                                 }
2204                                 else if (s.ftype == f_CheckBox) {
2205                                         // no dynamic cast possible due to some distributions shipped
2206                                         // without rtti support in irrlicht
2207                                         IGUIElement * element = getElementFromId(s.fid);
2208                                         gui::IGUICheckBox *e = NULL;
2209                                         if ((element) && (element->getType() == gui::EGUIET_CHECK_BOX)) {
2210                                                 e = static_cast<gui::IGUICheckBox*>(element);
2211                                         }
2212
2213                                         if (e != 0) {
2214                                                 if (e->isChecked())
2215                                                         fields[wide_to_narrow(s.fname.c_str())] = "true";
2216                                                 else
2217                                                         fields[wide_to_narrow(s.fname.c_str())] = "false";
2218                                         }
2219                                 }
2220                                 else
2221                                 {
2222                                         IGUIElement* e = getElementFromId(s.fid);
2223                                         if(e != NULL)
2224                                         {
2225                                                 fields[wide_to_narrow(s.fname.c_str())] = wide_to_narrow(e->getText());
2226                                         }
2227                                 }
2228                         }
2229                 }
2230
2231                 m_text_dst->gotText(fields);
2232         }
2233 }
2234
2235 bool GUIFormSpecMenu::preprocessEvent(const SEvent& event)
2236 {
2237         // Fix Esc/Return key being eaten by checkboxen and listboxen
2238         if(event.EventType==EET_KEY_INPUT_EVENT)
2239         {
2240                 KeyPress kp(event.KeyInput);
2241                 if (kp == EscapeKey || kp == getKeySetting("keymap_inventory")
2242                                 || event.KeyInput.Key==KEY_RETURN)
2243                 {
2244                         gui::IGUIElement *focused = Environment->getFocus();
2245                         if (focused && isMyChild(focused) &&
2246                                         (focused->getType() == gui::EGUIET_LIST_BOX ||
2247                                          focused->getType() == gui::EGUIET_CHECK_BOX)) {
2248                                 OnEvent(event);
2249                                 return true;
2250                         }
2251                 }
2252         }
2253         // Mouse wheel events: send to hovered element instead of focused
2254         if(event.EventType==EET_MOUSE_INPUT_EVENT
2255                         && event.MouseInput.Event == EMIE_MOUSE_WHEEL)
2256         {
2257                 s32 x = event.MouseInput.X;
2258                 s32 y = event.MouseInput.Y;
2259                 gui::IGUIElement *hovered =
2260                         Environment->getRootGUIElement()->getElementFromPoint(
2261                                 core::position2d<s32>(x, y));
2262                 if (hovered && isMyChild(hovered)) {
2263                         hovered->OnEvent(event);
2264                         return true;
2265                 }
2266         }
2267         return false;
2268 }
2269
2270 bool GUIFormSpecMenu::OnEvent(const SEvent& event)
2271 {
2272         if(event.EventType==EET_KEY_INPUT_EVENT)
2273         {
2274                 KeyPress kp(event.KeyInput);
2275                 if (event.KeyInput.PressedDown && (kp == EscapeKey ||
2276                         kp == getKeySetting("keymap_inventory")))
2277                 {
2278                         if (m_allowclose) {
2279                                 acceptInput(true);
2280                                 quitMenu();
2281                          } else {
2282                                 m_text_dst->gotText(narrow_to_wide("MenuQuit"));
2283                         }
2284                         return true;
2285                 }
2286                 if (event.KeyInput.PressedDown &&
2287                         (event.KeyInput.Key==KEY_RETURN ||
2288                          event.KeyInput.Key==KEY_UP ||
2289                          event.KeyInput.Key==KEY_DOWN)
2290                         ) {
2291
2292
2293                         switch (event.KeyInput.Key) {
2294                                 case KEY_RETURN:
2295                                         if (m_allowclose) {
2296                                                 acceptInput(true);
2297                                                 quitMenu();
2298                                         }
2299                                         else
2300                                                 current_keys_pending.key_enter = true;
2301                                         break;
2302                                 case KEY_UP:
2303                                         current_keys_pending.key_up = true;
2304                                         break;
2305                                 case KEY_DOWN:
2306                                         current_keys_pending.key_down = true;
2307                                         break;
2308                                 break;
2309                                 default:
2310                                         //can't happen at all!
2311                                         assert("reached a source line that can't ever been reached" == 0);
2312                                         break;
2313                         }
2314                         acceptInput();
2315                         return true;
2316                 }
2317
2318         }
2319         if(event.EventType==EET_MOUSE_INPUT_EVENT
2320                         && event.MouseInput.Event != EMIE_MOUSE_MOVED)
2321         {
2322                 // Mouse event other than movement
2323
2324                 // Get selected item and hovered/clicked item (s)
2325
2326                 updateSelectedItem();
2327                 ItemSpec s = getItemAtPos(m_pointer);
2328
2329                 Inventory *inv_selected = NULL;
2330                 Inventory *inv_s = NULL;
2331
2332                 if(m_selected_item)
2333                 {
2334                         inv_selected = m_invmgr->getInventory(m_selected_item->inventoryloc);
2335                         assert(inv_selected);
2336                         assert(inv_selected->getList(m_selected_item->listname) != NULL);
2337                 }
2338
2339                 u32 s_count = 0;
2340
2341                 if(s.isValid())
2342                 do{ // breakable
2343                         inv_s = m_invmgr->getInventory(s.inventoryloc);
2344
2345                         if(!inv_s){
2346                                 errorstream<<"InventoryMenu: The selected inventory location "
2347                                                 <<"\""<<s.inventoryloc.dump()<<"\" doesn't exist"
2348                                                 <<std::endl;
2349                                 s.i = -1;  // make it invalid again
2350                                 break;
2351                         }
2352
2353                         InventoryList *list = inv_s->getList(s.listname);
2354                         if(list == NULL){
2355                                 verbosestream<<"InventoryMenu: The selected inventory list \""
2356                                                 <<s.listname<<"\" does not exist"<<std::endl;
2357                                 s.i = -1;  // make it invalid again
2358                                 break;
2359                         }
2360
2361                         if((u32)s.i >= list->getSize()){
2362                                 infostream<<"InventoryMenu: The selected inventory list \""
2363                                                 <<s.listname<<"\" is too small (i="<<s.i<<", size="
2364                                                 <<list->getSize()<<")"<<std::endl;
2365                                 s.i = -1;  // make it invalid again
2366                                 break;
2367                         }
2368
2369                         s_count = list->getItem(s.i).count;
2370                 }while(0);
2371
2372                 bool identical = (m_selected_item != NULL) && s.isValid() &&
2373                         (inv_selected == inv_s) &&
2374                         (m_selected_item->listname == s.listname) &&
2375                         (m_selected_item->i == s.i);
2376
2377                 // buttons: 0 = left, 1 = right, 2 = middle
2378                 // up/down: 0 = down (press), 1 = up (release), 2 = unknown event
2379                 int button = 0;
2380                 int updown = 2;
2381                 if(event.MouseInput.Event == EMIE_LMOUSE_PRESSED_DOWN)
2382                         { button = 0; updown = 0; }
2383                 else if(event.MouseInput.Event == EMIE_RMOUSE_PRESSED_DOWN)
2384                         { button = 1; updown = 0; }
2385                 else if(event.MouseInput.Event == EMIE_MMOUSE_PRESSED_DOWN)
2386                         { button = 2; updown = 0; }
2387                 else if(event.MouseInput.Event == EMIE_LMOUSE_LEFT_UP)
2388                         { button = 0; updown = 1; }
2389                 else if(event.MouseInput.Event == EMIE_RMOUSE_LEFT_UP)
2390                         { button = 1; updown = 1; }
2391                 else if(event.MouseInput.Event == EMIE_MMOUSE_LEFT_UP)
2392                         { button = 2; updown = 1; }
2393
2394                 // Set this number to a positive value to generate a move action
2395                 // from m_selected_item to s.
2396                 u32 move_amount = 0;
2397
2398                 // Set this number to a positive value to generate a drop action
2399                 // from m_selected_item.
2400                 u32 drop_amount = 0;
2401
2402                 // Set this number to a positive value to generate a craft action at s.
2403                 u32 craft_amount = 0;
2404
2405                 if(updown == 0)
2406                 {
2407                         // Some mouse button has been pressed
2408
2409                         //infostream<<"Mouse button "<<button<<" pressed at p=("
2410                         //      <<p.X<<","<<p.Y<<")"<<std::endl;
2411
2412                         m_selected_dragging = false;
2413
2414                         if(s.isValid() && s.listname == "craftpreview")
2415                         {
2416                                 // Craft preview has been clicked: craft
2417                                 craft_amount = (button == 2 ? 10 : 1);
2418                         }
2419                         else if(m_selected_item == NULL)
2420                         {
2421                                 if(s_count != 0)
2422                                 {
2423                                         // Non-empty stack has been clicked: select it
2424                                         m_selected_item = new ItemSpec(s);
2425
2426                                         if(button == 1)  // right
2427                                                 m_selected_amount = (s_count + 1) / 2;
2428                                         else if(button == 2)  // middle
2429                                                 m_selected_amount = MYMIN(s_count, 10);
2430                                         else  // left
2431                                                 m_selected_amount = s_count;
2432
2433                                         m_selected_dragging = true;
2434                                 }
2435                         }
2436                         else  // m_selected_item != NULL
2437                         {
2438                                 assert(m_selected_amount >= 1);
2439
2440                                 if(s.isValid())
2441                                 {
2442                                         // Clicked a slot: move
2443                                         if(button == 1)  // right
2444                                                 move_amount = 1;
2445                                         else if(button == 2)  // middle
2446                                                 move_amount = MYMIN(m_selected_amount, 10);
2447                                         else  // left
2448                                                 move_amount = m_selected_amount;
2449
2450                                         if(identical)
2451                                         {
2452                                                 if(move_amount >= m_selected_amount)
2453                                                         m_selected_amount = 0;
2454                                                 else
2455                                                         m_selected_amount -= move_amount;
2456                                                 move_amount = 0;
2457                                         }
2458                                 }
2459                                 else if(getAbsoluteClippingRect().isPointInside(m_pointer))
2460                                 {
2461                                         // Clicked somewhere else: deselect
2462                                         m_selected_amount = 0;
2463                                 }
2464                                 else
2465                                 {
2466                                         // Clicked outside of the window: drop
2467                                         if(button == 1)  // right
2468                                                 drop_amount = 1;
2469                                         else if(button == 2)  // middle
2470                                                 drop_amount = MYMIN(m_selected_amount, 10);
2471                                         else  // left
2472                                                 drop_amount = m_selected_amount;
2473                                 }
2474                         }
2475                 }
2476                 else if(updown == 1)
2477                 {
2478                         // Some mouse button has been released
2479
2480                         //infostream<<"Mouse button "<<button<<" released at p=("
2481                         //      <<p.X<<","<<p.Y<<")"<<std::endl;
2482
2483                         if(m_selected_item != NULL && m_selected_dragging && s.isValid())
2484                         {
2485                                 if(!identical)
2486                                 {
2487                                         // Dragged to different slot: move all selected
2488                                         move_amount = m_selected_amount;
2489                                 }
2490                         }
2491                         else if(m_selected_item != NULL && m_selected_dragging &&
2492                                 !(getAbsoluteClippingRect().isPointInside(m_pointer)))
2493                         {
2494                                 // Dragged outside of window: drop all selected
2495                                 drop_amount = m_selected_amount;
2496                         }
2497
2498                         m_selected_dragging = false;
2499                 }
2500
2501                 // Possibly send inventory action to server
2502                 if(move_amount > 0)
2503                 {
2504                         // Send IACTION_MOVE
2505
2506                         assert(m_selected_item && m_selected_item->isValid());
2507                         assert(s.isValid());
2508
2509                         assert(inv_selected && inv_s);
2510                         InventoryList *list_from = inv_selected->getList(m_selected_item->listname);
2511                         InventoryList *list_to = inv_s->getList(s.listname);
2512                         assert(list_from && list_to);
2513                         ItemStack stack_from = list_from->getItem(m_selected_item->i);
2514                         ItemStack stack_to = list_to->getItem(s.i);
2515
2516                         // Check how many items can be moved
2517                         move_amount = stack_from.count = MYMIN(move_amount, stack_from.count);
2518                         ItemStack leftover = stack_to.addItem(stack_from, m_gamedef->idef());
2519                         // If source stack cannot be added to destination stack at all,
2520                         // they are swapped
2521                         if(leftover.count == stack_from.count && leftover.name == stack_from.name)
2522                         {
2523                                 m_selected_amount = stack_to.count;
2524                                 // In case the server doesn't directly swap them but instead
2525                                 // moves stack_to somewhere else, set this
2526                                 m_selected_content_guess = stack_to;
2527                                 m_selected_content_guess_inventory = s.inventoryloc;
2528                         }
2529                         // Source stack goes fully into destination stack
2530                         else if(leftover.empty())
2531                         {
2532                                 m_selected_amount -= move_amount;
2533                                 m_selected_content_guess = ItemStack(); // Clear
2534                         }
2535                         // Source stack goes partly into destination stack
2536                         else
2537                         {
2538                                 move_amount -= leftover.count;
2539                                 m_selected_amount -= move_amount;
2540                                 m_selected_content_guess = ItemStack(); // Clear
2541                         }
2542
2543                         infostream<<"Handing IACTION_MOVE to manager"<<std::endl;
2544                         IMoveAction *a = new IMoveAction();
2545                         a->count = move_amount;
2546                         a->from_inv = m_selected_item->inventoryloc;
2547                         a->from_list = m_selected_item->listname;
2548                         a->from_i = m_selected_item->i;
2549                         a->to_inv = s.inventoryloc;
2550                         a->to_list = s.listname;
2551                         a->to_i = s.i;
2552                         m_invmgr->inventoryAction(a);
2553                 }
2554                 else if(drop_amount > 0)
2555                 {
2556                         m_selected_content_guess = ItemStack(); // Clear
2557
2558                         // Send IACTION_DROP
2559
2560                         assert(m_selected_item && m_selected_item->isValid());
2561                         assert(inv_selected);
2562                         InventoryList *list_from = inv_selected->getList(m_selected_item->listname);
2563                         assert(list_from);
2564                         ItemStack stack_from = list_from->getItem(m_selected_item->i);
2565
2566                         // Check how many items can be dropped
2567                         drop_amount = stack_from.count = MYMIN(drop_amount, stack_from.count);
2568                         assert(drop_amount > 0 && drop_amount <= m_selected_amount);
2569                         m_selected_amount -= drop_amount;
2570
2571                         infostream<<"Handing IACTION_DROP to manager"<<std::endl;
2572                         IDropAction *a = new IDropAction();
2573                         a->count = drop_amount;
2574                         a->from_inv = m_selected_item->inventoryloc;
2575                         a->from_list = m_selected_item->listname;
2576                         a->from_i = m_selected_item->i;
2577                         m_invmgr->inventoryAction(a);
2578                 }
2579                 else if(craft_amount > 0)
2580                 {
2581                         m_selected_content_guess = ItemStack(); // Clear
2582
2583                         // Send IACTION_CRAFT
2584
2585                         assert(s.isValid());
2586                         assert(inv_s);
2587
2588                         infostream<<"Handing IACTION_CRAFT to manager"<<std::endl;
2589                         ICraftAction *a = new ICraftAction();
2590                         a->count = craft_amount;
2591                         a->craft_inv = s.inventoryloc;
2592                         m_invmgr->inventoryAction(a);
2593                 }
2594
2595                 // If m_selected_amount has been decreased to zero, deselect
2596                 if(m_selected_amount == 0)
2597                 {
2598                         delete m_selected_item;
2599                         m_selected_item = NULL;
2600                         m_selected_amount = 0;
2601                         m_selected_dragging = false;
2602                         m_selected_content_guess = ItemStack();
2603                 }
2604         }
2605         if(event.EventType==EET_GUI_EVENT)
2606         {
2607
2608                 if(event.GUIEvent.EventType==gui::EGET_TAB_CHANGED
2609                                                 && isVisible())
2610                 {
2611                         // find the element that was clicked
2612                         for(u32 i=0; i<m_fields.size(); i++)
2613                         {
2614                                 FieldSpec &s = m_fields[i];
2615                                 // if its a button, set the send field so
2616                                 // lua knows which button was pressed
2617                                 if ((s.ftype == f_TabHeader) && (s.fid == event.GUIEvent.Caller->getID()))
2618                                 {
2619                                         s.send = true;
2620                                         acceptInput();
2621                                         s.send = false;
2622                                         return true;
2623                                 }
2624                         }
2625                 }
2626                 if(event.GUIEvent.EventType==gui::EGET_ELEMENT_FOCUS_LOST
2627                                 && isVisible())
2628                 {
2629                         if(!canTakeFocus(event.GUIEvent.Element))
2630                         {
2631                                 infostream<<"GUIFormSpecMenu: Not allowing focus change."
2632                                                 <<std::endl;
2633                                 // Returning true disables focus change
2634                                 return true;
2635                         }
2636                 }
2637                 if((event.GUIEvent.EventType==gui::EGET_BUTTON_CLICKED) ||
2638                                 (event.GUIEvent.EventType==gui::EGET_CHECKBOX_CHANGED))
2639                 {
2640                         unsigned int btn_id = event.GUIEvent.Caller->getID();
2641
2642                         if (btn_id == 257) {
2643                                 if (m_allowclose) {
2644                                         acceptInput(true);
2645                                         quitMenu();
2646                                 } else {
2647                                         acceptInput();
2648                                         m_text_dst->gotText(narrow_to_wide("ExitButton"));
2649                                 }
2650                                 // quitMenu deallocates menu
2651                                 return true;
2652                         }
2653
2654                         // find the element that was clicked
2655                         for(u32 i=0; i<m_fields.size(); i++)
2656                         {
2657                                 FieldSpec &s = m_fields[i];
2658                                 // if its a button, set the send field so 
2659                                 // lua knows which button was pressed
2660                                 if (((s.ftype == f_Button) || (s.ftype == f_CheckBox)) &&
2661                                                 (s.fid == event.GUIEvent.Caller->getID()))
2662                                 {
2663                                         s.send = true;
2664                                         acceptInput();
2665                                         if(s.is_exit){
2666                                                 if (m_allowclose) {
2667                                                         acceptInput(true);
2668                                                         quitMenu();
2669                                                 } else {
2670                                                         m_text_dst->gotText(narrow_to_wide("ExitButton"));
2671                                                 }
2672                                                 return true;
2673                                         }else{
2674                                                 s.send = false;
2675                                                 return true;
2676                                         }
2677                                 }
2678                         }
2679                 }
2680                 if(event.GUIEvent.EventType==gui::EGET_EDITBOX_ENTER)
2681                 {
2682                         if(event.GUIEvent.Caller->getID() > 257)
2683                         {
2684
2685                                 if (m_allowclose) {
2686                                         acceptInput(true);
2687                                         quitMenu();
2688                                 }
2689                                 else {
2690                                         current_keys_pending.key_enter = true;
2691                                         acceptInput();
2692                                 }
2693                                 // quitMenu deallocates menu
2694                                 return true;
2695                         }
2696                 }
2697
2698                 if((event.GUIEvent.EventType==gui::EGET_LISTBOX_SELECTED_AGAIN) ||
2699                         (event.GUIEvent.EventType==gui::EGET_LISTBOX_CHANGED))
2700                 {
2701                         int current_id = event.GUIEvent.Caller->getID();
2702                         if(current_id > 257)
2703                         {
2704                                 // find the element that was clicked
2705                                 for(u32 i=0; i<m_fields.size(); i++)
2706                                 {
2707                                         FieldSpec &s = m_fields[i];
2708                                         // if its a listbox, set the send field so
2709                                         // lua knows which listbox was changed
2710                                         // checkListboxClick() is black magic
2711                                         // for properly handling double clicks
2712                                         if ((s.ftype == f_ListBox) && (s.fid == current_id)
2713                                                         && checkListboxClick(s.fname,
2714                                                                 event.GUIEvent.EventType))
2715                                         {
2716                                                 s.send = true;
2717                                                 acceptInput();
2718                                                 s.send=false;
2719                                         }
2720                                 }
2721                                 return true;
2722                         }
2723                 }
2724         }
2725
2726         return Parent ? Parent->OnEvent(event) : false;
2727 }
2728
2729 static inline bool hex_digit_decode(char hexdigit, unsigned char &value)
2730 {
2731         if(hexdigit >= '0' && hexdigit <= '9')
2732                 value = hexdigit - '0';
2733         else if(hexdigit >= 'A' && hexdigit <= 'F')
2734                 value = hexdigit - 'A' + 10;
2735         else if(hexdigit >= 'a' && hexdigit <= 'f')
2736                 value = hexdigit - 'a' + 10;
2737         else
2738                 return false;
2739         return true;
2740 }
2741
2742 bool GUIFormSpecMenu::parseColor(std::string &value, video::SColor &color, bool quiet)
2743 {
2744         const char *hexpattern = NULL;
2745         if (value[0] == '#') {
2746                 if (value.size() == 9)
2747                         hexpattern = "#RRGGBBAA";
2748                 else if (value.size() == 7)
2749                         hexpattern = "#RRGGBB";
2750                 else if (value.size() == 5)
2751                         hexpattern = "#RGBA";
2752                 else if (value.size() == 4)
2753                         hexpattern = "#RGB";
2754         }
2755
2756         if (hexpattern) {
2757                 assert(strlen(hexpattern) == value.size());
2758                 video::SColor outcolor(255, 255, 255, 255);
2759                 for (size_t pos = 0; pos < value.size(); ++pos) {
2760                         // '#' in the pattern means skip that character
2761                         if (hexpattern[pos] == '#')
2762                                 continue;
2763
2764                         // Else assume hexpattern[pos] is one of 'R' 'G' 'B' 'A'
2765                         // Read one or two digits, depending on hexpattern
2766                         unsigned char c1, c2;
2767                         if (hexpattern[pos+1] == hexpattern[pos]) {
2768                                 // Two digits, e.g. hexpattern == "#RRGGBB"
2769                                 if (!hex_digit_decode(value[pos], c1) ||
2770                                     !hex_digit_decode(value[pos+1], c2))
2771                                         goto fail;
2772                                 ++pos;
2773                         }
2774                         else {
2775                                 // One digit, e.g. hexpattern == "#RGB"
2776                                 if (!hex_digit_decode(value[pos], c1))
2777                                         goto fail;
2778                                 c2 = c1;
2779                         }
2780                         u32 colorpart = ((c1 & 0x0f) << 4) | (c2 & 0x0f);
2781
2782                         // Update outcolor with newly read color part
2783                         if (hexpattern[pos] == 'R')
2784                                 outcolor.setRed(colorpart);
2785                         else if (hexpattern[pos] == 'G')
2786                                 outcolor.setGreen(colorpart);
2787                         else if (hexpattern[pos] == 'B')
2788                                 outcolor.setBlue(colorpart);
2789                         else if (hexpattern[pos] == 'A')
2790                                 outcolor.setAlpha(colorpart);
2791                 }
2792
2793                 color = outcolor;
2794                 return true;
2795         }
2796
2797         // Optionally, named colors could be implemented here
2798
2799 fail:
2800         if (!quiet)
2801                 errorstream<<"Invalid color: \""<<value<<"\""<<std::endl;
2802         return false;
2803 }