]> git.lizzy.rs Git - dragonfireclient.git/blob - src/gui/guiFormSpecMenu.cpp
Ensure no item stack is being held before crafting (#4779)
[dragonfireclient.git] / src / gui / guiFormSpecMenu.cpp
1 /*
2 Minetest
3 Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com>
4
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU Lesser General Public License as published by
7 the Free Software Foundation; either version 2.1 of the License, or
8 (at your option) any later version.
9
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 GNU Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public License along
16 with this program; if not, write to the Free Software Foundation, Inc.,
17 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18 */
19
20
21 #include <cstdlib>
22 #include <algorithm>
23 #include <iterator>
24 #include <sstream>
25 #include <limits>
26 #include "guiFormSpecMenu.h"
27 #include "guiTable.h"
28 #include "constants.h"
29 #include "gamedef.h"
30 #include "keycode.h"
31 #include "util/strfnd.h"
32 #include <IGUICheckBox.h>
33 #include <IGUIEditBox.h>
34 #include <IGUIButton.h>
35 #include <IGUIStaticText.h>
36 #include <IGUIFont.h>
37 #include <IGUITabControl.h>
38 #include <IGUIComboBox.h>
39 #include "client/renderingengine.h"
40 #include "log.h"
41 #include "client/tile.h" // ITextureSource
42 #include "hud.h" // drawItemStack
43 #include "filesys.h"
44 #include "gettime.h"
45 #include "gettext.h"
46 #include "scripting_server.h"
47 #include "porting.h"
48 #include "settings.h"
49 #include "client.h"
50 #include "fontengine.h"
51 #include "util/hex.h"
52 #include "util/numeric.h"
53 #include "util/string.h" // for parseColorString()
54 #include "irrlicht_changes/static_text.h"
55 #include "guiscalingfilter.h"
56 #include "guiEditBoxWithScrollbar.h"
57
58 #if USE_FREETYPE && IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR < 9
59 #include "intlGUIEditBox.h"
60 #endif
61
62 #define MY_CHECKPOS(a,b)                                                                                                        \
63         if (v_pos.size() != 2) {                                                                                                \
64                 errorstream<< "Invalid pos for element " << a << "specified: \""        \
65                         << parts[b] << "\"" << std::endl;                                                               \
66                         return;                                                                                                                 \
67         }
68
69 #define MY_CHECKGEOM(a,b)                                                                                                       \
70         if (v_geom.size() != 2) {                                                                                               \
71                 errorstream<< "Invalid pos for element " << a << "specified: \""        \
72                         << parts[b] << "\"" << std::endl;                                                               \
73                         return;                                                                                                                 \
74         }
75 /*
76         GUIFormSpecMenu
77 */
78 static unsigned int font_line_height(gui::IGUIFont *font)
79 {
80         return font->getDimension(L"Ay").Height + font->getKerningHeight();
81 }
82
83 inline u32 clamp_u8(s32 value)
84 {
85         return (u32) MYMIN(MYMAX(value, 0), 255);
86 }
87
88 GUIFormSpecMenu::GUIFormSpecMenu(JoystickController *joystick,
89                 gui::IGUIElement *parent, s32 id, IMenuManager *menumgr,
90                 Client *client, ISimpleTextureSource *tsrc, IFormSource *fsrc, TextDest *tdst,
91                 bool remap_dbl_click) :
92         GUIModalMenu(RenderingEngine::get_gui_env(), parent, id, menumgr),
93         m_invmgr(client),
94         m_tsrc(tsrc),
95         m_client(client),
96         m_form_src(fsrc),
97         m_text_dst(tdst),
98         m_joystick(joystick),
99         m_remap_dbl_click(remap_dbl_click)
100 #ifdef __ANDROID__
101         , m_JavaDialogFieldName("")
102 #endif
103 {
104         current_keys_pending.key_down = false;
105         current_keys_pending.key_up = false;
106         current_keys_pending.key_enter = false;
107         current_keys_pending.key_escape = false;
108
109         m_doubleclickdetect[0].time = 0;
110         m_doubleclickdetect[1].time = 0;
111
112         m_doubleclickdetect[0].pos = v2s32(0, 0);
113         m_doubleclickdetect[1].pos = v2s32(0, 0);
114
115         m_tooltip_show_delay = (u32)g_settings->getS32("tooltip_show_delay");
116         m_tooltip_append_itemname = g_settings->getBool("tooltip_append_itemname");
117 }
118
119 GUIFormSpecMenu::~GUIFormSpecMenu()
120 {
121         removeChildren();
122
123         for (auto &table_it : m_tables) {
124                 table_it.second->drop();
125         }
126
127         delete m_selected_item;
128         delete m_form_src;
129         delete m_text_dst;
130 }
131
132 void GUIFormSpecMenu::removeChildren()
133 {
134         const core::list<gui::IGUIElement*> &children = getChildren();
135
136         while(!children.empty()) {
137                 (*children.getLast())->remove();
138         }
139
140         if(m_tooltip_element) {
141                 m_tooltip_element->remove();
142                 m_tooltip_element->drop();
143                 m_tooltip_element = NULL;
144         }
145
146 }
147
148 void GUIFormSpecMenu::setInitialFocus()
149 {
150         // Set initial focus according to following order of precedence:
151         // 1. first empty editbox
152         // 2. first editbox
153         // 3. first table
154         // 4. last button
155         // 5. first focusable (not statictext, not tabheader)
156         // 6. first child element
157
158         core::list<gui::IGUIElement*> children = getChildren();
159
160         // in case "children" contains any NULL elements, remove them
161         for (core::list<gui::IGUIElement*>::Iterator it = children.begin();
162                         it != children.end();) {
163                 if (*it)
164                         ++it;
165                 else
166                         it = children.erase(it);
167         }
168
169         // 1. first empty editbox
170         for (gui::IGUIElement *it : children) {
171                 if (it->getType() == gui::EGUIET_EDIT_BOX
172                                 && it->getText()[0] == 0) {
173                         Environment->setFocus(it);
174                         return;
175                 }
176         }
177
178         // 2. first editbox
179         for (gui::IGUIElement *it : children) {
180                 if (it->getType() == gui::EGUIET_EDIT_BOX) {
181                         Environment->setFocus(it);
182                         return;
183                 }
184         }
185
186         // 3. first table
187         for (gui::IGUIElement *it : children) {
188                 if (it->getTypeName() == std::string("GUITable")) {
189                         Environment->setFocus(it);
190                         return;
191                 }
192         }
193
194         // 4. last button
195         for (core::list<gui::IGUIElement*>::Iterator it = children.getLast();
196                         it != children.end(); --it) {
197                 if ((*it)->getType() == gui::EGUIET_BUTTON) {
198                         Environment->setFocus(*it);
199                         return;
200                 }
201         }
202
203         // 5. first focusable (not statictext, not tabheader)
204         for (gui::IGUIElement *it : children) {
205                 if (it->getType() != gui::EGUIET_STATIC_TEXT &&
206                         it->getType() != gui::EGUIET_TAB_CONTROL) {
207                         Environment->setFocus(it);
208                         return;
209                 }
210         }
211
212         // 6. first child element
213         if (children.empty())
214                 Environment->setFocus(this);
215         else
216                 Environment->setFocus(*(children.begin()));
217 }
218
219 GUITable* GUIFormSpecMenu::getTable(const std::string &tablename)
220 {
221         for (auto &table : m_tables) {
222                 if (tablename == table.first.fname)
223                         return table.second;
224         }
225         return 0;
226 }
227
228 std::vector<std::string>* GUIFormSpecMenu::getDropDownValues(const std::string &name)
229 {
230         for (auto &dropdown : m_dropdowns) {
231                 if (name == dropdown.first.fname)
232                         return &dropdown.second;
233         }
234         return NULL;
235 }
236
237 void GUIFormSpecMenu::parseSize(parserData* data, const std::string &element)
238 {
239         std::vector<std::string> parts = split(element,',');
240
241         if (((parts.size() == 2) || parts.size() == 3) ||
242                 ((parts.size() > 3) && (m_formspec_version > FORMSPEC_API_VERSION)))
243         {
244                 if (parts[1].find(';') != std::string::npos)
245                         parts[1] = parts[1].substr(0,parts[1].find(';'));
246
247                 data->invsize.X = MYMAX(0, stof(parts[0]));
248                 data->invsize.Y = MYMAX(0, stof(parts[1]));
249
250                 lockSize(false);
251                 if (parts.size() == 3) {
252                         if (parts[2] == "true") {
253                                 lockSize(true,v2u32(800,600));
254                         }
255                 }
256
257                 data->explicit_size = true;
258                 return;
259         }
260         errorstream<< "Invalid size element (" << parts.size() << "): '" << element << "'"  << std::endl;
261 }
262
263 void GUIFormSpecMenu::parseContainer(parserData* data, const std::string &element)
264 {
265         std::vector<std::string> parts = split(element, ',');
266
267         if (parts.size() >= 2) {
268                 if (parts[1].find(';') != std::string::npos)
269                         parts[1] = parts[1].substr(0, parts[1].find(';'));
270
271                 container_stack.push(pos_offset);
272                 pos_offset.X += MYMAX(0, stof(parts[0]));
273                 pos_offset.Y += MYMAX(0, stof(parts[1]));
274                 return;
275         }
276         errorstream<< "Invalid container start element (" << parts.size() << "): '" << element << "'"  << std::endl;
277 }
278
279 void GUIFormSpecMenu::parseContainerEnd(parserData* data)
280 {
281         if (container_stack.empty()) {
282                 errorstream<< "Invalid container end element, no matching container start element"  << std::endl;
283         } else {
284                 pos_offset = container_stack.top();
285                 container_stack.pop();
286         }
287 }
288
289 void GUIFormSpecMenu::parseList(parserData* data, const std::string &element)
290 {
291         if (m_client == 0) {
292                 warningstream<<"invalid use of 'list' with m_client==0"<<std::endl;
293                 return;
294         }
295
296         std::vector<std::string> parts = split(element,';');
297
298         if (((parts.size() == 4) || (parts.size() == 5)) ||
299                 ((parts.size() > 5) && (m_formspec_version > FORMSPEC_API_VERSION)))
300         {
301                 std::string location = parts[0];
302                 std::string listname = parts[1];
303                 std::vector<std::string> v_pos  = split(parts[2],',');
304                 std::vector<std::string> v_geom = split(parts[3],',');
305                 std::string startindex;
306                 if (parts.size() == 5)
307                         startindex = parts[4];
308
309                 MY_CHECKPOS("list",2);
310                 MY_CHECKGEOM("list",3);
311
312                 InventoryLocation loc;
313
314                 if(location == "context" || location == "current_name")
315                         loc = m_current_inventory_location;
316                 else
317                         loc.deSerialize(location);
318
319                 v2s32 pos = padding + AbsoluteRect.UpperLeftCorner + pos_offset * spacing;
320                 pos.X += stof(v_pos[0]) * (float)spacing.X;
321                 pos.Y += stof(v_pos[1]) * (float)spacing.Y;
322
323                 v2s32 geom;
324                 geom.X = stoi(v_geom[0]);
325                 geom.Y = stoi(v_geom[1]);
326
327                 s32 start_i = 0;
328                 if (!startindex.empty())
329                         start_i = stoi(startindex);
330
331                 if (geom.X < 0 || geom.Y < 0 || start_i < 0) {
332                         errorstream<< "Invalid list element: '" << element << "'"  << std::endl;
333                         return;
334                 }
335
336                 if(!data->explicit_size)
337                         warningstream<<"invalid use of list without a size[] element"<<std::endl;
338                 m_inventorylists.emplace_back(loc, listname, pos, geom, start_i);
339                 return;
340         }
341         errorstream<< "Invalid list element(" << parts.size() << "): '" << element << "'"  << std::endl;
342 }
343
344 void GUIFormSpecMenu::parseListRing(parserData* data, const std::string &element)
345 {
346         if (m_client == 0) {
347                 errorstream << "WARNING: invalid use of 'listring' with m_client==0" << std::endl;
348                 return;
349         }
350
351         std::vector<std::string> parts = split(element, ';');
352
353         if (parts.size() == 2) {
354                 std::string location = parts[0];
355                 std::string listname = parts[1];
356
357                 InventoryLocation loc;
358
359                 if (location == "context" || location == "current_name")
360                         loc = m_current_inventory_location;
361                 else
362                         loc.deSerialize(location);
363
364                 m_inventory_rings.emplace_back(loc, listname);
365                 return;
366         }
367
368         if (element.empty() && m_inventorylists.size() > 1) {
369                 size_t siz = m_inventorylists.size();
370                 // insert the last two inv list elements into the list ring
371                 const ListDrawSpec &spa = m_inventorylists[siz - 2];
372                 const ListDrawSpec &spb = m_inventorylists[siz - 1];
373                 m_inventory_rings.emplace_back(spa.inventoryloc, spa.listname);
374                 m_inventory_rings.emplace_back(spb.inventoryloc, spb.listname);
375                 return;
376         }
377
378         errorstream<< "Invalid list ring element(" << parts.size() << ", "
379                 << m_inventorylists.size() << "): '" << element << "'"  << std::endl;
380 }
381
382 void GUIFormSpecMenu::parseCheckbox(parserData* data, const std::string &element)
383 {
384         std::vector<std::string> parts = split(element,';');
385
386         if (((parts.size() >= 3) && (parts.size() <= 4)) ||
387                 ((parts.size() > 4) && (m_formspec_version > FORMSPEC_API_VERSION)))
388         {
389                 std::vector<std::string> v_pos = split(parts[0],',');
390                 std::string name = parts[1];
391                 std::string label = parts[2];
392                 std::string selected;
393
394                 if (parts.size() >= 4)
395                         selected = parts[3];
396
397                 MY_CHECKPOS("checkbox",0);
398
399                 v2s32 pos = padding + pos_offset * spacing;
400                 pos.X += stof(v_pos[0]) * (float) spacing.X;
401                 pos.Y += stof(v_pos[1]) * (float) spacing.Y;
402
403                 bool fselected = false;
404
405                 if (selected == "true")
406                         fselected = true;
407
408                 std::wstring wlabel = translate_string(utf8_to_wide(unescape_string(label)));
409
410                 core::rect<s32> rect = core::rect<s32>(
411                                 pos.X, pos.Y + ((imgsize.Y/2) - m_btn_height),
412                                 pos.X + m_font->getDimension(wlabel.c_str()).Width + 25, // text size + size of checkbox
413                                 pos.Y + ((imgsize.Y/2) + m_btn_height));
414
415                 FieldSpec spec(
416                                 name,
417                                 wlabel, //Needed for displaying text on MSVC
418                                 wlabel,
419                                 258+m_fields.size()
420                         );
421
422                 spec.ftype = f_CheckBox;
423
424                 gui::IGUICheckBox* e = Environment->addCheckBox(fselected, rect, this,
425                                         spec.fid, spec.flabel.c_str());
426
427                 if (spec.fname == data->focused_fieldname) {
428                         Environment->setFocus(e);
429                 }
430
431                 m_checkboxes.emplace_back(spec,e);
432                 m_fields.push_back(spec);
433                 return;
434         }
435         errorstream<< "Invalid checkbox element(" << parts.size() << "): '" << element << "'"  << std::endl;
436 }
437
438 void GUIFormSpecMenu::parseScrollBar(parserData* data, const std::string &element)
439 {
440         std::vector<std::string> parts = split(element,';');
441
442         if (parts.size() >= 5) {
443                 std::vector<std::string> v_pos = split(parts[0],',');
444                 std::vector<std::string> v_dim = split(parts[1],',');
445                 std::string name = parts[3];
446                 std::string value = parts[4];
447
448                 MY_CHECKPOS("scrollbar",0);
449
450                 v2s32 pos = padding + pos_offset * spacing;
451                 pos.X += stof(v_pos[0]) * (float) spacing.X;
452                 pos.Y += stof(v_pos[1]) * (float) spacing.Y;
453
454                 if (v_dim.size() != 2) {
455                         errorstream<< "Invalid size for element " << "scrollbar"
456                                 << "specified: \"" << parts[1] << "\"" << std::endl;
457                         return;
458                 }
459
460                 v2s32 dim;
461                 dim.X = stof(v_dim[0]) * (float) spacing.X;
462                 dim.Y = stof(v_dim[1]) * (float) spacing.Y;
463
464                 core::rect<s32> rect =
465                                 core::rect<s32>(pos.X, pos.Y, pos.X + dim.X, pos.Y + dim.Y);
466
467                 FieldSpec spec(
468                                 name,
469                                 L"",
470                                 L"",
471                                 258+m_fields.size()
472                         );
473
474                 bool is_horizontal = true;
475
476                 if (parts[2] == "vertical")
477                         is_horizontal = false;
478
479                 spec.ftype = f_ScrollBar;
480                 spec.send  = true;
481                 gui::IGUIScrollBar* e =
482                                 Environment->addScrollBar(is_horizontal,rect,this,spec.fid);
483
484                 e->setMax(1000);
485                 e->setMin(0);
486                 e->setPos(stoi(parts[4]));
487                 e->setSmallStep(10);
488                 e->setLargeStep(100);
489
490                 m_scrollbars.emplace_back(spec,e);
491                 m_fields.push_back(spec);
492                 return;
493         }
494         errorstream<< "Invalid scrollbar element(" << parts.size() << "): '" << element << "'"  << std::endl;
495 }
496
497 void GUIFormSpecMenu::parseImage(parserData* data, const std::string &element)
498 {
499         std::vector<std::string> parts = split(element,';');
500
501         if ((parts.size() == 3) ||
502                 ((parts.size() > 3) && (m_formspec_version > FORMSPEC_API_VERSION)))
503         {
504                 std::vector<std::string> v_pos = split(parts[0],',');
505                 std::vector<std::string> v_geom = split(parts[1],',');
506                 std::string name = unescape_string(parts[2]);
507
508                 MY_CHECKPOS("image", 0);
509                 MY_CHECKGEOM("image", 1);
510
511                 v2s32 pos = padding + AbsoluteRect.UpperLeftCorner + pos_offset * spacing;
512                 pos.X += stof(v_pos[0]) * (float) spacing.X;
513                 pos.Y += stof(v_pos[1]) * (float) spacing.Y;
514
515                 v2s32 geom;
516                 geom.X = stof(v_geom[0]) * (float)imgsize.X;
517                 geom.Y = stof(v_geom[1]) * (float)imgsize.Y;
518
519                 if (!data->explicit_size)
520                         warningstream<<"invalid use of image without a size[] element"<<std::endl;
521                 m_images.emplace_back(name, pos, geom);
522                 return;
523         }
524
525         if (parts.size() == 2) {
526                 std::vector<std::string> v_pos = split(parts[0],',');
527                 std::string name = unescape_string(parts[1]);
528
529                 MY_CHECKPOS("image", 0);
530
531                 v2s32 pos = padding + AbsoluteRect.UpperLeftCorner + pos_offset * spacing;
532                 pos.X += stof(v_pos[0]) * (float) spacing.X;
533                 pos.Y += stof(v_pos[1]) * (float) spacing.Y;
534
535                 if (!data->explicit_size)
536                         warningstream<<"invalid use of image without a size[] element"<<std::endl;
537                 m_images.emplace_back(name, pos);
538                 return;
539         }
540         errorstream<< "Invalid image element(" << parts.size() << "): '" << element << "'"  << std::endl;
541 }
542
543 void GUIFormSpecMenu::parseItemImage(parserData* data, const std::string &element)
544 {
545         std::vector<std::string> parts = split(element,';');
546
547         if ((parts.size() == 3) ||
548                 ((parts.size() > 3) && (m_formspec_version > FORMSPEC_API_VERSION)))
549         {
550                 std::vector<std::string> v_pos = split(parts[0],',');
551                 std::vector<std::string> v_geom = split(parts[1],',');
552                 std::string name = parts[2];
553
554                 MY_CHECKPOS("itemimage",0);
555                 MY_CHECKGEOM("itemimage",1);
556
557                 v2s32 pos = padding + AbsoluteRect.UpperLeftCorner + pos_offset * spacing;
558                 pos.X += stof(v_pos[0]) * (float) spacing.X;
559                 pos.Y += stof(v_pos[1]) * (float) spacing.Y;
560
561                 v2s32 geom;
562                 geom.X = stof(v_geom[0]) * (float)imgsize.X;
563                 geom.Y = stof(v_geom[1]) * (float)imgsize.Y;
564
565                 if(!data->explicit_size)
566                         warningstream<<"invalid use of item_image without a size[] element"<<std::endl;
567                 m_itemimages.emplace_back("", name, pos, geom);
568                 return;
569         }
570         errorstream<< "Invalid ItemImage element(" << parts.size() << "): '" << element << "'"  << std::endl;
571 }
572
573 void GUIFormSpecMenu::parseButton(parserData* data, const std::string &element,
574                 const std::string &type)
575 {
576         std::vector<std::string> parts = split(element,';');
577
578         if ((parts.size() == 4) ||
579                 ((parts.size() > 4) && (m_formspec_version > FORMSPEC_API_VERSION)))
580         {
581                 std::vector<std::string> v_pos = split(parts[0],',');
582                 std::vector<std::string> v_geom = split(parts[1],',');
583                 std::string name = parts[2];
584                 std::string label = parts[3];
585
586                 MY_CHECKPOS("button",0);
587                 MY_CHECKGEOM("button",1);
588
589                 v2s32 pos = padding + pos_offset * spacing;
590                 pos.X += stof(v_pos[0]) * (float)spacing.X;
591                 pos.Y += stof(v_pos[1]) * (float)spacing.Y;
592
593                 v2s32 geom;
594                 geom.X = (stof(v_geom[0]) * (float)spacing.X)-(spacing.X-imgsize.X);
595                 pos.Y += (stof(v_geom[1]) * (float)imgsize.Y)/2;
596
597                 core::rect<s32> rect =
598                                 core::rect<s32>(pos.X, pos.Y - m_btn_height,
599                                                 pos.X + geom.X, pos.Y + m_btn_height);
600
601                 if(!data->explicit_size)
602                         warningstream<<"invalid use of button without a size[] element"<<std::endl;
603
604                 std::wstring wlabel = translate_string(utf8_to_wide(unescape_string(label)));
605
606                 FieldSpec spec(
607                         name,
608                         wlabel,
609                         L"",
610                         258+m_fields.size()
611                 );
612                 spec.ftype = f_Button;
613                 if(type == "button_exit")
614                         spec.is_exit = true;
615                 gui::IGUIButton* e = Environment->addButton(rect, this, spec.fid,
616                                 spec.flabel.c_str());
617
618                 if (spec.fname == data->focused_fieldname) {
619                         Environment->setFocus(e);
620                 }
621
622                 m_fields.push_back(spec);
623                 return;
624         }
625         errorstream<< "Invalid button element(" << parts.size() << "): '" << element << "'"  << std::endl;
626 }
627
628 void GUIFormSpecMenu::parseBackground(parserData* data, const std::string &element)
629 {
630         std::vector<std::string> parts = split(element,';');
631
632         if (((parts.size() == 3) || (parts.size() == 4)) ||
633                 ((parts.size() > 4) && (m_formspec_version > FORMSPEC_API_VERSION)))
634         {
635                 std::vector<std::string> v_pos = split(parts[0],',');
636                 std::vector<std::string> v_geom = split(parts[1],',');
637                 std::string name = unescape_string(parts[2]);
638
639                 MY_CHECKPOS("background",0);
640                 MY_CHECKGEOM("background",1);
641
642                 v2s32 pos = padding + AbsoluteRect.UpperLeftCorner + pos_offset * spacing;
643                 pos.X += stof(v_pos[0]) * (float)spacing.X - ((float)spacing.X - (float)imgsize.X)/2;
644                 pos.Y += stof(v_pos[1]) * (float)spacing.Y - ((float)spacing.Y - (float)imgsize.Y)/2;
645
646                 v2s32 geom;
647                 geom.X = stof(v_geom[0]) * (float)spacing.X;
648                 geom.Y = stof(v_geom[1]) * (float)spacing.Y;
649
650                 if (!data->explicit_size)
651                         warningstream<<"invalid use of background without a size[] element"<<std::endl;
652
653                 bool clip = false;
654                 if (parts.size() == 4 && is_yes(parts[3])) {
655                         pos.X = stoi(v_pos[0]); //acts as offset
656                         pos.Y = stoi(v_pos[1]); //acts as offset
657                         clip = true;
658                 }
659                 m_backgrounds.emplace_back(name, pos, geom, clip);
660
661                 return;
662         }
663         errorstream<< "Invalid background element(" << parts.size() << "): '" << element << "'"  << std::endl;
664 }
665
666 void GUIFormSpecMenu::parseTableOptions(parserData* data, const std::string &element)
667 {
668         std::vector<std::string> parts = split(element,';');
669
670         data->table_options.clear();
671         for (const std::string &part : parts) {
672                 // Parse table option
673                 std::string opt = unescape_string(part);
674                 data->table_options.push_back(GUITable::splitOption(opt));
675         }
676 }
677
678 void GUIFormSpecMenu::parseTableColumns(parserData* data, const std::string &element)
679 {
680         std::vector<std::string> parts = split(element,';');
681
682         data->table_columns.clear();
683         for (const std::string &part : parts) {
684                 std::vector<std::string> col_parts = split(part,',');
685                 GUITable::TableColumn column;
686                 // Parse column type
687                 if (!col_parts.empty())
688                         column.type = col_parts[0];
689                 // Parse column options
690                 for (size_t j = 1; j < col_parts.size(); ++j) {
691                         std::string opt = unescape_string(col_parts[j]);
692                         column.options.push_back(GUITable::splitOption(opt));
693                 }
694                 data->table_columns.push_back(column);
695         }
696 }
697
698 void GUIFormSpecMenu::parseTable(parserData* data, const std::string &element)
699 {
700         std::vector<std::string> parts = split(element,';');
701
702         if (((parts.size() == 4) || (parts.size() == 5)) ||
703                 ((parts.size() > 5) && (m_formspec_version > FORMSPEC_API_VERSION)))
704         {
705                 std::vector<std::string> v_pos = split(parts[0],',');
706                 std::vector<std::string> v_geom = split(parts[1],',');
707                 std::string name = parts[2];
708                 std::vector<std::string> items = split(parts[3],',');
709                 std::string str_initial_selection;
710                 std::string str_transparent = "false";
711
712                 if (parts.size() >= 5)
713                         str_initial_selection = parts[4];
714
715                 MY_CHECKPOS("table",0);
716                 MY_CHECKGEOM("table",1);
717
718                 v2s32 pos = padding + pos_offset * spacing;
719                 pos.X += stof(v_pos[0]) * (float)spacing.X;
720                 pos.Y += stof(v_pos[1]) * (float)spacing.Y;
721
722                 v2s32 geom;
723                 geom.X = stof(v_geom[0]) * (float)spacing.X;
724                 geom.Y = stof(v_geom[1]) * (float)spacing.Y;
725
726                 core::rect<s32> rect = core::rect<s32>(pos.X, pos.Y, pos.X+geom.X, pos.Y+geom.Y);
727
728                 FieldSpec spec(
729                         name,
730                         L"",
731                         L"",
732                         258+m_fields.size()
733                 );
734
735                 spec.ftype = f_Table;
736
737                 for (std::string &item : items) {
738                         item = wide_to_utf8(unescape_translate(utf8_to_wide(unescape_string(item))));
739                 }
740
741                 //now really show table
742                 GUITable *e = new GUITable(Environment, this, spec.fid, rect,
743                                 m_tsrc);
744
745                 if (spec.fname == data->focused_fieldname) {
746                         Environment->setFocus(e);
747                 }
748
749                 e->setTable(data->table_options, data->table_columns, items);
750
751                 if (data->table_dyndata.find(name) != data->table_dyndata.end()) {
752                         e->setDynamicData(data->table_dyndata[name]);
753                 }
754
755                 if (!str_initial_selection.empty() && str_initial_selection != "0")
756                         e->setSelected(stoi(str_initial_selection));
757
758                 m_tables.emplace_back(spec, e);
759                 m_fields.push_back(spec);
760                 return;
761         }
762         errorstream<< "Invalid table element(" << parts.size() << "): '" << element << "'"  << std::endl;
763 }
764
765 void GUIFormSpecMenu::parseTextList(parserData* data, const std::string &element)
766 {
767         std::vector<std::string> parts = split(element,';');
768
769         if (((parts.size() == 4) || (parts.size() == 5) || (parts.size() == 6)) ||
770                 ((parts.size() > 6) && (m_formspec_version > FORMSPEC_API_VERSION)))
771         {
772                 std::vector<std::string> v_pos = split(parts[0],',');
773                 std::vector<std::string> v_geom = split(parts[1],',');
774                 std::string name = parts[2];
775                 std::vector<std::string> items = split(parts[3],',');
776                 std::string str_initial_selection;
777                 std::string str_transparent = "false";
778
779                 if (parts.size() >= 5)
780                         str_initial_selection = parts[4];
781
782                 if (parts.size() >= 6)
783                         str_transparent = parts[5];
784
785                 MY_CHECKPOS("textlist",0);
786                 MY_CHECKGEOM("textlist",1);
787
788                 v2s32 pos = padding + pos_offset * spacing;
789                 pos.X += stof(v_pos[0]) * (float)spacing.X;
790                 pos.Y += stof(v_pos[1]) * (float)spacing.Y;
791
792                 v2s32 geom;
793                 geom.X = stof(v_geom[0]) * (float)spacing.X;
794                 geom.Y = stof(v_geom[1]) * (float)spacing.Y;
795
796
797                 core::rect<s32> rect = core::rect<s32>(pos.X, pos.Y, pos.X+geom.X, pos.Y+geom.Y);
798
799                 FieldSpec spec(
800                         name,
801                         L"",
802                         L"",
803                         258+m_fields.size()
804                 );
805
806                 spec.ftype = f_Table;
807
808                 for (std::string &item : items) {
809                         item = wide_to_utf8(unescape_translate(utf8_to_wide(unescape_string(item))));
810                 }
811
812                 //now really show list
813                 GUITable *e = new GUITable(Environment, this, spec.fid, rect,
814                                 m_tsrc);
815
816                 if (spec.fname == data->focused_fieldname) {
817                         Environment->setFocus(e);
818                 }
819
820                 e->setTextList(items, is_yes(str_transparent));
821
822                 if (data->table_dyndata.find(name) != data->table_dyndata.end()) {
823                         e->setDynamicData(data->table_dyndata[name]);
824                 }
825
826                 if (!str_initial_selection.empty() && str_initial_selection != "0")
827                         e->setSelected(stoi(str_initial_selection));
828
829                 m_tables.emplace_back(spec, e);
830                 m_fields.push_back(spec);
831                 return;
832         }
833         errorstream<< "Invalid textlist element(" << parts.size() << "): '" << element << "'"  << std::endl;
834 }
835
836
837 void GUIFormSpecMenu::parseDropDown(parserData* data, const std::string &element)
838 {
839         std::vector<std::string> parts = split(element,';');
840
841         if ((parts.size() == 5) ||
842                 ((parts.size() > 5) && (m_formspec_version > FORMSPEC_API_VERSION)))
843         {
844                 std::vector<std::string> v_pos = split(parts[0],',');
845                 std::string name = parts[2];
846                 std::vector<std::string> items = split(parts[3],',');
847                 std::string str_initial_selection;
848                 str_initial_selection = parts[4];
849
850                 MY_CHECKPOS("dropdown",0);
851
852                 v2s32 pos = padding + pos_offset * spacing;
853                 pos.X += stof(v_pos[0]) * (float)spacing.X;
854                 pos.Y += stof(v_pos[1]) * (float)spacing.Y;
855
856                 s32 width = stof(parts[1]) * (float)spacing.Y;
857
858                 core::rect<s32> rect = core::rect<s32>(pos.X, pos.Y,
859                                 pos.X + width, pos.Y + (m_btn_height * 2));
860
861                 FieldSpec spec(
862                         name,
863                         L"",
864                         L"",
865                         258+m_fields.size()
866                 );
867
868                 spec.ftype = f_DropDown;
869                 spec.send = true;
870
871                 //now really show list
872                 gui::IGUIComboBox *e = Environment->addComboBox(rect, this,spec.fid);
873
874                 if (spec.fname == data->focused_fieldname) {
875                         Environment->setFocus(e);
876                 }
877
878                 for (const std::string &item : items) {
879                         e->addItem(unescape_translate(unescape_string(
880                                 utf8_to_wide(item))).c_str());
881                 }
882
883                 if (!str_initial_selection.empty())
884                         e->setSelected(stoi(str_initial_selection)-1);
885
886                 m_fields.push_back(spec);
887
888                 m_dropdowns.emplace_back(spec, std::vector<std::string>());
889                 std::vector<std::string> &values = m_dropdowns.back().second;
890                 for (const std::string &item : items) {
891                         values.push_back(unescape_string(item));
892                 }
893
894                 return;
895         }
896         errorstream << "Invalid dropdown element(" << parts.size() << "): '"
897                                 << element << "'"  << std::endl;
898 }
899
900 void GUIFormSpecMenu::parseFieldCloseOnEnter(parserData *data, const std::string &element)
901 {
902         std::vector<std::string> parts = split(element,';');
903         if (parts.size() == 2 ||
904                         (parts.size() > 2 && m_formspec_version > FORMSPEC_API_VERSION)) {
905                 field_close_on_enter[parts[0]] = is_yes(parts[1]);
906         }
907 }
908
909 void GUIFormSpecMenu::parsePwdField(parserData* data, const std::string &element)
910 {
911         std::vector<std::string> parts = split(element,';');
912
913         if ((parts.size() == 4) || (parts.size() == 5) ||
914                 ((parts.size() > 5) && (m_formspec_version > FORMSPEC_API_VERSION)))
915         {
916                 std::vector<std::string> v_pos = split(parts[0],',');
917                 std::vector<std::string> v_geom = split(parts[1],',');
918                 std::string name = parts[2];
919                 std::string label = parts[3];
920
921                 MY_CHECKPOS("pwdfield",0);
922                 MY_CHECKGEOM("pwdfield",1);
923
924                 v2s32 pos = pos_offset * spacing;
925                 pos.X += stof(v_pos[0]) * (float)spacing.X;
926                 pos.Y += stof(v_pos[1]) * (float)spacing.Y;
927
928                 v2s32 geom;
929                 geom.X = (stof(v_geom[0]) * (float)spacing.X)-(spacing.X-imgsize.X);
930
931                 pos.Y += (stof(v_geom[1]) * (float)imgsize.Y)/2;
932                 pos.Y -= m_btn_height;
933                 geom.Y = m_btn_height*2;
934
935                 core::rect<s32> rect = core::rect<s32>(pos.X, pos.Y, pos.X+geom.X, pos.Y+geom.Y);
936
937                 std::wstring wlabel = translate_string(utf8_to_wide(unescape_string(label)));
938
939                 FieldSpec spec(
940                         name,
941                         wlabel,
942                         L"",
943                         258+m_fields.size()
944                         );
945
946                 spec.send = true;
947                 gui::IGUIEditBox * e = Environment->addEditBox(0, rect, true, this, spec.fid);
948
949                 if (spec.fname == data->focused_fieldname) {
950                         Environment->setFocus(e);
951                 }
952
953                 if (label.length() >= 1)
954                 {
955                         int font_height = g_fontengine->getTextHeight();
956                         rect.UpperLeftCorner.Y -= font_height;
957                         rect.LowerRightCorner.Y = rect.UpperLeftCorner.Y + font_height;
958                         addStaticText(Environment, spec.flabel.c_str(), rect, false, true, this, 0);
959                 }
960
961                 e->setPasswordBox(true,L'*');
962
963                 irr::SEvent evt;
964                 evt.EventType            = EET_KEY_INPUT_EVENT;
965                 evt.KeyInput.Key         = KEY_END;
966                 evt.KeyInput.Char        = 0;
967                 evt.KeyInput.Control     = false;
968                 evt.KeyInput.Shift       = false;
969                 evt.KeyInput.PressedDown = true;
970                 e->OnEvent(evt);
971
972                 if (parts.size() >= 5) {
973                         // TODO: remove after 2016-11-03
974                         warningstream << "pwdfield: use field_close_on_enter[name, enabled]" <<
975                                         " instead of the 5th param" << std::endl;
976                         field_close_on_enter[name] = is_yes(parts[4]);
977                 }
978
979                 m_fields.push_back(spec);
980                 return;
981         }
982         errorstream<< "Invalid pwdfield element(" << parts.size() << "): '" << element << "'"  << std::endl;
983 }
984
985 void GUIFormSpecMenu::parseSimpleField(parserData* data,
986                 std::vector<std::string> &parts)
987 {
988         std::string name = parts[0];
989         std::string label = parts[1];
990         std::string default_val = parts[2];
991
992         core::rect<s32> rect;
993
994         if(data->explicit_size)
995                 warningstream<<"invalid use of unpositioned \"field\" in inventory"<<std::endl;
996
997         v2s32 pos = padding + AbsoluteRect.UpperLeftCorner + pos_offset * spacing;
998         pos.Y = ((m_fields.size()+2)*60);
999         v2s32 size = DesiredRect.getSize();
1000
1001         rect = core::rect<s32>(size.X / 2 - 150, pos.Y,
1002                         (size.X / 2 - 150) + 300, pos.Y + (m_btn_height*2));
1003
1004
1005         if(m_form_src)
1006                 default_val = m_form_src->resolveText(default_val);
1007
1008
1009         std::wstring wlabel = translate_string(utf8_to_wide(unescape_string(label)));
1010
1011         FieldSpec spec(
1012                 name,
1013                 wlabel,
1014                 utf8_to_wide(unescape_string(default_val)),
1015                 258+m_fields.size()
1016         );
1017
1018         if (name.empty()) {
1019                 // spec field id to 0, this stops submit searching for a value that isn't there
1020                 addStaticText(Environment, spec.flabel.c_str(), rect, false, true, this, spec.fid);
1021         } else {
1022                 spec.send = true;
1023                 gui::IGUIElement *e;
1024 #if USE_FREETYPE && IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR < 9
1025                 if (g_settings->getBool("freetype")) {
1026                         e = (gui::IGUIElement *) new gui::intlGUIEditBox(spec.fdefault.c_str(),
1027                                 true, Environment, this, spec.fid, rect);
1028                         e->drop();
1029                 } else {
1030 #else
1031                 {
1032 #endif
1033                         e = Environment->addEditBox(spec.fdefault.c_str(), rect, true, this, spec.fid);
1034                 }
1035                 if (spec.fname == data->focused_fieldname) {
1036                         Environment->setFocus(e);
1037                 }
1038
1039                 irr::SEvent evt;
1040                 evt.EventType            = EET_KEY_INPUT_EVENT;
1041                 evt.KeyInput.Key         = KEY_END;
1042                 evt.KeyInput.Char        = 0;
1043                 evt.KeyInput.Control     = 0;
1044                 evt.KeyInput.Shift       = 0;
1045                 evt.KeyInput.PressedDown = true;
1046                 e->OnEvent(evt);
1047
1048                 if (label.length() >= 1)
1049                 {
1050                         int font_height = g_fontengine->getTextHeight();
1051                         rect.UpperLeftCorner.Y -= font_height;
1052                         rect.LowerRightCorner.Y = rect.UpperLeftCorner.Y + font_height;
1053                         addStaticText(Environment, spec.flabel.c_str(), rect, false, true, this, 0);
1054                 }
1055         }
1056
1057         if (parts.size() >= 4) {
1058                 // TODO: remove after 2016-11-03
1059                 warningstream << "field/simple: use field_close_on_enter[name, enabled]" <<
1060                                 " instead of the 4th param" << std::endl;
1061                 field_close_on_enter[name] = is_yes(parts[3]);
1062         }
1063
1064         m_fields.push_back(spec);
1065 }
1066
1067 void GUIFormSpecMenu::parseTextArea(parserData* data, std::vector<std::string>& parts,
1068                 const std::string &type)
1069 {
1070
1071         std::vector<std::string> v_pos = split(parts[0],',');
1072         std::vector<std::string> v_geom = split(parts[1],',');
1073         std::string name = parts[2];
1074         std::string label = parts[3];
1075         std::string default_val = parts[4];
1076
1077         MY_CHECKPOS(type,0);
1078         MY_CHECKGEOM(type,1);
1079
1080         v2s32 pos = pos_offset * spacing;
1081         pos.X += stof(v_pos[0]) * (float) spacing.X;
1082         pos.Y += stof(v_pos[1]) * (float) spacing.Y;
1083
1084         v2s32 geom;
1085
1086         geom.X = (stof(v_geom[0]) * (float)spacing.X)-(spacing.X-imgsize.X);
1087
1088         if (type == "textarea")
1089         {
1090                 geom.Y = (stof(v_geom[1]) * (float)imgsize.Y) - (spacing.Y-imgsize.Y);
1091                 pos.Y += m_btn_height;
1092         }
1093         else
1094         {
1095                 pos.Y += (stof(v_geom[1]) * (float)imgsize.Y)/2;
1096                 pos.Y -= m_btn_height;
1097                 geom.Y = m_btn_height*2;
1098         }
1099
1100         core::rect<s32> rect = core::rect<s32>(pos.X, pos.Y, pos.X+geom.X, pos.Y+geom.Y);
1101
1102         if(!data->explicit_size)
1103                 warningstream<<"invalid use of positioned "<<type<<" without a size[] element"<<std::endl;
1104
1105         if(m_form_src)
1106                 default_val = m_form_src->resolveText(default_val);
1107
1108
1109         std::wstring wlabel = translate_string(utf8_to_wide(unescape_string(label)));
1110
1111         FieldSpec spec(
1112                 name,
1113                 wlabel,
1114                 utf8_to_wide(unescape_string(default_val)),
1115                 258+m_fields.size()
1116         );
1117
1118         bool is_editable = !name.empty();
1119
1120         if (is_editable)
1121                 spec.send = true;
1122
1123         gui::IGUIEditBox *e = nullptr;
1124         const wchar_t *text = spec.fdefault.empty() ?
1125                 wlabel.c_str() : spec.fdefault.c_str();
1126
1127 #if USE_FREETYPE && IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR < 9
1128         if (g_settings->getBool("freetype")) {
1129                 e = (gui::IGUIEditBox *) new gui::intlGUIEditBox(text,
1130                         true, Environment, this, spec.fid, rect, is_editable, true);
1131                 e->drop();
1132         } else {
1133 #else
1134         {
1135 #endif
1136                 e = new GUIEditBoxWithScrollBar(text, true,
1137                         Environment, this, spec.fid, rect, is_editable, true);
1138         }
1139
1140         if (is_editable && spec.fname == data->focused_fieldname)
1141                 Environment->setFocus(e);
1142
1143         if (e) {
1144                 if (type == "textarea")
1145                 {
1146                         e->setMultiLine(true);
1147                         e->setWordWrap(true);
1148                         e->setTextAlignment(gui::EGUIA_UPPERLEFT, gui::EGUIA_UPPERLEFT);
1149                 } else {
1150                         irr::SEvent evt;
1151                         evt.EventType            = EET_KEY_INPUT_EVENT;
1152                         evt.KeyInput.Key         = KEY_END;
1153                         evt.KeyInput.Char        = 0;
1154                         evt.KeyInput.Control     = 0;
1155                         evt.KeyInput.Shift       = 0;
1156                         evt.KeyInput.PressedDown = true;
1157                         e->OnEvent(evt);
1158                 }
1159         }
1160
1161         if (is_editable && !label.empty()) {
1162                 int font_height = g_fontengine->getTextHeight();
1163                 rect.UpperLeftCorner.Y -= font_height;
1164                 rect.LowerRightCorner.Y = rect.UpperLeftCorner.Y + font_height;
1165                 addStaticText(Environment, spec.flabel.c_str(), rect, false, true, this, 0);
1166         }
1167
1168         if (parts.size() >= 6) {
1169                 // TODO: remove after 2016-11-03
1170                 warningstream << "field/textarea: use field_close_on_enter[name, enabled]" <<
1171                                 " instead of the 6th param" << std::endl;
1172                 field_close_on_enter[name] = is_yes(parts[5]);
1173         }
1174
1175         m_fields.push_back(spec);
1176 }
1177
1178 void GUIFormSpecMenu::parseField(parserData* data, const std::string &element,
1179                 const std::string &type)
1180 {
1181         std::vector<std::string> parts = split(element,';');
1182
1183         if (parts.size() == 3 || parts.size() == 4) {
1184                 parseSimpleField(data,parts);
1185                 return;
1186         }
1187
1188         if ((parts.size() == 5) || (parts.size() == 6) ||
1189                 ((parts.size() > 6) && (m_formspec_version > FORMSPEC_API_VERSION)))
1190         {
1191                 parseTextArea(data,parts,type);
1192                 return;
1193         }
1194         errorstream<< "Invalid field element(" << parts.size() << "): '" << element << "'"  << std::endl;
1195 }
1196
1197 void GUIFormSpecMenu::parseLabel(parserData* data, const std::string &element)
1198 {
1199         std::vector<std::string> parts = split(element,';');
1200
1201         if ((parts.size() == 2) ||
1202                 ((parts.size() > 2) && (m_formspec_version > FORMSPEC_API_VERSION)))
1203         {
1204                 std::vector<std::string> v_pos = split(parts[0],',');
1205                 std::string text = parts[1];
1206
1207                 MY_CHECKPOS("label",0);
1208
1209                 v2s32 pos = padding + pos_offset * spacing;
1210                 pos.X += stof(v_pos[0]) * (float)spacing.X;
1211                 pos.Y += (stof(v_pos[1]) + 7.0/30.0) * (float)spacing.Y;
1212
1213                 if(!data->explicit_size)
1214                         warningstream<<"invalid use of label without a size[] element"<<std::endl;
1215
1216                 std::vector<std::string> lines = split(text, '\n');
1217
1218                 for (unsigned int i = 0; i != lines.size(); i++) {
1219                         // Lines are spaced at the nominal distance of
1220                         // 2/5 inventory slot, even if the font doesn't
1221                         // quite match that.  This provides consistent
1222                         // form layout, at the expense of sometimes
1223                         // having sub-optimal spacing for the font.
1224                         // We multiply by 2 and then divide by 5, rather
1225                         // than multiply by 0.4, to get exact results
1226                         // in the integer cases: 0.4 is not exactly
1227                         // representable in binary floating point.
1228                         s32 posy = pos.Y + ((float)i) * spacing.Y * 2.0 / 5.0;
1229                         std::wstring wlabel = utf8_to_wide(unescape_string(lines[i]));
1230                         core::rect<s32> rect = core::rect<s32>(
1231                                 pos.X, posy - m_btn_height,
1232                                 pos.X + m_font->getDimension(wlabel.c_str()).Width,
1233                                 posy + m_btn_height);
1234                         FieldSpec spec(
1235                                 "",
1236                                 wlabel,
1237                                 L"",
1238                                 258+m_fields.size()
1239                         );
1240                         gui::IGUIStaticText *e =
1241                                 addStaticText(Environment, spec.flabel.c_str(),
1242                                         rect, false, false, this, spec.fid);
1243                         e->setTextAlignment(gui::EGUIA_UPPERLEFT,
1244                                                 gui::EGUIA_CENTER);
1245                         m_fields.push_back(spec);
1246                 }
1247
1248                 return;
1249         }
1250         errorstream<< "Invalid label element(" << parts.size() << "): '" << element << "'"  << std::endl;
1251 }
1252
1253 void GUIFormSpecMenu::parseVertLabel(parserData* data, const std::string &element)
1254 {
1255         std::vector<std::string> parts = split(element,';');
1256
1257         if ((parts.size() == 2) ||
1258                 ((parts.size() > 2) && (m_formspec_version > FORMSPEC_API_VERSION)))
1259         {
1260                 std::vector<std::string> v_pos = split(parts[0],',');
1261                 std::wstring text = unescape_translate(
1262                         unescape_string(utf8_to_wide(parts[1])));
1263
1264                 MY_CHECKPOS("vertlabel",1);
1265
1266                 v2s32 pos = padding + pos_offset * spacing;
1267                 pos.X += stof(v_pos[0]) * (float)spacing.X;
1268                 pos.Y += stof(v_pos[1]) * (float)spacing.Y;
1269
1270                 core::rect<s32> rect = core::rect<s32>(
1271                                 pos.X, pos.Y+((imgsize.Y/2)- m_btn_height),
1272                                 pos.X+15, pos.Y +
1273                                         font_line_height(m_font)
1274                                         * (text.length()+1)
1275                                         +((imgsize.Y/2)- m_btn_height));
1276                 //actually text.length() would be correct but adding +1 avoids to break all mods
1277
1278                 if(!data->explicit_size)
1279                         warningstream<<"invalid use of label without a size[] element"<<std::endl;
1280
1281                 std::wstring label;
1282
1283                 for (wchar_t i : text) {
1284                         label += i;
1285                         label += L"\n";
1286                 }
1287
1288                 FieldSpec spec(
1289                         "",
1290                         label,
1291                         L"",
1292                         258+m_fields.size()
1293                 );
1294                 gui::IGUIStaticText *t =
1295                                 addStaticText(Environment, spec.flabel.c_str(), rect, false, false, this, spec.fid);
1296                 t->setTextAlignment(gui::EGUIA_CENTER, gui::EGUIA_CENTER);
1297                 m_fields.push_back(spec);
1298                 return;
1299         }
1300         errorstream<< "Invalid vertlabel element(" << parts.size() << "): '" << element << "'"  << std::endl;
1301 }
1302
1303 void GUIFormSpecMenu::parseImageButton(parserData* data, const std::string &element,
1304                 const std::string &type)
1305 {
1306         std::vector<std::string> parts = split(element,';');
1307
1308         if ((((parts.size() >= 5) && (parts.size() <= 8)) && (parts.size() != 6)) ||
1309                 ((parts.size() > 8) && (m_formspec_version > FORMSPEC_API_VERSION)))
1310         {
1311                 std::vector<std::string> v_pos = split(parts[0],',');
1312                 std::vector<std::string> v_geom = split(parts[1],',');
1313                 std::string image_name = parts[2];
1314                 std::string name = parts[3];
1315                 std::string label = parts[4];
1316
1317                 MY_CHECKPOS("imagebutton",0);
1318                 MY_CHECKGEOM("imagebutton",1);
1319
1320                 v2s32 pos = padding + pos_offset * spacing;
1321                 pos.X += stof(v_pos[0]) * (float)spacing.X;
1322                 pos.Y += stof(v_pos[1]) * (float)spacing.Y;
1323                 v2s32 geom;
1324                 geom.X = (stof(v_geom[0]) * (float)spacing.X)-(spacing.X-imgsize.X);
1325                 geom.Y = (stof(v_geom[1]) * (float)spacing.Y)-(spacing.Y-imgsize.Y);
1326
1327                 bool noclip     = false;
1328                 bool drawborder = true;
1329                 std::string pressed_image_name;
1330
1331                 if (parts.size() >= 7) {
1332                         if (parts[5] == "true")
1333                                 noclip = true;
1334                         if (parts[6] == "false")
1335                                 drawborder = false;
1336                 }
1337
1338                 if (parts.size() >= 8) {
1339                         pressed_image_name = parts[7];
1340                 }
1341
1342                 core::rect<s32> rect = core::rect<s32>(pos.X, pos.Y, pos.X+geom.X, pos.Y+geom.Y);
1343
1344                 if(!data->explicit_size)
1345                         warningstream<<"invalid use of image_button without a size[] element"<<std::endl;
1346
1347                 image_name = unescape_string(image_name);
1348                 pressed_image_name = unescape_string(pressed_image_name);
1349
1350                 std::wstring wlabel = utf8_to_wide(unescape_string(label));
1351
1352                 FieldSpec spec(
1353                         name,
1354                         wlabel,
1355                         utf8_to_wide(image_name),
1356                         258+m_fields.size()
1357                 );
1358                 spec.ftype = f_Button;
1359                 if(type == "image_button_exit")
1360                         spec.is_exit = true;
1361
1362                 video::ITexture *texture = 0;
1363                 video::ITexture *pressed_texture = 0;
1364                 texture = m_tsrc->getTexture(image_name);
1365                 if (!pressed_image_name.empty())
1366                         pressed_texture = m_tsrc->getTexture(pressed_image_name);
1367                 else
1368                         pressed_texture = texture;
1369
1370                 gui::IGUIButton *e = Environment->addButton(rect, this, spec.fid, spec.flabel.c_str());
1371
1372                 if (spec.fname == data->focused_fieldname) {
1373                         Environment->setFocus(e);
1374                 }
1375
1376                 e->setUseAlphaChannel(true);
1377                 e->setImage(guiScalingImageButton(
1378                         Environment->getVideoDriver(), texture, geom.X, geom.Y));
1379                 e->setPressedImage(guiScalingImageButton(
1380                         Environment->getVideoDriver(), pressed_texture, geom.X, geom.Y));
1381                 e->setScaleImage(true);
1382                 e->setNotClipped(noclip);
1383                 e->setDrawBorder(drawborder);
1384
1385                 m_fields.push_back(spec);
1386                 return;
1387         }
1388
1389         errorstream<< "Invalid imagebutton element(" << parts.size() << "): '" << element << "'"  << std::endl;
1390 }
1391
1392 void GUIFormSpecMenu::parseTabHeader(parserData* data, const std::string &element)
1393 {
1394         std::vector<std::string> parts = split(element,';');
1395
1396         if (((parts.size() == 4) || (parts.size() == 6)) ||
1397                 ((parts.size() > 6) && (m_formspec_version > FORMSPEC_API_VERSION)))
1398         {
1399                 std::vector<std::string> v_pos = split(parts[0],',');
1400                 std::string name = parts[1];
1401                 std::vector<std::string> buttons = split(parts[2],',');
1402                 std::string str_index = parts[3];
1403                 bool show_background = true;
1404                 bool show_border = true;
1405                 int tab_index = stoi(str_index) -1;
1406
1407                 MY_CHECKPOS("tabheader",0);
1408
1409                 if (parts.size() == 6) {
1410                         if (parts[4] == "true")
1411                                 show_background = false;
1412                         if (parts[5] == "false")
1413                                 show_border = false;
1414                 }
1415
1416                 FieldSpec spec(
1417                         name,
1418                         L"",
1419                         L"",
1420                         258+m_fields.size()
1421                 );
1422
1423                 spec.ftype = f_TabHeader;
1424
1425                 v2s32 pos = pos_offset * spacing;
1426                 pos.X += stof(v_pos[0]) * (float)spacing.X;
1427                 pos.Y += stof(v_pos[1]) * (float)spacing.Y - m_btn_height * 2;
1428                 v2s32 geom;
1429                 geom.X = DesiredRect.getWidth();
1430                 geom.Y = m_btn_height*2;
1431
1432                 core::rect<s32> rect = core::rect<s32>(pos.X, pos.Y, pos.X+geom.X,
1433                                 pos.Y+geom.Y);
1434
1435                 gui::IGUITabControl *e = Environment->addTabControl(rect, this,
1436                                 show_background, show_border, spec.fid);
1437                 e->setAlignment(irr::gui::EGUIA_UPPERLEFT, irr::gui::EGUIA_UPPERLEFT,
1438                                 irr::gui::EGUIA_UPPERLEFT, irr::gui::EGUIA_LOWERRIGHT);
1439                 e->setTabHeight(m_btn_height*2);
1440
1441                 if (spec.fname == data->focused_fieldname) {
1442                         Environment->setFocus(e);
1443                 }
1444
1445                 e->setNotClipped(true);
1446
1447                 for (const std::string &button : buttons) {
1448                         e->addTab(unescape_translate(unescape_string(
1449                                 utf8_to_wide(button))).c_str(), -1);
1450                 }
1451
1452                 if ((tab_index >= 0) &&
1453                                 (buttons.size() < INT_MAX) &&
1454                                 (tab_index < (int) buttons.size()))
1455                         e->setActiveTab(tab_index);
1456
1457                 m_fields.push_back(spec);
1458                 return;
1459         }
1460         errorstream << "Invalid TabHeader element(" << parts.size() << "): '"
1461                         << element << "'"  << std::endl;
1462 }
1463
1464 void GUIFormSpecMenu::parseItemImageButton(parserData* data, const std::string &element)
1465 {
1466
1467         if (m_client == 0) {
1468                 warningstream << "invalid use of item_image_button with m_client==0"
1469                         << std::endl;
1470                 return;
1471         }
1472
1473         std::vector<std::string> parts = split(element,';');
1474
1475         if ((parts.size() == 5) ||
1476                 ((parts.size() > 5) && (m_formspec_version > FORMSPEC_API_VERSION)))
1477         {
1478                 std::vector<std::string> v_pos = split(parts[0],',');
1479                 std::vector<std::string> v_geom = split(parts[1],',');
1480                 std::string item_name = parts[2];
1481                 std::string name = parts[3];
1482                 std::string label = parts[4];
1483
1484                 label = unescape_string(label);
1485                 item_name = unescape_string(item_name);
1486
1487                 MY_CHECKPOS("itemimagebutton",0);
1488                 MY_CHECKGEOM("itemimagebutton",1);
1489
1490                 v2s32 pos = padding + pos_offset * spacing;
1491                 pos.X += stof(v_pos[0]) * (float)spacing.X;
1492                 pos.Y += stof(v_pos[1]) * (float)spacing.Y;
1493                 v2s32 geom;
1494                 geom.X = (stof(v_geom[0]) * (float)spacing.X)-(spacing.X-imgsize.X);
1495                 geom.Y = (stof(v_geom[1]) * (float)spacing.Y)-(spacing.Y-imgsize.Y);
1496
1497                 core::rect<s32> rect = core::rect<s32>(pos.X, pos.Y, pos.X+geom.X, pos.Y+geom.Y);
1498
1499                 if(!data->explicit_size)
1500                         warningstream<<"invalid use of item_image_button without a size[] element"<<std::endl;
1501
1502                 IItemDefManager *idef = m_client->idef();
1503                 ItemStack item;
1504                 item.deSerialize(item_name, idef);
1505
1506                 m_tooltips[name] =
1507                         TooltipSpec(utf8_to_wide(item.getDefinition(idef).description),
1508                                                 m_default_tooltip_bgcolor,
1509                                                 m_default_tooltip_color);
1510
1511                 FieldSpec spec(
1512                         name,
1513                         utf8_to_wide(label),
1514                         utf8_to_wide(item_name),
1515                         258 + m_fields.size()
1516                 );
1517
1518                 gui::IGUIButton *e = Environment->addButton(rect, this, spec.fid, L"");
1519
1520                 if (spec.fname == data->focused_fieldname) {
1521                         Environment->setFocus(e);
1522                 }
1523
1524                 spec.ftype = f_Button;
1525                 rect+=data->basepos-padding;
1526                 spec.rect=rect;
1527                 m_fields.push_back(spec);
1528                 pos = padding + AbsoluteRect.UpperLeftCorner + pos_offset * spacing;
1529                 pos.X += stof(v_pos[0]) * (float) spacing.X;
1530                 pos.Y += stof(v_pos[1]) * (float) spacing.Y;
1531                 m_itemimages.emplace_back("", item_name, e, pos, geom);
1532                 m_static_texts.emplace_back(utf8_to_wide(label), rect, e);
1533                 return;
1534         }
1535         errorstream<< "Invalid ItemImagebutton element(" << parts.size() << "): '" << element << "'"  << std::endl;
1536 }
1537
1538 void GUIFormSpecMenu::parseBox(parserData* data, const std::string &element)
1539 {
1540         std::vector<std::string> parts = split(element,';');
1541
1542         if ((parts.size() == 3) ||
1543                 ((parts.size() > 3) && (m_formspec_version > FORMSPEC_API_VERSION)))
1544         {
1545                 std::vector<std::string> v_pos = split(parts[0],',');
1546                 std::vector<std::string> v_geom = split(parts[1],',');
1547
1548                 MY_CHECKPOS("box",0);
1549                 MY_CHECKGEOM("box",1);
1550
1551                 v2s32 pos = padding + AbsoluteRect.UpperLeftCorner + pos_offset * spacing;
1552                 pos.X += stof(v_pos[0]) * (float) spacing.X;
1553                 pos.Y += stof(v_pos[1]) * (float) spacing.Y;
1554
1555                 v2s32 geom;
1556                 geom.X = stof(v_geom[0]) * (float)spacing.X;
1557                 geom.Y = stof(v_geom[1]) * (float)spacing.Y;
1558
1559                 video::SColor tmp_color;
1560
1561                 if (parseColorString(parts[2], tmp_color, false)) {
1562                         BoxDrawSpec spec(pos, geom, tmp_color);
1563
1564                         m_boxes.push_back(spec);
1565                 }
1566                 else {
1567                         errorstream<< "Invalid Box element(" << parts.size() << "): '" << element << "'  INVALID COLOR"  << std::endl;
1568                 }
1569                 return;
1570         }
1571         errorstream<< "Invalid Box element(" << parts.size() << "): '" << element << "'"  << std::endl;
1572 }
1573
1574 void GUIFormSpecMenu::parseBackgroundColor(parserData* data, const std::string &element)
1575 {
1576         std::vector<std::string> parts = split(element,';');
1577
1578         if (((parts.size() == 1) || (parts.size() == 2)) ||
1579                         ((parts.size() > 2) && (m_formspec_version > FORMSPEC_API_VERSION))) {
1580                 parseColorString(parts[0], m_bgcolor, false);
1581
1582                 if (parts.size() == 2) {
1583                         std::string fullscreen = parts[1];
1584                         m_bgfullscreen = is_yes(fullscreen);
1585                 }
1586
1587                 return;
1588         }
1589
1590         errorstream << "Invalid bgcolor element(" << parts.size() << "): '" << element << "'"
1591                         << std::endl;
1592 }
1593
1594 void GUIFormSpecMenu::parseListColors(parserData* data, const std::string &element)
1595 {
1596         std::vector<std::string> parts = split(element,';');
1597
1598         if (((parts.size() == 2) || (parts.size() == 3) || (parts.size() == 5)) ||
1599                 ((parts.size() > 5) && (m_formspec_version > FORMSPEC_API_VERSION)))
1600         {
1601                 parseColorString(parts[0], m_slotbg_n, false);
1602                 parseColorString(parts[1], m_slotbg_h, false);
1603
1604                 if (parts.size() >= 3) {
1605                         if (parseColorString(parts[2], m_slotbordercolor, false)) {
1606                                 m_slotborder = true;
1607                         }
1608                 }
1609                 if (parts.size() == 5) {
1610                         video::SColor tmp_color;
1611
1612                         if (parseColorString(parts[3], tmp_color, false))
1613                                 m_default_tooltip_bgcolor = tmp_color;
1614                         if (parseColorString(parts[4], tmp_color, false))
1615                                 m_default_tooltip_color = tmp_color;
1616                 }
1617                 return;
1618         }
1619         errorstream<< "Invalid listcolors element(" << parts.size() << "): '" << element << "'"  << std::endl;
1620 }
1621
1622 void GUIFormSpecMenu::parseTooltip(parserData* data, const std::string &element)
1623 {
1624         std::vector<std::string> parts = split(element,';');
1625         if (parts.size() == 2) {
1626                 std::string name = parts[0];
1627                 m_tooltips[name] = TooltipSpec(utf8_to_wide(unescape_string(parts[1])),
1628                         m_default_tooltip_bgcolor, m_default_tooltip_color);
1629                 return;
1630         }
1631
1632         if (parts.size() == 4) {
1633                 std::string name = parts[0];
1634                 video::SColor tmp_color1, tmp_color2;
1635                 if ( parseColorString(parts[2], tmp_color1, false) && parseColorString(parts[3], tmp_color2, false) ) {
1636                         m_tooltips[name] = TooltipSpec(utf8_to_wide(unescape_string(parts[1])),
1637                                 tmp_color1, tmp_color2);
1638                         return;
1639                 }
1640         }
1641         errorstream<< "Invalid tooltip element(" << parts.size() << "): '" << element << "'"  << std::endl;
1642 }
1643
1644 bool GUIFormSpecMenu::parseVersionDirect(const std::string &data)
1645 {
1646         //some prechecks
1647         if (data.empty())
1648                 return false;
1649
1650         std::vector<std::string> parts = split(data,'[');
1651
1652         if (parts.size() < 2) {
1653                 return false;
1654         }
1655
1656         if (parts[0] != "formspec_version") {
1657                 return false;
1658         }
1659
1660         if (is_number(parts[1])) {
1661                 m_formspec_version = mystoi(parts[1]);
1662                 return true;
1663         }
1664
1665         return false;
1666 }
1667
1668 bool GUIFormSpecMenu::parseSizeDirect(parserData* data, const std::string &element)
1669 {
1670         if (element.empty())
1671                 return false;
1672
1673         std::vector<std::string> parts = split(element,'[');
1674
1675         if (parts.size() < 2)
1676                 return false;
1677
1678         std::string type = trim(parts[0]);
1679         std::string description = trim(parts[1]);
1680
1681         if (type != "size" && type != "invsize")
1682                 return false;
1683
1684         if (type == "invsize")
1685                 log_deprecated("Deprecated formspec element \"invsize\" is used");
1686
1687         parseSize(data, description);
1688
1689         return true;
1690 }
1691
1692 bool GUIFormSpecMenu::parsePositionDirect(parserData *data, const std::string &element)
1693 {
1694         if (element.empty())
1695                 return false;
1696
1697         std::vector<std::string> parts = split(element, '[');
1698
1699         if (parts.size() != 2)
1700                 return false;
1701
1702         std::string type = trim(parts[0]);
1703         std::string description = trim(parts[1]);
1704
1705         if (type != "position")
1706                 return false;
1707
1708         parsePosition(data, description);
1709
1710         return true;
1711 }
1712
1713 void GUIFormSpecMenu::parsePosition(parserData *data, const std::string &element)
1714 {
1715         std::vector<std::string> parts = split(element, ',');
1716
1717         if (parts.size() == 2) {
1718                 data->offset.X = stof(parts[0]);
1719                 data->offset.Y = stof(parts[1]);
1720                 return;
1721         }
1722
1723         errorstream << "Invalid position element (" << parts.size() << "): '" << element << "'" << std::endl;
1724 }
1725
1726 bool GUIFormSpecMenu::parseAnchorDirect(parserData *data, const std::string &element)
1727 {
1728         if (element.empty())
1729                 return false;
1730
1731         std::vector<std::string> parts = split(element, '[');
1732
1733         if (parts.size() != 2)
1734                 return false;
1735
1736         std::string type = trim(parts[0]);
1737         std::string description = trim(parts[1]);
1738
1739         if (type != "anchor")
1740                 return false;
1741
1742         parseAnchor(data, description);
1743
1744         return true;
1745 }
1746
1747 void GUIFormSpecMenu::parseAnchor(parserData *data, const std::string &element)
1748 {
1749         std::vector<std::string> parts = split(element, ',');
1750
1751         if (parts.size() == 2) {
1752                 data->anchor.X = stof(parts[0]);
1753                 data->anchor.Y = stof(parts[1]);
1754                 return;
1755         }
1756
1757         errorstream << "Invalid anchor element (" << parts.size() << "): '" << element
1758                         << "'" << std::endl;
1759 }
1760
1761 void GUIFormSpecMenu::parseElement(parserData* data, const std::string &element)
1762 {
1763         //some prechecks
1764         if (element.empty())
1765                 return;
1766
1767         std::vector<std::string> parts = split(element,'[');
1768
1769         // ugly workaround to keep compatibility
1770         if (parts.size() > 2) {
1771                 if (trim(parts[0]) == "image") {
1772                         for (unsigned int i=2;i< parts.size(); i++) {
1773                                 parts[1] += "[" + parts[i];
1774                         }
1775                 }
1776                 else { return; }
1777         }
1778
1779         if (parts.size() < 2) {
1780                 return;
1781         }
1782
1783         std::string type = trim(parts[0]);
1784         std::string description = trim(parts[1]);
1785
1786         if (type == "container") {
1787                 parseContainer(data, description);
1788                 return;
1789         }
1790
1791         if (type == "container_end") {
1792                 parseContainerEnd(data);
1793                 return;
1794         }
1795
1796         if (type == "list") {
1797                 parseList(data, description);
1798                 return;
1799         }
1800
1801         if (type == "listring") {
1802                 parseListRing(data, description);
1803                 return;
1804         }
1805
1806         if (type == "checkbox") {
1807                 parseCheckbox(data, description);
1808                 return;
1809         }
1810
1811         if (type == "image") {
1812                 parseImage(data, description);
1813                 return;
1814         }
1815
1816         if (type == "item_image") {
1817                 parseItemImage(data, description);
1818                 return;
1819         }
1820
1821         if (type == "button" || type == "button_exit") {
1822                 parseButton(data, description, type);
1823                 return;
1824         }
1825
1826         if (type == "background") {
1827                 parseBackground(data,description);
1828                 return;
1829         }
1830
1831         if (type == "tableoptions"){
1832                 parseTableOptions(data,description);
1833                 return;
1834         }
1835
1836         if (type == "tablecolumns"){
1837                 parseTableColumns(data,description);
1838                 return;
1839         }
1840
1841         if (type == "table"){
1842                 parseTable(data,description);
1843                 return;
1844         }
1845
1846         if (type == "textlist"){
1847                 parseTextList(data,description);
1848                 return;
1849         }
1850
1851         if (type == "dropdown"){
1852                 parseDropDown(data,description);
1853                 return;
1854         }
1855
1856         if (type == "field_close_on_enter") {
1857                 parseFieldCloseOnEnter(data, description);
1858                 return;
1859         }
1860
1861         if (type == "pwdfield") {
1862                 parsePwdField(data,description);
1863                 return;
1864         }
1865
1866         if ((type == "field") || (type == "textarea")){
1867                 parseField(data,description,type);
1868                 return;
1869         }
1870
1871         if (type == "label") {
1872                 parseLabel(data,description);
1873                 return;
1874         }
1875
1876         if (type == "vertlabel") {
1877                 parseVertLabel(data,description);
1878                 return;
1879         }
1880
1881         if (type == "item_image_button") {
1882                 parseItemImageButton(data,description);
1883                 return;
1884         }
1885
1886         if ((type == "image_button") || (type == "image_button_exit")) {
1887                 parseImageButton(data,description,type);
1888                 return;
1889         }
1890
1891         if (type == "tabheader") {
1892                 parseTabHeader(data,description);
1893                 return;
1894         }
1895
1896         if (type == "box") {
1897                 parseBox(data,description);
1898                 return;
1899         }
1900
1901         if (type == "bgcolor") {
1902                 parseBackgroundColor(data,description);
1903                 return;
1904         }
1905
1906         if (type == "listcolors") {
1907                 parseListColors(data,description);
1908                 return;
1909         }
1910
1911         if (type == "tooltip") {
1912                 parseTooltip(data,description);
1913                 return;
1914         }
1915
1916         if (type == "scrollbar") {
1917                 parseScrollBar(data, description);
1918                 return;
1919         }
1920
1921         // Ignore others
1922         infostream << "Unknown DrawSpec: type=" << type << ", data=\"" << description << "\""
1923                         << std::endl;
1924 }
1925
1926 void GUIFormSpecMenu::regenerateGui(v2u32 screensize)
1927 {
1928         /* useless to regenerate without a screensize */
1929         if ((screensize.X <= 0) || (screensize.Y <= 0)) {
1930                 return;
1931         }
1932
1933         parserData mydata;
1934
1935         //preserve tables
1936         for (auto &m_table : m_tables) {
1937                 std::string tablename = m_table.first.fname;
1938                 GUITable *table = m_table.second;
1939                 mydata.table_dyndata[tablename] = table->getDynamicData();
1940         }
1941
1942         //set focus
1943         if (!m_focused_element.empty())
1944                 mydata.focused_fieldname = m_focused_element;
1945
1946         //preserve focus
1947         gui::IGUIElement *focused_element = Environment->getFocus();
1948         if (focused_element && focused_element->getParent() == this) {
1949                 s32 focused_id = focused_element->getID();
1950                 if (focused_id > 257) {
1951                         for (const GUIFormSpecMenu::FieldSpec &field : m_fields) {
1952                                 if (field.fid == focused_id) {
1953                                         mydata.focused_fieldname = field.fname;
1954                                         break;
1955                                 }
1956                         }
1957                 }
1958         }
1959
1960         // Remove children
1961         removeChildren();
1962
1963         for (auto &table_it : m_tables) {
1964                 table_it.second->drop();
1965         }
1966
1967         mydata.size= v2s32(100,100);
1968         mydata.screensize = screensize;
1969         mydata.offset = v2f32(0.5f, 0.5f);
1970         mydata.anchor = v2f32(0.5f, 0.5f);
1971
1972         // Base position of contents of form
1973         mydata.basepos = getBasePos();
1974
1975         /* Convert m_init_draw_spec to m_inventorylists */
1976
1977         m_inventorylists.clear();
1978         m_images.clear();
1979         m_backgrounds.clear();
1980         m_itemimages.clear();
1981         m_tables.clear();
1982         m_checkboxes.clear();
1983         m_scrollbars.clear();
1984         m_fields.clear();
1985         m_boxes.clear();
1986         m_tooltips.clear();
1987         m_inventory_rings.clear();
1988         m_static_texts.clear();
1989         m_dropdowns.clear();
1990
1991         m_bgfullscreen = false;
1992
1993         {
1994                 v3f formspec_bgcolor = g_settings->getV3F("formspec_default_bg_color");
1995                 m_bgcolor = video::SColor(
1996                         (u8) clamp_u8(g_settings->getS32("formspec_default_bg_opacity")),
1997                         clamp_u8(myround(formspec_bgcolor.X)),
1998                         clamp_u8(myround(formspec_bgcolor.Y)),
1999                         clamp_u8(myround(formspec_bgcolor.Z))
2000                 );
2001         }
2002
2003         {
2004                 v3f formspec_bgcolor = g_settings->getV3F("formspec_fullscreen_bg_color");
2005                 m_fullscreen_bgcolor = video::SColor(
2006                         (u8) clamp_u8(g_settings->getS32("formspec_fullscreen_bg_opacity")),
2007                         clamp_u8(myround(formspec_bgcolor.X)),
2008                         clamp_u8(myround(formspec_bgcolor.Y)),
2009                         clamp_u8(myround(formspec_bgcolor.Z))
2010                 );
2011         }
2012
2013
2014         m_slotbg_n = video::SColor(255,128,128,128);
2015         m_slotbg_h = video::SColor(255,192,192,192);
2016
2017         m_default_tooltip_bgcolor = video::SColor(255,110,130,60);
2018         m_default_tooltip_color = video::SColor(255,255,255,255);
2019
2020         m_slotbordercolor = video::SColor(200,0,0,0);
2021         m_slotborder = false;
2022
2023         // Add tooltip
2024         {
2025                 assert(!m_tooltip_element);
2026                 // Note: parent != this so that the tooltip isn't clipped by the menu rectangle
2027                 m_tooltip_element = addStaticText(Environment, L"",core::rect<s32>(0,0,110,18));
2028                 m_tooltip_element->enableOverrideColor(true);
2029                 m_tooltip_element->setBackgroundColor(m_default_tooltip_bgcolor);
2030                 m_tooltip_element->setDrawBackground(true);
2031                 m_tooltip_element->setDrawBorder(true);
2032                 m_tooltip_element->setOverrideColor(m_default_tooltip_color);
2033                 m_tooltip_element->setTextAlignment(gui::EGUIA_CENTER, gui::EGUIA_CENTER);
2034                 m_tooltip_element->setWordWrap(false);
2035                 //we're not parent so no autograb for this one!
2036                 m_tooltip_element->grab();
2037         }
2038
2039         std::vector<std::string> elements = split(m_formspec_string,']');
2040         unsigned int i = 0;
2041
2042         /* try to read version from first element only */
2043         if (!elements.empty()) {
2044                 if ( parseVersionDirect(elements[0]) ) {
2045                         i++;
2046                 }
2047         }
2048
2049         /* we need size first in order to calculate image scale */
2050         mydata.explicit_size = false;
2051         for (; i< elements.size(); i++) {
2052                 if (!parseSizeDirect(&mydata, elements[i])) {
2053                         break;
2054                 }
2055         }
2056
2057         /* "position" element is always after "size" element if it used */
2058         for (; i< elements.size(); i++) {
2059                 if (!parsePositionDirect(&mydata, elements[i])) {
2060                         break;
2061                 }
2062         }
2063
2064         /* "anchor" element is always after "position" (or  "size" element) if it used */
2065         for (; i< elements.size(); i++) {
2066                 if (!parseAnchorDirect(&mydata, elements[i])) {
2067                         break;
2068                 }
2069         }
2070
2071
2072         if (mydata.explicit_size) {
2073                 // compute scaling for specified form size
2074                 if (m_lock) {
2075                         v2u32 current_screensize = RenderingEngine::get_video_driver()->getScreenSize();
2076                         v2u32 delta = current_screensize - m_lockscreensize;
2077
2078                         if (current_screensize.Y > m_lockscreensize.Y)
2079                                 delta.Y /= 2;
2080                         else
2081                                 delta.Y = 0;
2082
2083                         if (current_screensize.X > m_lockscreensize.X)
2084                                 delta.X /= 2;
2085                         else
2086                                 delta.X = 0;
2087
2088                         offset = v2s32(delta.X,delta.Y);
2089
2090                         mydata.screensize = m_lockscreensize;
2091                 } else {
2092                         offset = v2s32(0,0);
2093                 }
2094
2095                 double gui_scaling = g_settings->getFloat("gui_scaling");
2096                 double screen_dpi = RenderingEngine::getDisplayDensity() * 96;
2097
2098                 double use_imgsize;
2099                 if (m_lock) {
2100                         // In fixed-size mode, inventory image size
2101                         // is 0.53 inch multiplied by the gui_scaling
2102                         // config parameter.  This magic size is chosen
2103                         // to make the main menu (15.5 inventory images
2104                         // wide, including border) just fit into the
2105                         // default window (800 pixels wide) at 96 DPI
2106                         // and default scaling (1.00).
2107                         use_imgsize = 0.5555 * screen_dpi * gui_scaling;
2108                 } else {
2109                         // In variable-size mode, we prefer to make the
2110                         // inventory image size 1/15 of screen height,
2111                         // multiplied by the gui_scaling config parameter.
2112                         // If the preferred size won't fit the whole
2113                         // form on the screen, either horizontally or
2114                         // vertically, then we scale it down to fit.
2115                         // (The magic numbers in the computation of what
2116                         // fits arise from the scaling factors in the
2117                         // following stanza, including the form border,
2118                         // help text space, and 0.1 inventory slot spare.)
2119                         // However, a minimum size is also set, that
2120                         // the image size can't be less than 0.3 inch
2121                         // multiplied by gui_scaling, even if this means
2122                         // the form doesn't fit the screen.
2123                         double prefer_imgsize = mydata.screensize.Y / 15 *
2124                                                         gui_scaling;
2125                         double fitx_imgsize = mydata.screensize.X /
2126                                 ((5.0/4.0) * (0.5 + mydata.invsize.X));
2127                         double fity_imgsize = mydata.screensize.Y /
2128                                 ((15.0/13.0) * (0.85 * mydata.invsize.Y));
2129                         double screen_dpi = RenderingEngine::getDisplayDensity() * 96;
2130                         double min_imgsize = 0.3 * screen_dpi * gui_scaling;
2131                         use_imgsize = MYMAX(min_imgsize, MYMIN(prefer_imgsize,
2132                                 MYMIN(fitx_imgsize, fity_imgsize)));
2133                 }
2134
2135                 // Everything else is scaled in proportion to the
2136                 // inventory image size.  The inventory slot spacing
2137                 // is 5/4 image size horizontally and 15/13 image size
2138                 // vertically.  The padding around the form (incorporating
2139                 // the border of the outer inventory slots) is 3/8
2140                 // image size.  Font height (baseline to baseline)
2141                 // is 2/5 vertical inventory slot spacing, and button
2142                 // half-height is 7/8 of font height.
2143                 imgsize = v2s32(use_imgsize, use_imgsize);
2144                 spacing = v2s32(use_imgsize*5.0/4, use_imgsize*15.0/13);
2145                 padding = v2s32(use_imgsize*3.0/8, use_imgsize*3.0/8);
2146                 m_btn_height = use_imgsize*15.0/13 * 0.35;
2147
2148                 m_font = g_fontengine->getFont();
2149
2150                 mydata.size = v2s32(
2151                         padding.X*2+spacing.X*(mydata.invsize.X-1.0)+imgsize.X,
2152                         padding.Y*2+spacing.Y*(mydata.invsize.Y-1.0)+imgsize.Y + m_btn_height*2.0/3.0
2153                 );
2154                 DesiredRect = mydata.rect = core::rect<s32>(
2155                                 (s32)((f32)mydata.screensize.X * mydata.offset.X) - (s32)(mydata.anchor.X * (f32)mydata.size.X) + offset.X,
2156                                 (s32)((f32)mydata.screensize.Y * mydata.offset.Y) - (s32)(mydata.anchor.Y * (f32)mydata.size.Y) + offset.Y,
2157                                 (s32)((f32)mydata.screensize.X * mydata.offset.X) + (s32)((1.0 - mydata.anchor.X) * (f32)mydata.size.X) + offset.X,
2158                                 (s32)((f32)mydata.screensize.Y * mydata.offset.Y) + (s32)((1.0 - mydata.anchor.Y) * (f32)mydata.size.Y) + offset.Y
2159                 );
2160         } else {
2161                 // Non-size[] form must consist only of text fields and
2162                 // implicit "Proceed" button.  Use default font, and
2163                 // temporary form size which will be recalculated below.
2164                 m_font = g_fontengine->getFont();
2165                 m_btn_height = font_line_height(m_font) * 0.875;
2166                 DesiredRect = core::rect<s32>(
2167                         (s32)((f32)mydata.screensize.X * mydata.offset.X) - (s32)(mydata.anchor.X * 580.0),
2168                         (s32)((f32)mydata.screensize.Y * mydata.offset.Y) - (s32)(mydata.anchor.Y * 300.0),
2169                         (s32)((f32)mydata.screensize.X * mydata.offset.X) + (s32)((1.0 - mydata.anchor.X) * 580.0),
2170                         (s32)((f32)mydata.screensize.Y * mydata.offset.Y) + (s32)((1.0 - mydata.anchor.Y) * 300.0)
2171                 );
2172         }
2173         recalculateAbsolutePosition(false);
2174         mydata.basepos = getBasePos();
2175         m_tooltip_element->setOverrideFont(m_font);
2176
2177         gui::IGUISkin* skin = Environment->getSkin();
2178         sanity_check(skin);
2179         gui::IGUIFont *old_font = skin->getFont();
2180         skin->setFont(m_font);
2181
2182         pos_offset = v2s32();
2183         for (; i< elements.size(); i++) {
2184                 parseElement(&mydata, elements[i]);
2185         }
2186
2187         if (!container_stack.empty()) {
2188                 errorstream << "Invalid formspec string: container was never closed!"
2189                         << std::endl;
2190         }
2191
2192         // If there are fields without explicit size[], add a "Proceed"
2193         // button and adjust size to fit all the fields.
2194         if (!m_fields.empty() && !mydata.explicit_size) {
2195                 mydata.rect = core::rect<s32>(
2196                                 mydata.screensize.X/2 - 580/2,
2197                                 mydata.screensize.Y/2 - 300/2,
2198                                 mydata.screensize.X/2 + 580/2,
2199                                 mydata.screensize.Y/2 + 240/2+(m_fields.size()*60)
2200                 );
2201                 DesiredRect = mydata.rect;
2202                 recalculateAbsolutePosition(false);
2203                 mydata.basepos = getBasePos();
2204
2205                 {
2206                         v2s32 pos = mydata.basepos;
2207                         pos.Y = ((m_fields.size()+2)*60);
2208
2209                         v2s32 size = DesiredRect.getSize();
2210                         mydata.rect =
2211                                         core::rect<s32>(size.X/2-70, pos.Y,
2212                                                         (size.X/2-70)+140, pos.Y + (m_btn_height*2));
2213                         const wchar_t *text = wgettext("Proceed");
2214                         Environment->addButton(mydata.rect, this, 257, text);
2215                         delete[] text;
2216                 }
2217
2218         }
2219
2220         //set initial focus if parser didn't set it
2221         focused_element = Environment->getFocus();
2222         if (!focused_element
2223                         || !isMyChild(focused_element)
2224                         || focused_element->getType() == gui::EGUIET_TAB_CONTROL)
2225                 setInitialFocus();
2226
2227         skin->setFont(old_font);
2228 }
2229
2230 #ifdef __ANDROID__
2231 bool GUIFormSpecMenu::getAndroidUIInput()
2232 {
2233         /* no dialog shown */
2234         if (m_JavaDialogFieldName == "") {
2235                 return false;
2236         }
2237
2238         /* still waiting */
2239         if (porting::getInputDialogState() == -1) {
2240                 return true;
2241         }
2242
2243         std::string fieldname = m_JavaDialogFieldName;
2244         m_JavaDialogFieldName = "";
2245
2246         /* no value abort dialog processing */
2247         if (porting::getInputDialogState() != 0) {
2248                 return false;
2249         }
2250
2251         for(std::vector<FieldSpec>::iterator iter =  m_fields.begin();
2252                         iter != m_fields.end(); ++iter) {
2253
2254                 if (iter->fname != fieldname) {
2255                         continue;
2256                 }
2257                 IGUIElement* tochange = getElementFromId(iter->fid);
2258
2259                 if (tochange == 0) {
2260                         return false;
2261                 }
2262
2263                 if (tochange->getType() != irr::gui::EGUIET_EDIT_BOX) {
2264                         return false;
2265                 }
2266
2267                 std::string text = porting::getInputDialogValue();
2268
2269                 ((gui::IGUIEditBox*) tochange)->
2270                         setText(utf8_to_wide(text).c_str());
2271         }
2272         return false;
2273 }
2274 #endif
2275
2276 GUIFormSpecMenu::ItemSpec GUIFormSpecMenu::getItemAtPos(v2s32 p) const
2277 {
2278         core::rect<s32> imgrect(0,0,imgsize.X,imgsize.Y);
2279
2280         for (const GUIFormSpecMenu::ListDrawSpec &s : m_inventorylists) {
2281                 for(s32 i=0; i<s.geom.X*s.geom.Y; i++) {
2282                         s32 item_i = i + s.start_item_i;
2283                         s32 x = (i%s.geom.X) * spacing.X;
2284                         s32 y = (i/s.geom.X) * spacing.Y;
2285                         v2s32 p0(x,y);
2286                         core::rect<s32> rect = imgrect + s.pos + p0;
2287                         if(rect.isPointInside(p))
2288                         {
2289                                 return ItemSpec(s.inventoryloc, s.listname, item_i);
2290                         }
2291                 }
2292         }
2293
2294         return ItemSpec(InventoryLocation(), "", -1);
2295 }
2296
2297 void GUIFormSpecMenu::drawList(const ListDrawSpec &s, int phase,
2298                 bool &item_hovered)
2299 {
2300         video::IVideoDriver* driver = Environment->getVideoDriver();
2301
2302         Inventory *inv = m_invmgr->getInventory(s.inventoryloc);
2303         if(!inv){
2304                 warningstream<<"GUIFormSpecMenu::drawList(): "
2305                                 <<"The inventory location "
2306                                 <<"\""<<s.inventoryloc.dump()<<"\" doesn't exist"
2307                                 <<std::endl;
2308                 return;
2309         }
2310         InventoryList *ilist = inv->getList(s.listname);
2311         if(!ilist){
2312                 warningstream<<"GUIFormSpecMenu::drawList(): "
2313                                 <<"The inventory list \""<<s.listname<<"\" @ \""
2314                                 <<s.inventoryloc.dump()<<"\" doesn't exist"
2315                                 <<std::endl;
2316                 return;
2317         }
2318
2319         core::rect<s32> imgrect(0,0,imgsize.X,imgsize.Y);
2320
2321         for(s32 i=0; i<s.geom.X*s.geom.Y; i++)
2322         {
2323                 s32 item_i = i + s.start_item_i;
2324                 if(item_i >= (s32) ilist->getSize())
2325                         break;
2326                 s32 x = (i%s.geom.X) * spacing.X;
2327                 s32 y = (i/s.geom.X) * spacing.Y;
2328                 v2s32 p(x,y);
2329                 core::rect<s32> rect = imgrect + s.pos + p;
2330                 ItemStack item;
2331                 if(ilist)
2332                         item = ilist->getItem(item_i);
2333
2334                 bool selected = m_selected_item
2335                         && m_invmgr->getInventory(m_selected_item->inventoryloc) == inv
2336                         && m_selected_item->listname == s.listname
2337                         && m_selected_item->i == item_i;
2338                 bool hovering = rect.isPointInside(m_pointer);
2339                 ItemRotationKind rotation_kind = selected ? IT_ROT_SELECTED :
2340                         (hovering ? IT_ROT_HOVERED : IT_ROT_NONE);
2341
2342                 if (phase == 0) {
2343                         if (hovering) {
2344                                 item_hovered = true;
2345                                 driver->draw2DRectangle(m_slotbg_h, rect, &AbsoluteClippingRect);
2346                         } else {
2347                                 driver->draw2DRectangle(m_slotbg_n, rect, &AbsoluteClippingRect);
2348                         }
2349                 }
2350
2351                 //Draw inv slot borders
2352                 if (m_slotborder) {
2353                         s32 x1 = rect.UpperLeftCorner.X;
2354                         s32 y1 = rect.UpperLeftCorner.Y;
2355                         s32 x2 = rect.LowerRightCorner.X;
2356                         s32 y2 = rect.LowerRightCorner.Y;
2357                         s32 border = 1;
2358                         driver->draw2DRectangle(m_slotbordercolor,
2359                                 core::rect<s32>(v2s32(x1 - border, y1 - border),
2360                                                                 v2s32(x2 + border, y1)), NULL);
2361                         driver->draw2DRectangle(m_slotbordercolor,
2362                                 core::rect<s32>(v2s32(x1 - border, y2),
2363                                                                 v2s32(x2 + border, y2 + border)), NULL);
2364                         driver->draw2DRectangle(m_slotbordercolor,
2365                                 core::rect<s32>(v2s32(x1 - border, y1),
2366                                                                 v2s32(x1, y2)), NULL);
2367                         driver->draw2DRectangle(m_slotbordercolor,
2368                                 core::rect<s32>(v2s32(x2, y1),
2369                                                                 v2s32(x2 + border, y2)), NULL);
2370                 }
2371
2372                 if(phase == 1)
2373                 {
2374                         // Draw item stack
2375                         if(selected)
2376                         {
2377                                 item.takeItem(m_selected_amount);
2378                         }
2379                         if(!item.empty())
2380                         {
2381                                 drawItemStack(driver, m_font, item,
2382                                         rect, &AbsoluteClippingRect, m_client,
2383                                         rotation_kind);
2384                         }
2385
2386                         // Draw tooltip
2387                         std::wstring tooltip_text;
2388                         if (hovering && !m_selected_item) {
2389                                 const std::string &desc = item.metadata.getString("description");
2390                                 if (desc.empty())
2391                                         tooltip_text =
2392                                                 utf8_to_wide(item.getDefinition(m_client->idef()).description);
2393                                 else
2394                                         tooltip_text = utf8_to_wide(desc);
2395
2396                                 if (!item.name.empty()) {
2397                                         if (tooltip_text.empty())
2398                                                 tooltip_text = utf8_to_wide(item.name);
2399                                         if (m_tooltip_append_itemname)
2400                                                 tooltip_text += utf8_to_wide(" [" + item.name + "]");
2401                                 }
2402                         }
2403                         if (!tooltip_text.empty()) {
2404                                 showTooltip(tooltip_text, m_default_tooltip_color,
2405                                         m_default_tooltip_bgcolor);
2406                         }
2407                 }
2408         }
2409 }
2410
2411 void GUIFormSpecMenu::drawSelectedItem()
2412 {
2413         video::IVideoDriver* driver = Environment->getVideoDriver();
2414
2415         if (!m_selected_item) {
2416                 drawItemStack(driver, m_font, ItemStack(),
2417                         core::rect<s32>(v2s32(0, 0), v2s32(0, 0)),
2418                         NULL, m_client, IT_ROT_DRAGGED);
2419                 return;
2420         }
2421
2422         Inventory *inv = m_invmgr->getInventory(m_selected_item->inventoryloc);
2423         sanity_check(inv);
2424         InventoryList *list = inv->getList(m_selected_item->listname);
2425         sanity_check(list);
2426         ItemStack stack = list->getItem(m_selected_item->i);
2427         stack.count = m_selected_amount;
2428
2429         core::rect<s32> imgrect(0,0,imgsize.X,imgsize.Y);
2430         core::rect<s32> rect = imgrect + (m_pointer - imgrect.getCenter());
2431         rect.constrainTo(driver->getViewPort());
2432         drawItemStack(driver, m_font, stack, rect, NULL, m_client, IT_ROT_DRAGGED);
2433 }
2434
2435 void GUIFormSpecMenu::drawMenu()
2436 {
2437         if (m_form_src) {
2438                 const std::string &newform = m_form_src->getForm();
2439                 if (newform != m_formspec_string) {
2440                         m_formspec_string = newform;
2441                         regenerateGui(m_screensize_old);
2442                 }
2443         }
2444
2445         gui::IGUISkin* skin = Environment->getSkin();
2446         sanity_check(skin != NULL);
2447         gui::IGUIFont *old_font = skin->getFont();
2448         skin->setFont(m_font);
2449
2450         updateSelectedItem();
2451
2452         video::IVideoDriver* driver = Environment->getVideoDriver();
2453
2454         v2u32 screenSize = driver->getScreenSize();
2455         core::rect<s32> allbg(0, 0, screenSize.X, screenSize.Y);
2456
2457         if (m_bgfullscreen)
2458                 driver->draw2DRectangle(m_fullscreen_bgcolor, allbg, &allbg);
2459         else
2460                 driver->draw2DRectangle(m_bgcolor, AbsoluteRect, &AbsoluteClippingRect);
2461
2462         m_tooltip_element->setVisible(false);
2463
2464         /*
2465                 Draw backgrounds
2466         */
2467         for (const GUIFormSpecMenu::ImageDrawSpec &spec : m_backgrounds) {
2468                 video::ITexture *texture = m_tsrc->getTexture(spec.name);
2469
2470                 if (texture != 0) {
2471                         // Image size on screen
2472                         core::rect<s32> imgrect(0, 0, spec.geom.X, spec.geom.Y);
2473                         // Image rectangle on screen
2474                         core::rect<s32> rect = imgrect + spec.pos;
2475
2476                         if (spec.clip) {
2477                                 core::dimension2d<s32> absrec_size = AbsoluteRect.getSize();
2478                                 rect = core::rect<s32>(AbsoluteRect.UpperLeftCorner.X - spec.pos.X,
2479                                                                         AbsoluteRect.UpperLeftCorner.Y - spec.pos.Y,
2480                                                                         AbsoluteRect.UpperLeftCorner.X + absrec_size.Width + spec.pos.X,
2481                                                                         AbsoluteRect.UpperLeftCorner.Y + absrec_size.Height + spec.pos.Y);
2482                         }
2483
2484                         const video::SColor color(255,255,255,255);
2485                         const video::SColor colors[] = {color,color,color,color};
2486                         draw2DImageFilterScaled(driver, texture, rect,
2487                                 core::rect<s32>(core::position2d<s32>(0,0),
2488                                                 core::dimension2di(texture->getOriginalSize())),
2489                                 NULL/*&AbsoluteClippingRect*/, colors, true);
2490                 } else {
2491                         errorstream << "GUIFormSpecMenu::drawMenu() Draw backgrounds unable to load texture:" << std::endl;
2492                         errorstream << "\t" << spec.name << std::endl;
2493                 }
2494         }
2495
2496         /*
2497                 Draw Boxes
2498         */
2499         for (const GUIFormSpecMenu::BoxDrawSpec &spec : m_boxes) {
2500                 irr::video::SColor todraw = spec.color;
2501
2502                 todraw.setAlpha(140);
2503
2504                 core::rect<s32> rect(spec.pos.X,spec.pos.Y,
2505                                                         spec.pos.X + spec.geom.X,spec.pos.Y + spec.geom.Y);
2506
2507                 driver->draw2DRectangle(todraw, rect, 0);
2508         }
2509
2510         /*
2511                 Call base class
2512         */
2513         gui::IGUIElement::draw();
2514
2515         /*
2516                 Draw images
2517         */
2518         for (const GUIFormSpecMenu::ImageDrawSpec &spec : m_images) {
2519                 video::ITexture *texture = m_tsrc->getTexture(spec.name);
2520
2521                 if (texture != 0) {
2522                         const core::dimension2d<u32>& img_origsize = texture->getOriginalSize();
2523                         // Image size on screen
2524                         core::rect<s32> imgrect;
2525
2526                         if (spec.scale)
2527                                 imgrect = core::rect<s32>(0,0,spec.geom.X, spec.geom.Y);
2528                         else {
2529
2530                                 imgrect = core::rect<s32>(0,0,img_origsize.Width,img_origsize.Height);
2531                         }
2532                         // Image rectangle on screen
2533                         core::rect<s32> rect = imgrect + spec.pos;
2534                         const video::SColor color(255,255,255,255);
2535                         const video::SColor colors[] = {color,color,color,color};
2536                         draw2DImageFilterScaled(driver, texture, rect,
2537                                 core::rect<s32>(core::position2d<s32>(0,0),img_origsize),
2538                                 NULL/*&AbsoluteClippingRect*/, colors, true);
2539                 }
2540                 else {
2541                         errorstream << "GUIFormSpecMenu::drawMenu() Draw images unable to load texture:" << std::endl;
2542                         errorstream << "\t" << spec.name << std::endl;
2543                 }
2544         }
2545
2546         /*
2547                 Draw item images
2548         */
2549         for (const GUIFormSpecMenu::ImageDrawSpec &spec : m_itemimages) {
2550                 if (m_client == 0)
2551                         break;
2552
2553                 IItemDefManager *idef = m_client->idef();
2554                 ItemStack item;
2555                 item.deSerialize(spec.item_name, idef);
2556                 core::rect<s32> imgrect(0, 0, spec.geom.X, spec.geom.Y);
2557                 // Viewport rectangle on screen
2558                 core::rect<s32> rect = imgrect + spec.pos;
2559                 if (spec.parent_button && spec.parent_button->isPressed()) {
2560 #if (IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR < 8)
2561                         rect += core::dimension2d<s32>(
2562                                 0.05 * (float)rect.getWidth(), 0.05 * (float)rect.getHeight());
2563 #else
2564                         rect += core::dimension2d<s32>(
2565                                 skin->getSize(irr::gui::EGDS_BUTTON_PRESSED_IMAGE_OFFSET_X),
2566                                 skin->getSize(irr::gui::EGDS_BUTTON_PRESSED_IMAGE_OFFSET_Y));
2567 #endif
2568                 }
2569                 drawItemStack(driver, m_font, item, rect, &AbsoluteClippingRect,
2570                                 m_client, IT_ROT_NONE);
2571         }
2572
2573         /*
2574                 Draw items
2575                 Phase 0: Item slot rectangles
2576                 Phase 1: Item images; prepare tooltip
2577         */
2578         bool item_hovered = false;
2579         int start_phase = 0;
2580         for (int phase = start_phase; phase <= 1; phase++) {
2581                 for (const GUIFormSpecMenu::ListDrawSpec &spec : m_inventorylists) {
2582                         drawList(spec, phase, item_hovered);
2583                 }
2584         }
2585         if (!item_hovered) {
2586                 drawItemStack(driver, m_font, ItemStack(),
2587                         core::rect<s32>(v2s32(0, 0), v2s32(0, 0)),
2588                         NULL, m_client, IT_ROT_HOVERED);
2589         }
2590
2591 /* TODO find way to show tooltips on touchscreen */
2592 #ifndef HAVE_TOUCHSCREENGUI
2593         m_pointer = RenderingEngine::get_raw_device()->getCursorControl()->getPosition();
2594 #endif
2595
2596         /*
2597                 Draw static text elements
2598         */
2599         for (const GUIFormSpecMenu::StaticTextSpec &spec : m_static_texts) {
2600                 core::rect<s32> rect = spec.rect;
2601                 if (spec.parent_button && spec.parent_button->isPressed()) {
2602 #if (IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR < 8)
2603                         rect += core::dimension2d<s32>(
2604                                 0.05 * (float)rect.getWidth(), 0.05 * (float)rect.getHeight());
2605 #else
2606                         // Use image offset instead of text's because its a bit smaller
2607                         // and fits better, also TEXT_OFFSET_X is always 0
2608                         rect += core::dimension2d<s32>(
2609                                 skin->getSize(irr::gui::EGDS_BUTTON_PRESSED_IMAGE_OFFSET_X),
2610                                 skin->getSize(irr::gui::EGDS_BUTTON_PRESSED_IMAGE_OFFSET_Y));
2611 #endif
2612                 }
2613                 video::SColor color(255, 255, 255, 255);
2614                 m_font->draw(spec.text.c_str(), rect, color, true, true, &rect);
2615         }
2616
2617         /*
2618                 Draw fields/buttons tooltips
2619         */
2620         gui::IGUIElement *hovered =
2621                         Environment->getRootGUIElement()->getElementFromPoint(m_pointer);
2622
2623         if (hovered != NULL) {
2624                 s32 id = hovered->getID();
2625
2626                 u64 delta = 0;
2627                 if (id == -1) {
2628                         m_old_tooltip_id = id;
2629                 } else {
2630                         if (id == m_old_tooltip_id) {
2631                                 delta = porting::getDeltaMs(m_hovered_time, porting::getTimeMs());
2632                         } else {
2633                                 m_hovered_time = porting::getTimeMs();
2634                                 m_old_tooltip_id = id;
2635                         }
2636                 }
2637
2638                 // Find and update the current tooltip
2639                 if (id != -1 && delta >= m_tooltip_show_delay) {
2640                         for (const FieldSpec &field : m_fields) {
2641
2642                                 if (field.fid != id)
2643                                         continue;
2644
2645                                 const std::wstring &text = m_tooltips[field.fname].tooltip;
2646                                 if (!text.empty())
2647                                         showTooltip(text, m_tooltips[field.fname].color,
2648                                                 m_tooltips[field.fname].bgcolor);
2649
2650                                 break;
2651                         }
2652                 }
2653         }
2654
2655         m_tooltip_element->draw();
2656
2657         /*
2658                 Draw dragged item stack
2659         */
2660         drawSelectedItem();
2661
2662         skin->setFont(old_font);
2663 }
2664
2665
2666 void GUIFormSpecMenu::showTooltip(const std::wstring &text,
2667         const irr::video::SColor &color, const irr::video::SColor &bgcolor)
2668 {
2669         const std::wstring ntext = translate_string(text);
2670         m_tooltip_element->setOverrideColor(color);
2671         m_tooltip_element->setBackgroundColor(bgcolor);
2672         setStaticText(m_tooltip_element, ntext.c_str());
2673
2674         // Tooltip size and offset
2675         s32 tooltip_width = m_tooltip_element->getTextWidth() + m_btn_height;
2676 #if (IRRLICHT_VERSION_MAJOR <= 1 && IRRLICHT_VERSION_MINOR <= 8 && IRRLICHT_VERSION_REVISION < 2) || USE_FREETYPE == 1
2677         std::vector<std::wstring> text_rows = str_split(ntext, L'\n');
2678         s32 tooltip_height = m_tooltip_element->getTextHeight() * text_rows.size() + 5;
2679 #else
2680         s32 tooltip_height = m_tooltip_element->getTextHeight() + 5;
2681 #endif
2682         v2u32 screenSize = Environment->getVideoDriver()->getScreenSize();
2683         int tooltip_offset_x = m_btn_height;
2684         int tooltip_offset_y = m_btn_height;
2685 #ifdef __ANDROID__
2686         tooltip_offset_x *= 3;
2687         tooltip_offset_y  = 0;
2688         if (m_pointer.X > (s32)screenSize.X / 2)
2689                 tooltip_offset_x = -(tooltip_offset_x + tooltip_width);
2690 #endif
2691
2692         // Calculate and set the tooltip position
2693         s32 tooltip_x = m_pointer.X + tooltip_offset_x;
2694         s32 tooltip_y = m_pointer.Y + tooltip_offset_y;
2695         if (tooltip_x + tooltip_width > (s32)screenSize.X)
2696                 tooltip_x = (s32)screenSize.X - tooltip_width  - m_btn_height;
2697         if (tooltip_y + tooltip_height > (s32)screenSize.Y)
2698                 tooltip_y = (s32)screenSize.Y - tooltip_height - m_btn_height;
2699
2700         m_tooltip_element->setRelativePosition(
2701                 core::rect<s32>(
2702                         core::position2d<s32>(tooltip_x, tooltip_y),
2703                         core::dimension2d<s32>(tooltip_width, tooltip_height)
2704                 )
2705         );
2706
2707         // Display the tooltip
2708         m_tooltip_element->setVisible(true);
2709         bringToFront(m_tooltip_element);
2710 }
2711
2712 void GUIFormSpecMenu::updateSelectedItem()
2713 {
2714         // If the selected stack has become empty for some reason, deselect it.
2715         // If the selected stack has become inaccessible, deselect it.
2716         // If the selected stack has become smaller, adjust m_selected_amount.
2717         ItemStack selected = verifySelectedItem();
2718
2719         // WARNING: BLACK MAGIC
2720         // See if there is a stack suited for our current guess.
2721         // If such stack does not exist, clear the guess.
2722         if (!m_selected_content_guess.name.empty() &&
2723                         selected.name == m_selected_content_guess.name &&
2724                         selected.count == m_selected_content_guess.count){
2725                 // Selected item fits the guess. Skip the black magic.
2726         } else if (!m_selected_content_guess.name.empty()) {
2727                 bool found = false;
2728                 for(u32 i=0; i<m_inventorylists.size() && !found; i++){
2729                         const ListDrawSpec &s = m_inventorylists[i];
2730                         Inventory *inv = m_invmgr->getInventory(s.inventoryloc);
2731                         if(!inv)
2732                                 continue;
2733                         InventoryList *list = inv->getList(s.listname);
2734                         if(!list)
2735                                 continue;
2736                         for(s32 i=0; i<s.geom.X*s.geom.Y && !found; i++){
2737                                 u32 item_i = i + s.start_item_i;
2738                                 if(item_i >= list->getSize())
2739                                         continue;
2740                                 ItemStack stack = list->getItem(item_i);
2741                                 if(stack.name == m_selected_content_guess.name &&
2742                                                 stack.count == m_selected_content_guess.count){
2743                                         found = true;
2744                                         infostream<<"Client: Changing selected content guess to "
2745                                                         <<s.inventoryloc.dump()<<" "<<s.listname
2746                                                         <<" "<<item_i<<std::endl;
2747                                         delete m_selected_item;
2748                                         m_selected_item = new ItemSpec(s.inventoryloc, s.listname, item_i);
2749                                         m_selected_amount = stack.count;
2750                                 }
2751                         }
2752                 }
2753                 if(!found){
2754                         infostream<<"Client: Discarding selected content guess: "
2755                                         <<m_selected_content_guess.getItemString()<<std::endl;
2756                         m_selected_content_guess.name = "";
2757                 }
2758         }
2759
2760         // If craftresult is nonempty and nothing else is selected, select it now.
2761         if(!m_selected_item)
2762         {
2763                 for (const GUIFormSpecMenu::ListDrawSpec &s : m_inventorylists) {
2764                         if(s.listname == "craftpreview")
2765                         {
2766                                 Inventory *inv = m_invmgr->getInventory(s.inventoryloc);
2767                                 InventoryList *list = inv->getList("craftresult");
2768                                 if(list && list->getSize() >= 1 && !list->getItem(0).empty())
2769                                 {
2770                                         m_selected_item = new ItemSpec;
2771                                         m_selected_item->inventoryloc = s.inventoryloc;
2772                                         m_selected_item->listname = "craftresult";
2773                                         m_selected_item->i = 0;
2774                                         m_selected_amount = 0;
2775                                         m_selected_dragging = false;
2776                                         break;
2777                                 }
2778                         }
2779                 }
2780         }
2781
2782         // If craftresult is selected, keep the whole stack selected
2783         if(m_selected_item && m_selected_item->listname == "craftresult")
2784         {
2785                 m_selected_amount = verifySelectedItem().count;
2786         }
2787 }
2788
2789 ItemStack GUIFormSpecMenu::verifySelectedItem()
2790 {
2791         // If the selected stack has become empty for some reason, deselect it.
2792         // If the selected stack has become inaccessible, deselect it.
2793         // If the selected stack has become smaller, adjust m_selected_amount.
2794         // Return the selected stack.
2795
2796         if(m_selected_item)
2797         {
2798                 if(m_selected_item->isValid())
2799                 {
2800                         Inventory *inv = m_invmgr->getInventory(m_selected_item->inventoryloc);
2801                         if(inv)
2802                         {
2803                                 InventoryList *list = inv->getList(m_selected_item->listname);
2804                                 if(list && (u32) m_selected_item->i < list->getSize())
2805                                 {
2806                                         ItemStack stack = list->getItem(m_selected_item->i);
2807                                         if(m_selected_amount > stack.count)
2808                                                 m_selected_amount = stack.count;
2809                                         if(!stack.empty())
2810                                                 return stack;
2811                                 }
2812                         }
2813                 }
2814
2815                 // selection was not valid
2816                 delete m_selected_item;
2817                 m_selected_item = NULL;
2818                 m_selected_amount = 0;
2819                 m_selected_dragging = false;
2820         }
2821         return ItemStack();
2822 }
2823
2824 void GUIFormSpecMenu::acceptInput(FormspecQuitMode quitmode=quit_mode_no)
2825 {
2826         if(m_text_dst)
2827         {
2828                 StringMap fields;
2829
2830                 if (quitmode == quit_mode_accept) {
2831                         fields["quit"] = "true";
2832                 }
2833
2834                 if (quitmode == quit_mode_cancel) {
2835                         fields["quit"] = "true";
2836                         m_text_dst->gotText(fields);
2837                         return;
2838                 }
2839
2840                 if (current_keys_pending.key_down) {
2841                         fields["key_down"] = "true";
2842                         current_keys_pending.key_down = false;
2843                 }
2844
2845                 if (current_keys_pending.key_up) {
2846                         fields["key_up"] = "true";
2847                         current_keys_pending.key_up = false;
2848                 }
2849
2850                 if (current_keys_pending.key_enter) {
2851                         fields["key_enter"] = "true";
2852                         current_keys_pending.key_enter = false;
2853                 }
2854
2855                 if (!current_field_enter_pending.empty()) {
2856                         fields["key_enter_field"] = current_field_enter_pending;
2857                         current_field_enter_pending = "";
2858                 }
2859
2860                 if (current_keys_pending.key_escape) {
2861                         fields["key_escape"] = "true";
2862                         current_keys_pending.key_escape = false;
2863                 }
2864
2865                 for (const GUIFormSpecMenu::FieldSpec &s : m_fields) {
2866                         if(s.send) {
2867                                 std::string name = s.fname;
2868                                 if (s.ftype == f_Button) {
2869                                         fields[name] = wide_to_utf8(s.flabel);
2870                                 } else if (s.ftype == f_Table) {
2871                                         GUITable *table = getTable(s.fname);
2872                                         if (table) {
2873                                                 fields[name] = table->checkEvent();
2874                                         }
2875                                 }
2876                                 else if(s.ftype == f_DropDown) {
2877                                         // no dynamic cast possible due to some distributions shipped
2878                                         // without rtti support in irrlicht
2879                                         IGUIElement * element = getElementFromId(s.fid);
2880                                         gui::IGUIComboBox *e = NULL;
2881                                         if ((element) && (element->getType() == gui::EGUIET_COMBO_BOX)) {
2882                                                 e = static_cast<gui::IGUIComboBox*>(element);
2883                                         }
2884                                         s32 selected = e->getSelected();
2885                                         if (selected >= 0) {
2886                                                 std::vector<std::string> *dropdown_values =
2887                                                         getDropDownValues(s.fname);
2888                                                 if (dropdown_values && selected < (s32)dropdown_values->size()) {
2889                                                         fields[name] = (*dropdown_values)[selected];
2890                                                 }
2891                                         }
2892                                 }
2893                                 else if (s.ftype == f_TabHeader) {
2894                                         // no dynamic cast possible due to some distributions shipped
2895                                         // without rttzi support in irrlicht
2896                                         IGUIElement * element = getElementFromId(s.fid);
2897                                         gui::IGUITabControl *e = NULL;
2898                                         if ((element) && (element->getType() == gui::EGUIET_TAB_CONTROL)) {
2899                                                 e = static_cast<gui::IGUITabControl *>(element);
2900                                         }
2901
2902                                         if (e != 0) {
2903                                                 std::stringstream ss;
2904                                                 ss << (e->getActiveTab() +1);
2905                                                 fields[name] = ss.str();
2906                                         }
2907                                 }
2908                                 else if (s.ftype == f_CheckBox) {
2909                                         // no dynamic cast possible due to some distributions shipped
2910                                         // without rtti support in irrlicht
2911                                         IGUIElement * element = getElementFromId(s.fid);
2912                                         gui::IGUICheckBox *e = NULL;
2913                                         if ((element) && (element->getType() == gui::EGUIET_CHECK_BOX)) {
2914                                                 e = static_cast<gui::IGUICheckBox*>(element);
2915                                         }
2916
2917                                         if (e != 0) {
2918                                                 if (e->isChecked())
2919                                                         fields[name] = "true";
2920                                                 else
2921                                                         fields[name] = "false";
2922                                         }
2923                                 }
2924                                 else if (s.ftype == f_ScrollBar) {
2925                                         // no dynamic cast possible due to some distributions shipped
2926                                         // without rtti support in irrlicht
2927                                         IGUIElement * element = getElementFromId(s.fid);
2928                                         gui::IGUIScrollBar *e = NULL;
2929                                         if ((element) && (element->getType() == gui::EGUIET_SCROLL_BAR)) {
2930                                                 e = static_cast<gui::IGUIScrollBar*>(element);
2931                                         }
2932
2933                                         if (e != 0) {
2934                                                 std::stringstream os;
2935                                                 os << e->getPos();
2936                                                 if (s.fdefault == L"Changed")
2937                                                         fields[name] = "CHG:" + os.str();
2938                                                 else
2939                                                         fields[name] = "VAL:" + os.str();
2940                                         }
2941                                 }
2942                                 else
2943                                 {
2944                                         IGUIElement* e = getElementFromId(s.fid);
2945                                         if(e != NULL) {
2946                                                 fields[name] = wide_to_utf8(e->getText());
2947                                         }
2948                                 }
2949                         }
2950                 }
2951
2952                 m_text_dst->gotText(fields);
2953         }
2954 }
2955
2956 static bool isChild(gui::IGUIElement * tocheck, gui::IGUIElement * parent)
2957 {
2958         while(tocheck != NULL) {
2959                 if (tocheck == parent) {
2960                         return true;
2961                 }
2962                 tocheck = tocheck->getParent();
2963         }
2964         return false;
2965 }
2966
2967 bool GUIFormSpecMenu::preprocessEvent(const SEvent& event)
2968 {
2969         // The IGUITabControl renders visually using the skin's selected
2970         // font, which we override for the duration of form drawing,
2971         // but computes tab hotspots based on how it would have rendered
2972         // using the font that is selected at the time of button release.
2973         // To make these two consistent, temporarily override the skin's
2974         // font while the IGUITabControl is processing the event.
2975         if (event.EventType == EET_MOUSE_INPUT_EVENT &&
2976                         event.MouseInput.Event == EMIE_LMOUSE_LEFT_UP) {
2977                 s32 x = event.MouseInput.X;
2978                 s32 y = event.MouseInput.Y;
2979                 gui::IGUIElement *hovered =
2980                         Environment->getRootGUIElement()->getElementFromPoint(
2981                                 core::position2d<s32>(x, y));
2982                 if (hovered && isMyChild(hovered) &&
2983                                 hovered->getType() == gui::EGUIET_TAB_CONTROL) {
2984                         gui::IGUISkin* skin = Environment->getSkin();
2985                         sanity_check(skin != NULL);
2986                         gui::IGUIFont *old_font = skin->getFont();
2987                         skin->setFont(m_font);
2988                         bool retval = hovered->OnEvent(event);
2989                         skin->setFont(old_font);
2990                         return retval;
2991                 }
2992         }
2993
2994         // Fix Esc/Return key being eaten by checkboxen and tables
2995         if(event.EventType==EET_KEY_INPUT_EVENT) {
2996                 KeyPress kp(event.KeyInput);
2997                 if (kp == EscapeKey || kp == CancelKey
2998                                 || kp == getKeySetting("keymap_inventory")
2999                                 || event.KeyInput.Key==KEY_RETURN) {
3000                         gui::IGUIElement *focused = Environment->getFocus();
3001                         if (focused && isMyChild(focused) &&
3002                                         (focused->getType() == gui::EGUIET_LIST_BOX ||
3003                                          focused->getType() == gui::EGUIET_CHECK_BOX)) {
3004                                 OnEvent(event);
3005                                 return true;
3006                         }
3007                 }
3008         }
3009         // Mouse wheel events: send to hovered element instead of focused
3010         if(event.EventType==EET_MOUSE_INPUT_EVENT
3011                         && event.MouseInput.Event == EMIE_MOUSE_WHEEL) {
3012                 s32 x = event.MouseInput.X;
3013                 s32 y = event.MouseInput.Y;
3014                 gui::IGUIElement *hovered =
3015                         Environment->getRootGUIElement()->getElementFromPoint(
3016                                 core::position2d<s32>(x, y));
3017                 if (hovered && isMyChild(hovered)) {
3018                         hovered->OnEvent(event);
3019                         return true;
3020                 }
3021         }
3022
3023         if (event.EventType == EET_MOUSE_INPUT_EVENT) {
3024                 s32 x = event.MouseInput.X;
3025                 s32 y = event.MouseInput.Y;
3026                 gui::IGUIElement *hovered =
3027                         Environment->getRootGUIElement()->getElementFromPoint(
3028                                 core::position2d<s32>(x, y));
3029                 if (event.MouseInput.Event == EMIE_LMOUSE_PRESSED_DOWN) {
3030                         m_old_tooltip_id = -1;
3031                 }
3032                 if (!isChild(hovered,this)) {
3033                         if (DoubleClickDetection(event)) {
3034                                 return true;
3035                         }
3036                 }
3037         }
3038
3039         #ifdef __ANDROID__
3040         // display software keyboard when clicking edit boxes
3041         if (event.EventType == EET_MOUSE_INPUT_EVENT
3042                         && event.MouseInput.Event == EMIE_LMOUSE_PRESSED_DOWN) {
3043                 gui::IGUIElement *hovered =
3044                         Environment->getRootGUIElement()->getElementFromPoint(
3045                                 core::position2d<s32>(event.MouseInput.X, event.MouseInput.Y));
3046                 if ((hovered) && (hovered->getType() == irr::gui::EGUIET_EDIT_BOX)) {
3047                         bool retval = hovered->OnEvent(event);
3048                         if (retval) {
3049                                 Environment->setFocus(hovered);
3050                         }
3051                         m_JavaDialogFieldName = getNameByID(hovered->getID());
3052                         std::string message   = gettext("Enter ");
3053                         std::string label     = wide_to_utf8(getLabelByID(hovered->getID()));
3054                         if (label == "") {
3055                                 label = "text";
3056                         }
3057                         message += gettext(label) + ":";
3058
3059                         /* single line text input */
3060                         int type = 2;
3061
3062                         /* multi line text input */
3063                         if (((gui::IGUIEditBox*) hovered)->isMultiLineEnabled()) {
3064                                 type = 1;
3065                         }
3066
3067                         /* passwords are always single line */
3068                         if (((gui::IGUIEditBox*) hovered)->isPasswordBox()) {
3069                                 type = 3;
3070                         }
3071
3072                         porting::showInputDialog(gettext("ok"), "",
3073                                         wide_to_utf8(((gui::IGUIEditBox*) hovered)->getText()),
3074                                         type);
3075                         return retval;
3076                 }
3077         }
3078
3079         if (event.EventType == EET_TOUCH_INPUT_EVENT)
3080         {
3081                 SEvent translated;
3082                 memset(&translated, 0, sizeof(SEvent));
3083                 translated.EventType   = EET_MOUSE_INPUT_EVENT;
3084                 gui::IGUIElement* root = Environment->getRootGUIElement();
3085
3086                 if (!root) {
3087                         errorstream
3088                         << "GUIFormSpecMenu::preprocessEvent unable to get root element"
3089                         << std::endl;
3090                         return false;
3091                 }
3092                 gui::IGUIElement* hovered = root->getElementFromPoint(
3093                         core::position2d<s32>(
3094                                         event.TouchInput.X,
3095                                         event.TouchInput.Y));
3096
3097                 translated.MouseInput.X = event.TouchInput.X;
3098                 translated.MouseInput.Y = event.TouchInput.Y;
3099                 translated.MouseInput.Control = false;
3100
3101                 bool dont_send_event = false;
3102
3103                 if (event.TouchInput.touchedCount == 1) {
3104                         switch (event.TouchInput.Event) {
3105                                 case ETIE_PRESSED_DOWN:
3106                                         m_pointer = v2s32(event.TouchInput.X,event.TouchInput.Y);
3107                                         translated.MouseInput.Event = EMIE_LMOUSE_PRESSED_DOWN;
3108                                         translated.MouseInput.ButtonStates = EMBSM_LEFT;
3109                                         m_down_pos = m_pointer;
3110                                         break;
3111                                 case ETIE_MOVED:
3112                                         m_pointer = v2s32(event.TouchInput.X,event.TouchInput.Y);
3113                                         translated.MouseInput.Event = EMIE_MOUSE_MOVED;
3114                                         translated.MouseInput.ButtonStates = EMBSM_LEFT;
3115                                         break;
3116                                 case ETIE_LEFT_UP:
3117                                         translated.MouseInput.Event = EMIE_LMOUSE_LEFT_UP;
3118                                         translated.MouseInput.ButtonStates = 0;
3119                                         hovered = root->getElementFromPoint(m_down_pos);
3120                                         /* we don't have a valid pointer element use last
3121                                          * known pointer pos */
3122                                         translated.MouseInput.X = m_pointer.X;
3123                                         translated.MouseInput.Y = m_pointer.Y;
3124
3125                                         /* reset down pos */
3126                                         m_down_pos = v2s32(0,0);
3127                                         break;
3128                                 default:
3129                                         dont_send_event = true;
3130                                         //this is not supposed to happen
3131                                         errorstream
3132                                         << "GUIFormSpecMenu::preprocessEvent unexpected usecase Event="
3133                                         << event.TouchInput.Event << std::endl;
3134                         }
3135                 } else if ( (event.TouchInput.touchedCount == 2) &&
3136                                 (event.TouchInput.Event == ETIE_PRESSED_DOWN) ) {
3137                         hovered = root->getElementFromPoint(m_down_pos);
3138
3139                         translated.MouseInput.Event = EMIE_RMOUSE_PRESSED_DOWN;
3140                         translated.MouseInput.ButtonStates = EMBSM_LEFT | EMBSM_RIGHT;
3141                         translated.MouseInput.X = m_pointer.X;
3142                         translated.MouseInput.Y = m_pointer.Y;
3143
3144                         if (hovered) {
3145                                 hovered->OnEvent(translated);
3146                         }
3147
3148                         translated.MouseInput.Event = EMIE_RMOUSE_LEFT_UP;
3149                         translated.MouseInput.ButtonStates = EMBSM_LEFT;
3150
3151
3152                         if (hovered) {
3153                                 hovered->OnEvent(translated);
3154                         }
3155                         dont_send_event = true;
3156                 }
3157                 /* ignore unhandled 2 touch events ... accidental moving for example */
3158                 else if (event.TouchInput.touchedCount == 2) {
3159                         dont_send_event = true;
3160                 }
3161                 else if (event.TouchInput.touchedCount > 2) {
3162                         errorstream
3163                         << "GUIFormSpecMenu::preprocessEvent to many multitouch events "
3164                         << event.TouchInput.touchedCount << " ignoring them" << std::endl;
3165                 }
3166
3167                 if (dont_send_event) {
3168                         return true;
3169                 }
3170
3171                 /* check if translated event needs to be preprocessed again */
3172                 if (preprocessEvent(translated)) {
3173                         return true;
3174                 }
3175                 if (hovered) {
3176                         grab();
3177                         bool retval = hovered->OnEvent(translated);
3178
3179                         if (event.TouchInput.Event == ETIE_LEFT_UP) {
3180                                 /* reset pointer */
3181                                 m_pointer = v2s32(0,0);
3182                         }
3183                         drop();
3184                         return retval;
3185                 }
3186         }
3187         #endif
3188
3189         if (event.EventType == irr::EET_JOYSTICK_INPUT_EVENT) {
3190                 /* TODO add a check like:
3191                 if (event.JoystickEvent != joystick_we_listen_for)
3192                         return false;
3193                 */
3194                 bool handled = m_joystick->handleEvent(event.JoystickEvent);
3195                 if (handled) {
3196                         if (m_joystick->wasKeyDown(KeyType::ESC)) {
3197                                 tryClose();
3198                         } else if (m_joystick->wasKeyDown(KeyType::JUMP)) {
3199                                 if (m_allowclose) {
3200                                         acceptInput(quit_mode_accept);
3201                                         quitMenu();
3202                                 }
3203                         }
3204                 }
3205                 return handled;
3206         }
3207
3208         return false;
3209 }
3210
3211 /******************************************************************************/
3212 bool GUIFormSpecMenu::DoubleClickDetection(const SEvent event)
3213 {
3214         /* The following code is for capturing double-clicks of the mouse button
3215          * and translating the double-click into an EET_KEY_INPUT_EVENT event
3216          * -- which closes the form -- under some circumstances.
3217          *
3218          * There have been many github issues reporting this as a bug even though it
3219          * was an intended feature.  For this reason, remapping the double-click as
3220          * an ESC must be explicitly set when creating this class via the
3221          * /p remap_dbl_click parameter of the constructor.
3222          */
3223
3224         if (!m_remap_dbl_click)
3225                 return false;
3226
3227         if (event.MouseInput.Event == EMIE_LMOUSE_PRESSED_DOWN) {
3228                 m_doubleclickdetect[0].pos  = m_doubleclickdetect[1].pos;
3229                 m_doubleclickdetect[0].time = m_doubleclickdetect[1].time;
3230
3231                 m_doubleclickdetect[1].pos  = m_pointer;
3232                 m_doubleclickdetect[1].time = porting::getTimeMs();
3233         }
3234         else if (event.MouseInput.Event == EMIE_LMOUSE_LEFT_UP) {
3235                 u64 delta = porting::getDeltaMs(m_doubleclickdetect[0].time, porting::getTimeMs());
3236                 if (delta > 400) {
3237                         return false;
3238                 }
3239
3240                 double squaredistance =
3241                                 m_doubleclickdetect[0].pos
3242                                 .getDistanceFromSQ(m_doubleclickdetect[1].pos);
3243
3244                 if (squaredistance > (30*30)) {
3245                         return false;
3246                 }
3247
3248                 SEvent* translated = new SEvent();
3249                 assert(translated != 0);
3250                 //translate doubleclick to escape
3251                 memset(translated, 0, sizeof(SEvent));
3252                 translated->EventType = irr::EET_KEY_INPUT_EVENT;
3253                 translated->KeyInput.Key         = KEY_ESCAPE;
3254                 translated->KeyInput.Control     = false;
3255                 translated->KeyInput.Shift       = false;
3256                 translated->KeyInput.PressedDown = true;
3257                 translated->KeyInput.Char        = 0;
3258                 OnEvent(*translated);
3259
3260                 // no need to send the key up event as we're already deleted
3261                 // and no one else did notice this event
3262                 delete translated;
3263                 return true;
3264         }
3265
3266         return false;
3267 }
3268
3269 void GUIFormSpecMenu::tryClose()
3270 {
3271         if (m_allowclose) {
3272                 doPause = false;
3273                 acceptInput(quit_mode_cancel);
3274                 quitMenu();
3275         } else {
3276                 m_text_dst->gotText(L"MenuQuit");
3277         }
3278 }
3279
3280 bool GUIFormSpecMenu::OnEvent(const SEvent& event)
3281 {
3282         if (event.EventType==EET_KEY_INPUT_EVENT) {
3283                 KeyPress kp(event.KeyInput);
3284                 if (event.KeyInput.PressedDown && (
3285                                 (kp == EscapeKey) || (kp == CancelKey) ||
3286                                 ((m_client != NULL) && (kp == getKeySetting("keymap_inventory"))))) {
3287                         tryClose();
3288                         return true;
3289                 }
3290
3291                 if (m_client != NULL && event.KeyInput.PressedDown &&
3292                                 (kp == getKeySetting("keymap_screenshot"))) {
3293                         m_client->makeScreenshot();
3294                 }
3295                 if (event.KeyInput.PressedDown &&
3296                         (event.KeyInput.Key==KEY_RETURN ||
3297                          event.KeyInput.Key==KEY_UP ||
3298                          event.KeyInput.Key==KEY_DOWN)
3299                         ) {
3300                         switch (event.KeyInput.Key) {
3301                                 case KEY_RETURN:
3302                                         current_keys_pending.key_enter = true;
3303                                         break;
3304                                 case KEY_UP:
3305                                         current_keys_pending.key_up = true;
3306                                         break;
3307                                 case KEY_DOWN:
3308                                         current_keys_pending.key_down = true;
3309                                         break;
3310                                 break;
3311                                 default:
3312                                         //can't happen at all!
3313                                         FATAL_ERROR("Reached a source line that can't ever been reached");
3314                                         break;
3315                         }
3316                         if (current_keys_pending.key_enter && m_allowclose) {
3317                                 acceptInput(quit_mode_accept);
3318                                 quitMenu();
3319                         } else {
3320                                 acceptInput();
3321                         }
3322                         return true;
3323                 }
3324
3325         }
3326
3327         /* Mouse event other than movement, or crossing the border of inventory
3328           field while holding right mouse button
3329          */
3330         if (event.EventType == EET_MOUSE_INPUT_EVENT &&
3331                         (event.MouseInput.Event != EMIE_MOUSE_MOVED ||
3332                          (event.MouseInput.Event == EMIE_MOUSE_MOVED &&
3333                           event.MouseInput.isRightPressed() &&
3334                           getItemAtPos(m_pointer).i != getItemAtPos(m_old_pointer).i))) {
3335
3336                 // Get selected item and hovered/clicked item (s)
3337
3338                 m_old_tooltip_id = -1;
3339                 updateSelectedItem();
3340                 ItemSpec s = getItemAtPos(m_pointer);
3341
3342                 Inventory *inv_selected = NULL;
3343                 Inventory *inv_s = NULL;
3344                 InventoryList *list_s = NULL;
3345
3346                 if (m_selected_item) {
3347                         inv_selected = m_invmgr->getInventory(m_selected_item->inventoryloc);
3348                         sanity_check(inv_selected);
3349                         sanity_check(inv_selected->getList(m_selected_item->listname) != NULL);
3350                 }
3351
3352                 u32 s_count = 0;
3353
3354                 if (s.isValid())
3355                 do { // breakable
3356                         inv_s = m_invmgr->getInventory(s.inventoryloc);
3357
3358                         if (!inv_s) {
3359                                 errorstream << "InventoryMenu: The selected inventory location "
3360                                                 << "\"" << s.inventoryloc.dump() << "\" doesn't exist"
3361                                                 << std::endl;
3362                                 s.i = -1;  // make it invalid again
3363                                 break;
3364                         }
3365
3366                         list_s = inv_s->getList(s.listname);
3367                         if (list_s == NULL) {
3368                                 verbosestream << "InventoryMenu: The selected inventory list \""
3369                                                 << s.listname << "\" does not exist" << std::endl;
3370                                 s.i = -1;  // make it invalid again
3371                                 break;
3372                         }
3373
3374                         if ((u32)s.i >= list_s->getSize()) {
3375                                 infostream << "InventoryMenu: The selected inventory list \""
3376                                                 << s.listname << "\" is too small (i=" << s.i << ", size="
3377                                                 << list_s->getSize() << ")" << std::endl;
3378                                 s.i = -1;  // make it invalid again
3379                                 break;
3380                         }
3381
3382                         s_count = list_s->getItem(s.i).count;
3383                 } while(0);
3384
3385                 bool identical = (m_selected_item != NULL) && s.isValid() &&
3386                         (inv_selected == inv_s) &&
3387                         (m_selected_item->listname == s.listname) &&
3388                         (m_selected_item->i == s.i);
3389
3390                 // buttons: 0 = left, 1 = right, 2 = middle
3391                 // up/down: 0 = down (press), 1 = up (release), 2 = unknown event, -1 movement
3392                 int button = 0;
3393                 int updown = 2;
3394                 if (event.MouseInput.Event == EMIE_LMOUSE_PRESSED_DOWN)
3395                         { button = 0; updown = 0; }
3396                 else if (event.MouseInput.Event == EMIE_RMOUSE_PRESSED_DOWN)
3397                         { button = 1; updown = 0; }
3398                 else if (event.MouseInput.Event == EMIE_MMOUSE_PRESSED_DOWN)
3399                         { button = 2; updown = 0; }
3400                 else if (event.MouseInput.Event == EMIE_LMOUSE_LEFT_UP)
3401                         { button = 0; updown = 1; }
3402                 else if (event.MouseInput.Event == EMIE_RMOUSE_LEFT_UP)
3403                         { button = 1; updown = 1; }
3404                 else if (event.MouseInput.Event == EMIE_MMOUSE_LEFT_UP)
3405                         { button = 2; updown = 1; }
3406                 else if (event.MouseInput.Event == EMIE_MOUSE_MOVED)
3407                         { updown = -1;}
3408
3409                 // Set this number to a positive value to generate a move action
3410                 // from m_selected_item to s.
3411                 u32 move_amount = 0;
3412
3413                 // Set this number to a positive value to generate a move action
3414                 // from s to the next inventory ring.
3415                 u32 shift_move_amount = 0;
3416
3417                 // Set this number to a positive value to generate a drop action
3418                 // from m_selected_item.
3419                 u32 drop_amount = 0;
3420
3421                 // Set this number to a positive value to generate a craft action at s.
3422                 u32 craft_amount = 0;
3423
3424                 if (updown == 0) {
3425                         // Some mouse button has been pressed
3426
3427                         //infostream<<"Mouse button "<<button<<" pressed at p=("
3428                         //      <<p.X<<","<<p.Y<<")"<<std::endl;
3429
3430                         m_selected_dragging = false;
3431
3432                         if (s.isValid() && s.listname == "craftpreview") {
3433                                 // Craft preview has been clicked: craft
3434                                 craft_amount = (button == 2 ? 10 : 1);
3435                         } else if (m_selected_item == NULL) {
3436                                 if (s_count != 0) {
3437                                         // Non-empty stack has been clicked: select or shift-move it
3438                                         m_selected_item = new ItemSpec(s);
3439
3440                                         u32 count;
3441                                         if (button == 1)  // right
3442                                                 count = (s_count + 1) / 2;
3443                                         else if (button == 2)  // middle
3444                                                 count = MYMIN(s_count, 10);
3445                                         else  // left
3446                                                 count = s_count;
3447
3448                                         if (!event.MouseInput.Shift) {
3449                                                 // no shift: select item
3450                                                 m_selected_amount = count;
3451                                                 m_selected_dragging = true;
3452                                                 m_auto_place = false;
3453                                         } else {
3454                                                 // shift pressed: move item
3455                                                 if (button != 1)
3456                                                         shift_move_amount = count;
3457                                                 else // count of 1 at left click like after drag & drop
3458                                                         shift_move_amount = 1;
3459                                         }
3460                                 }
3461                         } else { // m_selected_item != NULL
3462                                 assert(m_selected_amount >= 1);
3463
3464                                 if (s.isValid()) {
3465                                         // Clicked a slot: move
3466                                         if (button == 1)  // right
3467                                                 move_amount = 1;
3468                                         else if (button == 2)  // middle
3469                                                 move_amount = MYMIN(m_selected_amount, 10);
3470                                         else  // left
3471                                                 move_amount = m_selected_amount;
3472
3473                                         if (identical) {
3474                                                 if (move_amount >= m_selected_amount)
3475                                                         m_selected_amount = 0;
3476                                                 else
3477                                                         m_selected_amount -= move_amount;
3478                                                 move_amount = 0;
3479                                         }
3480                                 }
3481                                 else if (!getAbsoluteClippingRect().isPointInside(m_pointer)) {
3482                                         // Clicked outside of the window: drop
3483                                         if (button == 1)  // right
3484                                                 drop_amount = 1;
3485                                         else if (button == 2)  // middle
3486                                                 drop_amount = MYMIN(m_selected_amount, 10);
3487                                         else  // left
3488                                                 drop_amount = m_selected_amount;
3489                                 }
3490                         }
3491                 }
3492                 else if (updown == 1) {
3493                         // Some mouse button has been released
3494
3495                         //infostream<<"Mouse button "<<button<<" released at p=("
3496                         //      <<p.X<<","<<p.Y<<")"<<std::endl;
3497
3498                         if (m_selected_item != NULL && m_selected_dragging && s.isValid()) {
3499                                 if (!identical) {
3500                                         // Dragged to different slot: move all selected
3501                                         move_amount = m_selected_amount;
3502                                 }
3503                         } else if (m_selected_item != NULL && m_selected_dragging &&
3504                                         !(getAbsoluteClippingRect().isPointInside(m_pointer))) {
3505                                 // Dragged outside of window: drop all selected
3506                                 drop_amount = m_selected_amount;
3507                         }
3508
3509                         m_selected_dragging = false;
3510                         // Keep track of whether the mouse button be released
3511                         // One click is drag without dropping. Click + release
3512                         // + click changes to drop item when moved mode
3513                         if (m_selected_item)
3514                                 m_auto_place = true;
3515                 } else if (updown == -1) {
3516                         // Mouse has been moved and rmb is down and mouse pointer just
3517                         // entered a new inventory field (checked in the entry-if, this
3518                         // is the only action here that is generated by mouse movement)
3519                         if (m_selected_item != NULL && s.isValid()) {
3520                                 // Move 1 item
3521                                 // TODO: middle mouse to move 10 items might be handy
3522                                 if (m_auto_place) {
3523                                         // Only move an item if the destination slot is empty
3524                                         // or contains the same item type as what is going to be
3525                                         // moved
3526                                         InventoryList *list_from = inv_selected->getList(m_selected_item->listname);
3527                                         InventoryList *list_to = list_s;
3528                                         assert(list_from && list_to);
3529                                         ItemStack stack_from = list_from->getItem(m_selected_item->i);
3530                                         ItemStack stack_to = list_to->getItem(s.i);
3531                                         if (stack_to.empty() || stack_to.name == stack_from.name)
3532                                                 move_amount = 1;
3533                                 }
3534                         }
3535                 }
3536
3537                 // Possibly send inventory action to server
3538                 if (move_amount > 0) {
3539                         // Send IAction::Move
3540
3541                         assert(m_selected_item && m_selected_item->isValid());
3542                         assert(s.isValid());
3543
3544                         assert(inv_selected && inv_s);
3545                         InventoryList *list_from = inv_selected->getList(m_selected_item->listname);
3546                         InventoryList *list_to = list_s;
3547                         assert(list_from && list_to);
3548                         ItemStack stack_from = list_from->getItem(m_selected_item->i);
3549                         ItemStack stack_to = list_to->getItem(s.i);
3550
3551                         // Check how many items can be moved
3552                         move_amount = stack_from.count = MYMIN(move_amount, stack_from.count);
3553                         ItemStack leftover = stack_to.addItem(stack_from, m_client->idef());
3554                         // If source stack cannot be added to destination stack at all,
3555                         // they are swapped
3556                         if ((leftover.count == stack_from.count) &&
3557                                         (leftover.name == stack_from.name)) {
3558                                 m_selected_amount = stack_to.count;
3559                                 // In case the server doesn't directly swap them but instead
3560                                 // moves stack_to somewhere else, set this
3561                                 m_selected_content_guess = stack_to;
3562                                 m_selected_content_guess_inventory = s.inventoryloc;
3563                         }
3564                         // Source stack goes fully into destination stack
3565                         else if (leftover.empty()) {
3566                                 m_selected_amount -= move_amount;
3567                                 m_selected_content_guess = ItemStack(); // Clear
3568                         }
3569                         // Source stack goes partly into destination stack
3570                         else {
3571                                 move_amount -= leftover.count;
3572                                 m_selected_amount -= move_amount;
3573                                 m_selected_content_guess = ItemStack(); // Clear
3574                         }
3575
3576                         infostream << "Handing IAction::Move to manager" << std::endl;
3577                         IMoveAction *a = new IMoveAction();
3578                         a->count = move_amount;
3579                         a->from_inv = m_selected_item->inventoryloc;
3580                         a->from_list = m_selected_item->listname;
3581                         a->from_i = m_selected_item->i;
3582                         a->to_inv = s.inventoryloc;
3583                         a->to_list = s.listname;
3584                         a->to_i = s.i;
3585                         m_invmgr->inventoryAction(a);
3586                 } else if (shift_move_amount > 0) {
3587                         u32 mis = m_inventory_rings.size();
3588                         u32 i = 0;
3589                         for (; i < mis; i++) {
3590                                 const ListRingSpec &sp = m_inventory_rings[i];
3591                                 if (sp.inventoryloc == s.inventoryloc
3592                                                 && sp.listname == s.listname)
3593                                         break;
3594                         }
3595                         do {
3596                                 if (i >= mis) // if not found
3597                                         break;
3598                                 u32 to_inv_ind = (i + 1) % mis;
3599                                 const ListRingSpec &to_inv_sp = m_inventory_rings[to_inv_ind];
3600                                 InventoryList *list_from = list_s;
3601                                 if (!s.isValid())
3602                                         break;
3603                                 Inventory *inv_to = m_invmgr->getInventory(to_inv_sp.inventoryloc);
3604                                 if (!inv_to)
3605                                         break;
3606                                 InventoryList *list_to = inv_to->getList(to_inv_sp.listname);
3607                                 if (!list_to)
3608                                         break;
3609                                 ItemStack stack_from = list_from->getItem(s.i);
3610                                 assert(shift_move_amount <= stack_from.count);
3611                                 if (m_client->getProtoVersion() >= 25) {
3612                                         infostream << "Handing IAction::Move to manager" << std::endl;
3613                                         IMoveAction *a = new IMoveAction();
3614                                         a->count = shift_move_amount;
3615                                         a->from_inv = s.inventoryloc;
3616                                         a->from_list = s.listname;
3617                                         a->from_i = s.i;
3618                                         a->to_inv = to_inv_sp.inventoryloc;
3619                                         a->to_list = to_inv_sp.listname;
3620                                         a->move_somewhere = true;
3621                                         m_invmgr->inventoryAction(a);
3622                                 } else {
3623                                         // find a place (or more than one) to add the new item
3624                                         u32 ilt_size = list_to->getSize();
3625                                         ItemStack leftover;
3626                                         for (u32 slot_to = 0; slot_to < ilt_size
3627                                                         && shift_move_amount > 0; slot_to++) {
3628                                                 list_to->itemFits(slot_to, stack_from, &leftover);
3629                                                 if (leftover.count < stack_from.count) {
3630                                                         infostream << "Handing IAction::Move to manager" << std::endl;
3631                                                         IMoveAction *a = new IMoveAction();
3632                                                         a->count = MYMIN(shift_move_amount,
3633                                                                 (u32) (stack_from.count - leftover.count));
3634                                                         shift_move_amount -= a->count;
3635                                                         a->from_inv = s.inventoryloc;
3636                                                         a->from_list = s.listname;
3637                                                         a->from_i = s.i;
3638                                                         a->to_inv = to_inv_sp.inventoryloc;
3639                                                         a->to_list = to_inv_sp.listname;
3640                                                         a->to_i = slot_to;
3641                                                         m_invmgr->inventoryAction(a);
3642                                                         stack_from = leftover;
3643                                                 }
3644                                         }
3645                                 }
3646                         } while (0);
3647                 } else if (drop_amount > 0) {
3648                         m_selected_content_guess = ItemStack(); // Clear
3649
3650                         // Send IAction::Drop
3651
3652                         assert(m_selected_item && m_selected_item->isValid());
3653                         assert(inv_selected);
3654                         InventoryList *list_from = inv_selected->getList(m_selected_item->listname);
3655                         assert(list_from);
3656                         ItemStack stack_from = list_from->getItem(m_selected_item->i);
3657
3658                         // Check how many items can be dropped
3659                         drop_amount = stack_from.count = MYMIN(drop_amount, stack_from.count);
3660                         assert(drop_amount > 0 && drop_amount <= m_selected_amount);
3661                         m_selected_amount -= drop_amount;
3662
3663                         infostream << "Handing IAction::Drop to manager" << std::endl;
3664                         IDropAction *a = new IDropAction();
3665                         a->count = drop_amount;
3666                         a->from_inv = m_selected_item->inventoryloc;
3667                         a->from_list = m_selected_item->listname;
3668                         a->from_i = m_selected_item->i;
3669                         m_invmgr->inventoryAction(a);
3670                 } else if (craft_amount > 0) {
3671                         assert(s.isValid());
3672                         
3673                         // if there are no items selected or the selected item
3674                         // belongs to craftresult list, proceed with crafting
3675                         if (m_selected_item == NULL ||
3676                                         !m_selected_item->isValid() || m_selected_item->listname == "craftresult") {
3677                                 
3678                                 m_selected_content_guess = ItemStack(); // Clear
3679                                 
3680                                 assert(inv_s);
3681
3682                                 // Send IACTION_CRAFT
3683                                 infostream << "Handing IACTION_CRAFT to manager" << std::endl;
3684                                 ICraftAction *a = new ICraftAction();
3685                                 a->count = craft_amount;
3686                                 a->craft_inv = s.inventoryloc;
3687                                 m_invmgr->inventoryAction(a);
3688                         }
3689                 }
3690
3691                 // If m_selected_amount has been decreased to zero, deselect
3692                 if (m_selected_amount == 0) {
3693                         delete m_selected_item;
3694                         m_selected_item = NULL;
3695                         m_selected_amount = 0;
3696                         m_selected_dragging = false;
3697                         m_selected_content_guess = ItemStack();
3698                 }
3699                 m_old_pointer = m_pointer;
3700         }
3701         if (event.EventType == EET_GUI_EVENT) {
3702
3703                 if (event.GUIEvent.EventType == gui::EGET_TAB_CHANGED
3704                                 && isVisible()) {
3705                         // find the element that was clicked
3706                         for (GUIFormSpecMenu::FieldSpec &s : m_fields) {
3707                                 if ((s.ftype == f_TabHeader) &&
3708                                                 (s.fid == event.GUIEvent.Caller->getID())) {
3709                                         s.send = true;
3710                                         acceptInput();
3711                                         s.send = false;
3712                                         return true;
3713                                 }
3714                         }
3715                 }
3716                 if (event.GUIEvent.EventType == gui::EGET_ELEMENT_FOCUS_LOST
3717                                 && isVisible()) {
3718                         if (!canTakeFocus(event.GUIEvent.Element)) {
3719                                 infostream<<"GUIFormSpecMenu: Not allowing focus change."
3720                                                 <<std::endl;
3721                                 // Returning true disables focus change
3722                                 return true;
3723                         }
3724                 }
3725                 if ((event.GUIEvent.EventType == gui::EGET_BUTTON_CLICKED) ||
3726                                 (event.GUIEvent.EventType == gui::EGET_CHECKBOX_CHANGED) ||
3727                                 (event.GUIEvent.EventType == gui::EGET_COMBO_BOX_CHANGED) ||
3728                                 (event.GUIEvent.EventType == gui::EGET_SCROLL_BAR_CHANGED)) {
3729                         unsigned int btn_id = event.GUIEvent.Caller->getID();
3730
3731                         if (btn_id == 257) {
3732                                 if (m_allowclose) {
3733                                         acceptInput(quit_mode_accept);
3734                                         quitMenu();
3735                                 } else {
3736                                         acceptInput();
3737                                         m_text_dst->gotText(L"ExitButton");
3738                                 }
3739                                 // quitMenu deallocates menu
3740                                 return true;
3741                         }
3742
3743                         // find the element that was clicked
3744                         for (GUIFormSpecMenu::FieldSpec &s : m_fields) {
3745                                 // if its a button, set the send field so
3746                                 // lua knows which button was pressed
3747                                 if ((s.ftype == f_Button || s.ftype == f_CheckBox) &&
3748                                                 s.fid == event.GUIEvent.Caller->getID()) {
3749                                         s.send = true;
3750                                         if (s.is_exit) {
3751                                                 if (m_allowclose) {
3752                                                         acceptInput(quit_mode_accept);
3753                                                         quitMenu();
3754                                                 } else {
3755                                                         m_text_dst->gotText(L"ExitButton");
3756                                                 }
3757                                                 return true;
3758                                         }
3759
3760                                         acceptInput(quit_mode_no);
3761                                         s.send = false;
3762                                         return true;
3763
3764                                 } else if ((s.ftype == f_DropDown) &&
3765                                                 (s.fid == event.GUIEvent.Caller->getID())) {
3766                                         // only send the changed dropdown
3767                                         for (GUIFormSpecMenu::FieldSpec &s2 : m_fields) {
3768                                                 if (s2.ftype == f_DropDown) {
3769                                                         s2.send = false;
3770                                                 }
3771                                         }
3772                                         s.send = true;
3773                                         acceptInput(quit_mode_no);
3774
3775                                         // revert configuration to make sure dropdowns are sent on
3776                                         // regular button click
3777                                         for (GUIFormSpecMenu::FieldSpec &s2 : m_fields) {
3778                                                 if (s2.ftype == f_DropDown) {
3779                                                         s2.send = true;
3780                                                 }
3781                                         }
3782                                         return true;
3783                                 } else if ((s.ftype == f_ScrollBar) &&
3784                                                 (s.fid == event.GUIEvent.Caller->getID())) {
3785                                         s.fdefault = L"Changed";
3786                                         acceptInput(quit_mode_no);
3787                                         s.fdefault = L"";
3788                                 }
3789                         }
3790                 }
3791
3792                 if (event.GUIEvent.EventType == gui::EGET_EDITBOX_ENTER) {
3793                         if (event.GUIEvent.Caller->getID() > 257) {
3794                                 bool close_on_enter = true;
3795                                 for (GUIFormSpecMenu::FieldSpec &s : m_fields) {
3796                                         if (s.ftype == f_Unknown &&
3797                                                         s.fid == event.GUIEvent.Caller->getID()) {
3798                                                 current_field_enter_pending = s.fname;
3799                                                 std::unordered_map<std::string, bool>::const_iterator it =
3800                                                         field_close_on_enter.find(s.fname);
3801                                                 if (it != field_close_on_enter.end())
3802                                                         close_on_enter = (*it).second;
3803
3804                                                 break;
3805                                         }
3806                                 }
3807
3808                                 if (m_allowclose && close_on_enter) {
3809                                         current_keys_pending.key_enter = true;
3810                                         acceptInput(quit_mode_accept);
3811                                         quitMenu();
3812                                 } else {
3813                                         current_keys_pending.key_enter = true;
3814                                         acceptInput();
3815                                 }
3816                                 // quitMenu deallocates menu
3817                                 return true;
3818                         }
3819                 }
3820
3821                 if (event.GUIEvent.EventType == gui::EGET_TABLE_CHANGED) {
3822                         int current_id = event.GUIEvent.Caller->getID();
3823                         if (current_id > 257) {
3824                                 // find the element that was clicked
3825                                 for (GUIFormSpecMenu::FieldSpec &s : m_fields) {
3826                                         // if it's a table, set the send field
3827                                         // so lua knows which table was changed
3828                                         if ((s.ftype == f_Table) && (s.fid == current_id)) {
3829                                                 s.send = true;
3830                                                 acceptInput();
3831                                                 s.send=false;
3832                                         }
3833                                 }
3834                                 return true;
3835                         }
3836                 }
3837         }
3838
3839         return Parent ? Parent->OnEvent(event) : false;
3840 }
3841
3842 /**
3843  * get name of element by element id
3844  * @param id of element
3845  * @return name string or empty string
3846  */
3847 std::string GUIFormSpecMenu::getNameByID(s32 id)
3848 {
3849         for (FieldSpec &spec : m_fields) {
3850                 if (spec.fid == id) {
3851                         return spec.fname;
3852                 }
3853         }
3854         return "";
3855 }
3856
3857 /**
3858  * get label of element by id
3859  * @param id of element
3860  * @return label string or empty string
3861  */
3862 std::wstring GUIFormSpecMenu::getLabelByID(s32 id)
3863 {
3864         for (FieldSpec &spec : m_fields) {
3865                 if (spec.fid == id) {
3866                         return spec.flabel;
3867                 }
3868         }
3869         return L"";
3870 }