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