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