Add warning when disabling secure.enable_security (#9943)
[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 <limits>
25 #include <sstream>
26 #include "guiFormSpecMenu.h"
27 #include "guiScrollBar.h"
28 #include "guiTable.h"
29 #include "constants.h"
30 #include "gamedef.h"
31 #include "client/keycode.h"
32 #include "util/strfnd.h"
33 #include <IGUIButton.h>
34 #include <IGUICheckBox.h>
35 #include <IGUIComboBox.h>
36 #include <IGUIEditBox.h>
37 #include <IGUIStaticText.h>
38 #include <IGUIFont.h>
39 #include <IGUITabControl.h>
40 #include "client/renderingengine.h"
41 #include "log.h"
42 #include "client/tile.h" // ITextureSource
43 #include "client/hud.h" // drawItemStack
44 #include "filesys.h"
45 #include "gettime.h"
46 #include "gettext.h"
47 #include "scripting_server.h"
48 #include "mainmenumanager.h"
49 #include "porting.h"
50 #include "settings.h"
51 #include "client/client.h"
52 #include "client/fontengine.h"
53 #include "util/hex.h"
54 #include "util/numeric.h"
55 #include "util/string.h" // for parseColorString()
56 #include "irrlicht_changes/static_text.h"
57 #include "client/guiscalingfilter.h"
58 #include "guiAnimatedImage.h"
59 #include "guiBackgroundImage.h"
60 #include "guiBox.h"
61 #include "guiButton.h"
62 #include "guiButtonImage.h"
63 #include "guiButtonItemImage.h"
64 #include "guiEditBoxWithScrollbar.h"
65 #include "guiInventoryList.h"
66 #include "guiItemImage.h"
67 #include "guiScrollBar.h"
68 #include "guiScrollContainer.h"
69 #include "guiTable.h"
70 #include "intlGUIEditBox.h"
71 #include "guiHyperText.h"
72
73 #define MY_CHECKPOS(a,b)                                                                                                        \
74         if (v_pos.size() != 2) {                                                                                                \
75                 errorstream<< "Invalid pos for element " << a << "specified: \""        \
76                         << parts[b] << "\"" << std::endl;                                                               \
77                         return;                                                                                                                 \
78         }
79
80 #define MY_CHECKGEOM(a,b)                                                                                                       \
81         if (v_geom.size() != 2) {                                                                                               \
82                 errorstream<< "Invalid geometry for element " << a <<                           \
83                         "specified: \"" << parts[b] << "\"" << std::endl;                               \
84                         return;                                                                                                                 \
85         }
86 /*
87         GUIFormSpecMenu
88 */
89 static unsigned int font_line_height(gui::IGUIFont *font)
90 {
91         return font->getDimension(L"Ay").Height + font->getKerningHeight();
92 }
93
94 inline u32 clamp_u8(s32 value)
95 {
96         return (u32) MYMIN(MYMAX(value, 0), 255);
97 }
98
99 GUIFormSpecMenu::GUIFormSpecMenu(JoystickController *joystick,
100                 gui::IGUIElement *parent, s32 id, IMenuManager *menumgr,
101                 Client *client, ISimpleTextureSource *tsrc, IFormSource *fsrc, TextDest *tdst,
102                 const std::string &formspecPrepend,
103                 bool remap_dbl_click):
104         GUIModalMenu(RenderingEngine::get_gui_env(), parent, id, menumgr),
105         m_invmgr(client),
106         m_tsrc(tsrc),
107         m_client(client),
108         m_formspec_prepend(formspecPrepend),
109         m_form_src(fsrc),
110         m_text_dst(tdst),
111         m_joystick(joystick),
112         m_remap_dbl_click(remap_dbl_click)
113 {
114         current_keys_pending.key_down = false;
115         current_keys_pending.key_up = false;
116         current_keys_pending.key_enter = false;
117         current_keys_pending.key_escape = false;
118
119         m_doubleclickdetect[0].time = 0;
120         m_doubleclickdetect[1].time = 0;
121
122         m_doubleclickdetect[0].pos = v2s32(0, 0);
123         m_doubleclickdetect[1].pos = v2s32(0, 0);
124
125         m_tooltip_show_delay = (u32)g_settings->getS32("tooltip_show_delay");
126         m_tooltip_append_itemname = g_settings->getBool("tooltip_append_itemname");
127 }
128
129 GUIFormSpecMenu::~GUIFormSpecMenu()
130 {
131         removeChildren();
132
133         for (auto &table_it : m_tables)
134                 table_it.second->drop();
135         for (auto &inventorylist_it : m_inventorylists)
136                 inventorylist_it->drop();
137         for (auto &checkbox_it : m_checkboxes)
138                 checkbox_it.second->drop();
139         for (auto &scrollbar_it : m_scrollbars)
140                 scrollbar_it.second->drop();
141         for (auto &background_it : m_backgrounds)
142                 background_it->drop();
143         for (auto &tooltip_rect_it : m_tooltip_rects)
144                 tooltip_rect_it.first->drop();
145         for (auto &clickthrough_it : m_clickthrough_elements)
146                 clickthrough_it->drop();
147         for (auto &scroll_container_it : m_scroll_containers)
148                 scroll_container_it.second->drop();
149
150         delete m_selected_item;
151         delete m_form_src;
152         delete m_text_dst;
153 }
154
155 void GUIFormSpecMenu::create(GUIFormSpecMenu *&cur_formspec, Client *client,
156         JoystickController *joystick, IFormSource *fs_src, TextDest *txt_dest,
157         const std::string &formspecPrepend)
158 {
159         if (cur_formspec == nullptr) {
160                 cur_formspec = new GUIFormSpecMenu(joystick, guiroot, -1, &g_menumgr,
161                         client, client->getTextureSource(), fs_src, txt_dest, formspecPrepend);
162                 cur_formspec->doPause = false;
163
164                 /*
165                         Caution: do not call (*cur_formspec)->drop() here --
166                         the reference might outlive the menu, so we will
167                         periodically check if *cur_formspec is the only
168                         remaining reference (i.e. the menu was removed)
169                         and delete it in that case.
170                 */
171
172         } else {
173                 cur_formspec->setFormspecPrepend(formspecPrepend);
174                 cur_formspec->setFormSource(fs_src);
175                 cur_formspec->setTextDest(txt_dest);
176         }
177 }
178
179 void GUIFormSpecMenu::removeChildren()
180 {
181         const core::list<gui::IGUIElement*> &children = getChildren();
182
183         while (!children.empty()) {
184                 (*children.getLast())->remove();
185         }
186
187         if (m_tooltip_element) {
188                 m_tooltip_element->remove();
189                 m_tooltip_element->drop();
190                 m_tooltip_element = nullptr;
191         }
192 }
193
194 void GUIFormSpecMenu::setInitialFocus()
195 {
196         // Set initial focus according to following order of precedence:
197         // 1. first empty editbox
198         // 2. first editbox
199         // 3. first table
200         // 4. last button
201         // 5. first focusable (not statictext, not tabheader)
202         // 6. first child element
203
204         core::list<gui::IGUIElement*> children = getChildren();
205
206         // in case "children" contains any NULL elements, remove them
207         for (core::list<gui::IGUIElement*>::Iterator it = children.begin();
208                         it != children.end();) {
209                 if (*it)
210                         ++it;
211                 else
212                         it = children.erase(it);
213         }
214
215         // 1. first empty editbox
216         for (gui::IGUIElement *it : children) {
217                 if (it->getType() == gui::EGUIET_EDIT_BOX
218                                 && it->getText()[0] == 0) {
219                         Environment->setFocus(it);
220                         return;
221                 }
222         }
223
224         // 2. first editbox
225         for (gui::IGUIElement *it : children) {
226                 if (it->getType() == gui::EGUIET_EDIT_BOX) {
227                         Environment->setFocus(it);
228                         return;
229                 }
230         }
231
232         // 3. first table
233         for (gui::IGUIElement *it : children) {
234                 if (it->getTypeName() == std::string("GUITable")) {
235                         Environment->setFocus(it);
236                         return;
237                 }
238         }
239
240         // 4. last button
241         for (core::list<gui::IGUIElement*>::Iterator it = children.getLast();
242                         it != children.end(); --it) {
243                 if ((*it)->getType() == gui::EGUIET_BUTTON) {
244                         Environment->setFocus(*it);
245                         return;
246                 }
247         }
248
249         // 5. first focusable (not statictext, not tabheader)
250         for (gui::IGUIElement *it : children) {
251                 if (it->getType() != gui::EGUIET_STATIC_TEXT &&
252                         it->getType() != gui::EGUIET_TAB_CONTROL) {
253                         Environment->setFocus(it);
254                         return;
255                 }
256         }
257
258         // 6. first child element
259         if (children.empty())
260                 Environment->setFocus(this);
261         else
262                 Environment->setFocus(*(children.begin()));
263 }
264
265 GUITable* GUIFormSpecMenu::getTable(const std::string &tablename)
266 {
267         for (auto &table : m_tables) {
268                 if (tablename == table.first.fname)
269                         return table.second;
270         }
271         return 0;
272 }
273
274 std::vector<std::string>* GUIFormSpecMenu::getDropDownValues(const std::string &name)
275 {
276         for (auto &dropdown : m_dropdowns) {
277                 if (name == dropdown.first.fname)
278                         return &dropdown.second;
279         }
280         return NULL;
281 }
282
283 v2s32 GUIFormSpecMenu::getElementBasePos(const std::vector<std::string> *v_pos)
284 {
285         v2f32 pos_f = v2f32(padding.X, padding.Y) + pos_offset * spacing;
286         if (v_pos) {
287                 pos_f.X += stof((*v_pos)[0]) * spacing.X;
288                 pos_f.Y += stof((*v_pos)[1]) * spacing.Y;
289         }
290         return v2s32(pos_f.X, pos_f.Y);
291 }
292
293 v2s32 GUIFormSpecMenu::getRealCoordinateBasePos(const std::vector<std::string> &v_pos)
294 {
295         return v2s32((stof(v_pos[0]) + pos_offset.X) * imgsize.X,
296                 (stof(v_pos[1]) + pos_offset.Y) * imgsize.Y);
297 }
298
299 v2s32 GUIFormSpecMenu::getRealCoordinateGeometry(const std::vector<std::string> &v_geom)
300 {
301         return v2s32(stof(v_geom[0]) * imgsize.X, stof(v_geom[1]) * imgsize.Y);
302 }
303
304 void GUIFormSpecMenu::parseSize(parserData* data, const std::string &element)
305 {
306         std::vector<std::string> parts = split(element,',');
307
308         if (((parts.size() == 2) || parts.size() == 3) ||
309                 ((parts.size() > 3) && (m_formspec_version > FORMSPEC_API_VERSION)))
310         {
311                 if (parts[1].find(';') != std::string::npos)
312                         parts[1] = parts[1].substr(0,parts[1].find(';'));
313
314                 data->invsize.X = MYMAX(0, stof(parts[0]));
315                 data->invsize.Y = MYMAX(0, stof(parts[1]));
316
317                 lockSize(false);
318 #ifndef __ANDROID__
319                 if (parts.size() == 3) {
320                         if (parts[2] == "true") {
321                                 lockSize(true,v2u32(800,600));
322                         }
323                 }
324 #endif
325                 data->explicit_size = true;
326                 return;
327         }
328         errorstream<< "Invalid size element (" << parts.size() << "): '" << element << "'"  << std::endl;
329 }
330
331 void GUIFormSpecMenu::parseContainer(parserData* data, const std::string &element)
332 {
333         std::vector<std::string> parts = split(element, ',');
334
335         if (parts.size() >= 2) {
336                 if (parts[1].find(';') != std::string::npos)
337                         parts[1] = parts[1].substr(0, parts[1].find(';'));
338
339                 container_stack.push(pos_offset);
340                 pos_offset.X += stof(parts[0]);
341                 pos_offset.Y += stof(parts[1]);
342                 return;
343         }
344         errorstream<< "Invalid container start element (" << parts.size() << "): '" << element << "'"  << std::endl;
345 }
346
347 void GUIFormSpecMenu::parseContainerEnd(parserData* data)
348 {
349         if (container_stack.empty()) {
350                 errorstream<< "Invalid container end element, no matching container start element"  << std::endl;
351         } else {
352                 pos_offset = container_stack.top();
353                 container_stack.pop();
354         }
355 }
356
357 void GUIFormSpecMenu::parseScrollContainer(parserData *data, const std::string &element)
358 {
359         std::vector<std::string> parts = split(element, ';');
360
361         if (parts.size() < 4 ||
362                         (parts.size() > 5 && m_formspec_version <= FORMSPEC_API_VERSION)) {
363                 errorstream << "Invalid scroll_container start element (" << parts.size()
364                                 << "): '" << element << "'" << std::endl;
365                 return;
366         }
367
368         std::vector<std::string> v_pos  = split(parts[0], ',');
369         std::vector<std::string> v_geom = split(parts[1], ',');
370         std::string scrollbar_name = parts[2];
371         std::string orientation = parts[3];
372         f32 scroll_factor = 0.1f;
373         if (parts.size() >= 5 && !parts[4].empty())
374                 scroll_factor = stof(parts[4]);
375
376         MY_CHECKPOS("scroll_container", 0);
377         MY_CHECKGEOM("scroll_container", 1);
378
379         v2s32 pos = getRealCoordinateBasePos(v_pos);
380         v2s32 geom = getRealCoordinateGeometry(v_geom);
381
382         if (orientation == "vertical")
383                 scroll_factor *= -imgsize.Y;
384         else if (orientation == "horizontal")
385                 scroll_factor *= -imgsize.X;
386         else
387                 warningstream << "GUIFormSpecMenu::parseScrollContainer(): "
388                                 << "Invalid scroll_container orientation: " << orientation
389                                 << std::endl;
390
391         // old parent (at first: this)
392         // ^ is parent of clipper
393         // ^ is parent of mover
394         // ^ is parent of other elements
395
396         // make clipper
397         core::rect<s32> rect_clipper = core::rect<s32>(pos, pos + geom);
398
399         gui::IGUIElement *clipper = new gui::IGUIElement(EGUIET_ELEMENT, Environment,
400                         data->current_parent, 0, rect_clipper);
401
402         // make mover
403         FieldSpec spec_mover(
404                 "",
405                 L"",
406                 L"",
407                 258 + m_fields.size()
408         );
409
410         core::rect<s32> rect_mover = core::rect<s32>(0, 0, geom.X, geom.Y);
411
412         GUIScrollContainer *mover = new GUIScrollContainer(Environment,
413                         clipper, spec_mover.fid, rect_mover, orientation, scroll_factor);
414
415         data->current_parent = mover;
416
417         m_scroll_containers.emplace_back(scrollbar_name, mover);
418
419         m_fields.push_back(spec_mover);
420
421         clipper->drop();
422
423         // remove interferring offset of normal containers
424         container_stack.push(pos_offset);
425         pos_offset.X = 0.0f;
426         pos_offset.Y = 0.0f;
427 }
428
429 void GUIFormSpecMenu::parseScrollContainerEnd(parserData *data)
430 {
431         if (data->current_parent == this || data->current_parent->getParent() == this ||
432                         container_stack.empty()) {
433                 errorstream << "Invalid scroll_container end element, "
434                                 << "no matching scroll_container start element" << std::endl;
435                 return;
436         }
437
438         if (pos_offset.getLengthSQ() != 0.0f) {
439                 // pos_offset is only set by containers and scroll_containers.
440                 // scroll_containers always set it to 0,0 which means that if it is
441                 // not 0,0, it is a normal container that was opened last, not a
442                 // scroll_container
443                 errorstream << "Invalid scroll_container end element, "
444                                 << "an inner container was left open" << std::endl;
445                 return;
446         }
447
448         data->current_parent = data->current_parent->getParent()->getParent();
449         pos_offset = container_stack.top();
450         container_stack.pop();
451 }
452
453 void GUIFormSpecMenu::parseList(parserData *data, const std::string &element)
454 {
455         if (m_client == 0) {
456                 warningstream<<"invalid use of 'list' with m_client==0"<<std::endl;
457                 return;
458         }
459
460         std::vector<std::string> parts = split(element,';');
461
462         if (((parts.size() == 4) || (parts.size() == 5)) ||
463                 ((parts.size() > 5) && (m_formspec_version > FORMSPEC_API_VERSION)))
464         {
465                 std::string location = parts[0];
466                 std::string listname = parts[1];
467                 std::vector<std::string> v_pos  = split(parts[2],',');
468                 std::vector<std::string> v_geom = split(parts[3],',');
469                 std::string startindex;
470                 if (parts.size() == 5)
471                         startindex = parts[4];
472
473                 MY_CHECKPOS("list",2);
474                 MY_CHECKGEOM("list",3);
475
476                 InventoryLocation loc;
477
478                 if (location == "context" || location == "current_name")
479                         loc = m_current_inventory_location;
480                 else
481                         loc.deSerialize(location);
482
483                 v2s32 geom;
484                 geom.X = stoi(v_geom[0]);
485                 geom.Y = stoi(v_geom[1]);
486
487                 s32 start_i = 0;
488                 if (!startindex.empty())
489                         start_i = stoi(startindex);
490
491                 if (geom.X < 0 || geom.Y < 0 || start_i < 0) {
492                         errorstream << "Invalid list element: '" << element << "'"  << std::endl;
493                         return;
494                 }
495
496                 if (!data->explicit_size)
497                         warningstream << "invalid use of list without a size[] element" << std::endl;
498
499                 FieldSpec spec(
500                         "",
501                         L"",
502                         L"",
503                         258 + m_fields.size(),
504                         3
505                 );
506
507                 v2f32 slot_spacing = data->real_coordinates ?
508                                 v2f32(imgsize.X * 1.25f, imgsize.Y * 1.25f) : spacing;
509
510                 v2s32 pos = data->real_coordinates ? getRealCoordinateBasePos(v_pos)
511                                 : getElementBasePos(&v_pos);
512
513                 core::rect<s32> rect = core::rect<s32>(pos.X, pos.Y,
514                                 pos.X + (geom.X - 1) * slot_spacing.X + imgsize.X,
515                                 pos.Y + (geom.Y - 1) * slot_spacing.Y + imgsize.Y);
516
517                 GUIInventoryList *e = new GUIInventoryList(Environment, data->current_parent,
518                                 spec.fid, rect, m_invmgr, loc, listname, geom, start_i, imgsize,
519                                 slot_spacing, this, data->inventorylist_options, m_font);
520
521                 m_inventorylists.push_back(e);
522                 m_fields.push_back(spec);
523                 return;
524         }
525         errorstream<< "Invalid list element(" << parts.size() << "): '" << element << "'"  << std::endl;
526 }
527
528 void GUIFormSpecMenu::parseListRing(parserData *data, const std::string &element)
529 {
530         if (m_client == 0) {
531                 errorstream << "WARNING: invalid use of 'listring' with m_client==0" << std::endl;
532                 return;
533         }
534
535         std::vector<std::string> parts = split(element, ';');
536
537         if (parts.size() == 2) {
538                 std::string location = parts[0];
539                 std::string listname = parts[1];
540
541                 InventoryLocation loc;
542
543                 if (location == "context" || location == "current_name")
544                         loc = m_current_inventory_location;
545                 else
546                         loc.deSerialize(location);
547
548                 m_inventory_rings.emplace_back(loc, listname);
549                 return;
550         }
551
552         if (element.empty() && m_inventorylists.size() > 1) {
553                 size_t siz = m_inventorylists.size();
554                 // insert the last two inv list elements into the list ring
555                 const GUIInventoryList *spa = m_inventorylists[siz - 2];
556                 const GUIInventoryList *spb = m_inventorylists[siz - 1];
557                 m_inventory_rings.emplace_back(spa->getInventoryloc(), spa->getListname());
558                 m_inventory_rings.emplace_back(spb->getInventoryloc(), spb->getListname());
559                 return;
560         }
561
562         errorstream<< "Invalid list ring element(" << parts.size() << ", "
563                 << m_inventorylists.size() << "): '" << element << "'"  << std::endl;
564 }
565
566 void GUIFormSpecMenu::parseCheckbox(parserData* data, const std::string &element)
567 {
568         std::vector<std::string> parts = split(element,';');
569
570         if (((parts.size() >= 3) && (parts.size() <= 4)) ||
571                 ((parts.size() > 4) && (m_formspec_version > FORMSPEC_API_VERSION)))
572         {
573                 std::vector<std::string> v_pos = split(parts[0],',');
574                 std::string name = parts[1];
575                 std::string label = parts[2];
576                 std::string selected;
577
578                 if (parts.size() >= 4)
579                         selected = parts[3];
580
581                 MY_CHECKPOS("checkbox",0);
582
583                 bool fselected = false;
584
585                 if (selected == "true")
586                         fselected = true;
587
588                 std::wstring wlabel = translate_string(utf8_to_wide(unescape_string(label)));
589                 const core::dimension2d<u32> label_size = m_font->getDimension(wlabel.c_str());
590                 s32 cb_size = Environment->getSkin()->getSize(gui::EGDS_CHECK_BOX_WIDTH);
591                 s32 y_center = (std::max(label_size.Height, (u32)cb_size) + 1) / 2;
592
593                 v2s32 pos;
594                 core::rect<s32> rect;
595
596                 if (data->real_coordinates) {
597                         pos = getRealCoordinateBasePos(v_pos);
598
599                         rect = core::rect<s32>(
600                                         pos.X,
601                                         pos.Y - y_center,
602                                         pos.X + label_size.Width + cb_size + 7,
603                                         pos.Y + y_center
604                                 );
605                 } else {
606                         pos = getElementBasePos(&v_pos);
607                         rect = core::rect<s32>(
608                                         pos.X,
609                                         pos.Y + imgsize.Y / 2 - y_center,
610                                         pos.X + label_size.Width + cb_size + 7,
611                                         pos.Y + imgsize.Y / 2 + y_center
612                                 );
613                 }
614
615                 FieldSpec spec(
616                                 name,
617                                 wlabel, //Needed for displaying text on MSVC
618                                 wlabel,
619                                 258+m_fields.size()
620                         );
621
622                 spec.ftype = f_CheckBox;
623
624                 gui::IGUICheckBox *e = Environment->addCheckBox(fselected, rect,
625                                 data->current_parent, spec.fid, spec.flabel.c_str());
626
627                 auto style = getDefaultStyleForElement("checkbox", name);
628                 e->setNotClipped(style.getBool(StyleSpec::NOCLIP, false));
629
630                 if (spec.fname == data->focused_fieldname) {
631                         Environment->setFocus(e);
632                 }
633
634                 e->grab();
635                 m_checkboxes.emplace_back(spec, e);
636                 m_fields.push_back(spec);
637                 return;
638         }
639         errorstream<< "Invalid checkbox element(" << parts.size() << "): '" << element << "'"  << std::endl;
640 }
641
642 void GUIFormSpecMenu::parseScrollBar(parserData* data, const std::string &element)
643 {
644         std::vector<std::string> parts = split(element,';');
645
646         if (parts.size() >= 5) {
647                 std::vector<std::string> v_pos = split(parts[0],',');
648                 std::vector<std::string> v_geom = split(parts[1],',');
649                 std::string name = parts[3];
650                 std::string value = parts[4];
651
652                 MY_CHECKPOS("scrollbar",0);
653                 MY_CHECKGEOM("scrollbar",1);
654
655                 v2s32 pos;
656                 v2s32 dim;
657
658                 if (data->real_coordinates) {
659                         pos = getRealCoordinateBasePos(v_pos);
660                         dim = getRealCoordinateGeometry(v_geom);
661                 } else {
662                         pos = getElementBasePos(&v_pos);
663                         dim.X = stof(v_geom[0]) * spacing.X;
664                         dim.Y = stof(v_geom[1]) * spacing.Y;
665                 }
666
667                 core::rect<s32> rect =
668                                 core::rect<s32>(pos.X, pos.Y, pos.X + dim.X, pos.Y + dim.Y);
669
670                 FieldSpec spec(
671                                 name,
672                                 L"",
673                                 L"",
674                                 258+m_fields.size()
675                         );
676
677                 bool is_horizontal = true;
678
679                 if (parts[2] == "vertical")
680                         is_horizontal = false;
681
682                 spec.ftype = f_ScrollBar;
683                 spec.send  = true;
684                 GUIScrollBar *e = new GUIScrollBar(Environment, data->current_parent,
685                                 spec.fid, rect, is_horizontal, true);
686
687                 auto style = getDefaultStyleForElement("scrollbar", name);
688                 e->setNotClipped(style.getBool(StyleSpec::NOCLIP, false));
689                 e->setArrowsVisible(data->scrollbar_options.arrow_visiblity);
690
691                 s32 max = data->scrollbar_options.max;
692                 s32 min = data->scrollbar_options.min;
693
694                 e->setMax(max);
695                 e->setMin(min);
696
697                 e->setPos(stoi(parts[4]));
698
699                 e->setSmallStep(data->scrollbar_options.small_step);
700                 e->setLargeStep(data->scrollbar_options.large_step);
701
702                 s32 scrollbar_size = is_horizontal ? dim.X : dim.Y;
703
704                 e->setPageSize(scrollbar_size * (max - min + 1) / data->scrollbar_options.thumb_size);
705
706                 m_scrollbars.emplace_back(spec,e);
707                 m_fields.push_back(spec);
708                 return;
709         }
710         errorstream << "Invalid scrollbar element(" << parts.size() << "): '" << element
711                 << "'" << std::endl;
712 }
713
714 void GUIFormSpecMenu::parseScrollBarOptions(parserData* data, const std::string &element)
715 {
716         std::vector<std::string> parts = split(element, ';');
717
718         if (parts.size() == 0) {
719                 warningstream << "Invalid scrollbaroptions element(" << parts.size() << "): '" <<
720                         element << "'"  << std::endl;
721                 return;
722         }
723
724         for (const std::string &i : parts) {
725                 std::vector<std::string> options = split(i, '=');
726
727                 if (options.size() != 2) {
728                         warningstream << "Invalid scrollbaroptions option syntax: '" <<
729                                 element << "'" << std::endl;
730                         continue; // Go to next option
731                 }
732
733                 if (options[0] == "max") {
734                         data->scrollbar_options.max = stoi(options[1]);
735                         continue;
736                 } else if (options[0] == "min") {
737                         data->scrollbar_options.min = stoi(options[1]);
738                         continue;
739                 } else if (options[0] == "smallstep") {
740                         int value = stoi(options[1]);
741                         data->scrollbar_options.small_step = value < 0 ? 10 : value;
742                         continue;
743                 } else if (options[0] == "largestep") {
744                         int value = stoi(options[1]);
745                         data->scrollbar_options.large_step = value < 0 ? 100 : value;
746                         continue;
747                 } else if (options[0] == "thumbsize") {
748                         int value = stoi(options[1]);
749                         data->scrollbar_options.thumb_size = value <= 0 ? 1 : value;
750                         continue;
751                 } else if (options[0] == "arrows") {
752                         std::string value = trim(options[1]);
753                         if (value == "hide")
754                                 data->scrollbar_options.arrow_visiblity = GUIScrollBar::HIDE;
755                         else if (value == "show")
756                                 data->scrollbar_options.arrow_visiblity = GUIScrollBar::SHOW;
757                         else // Auto hide/show
758                                 data->scrollbar_options.arrow_visiblity = GUIScrollBar::DEFAULT;
759                         continue;
760                 }
761
762                 warningstream << "Invalid scrollbaroptions option(" << options[0] <<
763                         "): '" << element << "'" << std::endl;
764         }
765 }
766
767 void GUIFormSpecMenu::parseImage(parserData* data, const std::string &element)
768 {
769         std::vector<std::string> parts = split(element,';');
770
771         if ((parts.size() == 3) ||
772                 ((parts.size() > 3) && (m_formspec_version > FORMSPEC_API_VERSION)))
773         {
774                 std::vector<std::string> v_pos = split(parts[0],',');
775                 std::vector<std::string> v_geom = split(parts[1],',');
776                 std::string name = unescape_string(parts[2]);
777
778                 MY_CHECKPOS("image", 0);
779                 MY_CHECKGEOM("image", 1);
780
781                 v2s32 pos;
782                 v2s32 geom;
783
784                 if (data->real_coordinates) {
785                         pos = getRealCoordinateBasePos(v_pos);
786                         geom = getRealCoordinateGeometry(v_geom);
787                 } else {
788                         pos = getElementBasePos(&v_pos);
789                         geom.X = stof(v_geom[0]) * (float)imgsize.X;
790                         geom.Y = stof(v_geom[1]) * (float)imgsize.Y;
791                 }
792
793                 if (!data->explicit_size)
794                         warningstream<<"invalid use of image without a size[] element"<<std::endl;
795
796                 video::ITexture *texture = m_tsrc->getTexture(name);
797                 if (!texture) {
798                         errorstream << "GUIFormSpecMenu::parseImage() Unable to load texture:"
799                                         << std::endl << "\t" << name << std::endl;
800                         return;
801                 }
802
803                 FieldSpec spec(
804                         name,
805                         L"",
806                         L"",
807                         258 + m_fields.size(),
808                         1
809                 );
810                 core::rect<s32> rect(pos, pos + geom);
811                 gui::IGUIImage *e = Environment->addImage(rect, data->current_parent,
812                                 spec.fid, 0, true);
813                 e->setImage(texture);
814                 e->setScaleImage(true);
815                 auto style = getDefaultStyleForElement("image", spec.fname);
816                 e->setNotClipped(style.getBool(StyleSpec::NOCLIP, m_formspec_version < 3));
817                 m_fields.push_back(spec);
818
819                 // images should let events through
820                 e->grab();
821                 m_clickthrough_elements.push_back(e);
822                 return;
823         }
824
825         if (parts.size() == 2) {
826                 std::vector<std::string> v_pos = split(parts[0],',');
827                 std::string name = unescape_string(parts[1]);
828
829                 MY_CHECKPOS("image", 0);
830
831                 v2s32 pos = getElementBasePos(&v_pos);
832
833                 if (!data->explicit_size)
834                         warningstream<<"invalid use of image without a size[] element"<<std::endl;
835
836                 video::ITexture *texture = m_tsrc->getTexture(name);
837                 if (!texture) {
838                         errorstream << "GUIFormSpecMenu::parseImage() Unable to load texture:"
839                                         << std::endl << "\t" << name << std::endl;
840                         return;
841                 }
842
843                 FieldSpec spec(
844                         name,
845                         L"",
846                         L"",
847                         258 + m_fields.size()
848                 );
849                 gui::IGUIImage *e = Environment->addImage(texture, pos, true,
850                                 data->current_parent, spec.fid, 0);
851                 auto style = getDefaultStyleForElement("image", spec.fname);
852                 e->setNotClipped(style.getBool(StyleSpec::NOCLIP, m_formspec_version < 3));
853                 m_fields.push_back(spec);
854
855                 // images should let events through
856                 e->grab();
857                 m_clickthrough_elements.push_back(e);
858                 return;
859         }
860         errorstream<< "Invalid image element(" << parts.size() << "): '" << element << "'"  << std::endl;
861 }
862
863 void GUIFormSpecMenu::parseAnimatedImage(parserData *data, const std::string &element)
864 {
865         std::vector<std::string> parts = split(element, ';');
866
867         if (parts.size() != 6 && parts.size() != 7 &&
868                         !(parts.size() > 7 && m_formspec_version > FORMSPEC_API_VERSION)) {
869                 errorstream << "Invalid animated_image element(" << parts.size()
870                         << "): '" << element << "'" << std::endl;
871                 return;
872         }
873
874         std::vector<std::string> v_pos  = split(parts[0], ',');
875         std::vector<std::string> v_geom = split(parts[1], ',');
876         std::string name = parts[2];
877         std::string texture_name = unescape_string(parts[3]);
878         s32 frame_count = stoi(parts[4]);
879         s32 frame_duration = stoi(parts[5]);
880
881         MY_CHECKPOS("animated_image", 0);
882         MY_CHECKGEOM("animated_image", 1);
883
884         v2s32 pos;
885         v2s32 geom;
886
887         if (data->real_coordinates) {
888                 pos = getRealCoordinateBasePos(v_pos);
889                 geom = getRealCoordinateGeometry(v_geom);
890         } else {
891                 pos = getElementBasePos(&v_pos);
892                 geom.X = stof(v_geom[0]) * (float)imgsize.X;
893                 geom.Y = stof(v_geom[1]) * (float)imgsize.Y;
894         }
895
896         if (!data->explicit_size)
897                 warningstream << "Invalid use of animated_image without a size[] element" << std::endl;
898
899         FieldSpec spec(
900                 name,
901                 L"",
902                 L"",
903                 258 + m_fields.size()
904         );
905         spec.ftype = f_AnimatedImage;
906         spec.send = true;
907
908         core::rect<s32> rect = core::rect<s32>(pos, pos + geom);
909
910         GUIAnimatedImage *e = new GUIAnimatedImage(Environment, this, spec.fid,
911                 rect, texture_name, frame_count, frame_duration, m_tsrc);
912
913         if (parts.size() >= 7)
914                 e->setFrameIndex(stoi(parts[6]) - 1);
915
916         auto style = getDefaultStyleForElement("animated_image", spec.fname, "image");
917         e->setNotClipped(style.getBool(StyleSpec::NOCLIP, false));
918
919         // Animated images should let events through
920         m_clickthrough_elements.push_back(e);
921
922         m_fields.push_back(spec);
923 }
924
925 void GUIFormSpecMenu::parseItemImage(parserData* data, const std::string &element)
926 {
927         std::vector<std::string> parts = split(element,';');
928
929         if ((parts.size() == 3) ||
930                 ((parts.size() > 3) && (m_formspec_version > FORMSPEC_API_VERSION)))
931         {
932                 std::vector<std::string> v_pos = split(parts[0],',');
933                 std::vector<std::string> v_geom = split(parts[1],',');
934                 std::string name = parts[2];
935
936                 MY_CHECKPOS("itemimage",0);
937                 MY_CHECKGEOM("itemimage",1);
938
939                 v2s32 pos;
940                 v2s32 geom;
941
942                 if (data->real_coordinates) {
943                         pos = getRealCoordinateBasePos(v_pos);
944                         geom = getRealCoordinateGeometry(v_geom);
945                 } else {
946                         pos = getElementBasePos(&v_pos);
947                         geom.X = stof(v_geom[0]) * (float)imgsize.X;
948                         geom.Y = stof(v_geom[1]) * (float)imgsize.Y;
949                 }
950
951                 if(!data->explicit_size)
952                         warningstream<<"invalid use of item_image without a size[] element"<<std::endl;
953
954                 FieldSpec spec(
955                         "",
956                         L"",
957                         L"",
958                         258 + m_fields.size(),
959                         2
960                 );
961                 spec.ftype = f_ItemImage;
962
963                 GUIItemImage *e = new GUIItemImage(Environment, data->current_parent, spec.fid,
964                                 core::rect<s32>(pos, pos + geom), name, m_font, m_client);
965                 auto style = getDefaultStyleForElement("item_image", spec.fname);
966                 e->setNotClipped(style.getBool(StyleSpec::NOCLIP, false));
967
968                 // item images should let events through
969                 m_clickthrough_elements.push_back(e);
970
971                 m_fields.push_back(spec);
972                 return;
973         }
974         errorstream<< "Invalid ItemImage element(" << parts.size() << "): '" << element << "'"  << std::endl;
975 }
976
977 void GUIFormSpecMenu::parseButton(parserData* data, const std::string &element,
978                 const std::string &type)
979 {
980         std::vector<std::string> parts = split(element,';');
981
982         if ((parts.size() == 4) ||
983                 ((parts.size() > 4) && (m_formspec_version > FORMSPEC_API_VERSION)))
984         {
985                 std::vector<std::string> v_pos = split(parts[0],',');
986                 std::vector<std::string> v_geom = split(parts[1],',');
987                 std::string name = parts[2];
988                 std::string label = parts[3];
989
990                 MY_CHECKPOS("button",0);
991                 MY_CHECKGEOM("button",1);
992
993                 v2s32 pos;
994                 v2s32 geom;
995                 core::rect<s32> rect;
996
997                 if (data->real_coordinates) {
998                         pos = getRealCoordinateBasePos(v_pos);
999                         geom = getRealCoordinateGeometry(v_geom);
1000                         rect = core::rect<s32>(pos.X, pos.Y, pos.X+geom.X,
1001                                 pos.Y+geom.Y);
1002                 } else {
1003                         pos = getElementBasePos(&v_pos);
1004                         geom.X = (stof(v_geom[0]) * spacing.X) - (spacing.X - imgsize.X);
1005                         pos.Y += (stof(v_geom[1]) * (float)imgsize.Y)/2;
1006
1007                         rect = core::rect<s32>(pos.X, pos.Y - m_btn_height,
1008                                                 pos.X + geom.X, pos.Y + m_btn_height);
1009                 }
1010
1011                 if(!data->explicit_size)
1012                         warningstream<<"invalid use of button without a size[] element"<<std::endl;
1013
1014                 std::wstring wlabel = translate_string(utf8_to_wide(unescape_string(label)));
1015
1016                 FieldSpec spec(
1017                         name,
1018                         wlabel,
1019                         L"",
1020                         258 + m_fields.size()
1021                 );
1022                 spec.ftype = f_Button;
1023                 if(type == "button_exit")
1024                         spec.is_exit = true;
1025
1026                 GUIButton *e = GUIButton::addButton(Environment, rect, m_tsrc,
1027                                 data->current_parent, spec.fid, spec.flabel.c_str());
1028
1029                 auto style = getStyleForElement(type, name, (type != "button") ? "button" : "");
1030                 e->setStyles(style);
1031
1032                 if (spec.fname == data->focused_fieldname) {
1033                         Environment->setFocus(e);
1034                 }
1035
1036                 m_fields.push_back(spec);
1037                 return;
1038         }
1039         errorstream<< "Invalid button element(" << parts.size() << "): '" << element << "'"  << std::endl;
1040 }
1041
1042 void GUIFormSpecMenu::parseBackground(parserData* data, const std::string &element)
1043 {
1044         std::vector<std::string> parts = split(element,';');
1045
1046         if ((parts.size() >= 3 && parts.size() <= 5) ||
1047                         (parts.size() > 5 && m_formspec_version > FORMSPEC_API_VERSION)) {
1048                 std::vector<std::string> v_pos = split(parts[0],',');
1049                 std::vector<std::string> v_geom = split(parts[1],',');
1050                 std::string name = unescape_string(parts[2]);
1051
1052                 MY_CHECKPOS("background",0);
1053                 MY_CHECKGEOM("background",1);
1054
1055                 v2s32 pos;
1056                 v2s32 geom;
1057
1058                 if (data->real_coordinates) {
1059                         pos = getRealCoordinateBasePos(v_pos);
1060                         geom = getRealCoordinateGeometry(v_geom);
1061                 } else {
1062                         pos = getElementBasePos(&v_pos);
1063                         pos.X -= (spacing.X - (float)imgsize.X) / 2;
1064                         pos.Y -= (spacing.Y - (float)imgsize.Y) / 2;
1065
1066                         geom.X = stof(v_geom[0]) * spacing.X;
1067                         geom.Y = stof(v_geom[1]) * spacing.Y;
1068                 }
1069
1070                 bool clip = false;
1071                 if (parts.size() >= 4 && is_yes(parts[3])) {
1072                         if (data->real_coordinates) {
1073                                 pos = getRealCoordinateBasePos(v_pos) * -1;
1074                                 geom = v2s32(0, 0);
1075                         } else {
1076                                 pos.X = stoi(v_pos[0]); //acts as offset
1077                                 pos.Y = stoi(v_pos[1]);
1078                         }
1079                         clip = true;
1080                 }
1081
1082                 core::rect<s32> middle;
1083                 if (parts.size() >= 5) {
1084                         std::vector<std::string> v_middle = split(parts[4], ',');
1085                         if (v_middle.size() == 1) {
1086                                 s32 x = stoi(v_middle[0]);
1087                                 middle.UpperLeftCorner = core::vector2di(x, x);
1088                                 middle.LowerRightCorner = core::vector2di(-x, -x);
1089                         } else if (v_middle.size() == 2) {
1090                                 s32 x = stoi(v_middle[0]);
1091                                 s32 y = stoi(v_middle[1]);
1092                                 middle.UpperLeftCorner = core::vector2di(x, y);
1093                                 middle.LowerRightCorner = core::vector2di(-x, -y);
1094                                 // `-x` is interpreted as `w - x`
1095                         } else if (v_middle.size() == 4) {
1096                                 middle.UpperLeftCorner = core::vector2di(stoi(v_middle[0]), stoi(v_middle[1]));
1097                                 middle.LowerRightCorner = core::vector2di(stoi(v_middle[2]), stoi(v_middle[3]));
1098                         } else {
1099                                 warningstream << "Invalid rectangle given to middle param of background[] element" << std::endl;
1100                         }
1101                 }
1102
1103                 if (!data->explicit_size && !clip)
1104                         warningstream << "invalid use of unclipped background without a size[] element" << std::endl;
1105
1106                 FieldSpec spec(
1107                         name,
1108                         L"",
1109                         L"",
1110                         258 + m_fields.size()
1111                 );
1112
1113                 core::rect<s32> rect;
1114                 if (!clip) {
1115                         // no auto_clip => position like normal image
1116                         rect = core::rect<s32>(pos, pos + geom);
1117                 } else {
1118                         // it will be auto-clipped when drawing
1119                         rect = core::rect<s32>(-pos, pos);
1120                 }
1121
1122                 GUIBackgroundImage *e = new GUIBackgroundImage(Environment, this, spec.fid,
1123                                 rect, name, middle, m_tsrc, clip);
1124
1125                 FATAL_ERROR_IF(!e, "Failed to create background formspec element");
1126
1127                 e->setNotClipped(true);
1128
1129                 e->setVisible(false); // the element is drawn manually before all others
1130
1131                 m_backgrounds.push_back(e);
1132                 m_fields.push_back(spec);
1133                 return;
1134         }
1135         errorstream<< "Invalid background element(" << parts.size() << "): '" << element << "'"  << std::endl;
1136 }
1137
1138 void GUIFormSpecMenu::parseTableOptions(parserData* data, const std::string &element)
1139 {
1140         std::vector<std::string> parts = split(element,';');
1141
1142         data->table_options.clear();
1143         for (const std::string &part : parts) {
1144                 // Parse table option
1145                 std::string opt = unescape_string(part);
1146                 data->table_options.push_back(GUITable::splitOption(opt));
1147         }
1148 }
1149
1150 void GUIFormSpecMenu::parseTableColumns(parserData* data, const std::string &element)
1151 {
1152         std::vector<std::string> parts = split(element,';');
1153
1154         data->table_columns.clear();
1155         for (const std::string &part : parts) {
1156                 std::vector<std::string> col_parts = split(part,',');
1157                 GUITable::TableColumn column;
1158                 // Parse column type
1159                 if (!col_parts.empty())
1160                         column.type = col_parts[0];
1161                 // Parse column options
1162                 for (size_t j = 1; j < col_parts.size(); ++j) {
1163                         std::string opt = unescape_string(col_parts[j]);
1164                         column.options.push_back(GUITable::splitOption(opt));
1165                 }
1166                 data->table_columns.push_back(column);
1167         }
1168 }
1169
1170 void GUIFormSpecMenu::parseTable(parserData* data, const std::string &element)
1171 {
1172         std::vector<std::string> parts = split(element,';');
1173
1174         if (((parts.size() == 4) || (parts.size() == 5)) ||
1175                 ((parts.size() > 5) && (m_formspec_version > FORMSPEC_API_VERSION)))
1176         {
1177                 std::vector<std::string> v_pos = split(parts[0],',');
1178                 std::vector<std::string> v_geom = split(parts[1],',');
1179                 std::string name = parts[2];
1180                 std::vector<std::string> items = split(parts[3],',');
1181                 std::string str_initial_selection;
1182                 std::string str_transparent = "false";
1183
1184                 if (parts.size() >= 5)
1185                         str_initial_selection = parts[4];
1186
1187                 MY_CHECKPOS("table",0);
1188                 MY_CHECKGEOM("table",1);
1189
1190                 v2s32 pos;
1191                 v2s32 geom;
1192
1193                 if (data->real_coordinates) {
1194                         pos = getRealCoordinateBasePos(v_pos);
1195                         geom = getRealCoordinateGeometry(v_geom);
1196                 } else {
1197                         pos = getElementBasePos(&v_pos);
1198                         geom.X = stof(v_geom[0]) * spacing.X;
1199                         geom.Y = stof(v_geom[1]) * spacing.Y;
1200                 }
1201
1202                 core::rect<s32> rect = core::rect<s32>(pos.X, pos.Y, pos.X+geom.X, pos.Y+geom.Y);
1203
1204                 FieldSpec spec(
1205                         name,
1206                         L"",
1207                         L"",
1208                         258 + m_fields.size()
1209                 );
1210
1211                 spec.ftype = f_Table;
1212
1213                 for (std::string &item : items) {
1214                         item = wide_to_utf8(unescape_translate(utf8_to_wide(unescape_string(item))));
1215                 }
1216
1217                 //now really show table
1218                 GUITable *e = new GUITable(Environment, data->current_parent, spec.fid,
1219                                 rect, m_tsrc);
1220
1221                 if (spec.fname == data->focused_fieldname) {
1222                         Environment->setFocus(e);
1223                 }
1224
1225                 e->setTable(data->table_options, data->table_columns, items);
1226
1227                 if (data->table_dyndata.find(name) != data->table_dyndata.end()) {
1228                         e->setDynamicData(data->table_dyndata[name]);
1229                 }
1230
1231                 if (!str_initial_selection.empty() && str_initial_selection != "0")
1232                         e->setSelected(stoi(str_initial_selection));
1233
1234                 auto style = getDefaultStyleForElement("table", name);
1235                 e->setNotClipped(style.getBool(StyleSpec::NOCLIP, false));
1236
1237                 m_tables.emplace_back(spec, e);
1238                 m_fields.push_back(spec);
1239                 return;
1240         }
1241         errorstream<< "Invalid table element(" << parts.size() << "): '" << element << "'"  << std::endl;
1242 }
1243
1244 void GUIFormSpecMenu::parseTextList(parserData* data, const std::string &element)
1245 {
1246         std::vector<std::string> parts = split(element,';');
1247
1248         if (((parts.size() == 4) || (parts.size() == 5) || (parts.size() == 6)) ||
1249                 ((parts.size() > 6) && (m_formspec_version > FORMSPEC_API_VERSION)))
1250         {
1251                 std::vector<std::string> v_pos = split(parts[0],',');
1252                 std::vector<std::string> v_geom = split(parts[1],',');
1253                 std::string name = parts[2];
1254                 std::vector<std::string> items = split(parts[3],',');
1255                 std::string str_initial_selection;
1256                 std::string str_transparent = "false";
1257
1258                 if (parts.size() >= 5)
1259                         str_initial_selection = parts[4];
1260
1261                 if (parts.size() >= 6)
1262                         str_transparent = parts[5];
1263
1264                 MY_CHECKPOS("textlist",0);
1265                 MY_CHECKGEOM("textlist",1);
1266
1267                 v2s32 pos;
1268                 v2s32 geom;
1269
1270                 if (data->real_coordinates) {
1271                         pos = getRealCoordinateBasePos(v_pos);
1272                         geom = getRealCoordinateGeometry(v_geom);
1273                 } else {
1274                         pos = getElementBasePos(&v_pos);
1275                         geom.X = stof(v_geom[0]) * spacing.X;
1276                         geom.Y = stof(v_geom[1]) * spacing.Y;
1277                 }
1278
1279                 core::rect<s32> rect = core::rect<s32>(pos.X, pos.Y, pos.X+geom.X, pos.Y+geom.Y);
1280
1281                 FieldSpec spec(
1282                         name,
1283                         L"",
1284                         L"",
1285                         258 + m_fields.size()
1286                 );
1287
1288                 spec.ftype = f_Table;
1289
1290                 for (std::string &item : items) {
1291                         item = wide_to_utf8(unescape_translate(utf8_to_wide(unescape_string(item))));
1292                 }
1293
1294                 //now really show list
1295                 GUITable *e = new GUITable(Environment, data->current_parent, spec.fid,
1296                                 rect, m_tsrc);
1297
1298                 if (spec.fname == data->focused_fieldname) {
1299                         Environment->setFocus(e);
1300                 }
1301
1302                 e->setTextList(items, is_yes(str_transparent));
1303
1304                 if (data->table_dyndata.find(name) != data->table_dyndata.end()) {
1305                         e->setDynamicData(data->table_dyndata[name]);
1306                 }
1307
1308                 if (!str_initial_selection.empty() && str_initial_selection != "0")
1309                         e->setSelected(stoi(str_initial_selection));
1310
1311                 auto style = getDefaultStyleForElement("textlist", name);
1312                 e->setNotClipped(style.getBool(StyleSpec::NOCLIP, false));
1313
1314                 m_tables.emplace_back(spec, e);
1315                 m_fields.push_back(spec);
1316                 return;
1317         }
1318         errorstream<< "Invalid textlist element(" << parts.size() << "): '" << element << "'"  << std::endl;
1319 }
1320
1321
1322 void GUIFormSpecMenu::parseDropDown(parserData* data, const std::string &element)
1323 {
1324         std::vector<std::string> parts = split(element,';');
1325
1326         if ((parts.size() == 5) ||
1327                 ((parts.size() > 5) && (m_formspec_version > FORMSPEC_API_VERSION)))
1328         {
1329                 std::vector<std::string> v_pos = split(parts[0],',');
1330                 std::string name = parts[2];
1331                 std::vector<std::string> items = split(parts[3],',');
1332                 std::string str_initial_selection;
1333                 str_initial_selection = parts[4];
1334
1335                 MY_CHECKPOS("dropdown",0);
1336
1337                 v2s32 pos;
1338                 v2s32 geom;
1339                 core::rect<s32> rect;
1340
1341                 if (data->real_coordinates) {
1342                         std::vector<std::string> v_geom = split(parts[1],',');
1343
1344                         if (v_geom.size() == 1)
1345                                 v_geom.emplace_back("1");
1346
1347                         MY_CHECKGEOM("dropdown",1);
1348
1349                         pos = getRealCoordinateBasePos(v_pos);
1350                         geom = getRealCoordinateGeometry(v_geom);
1351                         rect = core::rect<s32>(pos.X, pos.Y, pos.X+geom.X, pos.Y+geom.Y);
1352                 } else {
1353                         pos = getElementBasePos(&v_pos);
1354
1355                         s32 width = stof(parts[1]) * spacing.Y;
1356
1357                         rect = core::rect<s32>(pos.X, pos.Y,
1358                                         pos.X + width, pos.Y + (m_btn_height * 2));
1359                 }
1360
1361                 FieldSpec spec(
1362                         name,
1363                         L"",
1364                         L"",
1365                         258 + m_fields.size()
1366                 );
1367
1368                 spec.ftype = f_DropDown;
1369                 spec.send = true;
1370
1371                 //now really show list
1372                 gui::IGUIComboBox *e = Environment->addComboBox(rect, data->current_parent,
1373                                 spec.fid);
1374
1375                 if (spec.fname == data->focused_fieldname) {
1376                         Environment->setFocus(e);
1377                 }
1378
1379                 for (const std::string &item : items) {
1380                         e->addItem(unescape_translate(unescape_string(
1381                                 utf8_to_wide(item))).c_str());
1382                 }
1383
1384                 if (!str_initial_selection.empty())
1385                         e->setSelected(stoi(str_initial_selection)-1);
1386
1387                 auto style = getDefaultStyleForElement("dropdown", name);
1388                 e->setNotClipped(style.getBool(StyleSpec::NOCLIP, false));
1389
1390                 m_fields.push_back(spec);
1391
1392                 m_dropdowns.emplace_back(spec, std::vector<std::string>());
1393                 std::vector<std::string> &values = m_dropdowns.back().second;
1394                 for (const std::string &item : items) {
1395                         values.push_back(unescape_string(item));
1396                 }
1397
1398                 return;
1399         }
1400         errorstream << "Invalid dropdown element(" << parts.size() << "): '"
1401                                 << element << "'"  << std::endl;
1402 }
1403
1404 void GUIFormSpecMenu::parseFieldCloseOnEnter(parserData *data, const std::string &element)
1405 {
1406         std::vector<std::string> parts = split(element,';');
1407         if (parts.size() == 2 ||
1408                         (parts.size() > 2 && m_formspec_version > FORMSPEC_API_VERSION)) {
1409                 field_close_on_enter[parts[0]] = is_yes(parts[1]);
1410         }
1411 }
1412
1413 void GUIFormSpecMenu::parsePwdField(parserData* data, const std::string &element)
1414 {
1415         std::vector<std::string> parts = split(element,';');
1416
1417         if ((parts.size() == 4) ||
1418                 ((parts.size() > 4) && (m_formspec_version > FORMSPEC_API_VERSION)))
1419         {
1420                 std::vector<std::string> v_pos = split(parts[0],',');
1421                 std::vector<std::string> v_geom = split(parts[1],',');
1422                 std::string name = parts[2];
1423                 std::string label = parts[3];
1424
1425                 MY_CHECKPOS("pwdfield",0);
1426                 MY_CHECKGEOM("pwdfield",1);
1427
1428                 v2s32 pos;
1429                 v2s32 geom;
1430
1431                 if (data->real_coordinates) {
1432                         pos = getRealCoordinateBasePos(v_pos);
1433                         geom = getRealCoordinateGeometry(v_geom);
1434                 } else {
1435                         pos = getElementBasePos(&v_pos);
1436                         pos -= padding;
1437
1438                         geom.X = (stof(v_geom[0]) * spacing.X) - (spacing.X - imgsize.X);
1439
1440                         pos.Y += (stof(v_geom[1]) * (float)imgsize.Y)/2;
1441                         pos.Y -= m_btn_height;
1442                         geom.Y = m_btn_height*2;
1443                 }
1444
1445                 core::rect<s32> rect = core::rect<s32>(pos.X, pos.Y, pos.X+geom.X, pos.Y+geom.Y);
1446
1447                 std::wstring wlabel = translate_string(utf8_to_wide(unescape_string(label)));
1448
1449                 FieldSpec spec(
1450                         name,
1451                         wlabel,
1452                         L"",
1453                         258 + m_fields.size(),
1454                         0,
1455                         ECI_IBEAM
1456                         );
1457
1458                 spec.send = true;
1459                 gui::IGUIEditBox *e = Environment->addEditBox(0, rect, true,
1460                                 data->current_parent, spec.fid);
1461
1462                 if (spec.fname == data->focused_fieldname) {
1463                         Environment->setFocus(e);
1464                 }
1465
1466                 if (label.length() >= 1) {
1467                         int font_height = g_fontengine->getTextHeight();
1468                         rect.UpperLeftCorner.Y -= font_height;
1469                         rect.LowerRightCorner.Y = rect.UpperLeftCorner.Y + font_height;
1470                         gui::StaticText::add(Environment, spec.flabel.c_str(), rect, false, true,
1471                                 data->current_parent, 0);
1472                 }
1473
1474                 e->setPasswordBox(true,L'*');
1475
1476                 auto style = getDefaultStyleForElement("pwdfield", name, "field");
1477                 e->setNotClipped(style.getBool(StyleSpec::NOCLIP, false));
1478                 e->setDrawBorder(style.getBool(StyleSpec::BORDER, true));
1479                 e->setOverrideColor(style.getColor(StyleSpec::TEXTCOLOR, video::SColor(0xFFFFFFFF)));
1480
1481                 irr::SEvent evt;
1482                 evt.EventType            = EET_KEY_INPUT_EVENT;
1483                 evt.KeyInput.Key         = KEY_END;
1484                 evt.KeyInput.Char        = 0;
1485                 evt.KeyInput.Control     = false;
1486                 evt.KeyInput.Shift       = false;
1487                 evt.KeyInput.PressedDown = true;
1488                 e->OnEvent(evt);
1489
1490                 // Note: Before 5.2.0 "parts.size() >= 5" resulted in a
1491                 // warning referring to field_close_on_enter[]!
1492
1493                 m_fields.push_back(spec);
1494                 return;
1495         }
1496         errorstream<< "Invalid pwdfield element(" << parts.size() << "): '" << element << "'"  << std::endl;
1497 }
1498
1499 void GUIFormSpecMenu::createTextField(parserData *data, FieldSpec &spec,
1500         core::rect<s32> &rect, bool is_multiline)
1501 {
1502         bool is_editable = !spec.fname.empty();
1503         if (!is_editable && !is_multiline) {
1504                 // spec field id to 0, this stops submit searching for a value that isn't there
1505                 gui::StaticText::add(Environment, spec.flabel.c_str(), rect, false, true,
1506                                 data->current_parent, 0);
1507                 return;
1508         }
1509
1510         if (is_editable) {
1511                 spec.send = true;
1512         } else if (is_multiline &&
1513                         spec.fdefault.empty() && !spec.flabel.empty()) {
1514                 // Multiline textareas: swap default and label for backwards compat
1515                 spec.flabel.swap(spec.fdefault);
1516         }
1517
1518         gui::IGUIEditBox *e = nullptr;
1519         static constexpr bool use_intl_edit_box = USE_FREETYPE &&
1520                 IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR < 9;
1521
1522         if (use_intl_edit_box && g_settings->getBool("freetype")) {
1523                 e = new gui::intlGUIEditBox(spec.fdefault.c_str(), true, Environment,
1524                                 data->current_parent, spec.fid, rect, is_editable, is_multiline);
1525         } else {
1526                 if (is_multiline) {
1527                         e = new GUIEditBoxWithScrollBar(spec.fdefault.c_str(), true, Environment,
1528                                         data->current_parent, spec.fid, rect, is_editable, true);
1529                 } else if (is_editable) {
1530                         e = Environment->addEditBox(spec.fdefault.c_str(), rect, true,
1531                                         data->current_parent, spec.fid);
1532                         e->grab();
1533                 }
1534         }
1535
1536         auto style = getDefaultStyleForElement(is_multiline ? "textarea" : "field", spec.fname);
1537
1538         if (e) {
1539                 if (is_editable && spec.fname == data->focused_fieldname)
1540                         Environment->setFocus(e);
1541
1542                 if (is_multiline) {
1543                         e->setMultiLine(true);
1544                         e->setWordWrap(true);
1545                         e->setTextAlignment(gui::EGUIA_UPPERLEFT, gui::EGUIA_UPPERLEFT);
1546                 } else {
1547                         irr::SEvent evt;
1548                         evt.EventType            = EET_KEY_INPUT_EVENT;
1549                         evt.KeyInput.Key         = KEY_END;
1550                         evt.KeyInput.Char        = 0;
1551                         evt.KeyInput.Control     = 0;
1552                         evt.KeyInput.Shift       = 0;
1553                         evt.KeyInput.PressedDown = true;
1554                         e->OnEvent(evt);
1555                 }
1556
1557                 e->setNotClipped(style.getBool(StyleSpec::NOCLIP, false));
1558                 e->setDrawBorder(style.getBool(StyleSpec::BORDER, true));
1559                 e->setOverrideColor(style.getColor(StyleSpec::TEXTCOLOR, video::SColor(0xFFFFFFFF)));
1560                 if (style.get(StyleSpec::BGCOLOR, "") == "transparent") {
1561                         e->setDrawBackground(false);
1562                 }
1563
1564                 e->drop();
1565         }
1566
1567         if (!spec.flabel.empty()) {
1568                 int font_height = g_fontengine->getTextHeight();
1569                 rect.UpperLeftCorner.Y -= font_height;
1570                 rect.LowerRightCorner.Y = rect.UpperLeftCorner.Y + font_height;
1571                 IGUIElement *t = gui::StaticText::add(Environment, spec.flabel.c_str(),
1572                                 rect, false, true, data->current_parent, 0);
1573
1574                 if (t)
1575                         t->setNotClipped(style.getBool(StyleSpec::NOCLIP, false));
1576         }
1577 }
1578
1579 void GUIFormSpecMenu::parseSimpleField(parserData *data,
1580         std::vector<std::string> &parts)
1581 {
1582         std::string name = parts[0];
1583         std::string label = parts[1];
1584         std::string default_val = parts[2];
1585
1586         core::rect<s32> rect;
1587
1588         if (data->explicit_size)
1589                 warningstream << "invalid use of unpositioned \"field\" in inventory" << std::endl;
1590
1591         v2s32 pos = getElementBasePos(nullptr);
1592         pos.Y = (data->simple_field_count + 2) * 60;
1593         v2s32 size = DesiredRect.getSize();
1594
1595         rect = core::rect<s32>(
1596                         size.X / 2 - 150,       pos.Y,
1597                         size.X / 2 - 150 + 300, pos.Y + m_btn_height * 2
1598         );
1599
1600
1601         if (m_form_src)
1602                 default_val = m_form_src->resolveText(default_val);
1603
1604
1605         std::wstring wlabel = translate_string(utf8_to_wide(unescape_string(label)));
1606
1607         FieldSpec spec(
1608                 name,
1609                 wlabel,
1610                 utf8_to_wide(unescape_string(default_val)),
1611                 258 + m_fields.size(),
1612                 0,
1613                 ECI_IBEAM
1614         );
1615
1616         createTextField(data, spec, rect, false);
1617
1618         m_fields.push_back(spec);
1619
1620         data->simple_field_count++;
1621 }
1622
1623 void GUIFormSpecMenu::parseTextArea(parserData* data, std::vector<std::string>& parts,
1624                 const std::string &type)
1625 {
1626         std::vector<std::string> v_pos = split(parts[0],',');
1627         std::vector<std::string> v_geom = split(parts[1],',');
1628         std::string name = parts[2];
1629         std::string label = parts[3];
1630         std::string default_val = parts[4];
1631
1632         MY_CHECKPOS(type,0);
1633         MY_CHECKGEOM(type,1);
1634
1635         v2s32 pos;
1636         v2s32 geom;
1637
1638         if (data->real_coordinates) {
1639                 pos = getRealCoordinateBasePos(v_pos);
1640                 geom = getRealCoordinateGeometry(v_geom);
1641         } else {
1642                 pos = getElementBasePos(&v_pos);
1643                 pos -= padding;
1644
1645                 geom.X = (stof(v_geom[0]) * spacing.X) - (spacing.X - imgsize.X);
1646
1647                 if (type == "textarea")
1648                 {
1649                         geom.Y = (stof(v_geom[1]) * (float)imgsize.Y) - (spacing.Y-imgsize.Y);
1650                         pos.Y += m_btn_height;
1651                 }
1652                 else
1653                 {
1654                         pos.Y += (stof(v_geom[1]) * (float)imgsize.Y)/2;
1655                         pos.Y -= m_btn_height;
1656                         geom.Y = m_btn_height*2;
1657                 }
1658         }
1659
1660         core::rect<s32> rect = core::rect<s32>(pos.X, pos.Y, pos.X+geom.X, pos.Y+geom.Y);
1661
1662         if(!data->explicit_size)
1663                 warningstream<<"invalid use of positioned "<<type<<" without a size[] element"<<std::endl;
1664
1665         if(m_form_src)
1666                 default_val = m_form_src->resolveText(default_val);
1667
1668
1669         std::wstring wlabel = translate_string(utf8_to_wide(unescape_string(label)));
1670
1671         FieldSpec spec(
1672                 name,
1673                 wlabel,
1674                 utf8_to_wide(unescape_string(default_val)),
1675                 258 + m_fields.size(),
1676                 0,
1677                 ECI_IBEAM
1678         );
1679
1680         createTextField(data, spec, rect, type == "textarea");
1681
1682         // Note: Before 5.2.0 "parts.size() >= 6" resulted in a
1683         // warning referring to field_close_on_enter[]!
1684
1685         m_fields.push_back(spec);
1686 }
1687
1688 void GUIFormSpecMenu::parseField(parserData* data, const std::string &element,
1689                 const std::string &type)
1690 {
1691         std::vector<std::string> parts = split(element,';');
1692
1693         if (parts.size() == 3 || parts.size() == 4) {
1694                 parseSimpleField(data,parts);
1695                 return;
1696         }
1697
1698         if ((parts.size() == 5) ||
1699                 ((parts.size() > 5) && (m_formspec_version > FORMSPEC_API_VERSION)))
1700         {
1701                 parseTextArea(data,parts,type);
1702                 return;
1703         }
1704         errorstream<< "Invalid field element(" << parts.size() << "): '" << element << "'"  << std::endl;
1705 }
1706
1707 void GUIFormSpecMenu::parseHyperText(parserData *data, const std::string &element)
1708 {
1709         std::vector<std::string> parts = split(element, ';');
1710
1711         if (parts.size() != 4 && m_formspec_version < FORMSPEC_API_VERSION) {
1712                 errorstream << "Invalid text element(" << parts.size() << "): '" << element << "'"  << std::endl;
1713                 return;
1714         }
1715
1716         std::vector<std::string> v_pos = split(parts[0], ',');
1717         std::vector<std::string> v_geom = split(parts[1], ',');
1718         std::string name = parts[2];
1719         std::string text = parts[3];
1720
1721         MY_CHECKPOS("hypertext", 0);
1722         MY_CHECKGEOM("hypertext", 1);
1723
1724         v2s32 pos;
1725         v2s32 geom;
1726
1727         if (data->real_coordinates) {
1728                 pos = getRealCoordinateBasePos(v_pos);
1729                 geom = getRealCoordinateGeometry(v_geom);
1730         } else {
1731                 pos = getElementBasePos(&v_pos);
1732                 pos -= padding;
1733
1734                 geom.X = (stof(v_geom[0]) * spacing.X) - (spacing.X - imgsize.X);
1735                 geom.Y = (stof(v_geom[1]) * (float)imgsize.Y) - (spacing.Y - imgsize.Y);
1736                 pos.Y += m_btn_height;
1737         }
1738
1739         core::rect<s32> rect = core::rect<s32>(pos.X, pos.Y, pos.X + geom.X, pos.Y + geom.Y);
1740
1741         if(m_form_src)
1742                 text = m_form_src->resolveText(text);
1743
1744         FieldSpec spec(
1745                 name,
1746                 utf8_to_wide(unescape_string(text)),
1747                 L"",
1748                 258 + m_fields.size()
1749         );
1750
1751         spec.ftype = f_HyperText;
1752         GUIHyperText *e = new GUIHyperText(spec.flabel.c_str(), Environment,
1753                         data->current_parent, spec.fid, rect, m_client, m_tsrc);
1754         e->drop();
1755
1756         m_fields.push_back(spec);
1757 }
1758
1759 void GUIFormSpecMenu::parseLabel(parserData* data, const std::string &element)
1760 {
1761         std::vector<std::string> parts = split(element,';');
1762
1763         if ((parts.size() == 2) ||
1764                 ((parts.size() > 2) && (m_formspec_version > FORMSPEC_API_VERSION)))
1765         {
1766                 std::vector<std::string> v_pos = split(parts[0],',');
1767                 std::string text = parts[1];
1768
1769                 MY_CHECKPOS("label",0);
1770
1771                 if(!data->explicit_size)
1772                         warningstream<<"invalid use of label without a size[] element"<<std::endl;
1773
1774                 std::vector<std::string> lines = split(text, '\n');
1775
1776                 for (unsigned int i = 0; i != lines.size(); i++) {
1777                         std::wstring wlabel_colors = translate_string(
1778                                 utf8_to_wide(unescape_string(lines[i])));
1779                         // Without color escapes to get the font dimensions
1780                         std::wstring wlabel_plain = unescape_enriched(wlabel_colors);
1781
1782                         core::rect<s32> rect;
1783
1784                         if (data->real_coordinates) {
1785                                 // Lines are spaced at the distance of 1/2 imgsize.
1786                                 // This alows lines that line up with the new elements
1787                                 // easily without sacrificing good line distance.  If
1788                                 // it was one whole imgsize, it would have too much
1789                                 // spacing.
1790                                 v2s32 pos = getRealCoordinateBasePos(v_pos);
1791
1792                                 // Labels are positioned by their center, not their top.
1793                                 pos.Y += (((float) imgsize.Y) / -2) + (((float) imgsize.Y) * i / 2);
1794
1795                                 rect = core::rect<s32>(
1796                                         pos.X, pos.Y,
1797                                         pos.X + m_font->getDimension(wlabel_plain.c_str()).Width,
1798                                         pos.Y + imgsize.Y);
1799
1800                         } else {
1801                                 // Lines are spaced at the nominal distance of
1802                                 // 2/5 inventory slot, even if the font doesn't
1803                                 // quite match that.  This provides consistent
1804                                 // form layout, at the expense of sometimes
1805                                 // having sub-optimal spacing for the font.
1806                                 // We multiply by 2 and then divide by 5, rather
1807                                 // than multiply by 0.4, to get exact results
1808                                 // in the integer cases: 0.4 is not exactly
1809                                 // representable in binary floating point.
1810
1811                                 v2s32 pos = getElementBasePos(nullptr);
1812                                 pos.X += stof(v_pos[0]) * spacing.X;
1813                                 pos.Y += (stof(v_pos[1]) + 7.0f / 30.0f) * spacing.Y;
1814
1815                                 pos.Y += ((float) i) * spacing.Y * 2.0 / 5.0;
1816
1817                                 rect = core::rect<s32>(
1818                                         pos.X, pos.Y - m_btn_height,
1819                                         pos.X + m_font->getDimension(wlabel_plain.c_str()).Width,
1820                                         pos.Y + m_btn_height);
1821                         }
1822
1823                         FieldSpec spec(
1824                                 "",
1825                                 wlabel_colors,
1826                                 L"",
1827                                 258 + m_fields.size(),
1828                                 4
1829                         );
1830                         gui::IGUIStaticText *e = gui::StaticText::add(Environment,
1831                                         spec.flabel.c_str(), rect, false, false, data->current_parent,
1832                                         spec.fid);
1833                         e->setTextAlignment(gui::EGUIA_UPPERLEFT, gui::EGUIA_CENTER);
1834
1835                         auto style = getDefaultStyleForElement("label", spec.fname);
1836                         e->setNotClipped(style.getBool(StyleSpec::NOCLIP, false));
1837                         e->setOverrideColor(style.getColor(StyleSpec::TEXTCOLOR, video::SColor(0xFFFFFFFF)));
1838
1839                         m_fields.push_back(spec);
1840
1841                         // labels should let events through
1842                         e->grab();
1843                         m_clickthrough_elements.push_back(e);
1844                 }
1845
1846                 return;
1847         }
1848         errorstream << "Invalid label element(" << parts.size() << "): '" << element
1849                 << "'"  << std::endl;
1850 }
1851
1852 void GUIFormSpecMenu::parseVertLabel(parserData* data, const std::string &element)
1853 {
1854         std::vector<std::string> parts = split(element,';');
1855
1856         if ((parts.size() == 2) ||
1857                 ((parts.size() > 2) && (m_formspec_version > FORMSPEC_API_VERSION)))
1858         {
1859                 std::vector<std::string> v_pos = split(parts[0],',');
1860                 std::wstring text = unescape_translate(
1861                         unescape_string(utf8_to_wide(parts[1])));
1862
1863                 MY_CHECKPOS("vertlabel",1);
1864
1865                 v2s32 pos;
1866                 core::rect<s32> rect;
1867
1868                 if (data->real_coordinates) {
1869                         pos = getRealCoordinateBasePos(v_pos);
1870
1871                         // Vertlabels are positioned by center, not left.
1872                         pos.X -= imgsize.X / 2;
1873
1874                         // We use text.length + 1 because without it, the rect
1875                         // isn't quite tall enough and cuts off the text.
1876                         rect = core::rect<s32>(pos.X, pos.Y,
1877                                 pos.X + imgsize.X,
1878                                 pos.Y + font_line_height(m_font) *
1879                                 (text.length() + 1));
1880
1881                 } else {
1882                         pos = getElementBasePos(&v_pos);
1883
1884                         // As above, the length must be one longer. The width of
1885                         // the rect (15 pixels) seems rather arbitrary, but
1886                         // changing it might break something.
1887                         rect = core::rect<s32>(
1888                                 pos.X, pos.Y+((imgsize.Y/2) - m_btn_height),
1889                                 pos.X+15, pos.Y +
1890                                         font_line_height(m_font) *
1891                                         (text.length() + 1) +
1892                                         ((imgsize.Y/2) - m_btn_height));
1893                 }
1894
1895                 if(!data->explicit_size)
1896                         warningstream<<"invalid use of label without a size[] element"<<std::endl;
1897
1898                 std::wstring label;
1899
1900                 for (wchar_t i : text) {
1901                         label += i;
1902                         label += L"\n";
1903                 }
1904
1905                 FieldSpec spec(
1906                         "",
1907                         label,
1908                         L"",
1909                         258 + m_fields.size()
1910                 );
1911                 gui::IGUIStaticText *e = gui::StaticText::add(Environment, spec.flabel.c_str(),
1912                                 rect, false, false, data->current_parent, spec.fid);
1913                 e->setTextAlignment(gui::EGUIA_CENTER, gui::EGUIA_CENTER);
1914
1915                 auto style = getDefaultStyleForElement("vertlabel", spec.fname, "label");
1916                 e->setNotClipped(style.getBool(StyleSpec::NOCLIP, false));
1917                 e->setOverrideColor(style.getColor(StyleSpec::TEXTCOLOR, video::SColor(0xFFFFFFFF)));
1918
1919                 m_fields.push_back(spec);
1920
1921                 // vertlabels should let events through
1922                 e->grab();
1923                 m_clickthrough_elements.push_back(e);
1924                 return;
1925         }
1926         errorstream<< "Invalid vertlabel element(" << parts.size() << "): '" << element << "'"  << std::endl;
1927 }
1928
1929 void GUIFormSpecMenu::parseImageButton(parserData* data, const std::string &element,
1930                 const std::string &type)
1931 {
1932         std::vector<std::string> parts = split(element,';');
1933
1934         if ((((parts.size() >= 5) && (parts.size() <= 8)) && (parts.size() != 6)) ||
1935                 ((parts.size() > 8) && (m_formspec_version > FORMSPEC_API_VERSION)))
1936         {
1937                 std::vector<std::string> v_pos = split(parts[0],',');
1938                 std::vector<std::string> v_geom = split(parts[1],',');
1939                 std::string image_name = parts[2];
1940                 std::string name = parts[3];
1941                 std::string label = parts[4];
1942
1943                 MY_CHECKPOS("imagebutton",0);
1944                 MY_CHECKGEOM("imagebutton",1);
1945
1946                 std::string pressed_image_name;
1947
1948                 if (parts.size() >= 8) {
1949                         pressed_image_name = parts[7];
1950                 }
1951
1952                 v2s32 pos;
1953                 v2s32 geom;
1954
1955                 if (data->real_coordinates) {
1956                         pos = getRealCoordinateBasePos(v_pos);
1957                         geom = getRealCoordinateGeometry(v_geom);
1958                 } else {
1959                         pos = getElementBasePos(&v_pos);
1960                         geom.X = (stof(v_geom[0]) * spacing.X) - (spacing.X - imgsize.X);
1961                         geom.Y = (stof(v_geom[1]) * spacing.Y) - (spacing.Y - imgsize.Y);
1962                 }
1963
1964                 core::rect<s32> rect = core::rect<s32>(pos.X, pos.Y, pos.X+geom.X,
1965                         pos.Y+geom.Y);
1966
1967                 if (!data->explicit_size)
1968                         warningstream<<"invalid use of image_button without a size[] element"<<std::endl;
1969
1970                 image_name = unescape_string(image_name);
1971                 pressed_image_name = unescape_string(pressed_image_name);
1972
1973                 std::wstring wlabel = utf8_to_wide(unescape_string(label));
1974
1975                 FieldSpec spec(
1976                         name,
1977                         wlabel,
1978                         utf8_to_wide(image_name),
1979                         258 + m_fields.size()
1980                 );
1981                 spec.ftype = f_Button;
1982                 if (type == "image_button_exit")
1983                         spec.is_exit = true;
1984
1985                 GUIButtonImage *e = GUIButtonImage::addButton(Environment, rect, m_tsrc,
1986                                 data->current_parent, spec.fid, spec.flabel.c_str());
1987
1988                 if (spec.fname == data->focused_fieldname) {
1989                         Environment->setFocus(e);
1990                 }
1991
1992                 auto style = getStyleForElement("image_button", spec.fname);
1993
1994                 // Override style properties with values specified directly in the element
1995                 if (!image_name.empty())
1996                         style[StyleSpec::STATE_DEFAULT].set(StyleSpec::FGIMG, image_name);
1997
1998                 if (!pressed_image_name.empty())
1999                         style[StyleSpec::STATE_PRESSED].set(StyleSpec::FGIMG, pressed_image_name);
2000
2001                 if (parts.size() >= 7) {
2002                         style[StyleSpec::STATE_DEFAULT].set(StyleSpec::NOCLIP, parts[5]);
2003                         style[StyleSpec::STATE_DEFAULT].set(StyleSpec::BORDER, parts[6]);
2004                 }
2005
2006                 e->setStyles(style);
2007                 e->setScaleImage(true);
2008
2009                 m_fields.push_back(spec);
2010                 return;
2011         }
2012
2013         errorstream<< "Invalid imagebutton element(" << parts.size() << "): '" << element << "'"  << std::endl;
2014 }
2015
2016 void GUIFormSpecMenu::parseTabHeader(parserData* data, const std::string &element)
2017 {
2018         std::vector<std::string> parts = split(element, ';');
2019
2020         if (((parts.size() == 4) || (parts.size() == 6)) || (parts.size() == 7 &&
2021                 data->real_coordinates) || ((parts.size() > 6) &&
2022                 (m_formspec_version > FORMSPEC_API_VERSION)))
2023         {
2024                 std::vector<std::string> v_pos = split(parts[0],',');
2025
2026                 // If we're using real coordinates, add an extra field for height.
2027                 // Width is not here because tabs are the width of the text, and
2028                 // there's no reason to change that.
2029                 unsigned int i = 0;
2030                 std::vector<std::string> v_geom = {"1", "1"}; // Dummy width and height
2031                 bool auto_width = true;
2032                 if (parts.size() == 7) {
2033                         i++;
2034
2035                         v_geom = split(parts[1], ',');
2036                         if (v_geom.size() == 1)
2037                                 v_geom.insert(v_geom.begin(), "1"); // Dummy value
2038                         else
2039                                 auto_width = false;
2040                 }
2041
2042                 std::string name = parts[i+1];
2043                 std::vector<std::string> buttons = split(parts[i+2], ',');
2044                 std::string str_index = parts[i+3];
2045                 bool show_background = true;
2046                 bool show_border = true;
2047                 int tab_index = stoi(str_index) - 1;
2048
2049                 MY_CHECKPOS("tabheader", 0);
2050
2051                 if (parts.size() == 6 + i) {
2052                         if (parts[4+i] == "true")
2053                                 show_background = false;
2054                         if (parts[5+i] == "false")
2055                                 show_border = false;
2056                 }
2057
2058                 FieldSpec spec(
2059                         name,
2060                         L"",
2061                         L"",
2062                         258 + m_fields.size()
2063                 );
2064
2065                 spec.ftype = f_TabHeader;
2066
2067                 v2s32 pos;
2068                 v2s32 geom;
2069
2070                 if (data->real_coordinates) {
2071                         pos = getRealCoordinateBasePos(v_pos);
2072
2073                         geom = getRealCoordinateGeometry(v_geom);
2074                         // Set default height
2075                         if (parts.size() <= 6)
2076                                 geom.Y = m_btn_height * 2;
2077                         pos.Y -= geom.Y; // TabHeader base pos is the bottom, not the top.
2078                         if (auto_width)
2079                                 geom.X = DesiredRect.getWidth(); // Set automatic width
2080
2081                         MY_CHECKGEOM("tabheader", 1);
2082                 } else {
2083                         v2f32 pos_f = pos_offset * spacing;
2084                         pos_f.X += stof(v_pos[0]) * spacing.X;
2085                         pos_f.Y += stof(v_pos[1]) * spacing.Y - m_btn_height * 2;
2086                         pos = v2s32(pos_f.X, pos_f.Y);
2087
2088                         geom.Y = m_btn_height * 2;
2089                         geom.X = DesiredRect.getWidth();
2090                 }
2091
2092                 core::rect<s32> rect = core::rect<s32>(pos.X, pos.Y, pos.X+geom.X,
2093                                 pos.Y+geom.Y);
2094
2095                 gui::IGUITabControl *e = Environment->addTabControl(rect,
2096                                 data->current_parent, show_background, show_border, spec.fid);
2097                 e->setAlignment(irr::gui::EGUIA_UPPERLEFT, irr::gui::EGUIA_UPPERLEFT,
2098                                 irr::gui::EGUIA_UPPERLEFT, irr::gui::EGUIA_LOWERRIGHT);
2099                 e->setTabHeight(geom.Y);
2100
2101                 if (spec.fname == data->focused_fieldname) {
2102                         Environment->setFocus(e);
2103                 }
2104
2105                 auto style = getDefaultStyleForElement("tabheader", name);
2106                 e->setNotClipped(style.getBool(StyleSpec::NOCLIP, true));
2107
2108                 for (const std::string &button : buttons) {
2109                         auto tab = e->addTab(unescape_translate(unescape_string(
2110                                 utf8_to_wide(button))).c_str(), -1);
2111                         if (style.isNotDefault(StyleSpec::BGCOLOR))
2112                                 tab->setBackgroundColor(style.getColor(StyleSpec::BGCOLOR));
2113
2114                         tab->setTextColor(style.getColor(StyleSpec::TEXTCOLOR, video::SColor(0xFFFFFFFF)));
2115                 }
2116
2117                 if ((tab_index >= 0) &&
2118                                 (buttons.size() < INT_MAX) &&
2119                                 (tab_index < (int) buttons.size()))
2120                         e->setActiveTab(tab_index);
2121
2122                 m_fields.push_back(spec);
2123                 return;
2124         }
2125         errorstream << "Invalid TabHeader element(" << parts.size() << "): '"
2126                         << element << "'"  << std::endl;
2127 }
2128
2129 void GUIFormSpecMenu::parseItemImageButton(parserData* data, const std::string &element)
2130 {
2131         if (m_client == 0) {
2132                 warningstream << "invalid use of item_image_button with m_client==0"
2133                         << std::endl;
2134                 return;
2135         }
2136
2137         std::vector<std::string> parts = split(element,';');
2138
2139         if ((parts.size() == 5) ||
2140                 ((parts.size() > 5) && (m_formspec_version > FORMSPEC_API_VERSION)))
2141         {
2142                 std::vector<std::string> v_pos = split(parts[0],',');
2143                 std::vector<std::string> v_geom = split(parts[1],',');
2144                 std::string item_name = parts[2];
2145                 std::string name = parts[3];
2146                 std::string label = parts[4];
2147
2148                 label = unescape_string(label);
2149                 item_name = unescape_string(item_name);
2150
2151                 MY_CHECKPOS("itemimagebutton",0);
2152                 MY_CHECKGEOM("itemimagebutton",1);
2153
2154                 v2s32 pos;
2155                 v2s32 geom;
2156
2157                 if (data->real_coordinates) {
2158                         pos = getRealCoordinateBasePos(v_pos);
2159                         geom = getRealCoordinateGeometry(v_geom);
2160                 } else {
2161                         pos = getElementBasePos(&v_pos);
2162                         geom.X = (stof(v_geom[0]) * spacing.X) - (spacing.X - imgsize.X);
2163                         geom.Y = (stof(v_geom[1]) * spacing.Y) - (spacing.Y - imgsize.Y);
2164                 }
2165
2166                 core::rect<s32> rect = core::rect<s32>(pos.X, pos.Y, pos.X+geom.X, pos.Y+geom.Y);
2167
2168                 if(!data->explicit_size)
2169                         warningstream<<"invalid use of item_image_button without a size[] element"<<std::endl;
2170
2171                 IItemDefManager *idef = m_client->idef();
2172                 ItemStack item;
2173                 item.deSerialize(item_name, idef);
2174
2175                 m_tooltips[name] =
2176                         TooltipSpec(utf8_to_wide(item.getDefinition(idef).description),
2177                                                 m_default_tooltip_bgcolor,
2178                                                 m_default_tooltip_color);
2179
2180                 // the spec for the button
2181                 FieldSpec spec_btn(
2182                         name,
2183                         utf8_to_wide(label),
2184                         utf8_to_wide(item_name),
2185                         258 + m_fields.size(),
2186                         2
2187                 );
2188
2189                 GUIButtonItemImage *e_btn = GUIButtonItemImage::addButton(Environment,
2190                                 rect, m_tsrc, data->current_parent, spec_btn.fid, spec_btn.flabel.c_str(),
2191                                 item_name, m_client);
2192
2193                 auto style = getStyleForElement("item_image_button", spec_btn.fname, "image_button");
2194                 e_btn->setStyles(style);
2195
2196                 if (spec_btn.fname == data->focused_fieldname) {
2197                         Environment->setFocus(e_btn);
2198                 }
2199
2200                 spec_btn.ftype = f_Button;
2201                 rect += data->basepos-padding;
2202                 spec_btn.rect = rect;
2203                 m_fields.push_back(spec_btn);
2204                 return;
2205         }
2206         errorstream<< "Invalid ItemImagebutton element(" << parts.size() << "): '" << element << "'"  << std::endl;
2207 }
2208
2209 void GUIFormSpecMenu::parseBox(parserData* data, const std::string &element)
2210 {
2211         std::vector<std::string> parts = split(element,';');
2212
2213         if ((parts.size() == 3) ||
2214                 ((parts.size() > 3) && (m_formspec_version > FORMSPEC_API_VERSION)))
2215         {
2216                 std::vector<std::string> v_pos = split(parts[0],',');
2217                 std::vector<std::string> v_geom = split(parts[1],',');
2218
2219                 MY_CHECKPOS("box",0);
2220                 MY_CHECKGEOM("box",1);
2221
2222                 v2s32 pos;
2223                 v2s32 geom;
2224
2225                 if (data->real_coordinates) {
2226                         pos = getRealCoordinateBasePos(v_pos);
2227                         geom = getRealCoordinateGeometry(v_geom);
2228                 } else {
2229                         pos = getElementBasePos(&v_pos);
2230                         geom.X = stof(v_geom[0]) * spacing.X;
2231                         geom.Y = stof(v_geom[1]) * spacing.Y;
2232                 }
2233
2234                 video::SColor tmp_color;
2235
2236                 if (parseColorString(parts[2], tmp_color, false, 0x8C)) {
2237                         FieldSpec spec(
2238                                 "",
2239                                 L"",
2240                                 L"",
2241                                 258 + m_fields.size(),
2242                                 -2
2243                         );
2244                         spec.ftype = f_Box;
2245
2246                         core::rect<s32> rect(pos, pos + geom);
2247
2248                         GUIBox *e = new GUIBox(Environment, data->current_parent, spec.fid,
2249                                         rect, tmp_color);
2250
2251                         auto style = getDefaultStyleForElement("box", spec.fname);
2252                         e->setNotClipped(style.getBool(StyleSpec::NOCLIP, m_formspec_version < 3));
2253
2254                         e->drop();
2255
2256                         m_fields.push_back(spec);
2257
2258                 } else {
2259                         errorstream<< "Invalid Box element(" << parts.size() << "): '" << element << "'  INVALID COLOR"  << std::endl;
2260                 }
2261                 return;
2262         }
2263         errorstream<< "Invalid Box element(" << parts.size() << "): '" << element << "'"  << std::endl;
2264 }
2265
2266 void GUIFormSpecMenu::parseBackgroundColor(parserData* data, const std::string &element)
2267 {
2268         std::vector<std::string> parts = split(element,';');
2269         const u32 parameter_count = parts.size();
2270
2271         if ((parameter_count > 2 && m_formspec_version < 3) ||
2272                         (parameter_count > 3 && m_formspec_version <= FORMSPEC_API_VERSION)) {
2273                 errorstream << "Invalid bgcolor element(" << parameter_count << "): '"
2274                                 << element << "'" << std::endl;
2275                 return;
2276         }
2277
2278         // bgcolor
2279         if (parameter_count >= 1 && parts[0] != "")
2280                 parseColorString(parts[0], m_bgcolor, false);
2281
2282         // fullscreen
2283         if (parameter_count >= 2) {
2284                 if (parts[1] == "both") {
2285                         m_bgnonfullscreen = true;
2286                         m_bgfullscreen = true;
2287                 } else if (parts[1] == "neither") {
2288                         m_bgnonfullscreen = false;
2289                         m_bgfullscreen = false;
2290                 } else if (parts[1] != "" || m_formspec_version < 3) {
2291                         m_bgfullscreen = is_yes(parts[1]);
2292                         m_bgnonfullscreen = !m_bgfullscreen;
2293                 }
2294         }
2295
2296         // fbgcolor
2297         if (parameter_count >= 3 && parts[2] != "")
2298                 parseColorString(parts[2], m_fullscreen_bgcolor, false);
2299 }
2300
2301 void GUIFormSpecMenu::parseListColors(parserData* data, const std::string &element)
2302 {
2303         std::vector<std::string> parts = split(element,';');
2304
2305         if (((parts.size() == 2) || (parts.size() == 3) || (parts.size() == 5)) ||
2306                 ((parts.size() > 5) && (m_formspec_version > FORMSPEC_API_VERSION)))
2307         {
2308                 parseColorString(parts[0], data->inventorylist_options.slotbg_n, false);
2309                 parseColorString(parts[1], data->inventorylist_options.slotbg_h, false);
2310
2311                 if (parts.size() >= 3) {
2312                         if (parseColorString(parts[2], data->inventorylist_options.slotbordercolor,
2313                                         false)) {
2314                                 data->inventorylist_options.slotborder = true;
2315                         }
2316                 }
2317                 if (parts.size() == 5) {
2318                         video::SColor tmp_color;
2319
2320                         if (parseColorString(parts[3], tmp_color, false))
2321                                 m_default_tooltip_bgcolor = tmp_color;
2322                         if (parseColorString(parts[4], tmp_color, false))
2323                                 m_default_tooltip_color = tmp_color;
2324                 }
2325
2326                 // update all already parsed inventorylists
2327                 for (GUIInventoryList *e : m_inventorylists) {
2328                         e->setSlotBGColors(data->inventorylist_options.slotbg_n,
2329                                         data->inventorylist_options.slotbg_h);
2330                         e->setSlotBorders(data->inventorylist_options.slotborder,
2331                                         data->inventorylist_options.slotbordercolor);
2332                 }
2333                 return;
2334         }
2335         errorstream<< "Invalid listcolors element(" << parts.size() << "): '" << element << "'"  << std::endl;
2336 }
2337
2338 void GUIFormSpecMenu::parseTooltip(parserData* data, const std::string &element)
2339 {
2340         std::vector<std::string> parts = split(element,';');
2341         if (parts.size() < 2) {
2342                 errorstream << "Invalid tooltip element(" << parts.size() << "): '"
2343                                 << element << "'"  << std::endl;
2344                 return;
2345         }
2346
2347         // Get mode and check size
2348         bool rect_mode = parts[0].find(',') != std::string::npos;
2349         size_t base_size = rect_mode ? 3 : 2;
2350         if (parts.size() != base_size && parts.size() != base_size + 2) {
2351                 errorstream << "Invalid tooltip element(" << parts.size() << "): '"
2352                                 << element << "'"  << std::endl;
2353                 return;
2354         }
2355
2356         // Read colors
2357         video::SColor bgcolor = m_default_tooltip_bgcolor;
2358         video::SColor color   = m_default_tooltip_color;
2359         if (parts.size() == base_size + 2 &&
2360                         (!parseColorString(parts[base_size], bgcolor, false) ||
2361                                 !parseColorString(parts[base_size + 1], color, false))) {
2362                 errorstream << "Invalid color in tooltip element(" << parts.size()
2363                                 << "): '" << element << "'"  << std::endl;
2364                 return;
2365         }
2366
2367         // Make tooltip spec
2368         std::string text = unescape_string(parts[rect_mode ? 2 : 1]);
2369         TooltipSpec spec(utf8_to_wide(text), bgcolor, color);
2370
2371         // Add tooltip
2372         if (rect_mode) {
2373                 std::vector<std::string> v_pos  = split(parts[0], ',');
2374                 std::vector<std::string> v_geom = split(parts[1], ',');
2375
2376                 MY_CHECKPOS("tooltip", 0);
2377                 MY_CHECKGEOM("tooltip", 1);
2378
2379                 v2s32 pos;
2380                 v2s32 geom;
2381
2382                 if (data->real_coordinates) {
2383                         pos = getRealCoordinateBasePos(v_pos);
2384                         geom = getRealCoordinateGeometry(v_geom);
2385                 } else {
2386                         pos = getElementBasePos(&v_pos);
2387                         geom.X = stof(v_geom[0]) * spacing.X;
2388                         geom.Y = stof(v_geom[1]) * spacing.Y;
2389                 }
2390
2391                 FieldSpec fieldspec(
2392                         "",
2393                         L"",
2394                         L"",
2395                         258 + m_fields.size()
2396                 );
2397
2398                 core::rect<s32> rect(pos, pos + geom);
2399
2400                 gui::IGUIElement *e = new gui::IGUIElement(EGUIET_ELEMENT, Environment,
2401                                 data->current_parent, fieldspec.fid, rect);
2402
2403                 // the element the rect tooltip is bound to should not block mouse-clicks
2404                 e->setVisible(false);
2405
2406                 m_fields.push_back(fieldspec);
2407                 m_tooltip_rects.emplace_back(e, spec);
2408
2409         } else {
2410                 m_tooltips[parts[0]] = spec;
2411         }
2412 }
2413
2414 bool GUIFormSpecMenu::parseVersionDirect(const std::string &data)
2415 {
2416         //some prechecks
2417         if (data.empty())
2418                 return false;
2419
2420         std::vector<std::string> parts = split(data,'[');
2421
2422         if (parts.size() < 2) {
2423                 return false;
2424         }
2425
2426         if (trim(parts[0]) != "formspec_version") {
2427                 return false;
2428         }
2429
2430         if (is_number(parts[1])) {
2431                 m_formspec_version = mystoi(parts[1]);
2432                 return true;
2433         }
2434
2435         return false;
2436 }
2437
2438 bool GUIFormSpecMenu::parseSizeDirect(parserData* data, const std::string &element)
2439 {
2440         if (element.empty())
2441                 return false;
2442
2443         std::vector<std::string> parts = split(element,'[');
2444
2445         if (parts.size() < 2)
2446                 return false;
2447
2448         std::string type = trim(parts[0]);
2449         std::string description = trim(parts[1]);
2450
2451         if (type != "size" && type != "invsize")
2452                 return false;
2453
2454         if (type == "invsize")
2455                 warningstream << "Deprecated formspec element \"invsize\" is used" << std::endl;
2456
2457         parseSize(data, description);
2458
2459         return true;
2460 }
2461
2462 bool GUIFormSpecMenu::parsePositionDirect(parserData *data, const std::string &element)
2463 {
2464         if (element.empty())
2465                 return false;
2466
2467         std::vector<std::string> parts = split(element, '[');
2468
2469         if (parts.size() != 2)
2470                 return false;
2471
2472         std::string type = trim(parts[0]);
2473         std::string description = trim(parts[1]);
2474
2475         if (type != "position")
2476                 return false;
2477
2478         parsePosition(data, description);
2479
2480         return true;
2481 }
2482
2483 void GUIFormSpecMenu::parsePosition(parserData *data, const std::string &element)
2484 {
2485         std::vector<std::string> parts = split(element, ',');
2486
2487         if (parts.size() == 2) {
2488                 data->offset.X = stof(parts[0]);
2489                 data->offset.Y = stof(parts[1]);
2490                 return;
2491         }
2492
2493         errorstream << "Invalid position element (" << parts.size() << "): '" << element << "'" << std::endl;
2494 }
2495
2496 bool GUIFormSpecMenu::parseAnchorDirect(parserData *data, const std::string &element)
2497 {
2498         if (element.empty())
2499                 return false;
2500
2501         std::vector<std::string> parts = split(element, '[');
2502
2503         if (parts.size() != 2)
2504                 return false;
2505
2506         std::string type = trim(parts[0]);
2507         std::string description = trim(parts[1]);
2508
2509         if (type != "anchor")
2510                 return false;
2511
2512         parseAnchor(data, description);
2513
2514         return true;
2515 }
2516
2517 void GUIFormSpecMenu::parseAnchor(parserData *data, const std::string &element)
2518 {
2519         std::vector<std::string> parts = split(element, ',');
2520
2521         if (parts.size() == 2) {
2522                 data->anchor.X = stof(parts[0]);
2523                 data->anchor.Y = stof(parts[1]);
2524                 return;
2525         }
2526
2527         errorstream << "Invalid anchor element (" << parts.size() << "): '" << element
2528                         << "'" << std::endl;
2529 }
2530
2531 bool GUIFormSpecMenu::parseStyle(parserData *data, const std::string &element, bool style_type)
2532 {
2533         std::vector<std::string> parts = split(element, ';');
2534
2535         if (parts.size() < 2) {
2536                 errorstream << "Invalid style element (" << parts.size() << "): '" << element
2537                                         << "'" << std::endl;
2538                 return false;
2539         }
2540
2541         StyleSpec spec;
2542
2543         // Parse properties
2544         for (size_t i = 1; i < parts.size(); i++) {
2545                 size_t equal_pos = parts[i].find('=');
2546                 if (equal_pos == std::string::npos) {
2547                         errorstream << "Invalid style element (Property missing value): '" << element
2548                                                 << "'" << std::endl;
2549                         return false;
2550                 }
2551
2552                 std::string propname = trim(parts[i].substr(0, equal_pos));
2553                 std::string value    = trim(unescape_string(parts[i].substr(equal_pos + 1)));
2554
2555                 std::transform(propname.begin(), propname.end(), propname.begin(), ::tolower);
2556
2557                 StyleSpec::Property prop = StyleSpec::GetPropertyByName(propname);
2558                 if (prop == StyleSpec::NONE) {
2559                         if (property_warned.find(propname) != property_warned.end()) {
2560                                 warningstream << "Invalid style element (Unknown property " << propname << "): '"
2561                                                 << element
2562                                                 << "'" << std::endl;
2563                                 property_warned.insert(propname);
2564                         }
2565                         return false;
2566                 }
2567
2568                 spec.set(prop, value);
2569         }
2570
2571         std::vector<std::string> selectors = split(parts[0], ',');
2572         for (size_t sel = 0; sel < selectors.size(); sel++) {
2573                 std::string selector = trim(selectors[sel]);
2574
2575                 // Copy the style properties to a new StyleSpec
2576                 // This allows a separate state mask per-selector
2577                 StyleSpec selector_spec = spec;
2578
2579                 // Parse state information, if it exists
2580                 bool state_valid = true;
2581                 size_t state_pos = selector.find(':');
2582                 if (state_pos != std::string::npos) {
2583                         std::string state_str = selector.substr(state_pos + 1);
2584                         selector = selector.substr(0, state_pos);
2585
2586                         if (state_str.empty()) {
2587                                 errorstream << "Invalid style element (Invalid state): '" << element
2588                                         << "'" << std::endl;
2589                                 state_valid = false;
2590                         } else {
2591                                 std::vector<std::string> states = split(state_str, '+');
2592                                 for (std::string &state : states) {
2593                                         StyleSpec::State converted = StyleSpec::getStateByName(state);
2594                                         if (converted == StyleSpec::STATE_INVALID) {
2595                                                 infostream << "Unknown style state " << state <<
2596                                                         " in element '" << element << "'" << std::endl;
2597                                                 state_valid = false;
2598                                                 break;
2599                                         }
2600
2601                                         selector_spec.addState(converted);
2602                                 }
2603                         }
2604                 }
2605
2606                 if(!state_valid) {
2607                         // Skip this selector
2608                         continue;
2609                 }
2610
2611                 if (style_type) {
2612                         theme_by_type[selector].push_back(selector_spec);
2613                 } else {
2614                         theme_by_name[selector].push_back(selector_spec);
2615                 }
2616
2617                 // Backwards-compatibility for existing _hovered/_pressed properties
2618                 if (selector_spec.hasProperty(StyleSpec::BGCOLOR_HOVERED)
2619                                 || selector_spec.hasProperty(StyleSpec::BGIMG_HOVERED)
2620                                 || selector_spec.hasProperty(StyleSpec::FGIMG_HOVERED)) {
2621                         StyleSpec hover_spec;
2622                         hover_spec.addState(StyleSpec::STATE_HOVERED);
2623
2624                         if (selector_spec.hasProperty(StyleSpec::BGCOLOR_HOVERED)) {
2625                                 hover_spec.set(StyleSpec::BGCOLOR, selector_spec.get(StyleSpec::BGCOLOR_HOVERED, ""));
2626                         }
2627                         if (selector_spec.hasProperty(StyleSpec::BGIMG_HOVERED)) {
2628                                 hover_spec.set(StyleSpec::BGIMG, selector_spec.get(StyleSpec::BGIMG_HOVERED, ""));
2629                         }
2630                         if (selector_spec.hasProperty(StyleSpec::FGIMG_HOVERED)) {
2631                                 hover_spec.set(StyleSpec::FGIMG, selector_spec.get(StyleSpec::FGIMG_HOVERED, ""));
2632                         }
2633
2634                         if (style_type) {
2635                                 theme_by_type[selector].push_back(hover_spec);
2636                         } else {
2637                                 theme_by_name[selector].push_back(hover_spec);
2638                         }
2639                 }
2640                 if (selector_spec.hasProperty(StyleSpec::BGCOLOR_PRESSED)
2641                                 || selector_spec.hasProperty(StyleSpec::BGIMG_PRESSED)
2642                                 || selector_spec.hasProperty(StyleSpec::FGIMG_PRESSED)) {
2643                         StyleSpec press_spec;
2644                         press_spec.addState(StyleSpec::STATE_PRESSED);
2645
2646                         if (selector_spec.hasProperty(StyleSpec::BGCOLOR_PRESSED)) {
2647                                 press_spec.set(StyleSpec::BGCOLOR, selector_spec.get(StyleSpec::BGCOLOR_PRESSED, ""));
2648                         }
2649                         if (selector_spec.hasProperty(StyleSpec::BGIMG_PRESSED)) {
2650                                 press_spec.set(StyleSpec::BGIMG, selector_spec.get(StyleSpec::BGIMG_PRESSED, ""));
2651                         }
2652                         if (selector_spec.hasProperty(StyleSpec::FGIMG_PRESSED)) {
2653                                 press_spec.set(StyleSpec::FGIMG, selector_spec.get(StyleSpec::FGIMG_PRESSED, ""));
2654                         }
2655
2656                         if (style_type) {
2657                                 theme_by_type[selector].push_back(press_spec);
2658                         } else {
2659                                 theme_by_name[selector].push_back(press_spec);
2660                         }
2661                 }
2662         }
2663
2664         return true;
2665 }
2666
2667 void GUIFormSpecMenu::parseElement(parserData* data, const std::string &element)
2668 {
2669         //some prechecks
2670         if (element.empty())
2671                 return;
2672
2673         if (parseVersionDirect(element))
2674                 return;
2675
2676         size_t pos = element.find('[');
2677         if (pos == std::string::npos)
2678                 return;
2679
2680         std::string type = trim(element.substr(0, pos));
2681         std::string description = element.substr(pos+1);
2682
2683         if (type == "container") {
2684                 parseContainer(data, description);
2685                 return;
2686         }
2687
2688         if (type == "container_end") {
2689                 parseContainerEnd(data);
2690                 return;
2691         }
2692
2693         if (type == "list") {
2694                 parseList(data, description);
2695                 return;
2696         }
2697
2698         if (type == "listring") {
2699                 parseListRing(data, description);
2700                 return;
2701         }
2702
2703         if (type == "checkbox") {
2704                 parseCheckbox(data, description);
2705                 return;
2706         }
2707
2708         if (type == "image") {
2709                 parseImage(data, description);
2710                 return;
2711         }
2712
2713         if (type == "animated_image") {
2714                 parseAnimatedImage(data, description);
2715                 return;
2716         }
2717
2718         if (type == "item_image") {
2719                 parseItemImage(data, description);
2720                 return;
2721         }
2722
2723         if (type == "button" || type == "button_exit") {
2724                 parseButton(data, description, type);
2725                 return;
2726         }
2727
2728         if (type == "background" || type == "background9") {
2729                 parseBackground(data, description);
2730                 return;
2731         }
2732
2733         if (type == "tableoptions"){
2734                 parseTableOptions(data,description);
2735                 return;
2736         }
2737
2738         if (type == "tablecolumns"){
2739                 parseTableColumns(data,description);
2740                 return;
2741         }
2742
2743         if (type == "table"){
2744                 parseTable(data,description);
2745                 return;
2746         }
2747
2748         if (type == "textlist"){
2749                 parseTextList(data,description);
2750                 return;
2751         }
2752
2753         if (type == "dropdown"){
2754                 parseDropDown(data,description);
2755                 return;
2756         }
2757
2758         if (type == "field_close_on_enter") {
2759                 parseFieldCloseOnEnter(data, description);
2760                 return;
2761         }
2762
2763         if (type == "pwdfield") {
2764                 parsePwdField(data,description);
2765                 return;
2766         }
2767
2768         if ((type == "field") || (type == "textarea")){
2769                 parseField(data,description,type);
2770                 return;
2771         }
2772
2773         if (type == "hypertext") {
2774                 parseHyperText(data,description);
2775                 return;
2776         }
2777
2778         if (type == "label") {
2779                 parseLabel(data,description);
2780                 return;
2781         }
2782
2783         if (type == "vertlabel") {
2784                 parseVertLabel(data,description);
2785                 return;
2786         }
2787
2788         if (type == "item_image_button") {
2789                 parseItemImageButton(data,description);
2790                 return;
2791         }
2792
2793         if ((type == "image_button") || (type == "image_button_exit")) {
2794                 parseImageButton(data,description,type);
2795                 return;
2796         }
2797
2798         if (type == "tabheader") {
2799                 parseTabHeader(data,description);
2800                 return;
2801         }
2802
2803         if (type == "box") {
2804                 parseBox(data,description);
2805                 return;
2806         }
2807
2808         if (type == "bgcolor") {
2809                 parseBackgroundColor(data,description);
2810                 return;
2811         }
2812
2813         if (type == "listcolors") {
2814                 parseListColors(data,description);
2815                 return;
2816         }
2817
2818         if (type == "tooltip") {
2819                 parseTooltip(data,description);
2820                 return;
2821         }
2822
2823         if (type == "scrollbar") {
2824                 parseScrollBar(data, description);
2825                 return;
2826         }
2827
2828         if (type == "real_coordinates") {
2829                 data->real_coordinates = is_yes(description);
2830                 return;
2831         }
2832
2833         if (type == "style") {
2834                 parseStyle(data, description, false);
2835                 return;
2836         }
2837
2838         if (type == "style_type") {
2839                 parseStyle(data, description, true);
2840                 return;
2841         }
2842
2843         if (type == "scrollbaroptions") {
2844                 parseScrollBarOptions(data, description);
2845                 return;
2846         }
2847
2848         if (type == "scroll_container") {
2849                 parseScrollContainer(data, description);
2850                 return;
2851         }
2852
2853         if (type == "scroll_container_end") {
2854                 parseScrollContainerEnd(data);
2855                 return;
2856         }
2857
2858         // Ignore others
2859         infostream << "Unknown DrawSpec: type=" << type << ", data=\"" << description << "\""
2860                         << std::endl;
2861 }
2862
2863 void GUIFormSpecMenu::regenerateGui(v2u32 screensize)
2864 {
2865         /* useless to regenerate without a screensize */
2866         if ((screensize.X <= 0) || (screensize.Y <= 0)) {
2867                 return;
2868         }
2869
2870         parserData mydata;
2871
2872         //preserve tables
2873         for (auto &m_table : m_tables) {
2874                 std::string tablename = m_table.first.fname;
2875                 GUITable *table = m_table.second;
2876                 mydata.table_dyndata[tablename] = table->getDynamicData();
2877         }
2878
2879         //set focus
2880         if (!m_focused_element.empty())
2881                 mydata.focused_fieldname = m_focused_element;
2882
2883         //preserve focus
2884         gui::IGUIElement *focused_element = Environment->getFocus();
2885         if (focused_element && focused_element->getParent() == this) {
2886                 s32 focused_id = focused_element->getID();
2887                 if (focused_id > 257) {
2888                         for (const GUIFormSpecMenu::FieldSpec &field : m_fields) {
2889                                 if (field.fid == focused_id) {
2890                                         mydata.focused_fieldname = field.fname;
2891                                         break;
2892                                 }
2893                         }
2894                 }
2895         }
2896
2897         // Remove children
2898         removeChildren();
2899
2900         for (auto &table_it : m_tables)
2901                 table_it.second->drop();
2902         for (auto &inventorylist_it : m_inventorylists)
2903                 inventorylist_it->drop();
2904         for (auto &checkbox_it : m_checkboxes)
2905                 checkbox_it.second->drop();
2906         for (auto &scrollbar_it : m_scrollbars)
2907                 scrollbar_it.second->drop();
2908         for (auto &background_it : m_backgrounds)
2909                 background_it->drop();
2910         for (auto &tooltip_rect_it : m_tooltip_rects)
2911                 tooltip_rect_it.first->drop();
2912         for (auto &clickthrough_it : m_clickthrough_elements)
2913                 clickthrough_it->drop();
2914         for (auto &scroll_container_it : m_scroll_containers)
2915                 scroll_container_it.second->drop();
2916
2917         mydata.size = v2s32(100, 100);
2918         mydata.screensize = screensize;
2919         mydata.offset = v2f32(0.5f, 0.5f);
2920         mydata.anchor = v2f32(0.5f, 0.5f);
2921         mydata.simple_field_count = 0;
2922
2923         // Base position of contents of form
2924         mydata.basepos = getBasePos();
2925
2926         // the parent for the parsed elements
2927         mydata.current_parent = this;
2928
2929         m_inventorylists.clear();
2930         m_backgrounds.clear();
2931         m_tables.clear();
2932         m_checkboxes.clear();
2933         m_scrollbars.clear();
2934         m_fields.clear();
2935         m_tooltips.clear();
2936         m_tooltip_rects.clear();
2937         m_inventory_rings.clear();
2938         m_dropdowns.clear();
2939         m_scroll_containers.clear();
2940         theme_by_name.clear();
2941         theme_by_type.clear();
2942         m_clickthrough_elements.clear();
2943
2944         m_bgnonfullscreen = true;
2945         m_bgfullscreen = false;
2946
2947         m_formspec_version = 1;
2948
2949         {
2950                 v3f formspec_bgcolor = g_settings->getV3F("formspec_default_bg_color");
2951                 m_bgcolor = video::SColor(
2952                         (u8) clamp_u8(g_settings->getS32("formspec_default_bg_opacity")),
2953                         clamp_u8(myround(formspec_bgcolor.X)),
2954                         clamp_u8(myround(formspec_bgcolor.Y)),
2955                         clamp_u8(myround(formspec_bgcolor.Z))
2956                 );
2957         }
2958
2959         {
2960                 v3f formspec_bgcolor = g_settings->getV3F("formspec_fullscreen_bg_color");
2961                 m_fullscreen_bgcolor = video::SColor(
2962                         (u8) clamp_u8(g_settings->getS32("formspec_fullscreen_bg_opacity")),
2963                         clamp_u8(myround(formspec_bgcolor.X)),
2964                         clamp_u8(myround(formspec_bgcolor.Y)),
2965                         clamp_u8(myround(formspec_bgcolor.Z))
2966                 );
2967         }
2968
2969         m_default_tooltip_bgcolor = video::SColor(255,110,130,60);
2970         m_default_tooltip_color = video::SColor(255,255,255,255);
2971
2972         // Add tooltip
2973         {
2974                 assert(!m_tooltip_element);
2975                 // Note: parent != this so that the tooltip isn't clipped by the menu rectangle
2976                 m_tooltip_element = gui::StaticText::add(Environment, L"",
2977                         core::rect<s32>(0, 0, 110, 18));
2978                 m_tooltip_element->enableOverrideColor(true);
2979                 m_tooltip_element->setBackgroundColor(m_default_tooltip_bgcolor);
2980                 m_tooltip_element->setDrawBackground(true);
2981                 m_tooltip_element->setDrawBorder(true);
2982                 m_tooltip_element->setOverrideColor(m_default_tooltip_color);
2983                 m_tooltip_element->setTextAlignment(gui::EGUIA_CENTER, gui::EGUIA_CENTER);
2984                 m_tooltip_element->setWordWrap(false);
2985                 //we're not parent so no autograb for this one!
2986                 m_tooltip_element->grab();
2987         }
2988
2989         std::vector<std::string> elements = split(m_formspec_string,']');
2990         unsigned int i = 0;
2991
2992         /* try to read version from first element only */
2993         if (!elements.empty()) {
2994                 if (parseVersionDirect(elements[0])) {
2995                         i++;
2996                 }
2997         }
2998
2999         /* we need size first in order to calculate image scale */
3000         mydata.explicit_size = false;
3001         for (; i< elements.size(); i++) {
3002                 if (!parseSizeDirect(&mydata, elements[i])) {
3003                         break;
3004                 }
3005         }
3006
3007         /* "position" element is always after "size" element if it used */
3008         for (; i< elements.size(); i++) {
3009                 if (!parsePositionDirect(&mydata, elements[i])) {
3010                         break;
3011                 }
3012         }
3013
3014         /* "anchor" element is always after "position" (or  "size" element) if it used */
3015         for (; i< elements.size(); i++) {
3016                 if (!parseAnchorDirect(&mydata, elements[i])) {
3017                         break;
3018                 }
3019         }
3020
3021         /* "no_prepend" element is always after "position" (or  "size" element) if it used */
3022         bool enable_prepends = true;
3023         for (; i < elements.size(); i++) {
3024                 if (elements[i].empty())
3025                         break;
3026
3027                 std::vector<std::string> parts = split(elements[i], '[');
3028                 if (trim(parts[0]) == "no_prepend")
3029                         enable_prepends = false;
3030                 else
3031                         break;
3032         }
3033
3034         /* Copy of the "real_coordinates" element for after the form size. */
3035         mydata.real_coordinates = m_formspec_version >= 2;
3036         for (; i < elements.size(); i++) {
3037                 std::vector<std::string> parts = split(elements[i], '[');
3038                 std::string name = trim(parts[0]);
3039                 if (name != "real_coordinates" || parts.size() != 2)
3040                         break; // Invalid format
3041
3042                 mydata.real_coordinates = is_yes(trim(parts[1]));
3043         }
3044
3045         if (mydata.explicit_size) {
3046                 // compute scaling for specified form size
3047                 if (m_lock) {
3048                         v2u32 current_screensize = RenderingEngine::get_video_driver()->getScreenSize();
3049                         v2u32 delta = current_screensize - m_lockscreensize;
3050
3051                         if (current_screensize.Y > m_lockscreensize.Y)
3052                                 delta.Y /= 2;
3053                         else
3054                                 delta.Y = 0;
3055
3056                         if (current_screensize.X > m_lockscreensize.X)
3057                                 delta.X /= 2;
3058                         else
3059                                 delta.X = 0;
3060
3061                         offset = v2s32(delta.X,delta.Y);
3062
3063                         mydata.screensize = m_lockscreensize;
3064                 } else {
3065                         offset = v2s32(0,0);
3066                 }
3067
3068                 double gui_scaling = g_settings->getFloat("gui_scaling");
3069                 double screen_dpi = RenderingEngine::getDisplayDensity() * 96;
3070
3071                 double use_imgsize;
3072                 if (m_lock) {
3073                         // In fixed-size mode, inventory image size
3074                         // is 0.53 inch multiplied by the gui_scaling
3075                         // config parameter.  This magic size is chosen
3076                         // to make the main menu (15.5 inventory images
3077                         // wide, including border) just fit into the
3078                         // default window (800 pixels wide) at 96 DPI
3079                         // and default scaling (1.00).
3080                         use_imgsize = 0.5555 * screen_dpi * gui_scaling;
3081                 } else {
3082                         // In variable-size mode, we prefer to make the
3083                         // inventory image size 1/15 of screen height,
3084                         // multiplied by the gui_scaling config parameter.
3085                         // If the preferred size won't fit the whole
3086                         // form on the screen, either horizontally or
3087                         // vertically, then we scale it down to fit.
3088                         // (The magic numbers in the computation of what
3089                         // fits arise from the scaling factors in the
3090                         // following stanza, including the form border,
3091                         // help text space, and 0.1 inventory slot spare.)
3092                         // However, a minimum size is also set, that
3093                         // the image size can't be less than 0.3 inch
3094                         // multiplied by gui_scaling, even if this means
3095                         // the form doesn't fit the screen.
3096 #ifdef __ANDROID__
3097                         // For mobile devices these magic numbers are
3098                         // different and forms should always use the
3099                         // maximum screen space available.
3100                         double prefer_imgsize = mydata.screensize.Y / 10 * gui_scaling;
3101                         double fitx_imgsize = mydata.screensize.X /
3102                                 ((12.0 / 8.0) * (0.5 + mydata.invsize.X));
3103                         double fity_imgsize = mydata.screensize.Y /
3104                                 ((15.0 / 11.0) * (0.85 + mydata.invsize.Y));
3105                         use_imgsize = MYMIN(prefer_imgsize,
3106                                         MYMIN(fitx_imgsize, fity_imgsize));
3107 #else
3108                         double prefer_imgsize = mydata.screensize.Y / 15 * gui_scaling;
3109                         double fitx_imgsize = mydata.screensize.X /
3110                                 ((5.0 / 4.0) * (0.5 + mydata.invsize.X));
3111                         double fity_imgsize = mydata.screensize.Y /
3112                                 ((15.0 / 13.0) * (0.85 * mydata.invsize.Y));
3113                         double screen_dpi = RenderingEngine::getDisplayDensity() * 96;
3114                         double min_imgsize = 0.3 * screen_dpi * gui_scaling;
3115                         use_imgsize = MYMAX(min_imgsize, MYMIN(prefer_imgsize,
3116                                 MYMIN(fitx_imgsize, fity_imgsize)));
3117 #endif
3118                 }
3119
3120                 // Everything else is scaled in proportion to the
3121                 // inventory image size.  The inventory slot spacing
3122                 // is 5/4 image size horizontally and 15/13 image size
3123                 // vertically.  The padding around the form (incorporating
3124                 // the border of the outer inventory slots) is 3/8
3125                 // image size.  Font height (baseline to baseline)
3126                 // is 2/5 vertical inventory slot spacing, and button
3127                 // half-height is 7/8 of font height.
3128                 imgsize = v2s32(use_imgsize, use_imgsize);
3129                 spacing = v2f32(use_imgsize*5.0/4, use_imgsize*15.0/13);
3130                 padding = v2s32(use_imgsize*3.0/8, use_imgsize*3.0/8);
3131                 m_btn_height = use_imgsize*15.0/13 * 0.35;
3132
3133                 m_font = g_fontengine->getFont();
3134
3135                 if (mydata.real_coordinates) {
3136                         mydata.size = v2s32(
3137                                 mydata.invsize.X*imgsize.X,
3138                                 mydata.invsize.Y*imgsize.Y
3139                         );
3140                 } else {
3141                         mydata.size = v2s32(
3142                                 padding.X*2+spacing.X*(mydata.invsize.X-1.0)+imgsize.X,
3143                                 padding.Y*2+spacing.Y*(mydata.invsize.Y-1.0)+imgsize.Y + m_btn_height*2.0/3.0
3144                         );
3145                 }
3146
3147                 DesiredRect = mydata.rect = core::rect<s32>(
3148                                 (s32)((f32)mydata.screensize.X * mydata.offset.X) - (s32)(mydata.anchor.X * (f32)mydata.size.X) + offset.X,
3149                                 (s32)((f32)mydata.screensize.Y * mydata.offset.Y) - (s32)(mydata.anchor.Y * (f32)mydata.size.Y) + offset.Y,
3150                                 (s32)((f32)mydata.screensize.X * mydata.offset.X) + (s32)((1.0 - mydata.anchor.X) * (f32)mydata.size.X) + offset.X,
3151                                 (s32)((f32)mydata.screensize.Y * mydata.offset.Y) + (s32)((1.0 - mydata.anchor.Y) * (f32)mydata.size.Y) + offset.Y
3152                 );
3153         } else {
3154                 // Non-size[] form must consist only of text fields and
3155                 // implicit "Proceed" button.  Use default font, and
3156                 // temporary form size which will be recalculated below.
3157                 m_font = g_fontengine->getFont();
3158                 m_btn_height = font_line_height(m_font) * 0.875;
3159                 DesiredRect = core::rect<s32>(
3160                         (s32)((f32)mydata.screensize.X * mydata.offset.X) - (s32)(mydata.anchor.X * 580.0),
3161                         (s32)((f32)mydata.screensize.Y * mydata.offset.Y) - (s32)(mydata.anchor.Y * 300.0),
3162                         (s32)((f32)mydata.screensize.X * mydata.offset.X) + (s32)((1.0 - mydata.anchor.X) * 580.0),
3163                         (s32)((f32)mydata.screensize.Y * mydata.offset.Y) + (s32)((1.0 - mydata.anchor.Y) * 300.0)
3164                 );
3165         }
3166         recalculateAbsolutePosition(false);
3167         mydata.basepos = getBasePos();
3168         m_tooltip_element->setOverrideFont(m_font);
3169
3170         gui::IGUISkin *skin = Environment->getSkin();
3171         sanity_check(skin);
3172         gui::IGUIFont *old_font = skin->getFont();
3173         skin->setFont(m_font);
3174
3175         pos_offset = v2f32();
3176
3177         // used for formspec versions < 3
3178         core::list<IGUIElement *>::Iterator legacy_sort_start = Children.getLast();
3179
3180         if (enable_prepends) {
3181                 // Backup the coordinates so that prepends can use the coordinates of choice.
3182                 bool rc_backup = mydata.real_coordinates;
3183                 u16 version_backup = m_formspec_version;
3184                 mydata.real_coordinates = false; // Old coordinates by default.
3185
3186                 std::vector<std::string> prepend_elements = split(m_formspec_prepend, ']');
3187                 for (const auto &element : prepend_elements)
3188                         parseElement(&mydata, element);
3189
3190                 // legacy sorting for formspec versions < 3
3191                 if (m_formspec_version >= 3)
3192                         // prepends do not need to be reordered
3193                         legacy_sort_start = Children.getLast();
3194                 else if (version_backup >= 3)
3195                         // only prepends elements have to be reordered
3196                         legacySortElements(legacy_sort_start);
3197
3198                 m_formspec_version = version_backup;
3199                 mydata.real_coordinates = rc_backup; // Restore coordinates
3200         }
3201
3202         for (; i< elements.size(); i++) {
3203                 parseElement(&mydata, elements[i]);
3204         }
3205
3206         if (mydata.current_parent != this) {
3207                 errorstream << "Invalid formspec string: scroll_container was never closed!"
3208                         << std::endl;
3209         } else if (!container_stack.empty()) {
3210                 errorstream << "Invalid formspec string: container was never closed!"
3211                         << std::endl;
3212         }
3213
3214         // get the scrollbar elements for scroll_containers
3215         for (const std::pair<std::string, GUIScrollContainer *> &c : m_scroll_containers) {
3216                 for (const std::pair<FieldSpec, GUIScrollBar *> &b : m_scrollbars) {
3217                         if (c.first == b.first.fname) {
3218                                 c.second->setScrollBar(b.second);
3219                                 break;
3220                         }
3221                 }
3222         }
3223
3224         // If there are fields without explicit size[], add a "Proceed"
3225         // button and adjust size to fit all the fields.
3226         if (mydata.simple_field_count > 0 && !mydata.explicit_size) {
3227                 mydata.rect = core::rect<s32>(
3228                                 mydata.screensize.X / 2 - 580 / 2,
3229                                 mydata.screensize.Y / 2 - 300 / 2,
3230                                 mydata.screensize.X / 2 + 580 / 2,
3231                                 mydata.screensize.Y / 2 + 240 / 2 + mydata.simple_field_count * 60
3232                 );
3233
3234                 DesiredRect = mydata.rect;
3235                 recalculateAbsolutePosition(false);
3236                 mydata.basepos = getBasePos();
3237
3238                 {
3239                         v2s32 pos = mydata.basepos;
3240                         pos.Y = (mydata.simple_field_count + 2) * 60;
3241
3242                         v2s32 size = DesiredRect.getSize();
3243                         mydata.rect = core::rect<s32>(
3244                                         size.X / 2 - 70,       pos.Y,
3245                                         size.X / 2 - 70 + 140, pos.Y + m_btn_height * 2
3246                         );
3247                         const wchar_t *text = wgettext("Proceed");
3248                         GUIButton::addButton(Environment, mydata.rect, m_tsrc, this, 257, text);
3249                         delete[] text;
3250                 }
3251         }
3252
3253         //set initial focus if parser didn't set it
3254         focused_element = Environment->getFocus();
3255         if (!focused_element
3256                         || !isMyChild(focused_element)
3257                         || focused_element->getType() == gui::EGUIET_TAB_CONTROL)
3258                 setInitialFocus();
3259
3260         skin->setFont(old_font);
3261
3262         // legacy sorting
3263         if (m_formspec_version < 3)
3264                 legacySortElements(legacy_sort_start);
3265 }
3266
3267 void GUIFormSpecMenu::legacySortElements(core::list<IGUIElement *>::Iterator from)
3268 {
3269         /*
3270                 Draw order for formspec_version <= 2:
3271                 -3  bgcolor
3272                 -2  background
3273                 -1  box
3274                 0   All other elements
3275                 1   image
3276                 2   item_image, item_image_button
3277                 3   list
3278                 4   label
3279         */
3280
3281         if (from == Children.end())
3282                 from = Children.begin();
3283         else
3284                 from++;
3285
3286         core::list<IGUIElement *>::Iterator to = Children.end();
3287         // 1: Copy into a sortable container
3288         std::vector<IGUIElement *> elements;
3289         for (auto it = from; it != to; ++it)
3290                 elements.emplace_back(*it);
3291
3292         // 2: Sort the container
3293         std::stable_sort(elements.begin(), elements.end(),
3294                         [this] (const IGUIElement *a, const IGUIElement *b) -> bool {
3295                 const FieldSpec *spec_a = getSpecByID(a->getID());
3296                 const FieldSpec *spec_b = getSpecByID(b->getID());
3297                 return spec_a && spec_b &&
3298                         spec_a->priority < spec_b->priority;
3299         });
3300
3301         // 3: Re-assign the pointers
3302         for (auto e : elements) {
3303                 *from = e;
3304                 from++;
3305         }
3306 }
3307
3308 #ifdef __ANDROID__
3309 bool GUIFormSpecMenu::getAndroidUIInput()
3310 {
3311         if (!hasAndroidUIInput())
3312                 return false;
3313
3314         // still waiting
3315         if (porting::getInputDialogState() == -1)
3316                 return true;
3317
3318         std::string fieldname = m_jni_field_name;
3319         m_jni_field_name.clear();
3320
3321         for (const FieldSpec &field : m_fields) {
3322                 if (field.fname != fieldname)
3323                         continue;
3324
3325                 IGUIElement *element = getElementFromId(field.fid, true);
3326
3327                 if (!element || element->getType() != irr::gui::EGUIET_EDIT_BOX)
3328                         return false;
3329
3330                 std::string text = porting::getInputDialogValue();
3331                 ((gui::IGUIEditBox *)element)->setText(utf8_to_wide(text).c_str());
3332         }
3333         return false;
3334 }
3335 #endif
3336
3337 GUIInventoryList::ItemSpec GUIFormSpecMenu::getItemAtPos(v2s32 p) const
3338 {
3339         core::rect<s32> imgrect(0, 0, imgsize.X, imgsize.Y);
3340
3341         for (const GUIInventoryList *e : m_inventorylists) {
3342                 s32 item_index = e->getItemIndexAtPos(p);
3343                 if (item_index != -1)
3344                         return GUIInventoryList::ItemSpec(e->getInventoryloc(), e->getListname(),
3345                                         item_index);
3346         }
3347
3348         return GUIInventoryList::ItemSpec(InventoryLocation(), "", -1);
3349 }
3350
3351 void GUIFormSpecMenu::drawSelectedItem()
3352 {
3353         video::IVideoDriver* driver = Environment->getVideoDriver();
3354
3355         if (!m_selected_item) {
3356                 // reset rotation time
3357                 drawItemStack(driver, m_font, ItemStack(),
3358                                 core::rect<s32>(v2s32(0, 0), v2s32(0, 0)), NULL,
3359                                 m_client, IT_ROT_DRAGGED);
3360                 return;
3361         }
3362
3363         Inventory *inv = m_invmgr->getInventory(m_selected_item->inventoryloc);
3364         sanity_check(inv);
3365         InventoryList *list = inv->getList(m_selected_item->listname);
3366         sanity_check(list);
3367         ItemStack stack = list->getItem(m_selected_item->i);
3368         stack.count = m_selected_amount;
3369
3370         core::rect<s32> imgrect(0,0,imgsize.X,imgsize.Y);
3371         core::rect<s32> rect = imgrect + (m_pointer - imgrect.getCenter());
3372         rect.constrainTo(driver->getViewPort());
3373         drawItemStack(driver, m_font, stack, rect, NULL, m_client, IT_ROT_DRAGGED);
3374 }
3375
3376 void GUIFormSpecMenu::drawMenu()
3377 {
3378         if (m_form_src) {
3379                 const std::string &newform = m_form_src->getForm();
3380                 if (newform != m_formspec_string) {
3381                         m_formspec_string = newform;
3382                         regenerateGui(m_screensize_old);
3383                 }
3384         }
3385
3386         gui::IGUISkin* skin = Environment->getSkin();
3387         sanity_check(skin != NULL);
3388         gui::IGUIFont *old_font = skin->getFont();
3389         skin->setFont(m_font);
3390
3391         m_hovered_item_tooltips.clear();
3392
3393         updateSelectedItem();
3394
3395         video::IVideoDriver* driver = Environment->getVideoDriver();
3396
3397         /*
3398                 Draw background color
3399         */
3400         v2u32 screenSize = driver->getScreenSize();
3401         core::rect<s32> allbg(0, 0, screenSize.X, screenSize.Y);
3402
3403         if (m_bgfullscreen)
3404                 driver->draw2DRectangle(m_fullscreen_bgcolor, allbg, &allbg);
3405         if (m_bgnonfullscreen)
3406                 driver->draw2DRectangle(m_bgcolor, AbsoluteRect, &AbsoluteClippingRect);
3407
3408         /*
3409                 Draw rect_mode tooltip
3410         */
3411         m_tooltip_element->setVisible(false);
3412
3413         for (const auto &pair : m_tooltip_rects) {
3414                 const core::rect<s32> &rect = pair.first->getAbsoluteClippingRect();
3415                 if (rect.getArea() > 0 && rect.isPointInside(m_pointer)) {
3416                         const std::wstring &text = pair.second.tooltip;
3417                         if (!text.empty()) {
3418                                 showTooltip(text, pair.second.color, pair.second.bgcolor);
3419                                 break;
3420                         }
3421                 }
3422         }
3423
3424         /*
3425                 Draw backgrounds
3426         */
3427         for (gui::IGUIElement *e : m_backgrounds) {
3428                 e->setVisible(true);
3429                 e->draw();
3430                 e->setVisible(false);
3431         }
3432
3433         // Some elements are only visible while being drawn
3434         for (gui::IGUIElement *e : m_clickthrough_elements)
3435                 e->setVisible(true);
3436
3437         /*
3438                 Call base class
3439                 (This is where all the drawing happens.)
3440         */
3441         gui::IGUIElement::draw();
3442
3443         for (gui::IGUIElement *e : m_clickthrough_elements)
3444                 e->setVisible(false);
3445
3446         // Draw hovered item tooltips
3447         for (const std::string &tooltip : m_hovered_item_tooltips) {
3448                 showTooltip(utf8_to_wide(tooltip), m_default_tooltip_color,
3449                                 m_default_tooltip_bgcolor);
3450         }
3451
3452         if (m_hovered_item_tooltips.empty()) {
3453                 // reset rotation time
3454                 drawItemStack(driver, m_font, ItemStack(),
3455                         core::rect<s32>(v2s32(0, 0), v2s32(0, 0)),
3456                         NULL, m_client, IT_ROT_HOVERED);
3457         }
3458
3459 /* TODO find way to show tooltips on touchscreen */
3460 #ifndef HAVE_TOUCHSCREENGUI
3461         m_pointer = RenderingEngine::get_raw_device()->getCursorControl()->getPosition();
3462 #endif
3463
3464         /*
3465                 Draw fields/buttons tooltips and update the mouse cursor
3466         */
3467         gui::IGUIElement *hovered =
3468                         Environment->getRootGUIElement()->getElementFromPoint(m_pointer);
3469
3470 #ifndef HAVE_TOUCHSCREENGUI
3471         gui::ICursorControl *cursor_control = RenderingEngine::get_raw_device()->
3472                         getCursorControl();
3473         gui::ECURSOR_ICON current_cursor_icon = cursor_control->getActiveIcon();
3474 #endif
3475         bool hovered_element_found = false;
3476
3477         if (hovered != NULL) {
3478                 if (m_show_debug) {
3479                         core::rect<s32> rect = hovered->getAbsoluteClippingRect();
3480                         driver->draw2DRectangle(0x22FFFF00, rect, &rect);
3481                 }
3482
3483                 s32 id = hovered->getID();
3484                 u64 delta = 0;
3485                 if (id == -1) {
3486                         m_old_tooltip_id = id;
3487                 } else {
3488                         if (id == m_old_tooltip_id) {
3489                                 delta = porting::getDeltaMs(m_hovered_time, porting::getTimeMs());
3490                         } else {
3491                                 m_hovered_time = porting::getTimeMs();
3492                                 m_old_tooltip_id = id;
3493                         }
3494                 }
3495
3496                 // Find and update the current tooltip and cursor icon
3497                 if (id != -1) {
3498                         for (const FieldSpec &field : m_fields) {
3499
3500                                 if (field.fid != id)
3501                                         continue;
3502
3503                                 if (delta >= m_tooltip_show_delay) {
3504                                         const std::wstring &text = m_tooltips[field.fname].tooltip;
3505                                         if (!text.empty())
3506                                                 showTooltip(text, m_tooltips[field.fname].color,
3507                                                         m_tooltips[field.fname].bgcolor);
3508                                 }
3509
3510 #ifndef HAVE_TOUCHSCREENGUI
3511                                 if (field.ftype != f_HyperText && // Handled directly in guiHyperText
3512                                                 current_cursor_icon != field.fcursor_icon)
3513                                         cursor_control->setActiveIcon(field.fcursor_icon);
3514 #endif
3515
3516                                 hovered_element_found = true;
3517
3518                                 break;
3519                         }
3520                 }
3521         }
3522
3523         if (!hovered_element_found) {
3524                 // no element is hovered
3525 #ifndef HAVE_TOUCHSCREENGUI
3526                 if (current_cursor_icon != ECI_NORMAL)
3527                         cursor_control->setActiveIcon(ECI_NORMAL);
3528 #endif
3529         }
3530
3531         m_tooltip_element->draw();
3532
3533         /*
3534                 Draw dragged item stack
3535         */
3536         drawSelectedItem();
3537
3538         skin->setFont(old_font);
3539 }
3540
3541
3542 void GUIFormSpecMenu::showTooltip(const std::wstring &text,
3543         const irr::video::SColor &color, const irr::video::SColor &bgcolor)
3544 {
3545         EnrichedString ntext(text);
3546         ntext.setDefaultColor(color);
3547         ntext.setBackground(bgcolor);
3548
3549         setStaticText(m_tooltip_element, ntext);
3550
3551         // Tooltip size and offset
3552         s32 tooltip_width = m_tooltip_element->getTextWidth() + m_btn_height;
3553         s32 tooltip_height = m_tooltip_element->getTextHeight() + 5;
3554
3555         v2u32 screenSize = Environment->getVideoDriver()->getScreenSize();
3556         int tooltip_offset_x = m_btn_height;
3557         int tooltip_offset_y = m_btn_height;
3558 #ifdef __ANDROID__
3559         tooltip_offset_x *= 3;
3560         tooltip_offset_y  = 0;
3561         if (m_pointer.X > (s32)screenSize.X / 2)
3562                 tooltip_offset_x = -(tooltip_offset_x + tooltip_width);
3563
3564         // Hide tooltip after ETIE_LEFT_UP
3565         if (m_pointer.X == 0)
3566                 return;
3567 #endif
3568
3569         // Calculate and set the tooltip position
3570         s32 tooltip_x = m_pointer.X + tooltip_offset_x;
3571         s32 tooltip_y = m_pointer.Y + tooltip_offset_y;
3572         if (tooltip_x + tooltip_width > (s32)screenSize.X)
3573                 tooltip_x = (s32)screenSize.X - tooltip_width  - m_btn_height;
3574         if (tooltip_y + tooltip_height > (s32)screenSize.Y)
3575                 tooltip_y = (s32)screenSize.Y - tooltip_height - m_btn_height;
3576
3577         m_tooltip_element->setRelativePosition(
3578                 core::rect<s32>(
3579                         core::position2d<s32>(tooltip_x, tooltip_y),
3580                         core::dimension2d<s32>(tooltip_width, tooltip_height)
3581                 )
3582         );
3583
3584         // Display the tooltip
3585         m_tooltip_element->setVisible(true);
3586         bringToFront(m_tooltip_element);
3587 }
3588
3589 void GUIFormSpecMenu::updateSelectedItem()
3590 {
3591         verifySelectedItem();
3592
3593         // If craftresult is nonempty and nothing else is selected, select it now.
3594         if (!m_selected_item) {
3595                 for (const GUIInventoryList *e : m_inventorylists) {
3596                         if (e->getListname() != "craftpreview")
3597                                 continue;
3598
3599                         Inventory *inv = m_invmgr->getInventory(e->getInventoryloc());
3600                         if (!inv)
3601                                 continue;
3602
3603                         InventoryList *list = inv->getList("craftresult");
3604
3605                         if (!list || list->getSize() == 0)
3606                                 continue;
3607
3608                         const ItemStack &item = list->getItem(0);
3609                         if (item.empty())
3610                                 continue;
3611
3612                         // Grab selected item from the crafting result list
3613                         m_selected_item = new GUIInventoryList::ItemSpec;
3614                         m_selected_item->inventoryloc = e->getInventoryloc();
3615                         m_selected_item->listname = "craftresult";
3616                         m_selected_item->i = 0;
3617                         m_selected_amount = item.count;
3618                         m_selected_dragging = false;
3619                         break;
3620                 }
3621         }
3622
3623         // If craftresult is selected, keep the whole stack selected
3624         if (m_selected_item && m_selected_item->listname == "craftresult")
3625                 m_selected_amount = verifySelectedItem().count;
3626 }
3627
3628 ItemStack GUIFormSpecMenu::verifySelectedItem()
3629 {
3630         // If the selected stack has become empty for some reason, deselect it.
3631         // If the selected stack has become inaccessible, deselect it.
3632         // If the selected stack has become smaller, adjust m_selected_amount.
3633         // Return the selected stack.
3634
3635         if (m_selected_item) {
3636                 if (m_selected_item->isValid()) {
3637                         Inventory *inv = m_invmgr->getInventory(m_selected_item->inventoryloc);
3638                         if (inv) {
3639                                 InventoryList *list = inv->getList(m_selected_item->listname);
3640                                 if (list && (u32) m_selected_item->i < list->getSize()) {
3641                                         ItemStack stack = list->getItem(m_selected_item->i);
3642                                         if (!m_selected_swap.empty()) {
3643                                                 if (m_selected_swap.name == stack.name &&
3644                                                                 m_selected_swap.count == stack.count)
3645                                                         m_selected_swap.clear();
3646                                         } else {
3647                                                 m_selected_amount = std::min(m_selected_amount, stack.count);
3648                                         }
3649
3650                                         if (!stack.empty())
3651                                                 return stack;
3652                                 }
3653                         }
3654                 }
3655
3656                 // selection was not valid
3657                 delete m_selected_item;
3658                 m_selected_item = nullptr;
3659                 m_selected_amount = 0;
3660                 m_selected_dragging = false;
3661         }
3662         return ItemStack();
3663 }
3664
3665 void GUIFormSpecMenu::acceptInput(FormspecQuitMode quitmode=quit_mode_no)
3666 {
3667         if(m_text_dst)
3668         {
3669                 StringMap fields;
3670
3671                 if (quitmode == quit_mode_accept) {
3672                         fields["quit"] = "true";
3673                 }
3674
3675                 if (quitmode == quit_mode_cancel) {
3676                         fields["quit"] = "true";
3677                         m_text_dst->gotText(fields);
3678                         return;
3679                 }
3680
3681                 if (current_keys_pending.key_down) {
3682                         fields["key_down"] = "true";
3683                         current_keys_pending.key_down = false;
3684                 }
3685
3686                 if (current_keys_pending.key_up) {
3687                         fields["key_up"] = "true";
3688                         current_keys_pending.key_up = false;
3689                 }
3690
3691                 if (current_keys_pending.key_enter) {
3692                         fields["key_enter"] = "true";
3693                         current_keys_pending.key_enter = false;
3694                 }
3695
3696                 if (!current_field_enter_pending.empty()) {
3697                         fields["key_enter_field"] = current_field_enter_pending;
3698                         current_field_enter_pending = "";
3699                 }
3700
3701                 if (current_keys_pending.key_escape) {
3702                         fields["key_escape"] = "true";
3703                         current_keys_pending.key_escape = false;
3704                 }
3705
3706                 for (const GUIFormSpecMenu::FieldSpec &s : m_fields) {
3707                         if (s.send) {
3708                                 std::string name = s.fname;
3709                                 if (s.ftype == f_Button) {
3710                                         fields[name] = wide_to_utf8(s.flabel);
3711                                 } else if (s.ftype == f_Table) {
3712                                         GUITable *table = getTable(s.fname);
3713                                         if (table) {
3714                                                 fields[name] = table->checkEvent();
3715                                         }
3716                                 } else if (s.ftype == f_DropDown) {
3717                                         // No dynamic cast possible due to some distributions shipped
3718                                         // without rtti support in Irrlicht
3719                                         IGUIElement *element = getElementFromId(s.fid, true);
3720                                         gui::IGUIComboBox *e = NULL;
3721                                         if ((element) && (element->getType() == gui::EGUIET_COMBO_BOX)) {
3722                                                 e = static_cast<gui::IGUIComboBox *>(element);
3723                                         } else {
3724                                                 warningstream << "GUIFormSpecMenu::acceptInput: dropdown "
3725                                                                 << "field without dropdown element" << std::endl;
3726                                                 continue;
3727                                         }
3728                                         s32 selected = e->getSelected();
3729                                         if (selected >= 0) {
3730                                                 std::vector<std::string> *dropdown_values =
3731                                                         getDropDownValues(s.fname);
3732                                                 if (dropdown_values && selected < (s32)dropdown_values->size()) {
3733                                                         fields[name] = (*dropdown_values)[selected];
3734                                                 }
3735                                         }
3736                                 } else if (s.ftype == f_TabHeader) {
3737                                         // No dynamic cast possible due to some distributions shipped
3738                                         // without rtti support in Irrlicht
3739                                         IGUIElement *element = getElementFromId(s.fid, true);
3740                                         gui::IGUITabControl *e = nullptr;
3741                                         if ((element) && (element->getType() == gui::EGUIET_TAB_CONTROL)) {
3742                                                 e = static_cast<gui::IGUITabControl *>(element);
3743                                         }
3744
3745                                         if (e != 0) {
3746                                                 std::stringstream ss;
3747                                                 ss << (e->getActiveTab() +1);
3748                                                 fields[name] = ss.str();
3749                                         }
3750                                 } else if (s.ftype == f_CheckBox) {
3751                                         // No dynamic cast possible due to some distributions shipped
3752                                         // without rtti support in Irrlicht
3753                                         IGUIElement *element = getElementFromId(s.fid, true);
3754                                         gui::IGUICheckBox *e = nullptr;
3755                                         if ((element) && (element->getType() == gui::EGUIET_CHECK_BOX)) {
3756                                                 e = static_cast<gui::IGUICheckBox*>(element);
3757                                         }
3758
3759                                         if (e != 0) {
3760                                                 if (e->isChecked())
3761                                                         fields[name] = "true";
3762                                                 else
3763                                                         fields[name] = "false";
3764                                         }
3765                                 } else if (s.ftype == f_ScrollBar) {
3766                                         // No dynamic cast possible due to some distributions shipped
3767                                         // without rtti support in Irrlicht
3768                                         IGUIElement *element = getElementFromId(s.fid, true);
3769                                         GUIScrollBar *e = nullptr;
3770                                         if (element && element->getType() == gui::EGUIET_ELEMENT)
3771                                                 e = static_cast<GUIScrollBar *>(element);
3772
3773                                         if (e) {
3774                                                 std::stringstream os;
3775                                                 os << e->getPos();
3776                                                 if (s.fdefault == L"Changed")
3777                                                         fields[name] = "CHG:" + os.str();
3778                                                 else
3779                                                         fields[name] = "VAL:" + os.str();
3780                                         }
3781                                 } else if (s.ftype == f_AnimatedImage) {
3782                                         // No dynamic cast possible due to some distributions shipped
3783                                         // without rtti support in Irrlicht
3784                                         IGUIElement *element = getElementFromId(s.fid, true);
3785                                         GUIAnimatedImage *e = nullptr;
3786                                         if (element && element->getType() == gui::EGUIET_ELEMENT)
3787                                                 e = static_cast<GUIAnimatedImage *>(element);
3788
3789                                         if (e)
3790                                                 fields[name] = std::to_string(e->getFrameIndex() + 1);
3791                                 } else {
3792                                         IGUIElement *e = getElementFromId(s.fid, true);
3793                                         if (e)
3794                                                 fields[name] = wide_to_utf8(e->getText());
3795                                 }
3796                         }
3797                 }
3798
3799                 m_text_dst->gotText(fields);
3800         }
3801 }
3802
3803 static bool isChild(gui::IGUIElement *tocheck, gui::IGUIElement *parent)
3804 {
3805         while (tocheck) {
3806                 if (tocheck == parent) {
3807                         return true;
3808                 }
3809                 tocheck = tocheck->getParent();
3810         }
3811         return false;
3812 }
3813
3814 bool GUIFormSpecMenu::preprocessEvent(const SEvent& event)
3815 {
3816         // The IGUITabControl renders visually using the skin's selected
3817         // font, which we override for the duration of form drawing,
3818         // but computes tab hotspots based on how it would have rendered
3819         // using the font that is selected at the time of button release.
3820         // To make these two consistent, temporarily override the skin's
3821         // font while the IGUITabControl is processing the event.
3822         if (event.EventType == EET_MOUSE_INPUT_EVENT &&
3823                         event.MouseInput.Event == EMIE_LMOUSE_LEFT_UP) {
3824                 s32 x = event.MouseInput.X;
3825                 s32 y = event.MouseInput.Y;
3826                 gui::IGUIElement *hovered =
3827                         Environment->getRootGUIElement()->getElementFromPoint(
3828                                 core::position2d<s32>(x, y));
3829                 if (hovered && isMyChild(hovered) &&
3830                                 hovered->getType() == gui::EGUIET_TAB_CONTROL) {
3831                         gui::IGUISkin* skin = Environment->getSkin();
3832                         sanity_check(skin != NULL);
3833                         gui::IGUIFont *old_font = skin->getFont();
3834                         skin->setFont(m_font);
3835                         bool retval = hovered->OnEvent(event);
3836                         skin->setFont(old_font);
3837                         return retval;
3838                 }
3839         }
3840
3841         // Fix Esc/Return key being eaten by checkboxen and tables
3842         if (event.EventType == EET_KEY_INPUT_EVENT) {
3843                         KeyPress kp(event.KeyInput);
3844                 if (kp == EscapeKey || kp == CancelKey
3845                                 || kp == getKeySetting("keymap_inventory")
3846                                 || event.KeyInput.Key==KEY_RETURN) {
3847                         gui::IGUIElement *focused = Environment->getFocus();
3848                         if (focused && isMyChild(focused) &&
3849                                         (focused->getType() == gui::EGUIET_LIST_BOX ||
3850                                         focused->getType() == gui::EGUIET_CHECK_BOX) &&
3851                                         (focused->getParent()->getType() != gui::EGUIET_COMBO_BOX ||
3852                                         event.KeyInput.Key != KEY_RETURN)) {
3853                                 OnEvent(event);
3854                                 return true;
3855                         }
3856                 }
3857         }
3858         // Mouse wheel and move events: send to hovered element instead of focused
3859         if (event.EventType == EET_MOUSE_INPUT_EVENT &&
3860                         (event.MouseInput.Event == EMIE_MOUSE_WHEEL ||
3861                         (event.MouseInput.Event == EMIE_MOUSE_MOVED &&
3862                         event.MouseInput.ButtonStates == 0))) {
3863                 s32 x = event.MouseInput.X;
3864                 s32 y = event.MouseInput.Y;
3865                 gui::IGUIElement *hovered =
3866                         Environment->getRootGUIElement()->getElementFromPoint(
3867                                 core::position2d<s32>(x, y));
3868                 if (hovered && isMyChild(hovered)) {
3869                         hovered->OnEvent(event);
3870                         return event.MouseInput.Event == EMIE_MOUSE_WHEEL;
3871                 }
3872         }
3873
3874         if (event.EventType == EET_MOUSE_INPUT_EVENT) {
3875                 s32 x = event.MouseInput.X;
3876                 s32 y = event.MouseInput.Y;
3877                 gui::IGUIElement *hovered =
3878                         Environment->getRootGUIElement()->getElementFromPoint(
3879                                 core::position2d<s32>(x, y));
3880                 if (event.MouseInput.Event == EMIE_LMOUSE_PRESSED_DOWN) {
3881                         m_old_tooltip_id = -1;
3882                 }
3883                 if (!isChild(hovered, this)) {
3884                         if (DoubleClickDetection(event)) {
3885                                 return true;
3886                         }
3887                 }
3888         }
3889
3890         if (event.EventType == irr::EET_JOYSTICK_INPUT_EVENT) {
3891                 /* TODO add a check like:
3892                 if (event.JoystickEvent != joystick_we_listen_for)
3893                         return false;
3894                 */
3895                 bool handled = m_joystick->handleEvent(event.JoystickEvent);
3896                 if (handled) {
3897                         if (m_joystick->wasKeyDown(KeyType::ESC)) {
3898                                 tryClose();
3899                         } else if (m_joystick->wasKeyDown(KeyType::JUMP)) {
3900                                 if (m_allowclose) {
3901                                         acceptInput(quit_mode_accept);
3902                                         quitMenu();
3903                                 }
3904                         }
3905                 }
3906                 return handled;
3907         }
3908
3909         return GUIModalMenu::preprocessEvent(event);
3910 }
3911
3912 /******************************************************************************/
3913 bool GUIFormSpecMenu::DoubleClickDetection(const SEvent event)
3914 {
3915         /* The following code is for capturing double-clicks of the mouse button
3916          * and translating the double-click into an EET_KEY_INPUT_EVENT event
3917          * -- which closes the form -- under some circumstances.
3918          *
3919          * There have been many github issues reporting this as a bug even though it
3920          * was an intended feature.  For this reason, remapping the double-click as
3921          * an ESC must be explicitly set when creating this class via the
3922          * /p remap_dbl_click parameter of the constructor.
3923          */
3924
3925         if (!m_remap_dbl_click)
3926                 return false;
3927
3928         if (event.MouseInput.Event == EMIE_LMOUSE_PRESSED_DOWN) {
3929                 m_doubleclickdetect[0].pos  = m_doubleclickdetect[1].pos;
3930                 m_doubleclickdetect[0].time = m_doubleclickdetect[1].time;
3931
3932                 m_doubleclickdetect[1].pos  = m_pointer;
3933                 m_doubleclickdetect[1].time = porting::getTimeMs();
3934         }
3935         else if (event.MouseInput.Event == EMIE_LMOUSE_LEFT_UP) {
3936                 u64 delta = porting::getDeltaMs(m_doubleclickdetect[0].time, porting::getTimeMs());
3937                 if (delta > 400) {
3938                         return false;
3939                 }
3940
3941                 double squaredistance =
3942                                 m_doubleclickdetect[0].pos
3943                                 .getDistanceFromSQ(m_doubleclickdetect[1].pos);
3944
3945                 if (squaredistance > (30*30)) {
3946                         return false;
3947                 }
3948
3949                 SEvent* translated = new SEvent();
3950                 assert(translated != 0);
3951                 //translate doubleclick to escape
3952                 memset(translated, 0, sizeof(SEvent));
3953                 translated->EventType = irr::EET_KEY_INPUT_EVENT;
3954                 translated->KeyInput.Key         = KEY_ESCAPE;
3955                 translated->KeyInput.Control     = false;
3956                 translated->KeyInput.Shift       = false;
3957                 translated->KeyInput.PressedDown = true;
3958                 translated->KeyInput.Char        = 0;
3959                 OnEvent(*translated);
3960
3961                 // no need to send the key up event as we're already deleted
3962                 // and no one else did notice this event
3963                 delete translated;
3964                 return true;
3965         }
3966
3967         return false;
3968 }
3969
3970 void GUIFormSpecMenu::tryClose()
3971 {
3972         if (m_allowclose) {
3973                 doPause = false;
3974                 acceptInput(quit_mode_cancel);
3975                 quitMenu();
3976         } else {
3977                 m_text_dst->gotText(L"MenuQuit");
3978         }
3979 }
3980
3981 enum ButtonEventType : u8
3982 {
3983         BET_LEFT,
3984         BET_RIGHT,
3985         BET_MIDDLE,
3986         BET_WHEEL_UP,
3987         BET_WHEEL_DOWN,
3988         BET_UP,
3989         BET_DOWN,
3990         BET_MOVE,
3991         BET_OTHER
3992 };
3993
3994 bool GUIFormSpecMenu::OnEvent(const SEvent& event)
3995 {
3996         if (event.EventType==EET_KEY_INPUT_EVENT) {
3997                 KeyPress kp(event.KeyInput);
3998                 if (event.KeyInput.PressedDown && (
3999                                 (kp == EscapeKey) || (kp == CancelKey) ||
4000                                 ((m_client != NULL) && (kp == getKeySetting("keymap_inventory"))))) {
4001                         tryClose();
4002                         return true;
4003                 }
4004
4005                 if (m_client != NULL && event.KeyInput.PressedDown &&
4006                                 (kp == getKeySetting("keymap_screenshot"))) {
4007                         m_client->makeScreenshot();
4008                 }
4009
4010                 if (event.KeyInput.PressedDown && kp == getKeySetting("keymap_toggle_debug"))
4011                         m_show_debug = !m_show_debug;
4012
4013                 if (event.KeyInput.PressedDown &&
4014                         (event.KeyInput.Key==KEY_RETURN ||
4015                          event.KeyInput.Key==KEY_UP ||
4016                          event.KeyInput.Key==KEY_DOWN)
4017                         ) {
4018                         switch (event.KeyInput.Key) {
4019                                 case KEY_RETURN:
4020                                         current_keys_pending.key_enter = true;
4021                                         break;
4022                                 case KEY_UP:
4023                                         current_keys_pending.key_up = true;
4024                                         break;
4025                                 case KEY_DOWN:
4026                                         current_keys_pending.key_down = true;
4027                                         break;
4028                                 break;
4029                                 default:
4030                                         //can't happen at all!
4031                                         FATAL_ERROR("Reached a source line that can't ever been reached");
4032                                         break;
4033                         }
4034                         if (current_keys_pending.key_enter && m_allowclose) {
4035                                 acceptInput(quit_mode_accept);
4036                                 quitMenu();
4037                         } else {
4038                                 acceptInput();
4039                         }
4040                         return true;
4041                 }
4042
4043         }
4044
4045         /* Mouse event other than movement, or crossing the border of inventory
4046           field while holding right mouse button
4047          */
4048         if (event.EventType == EET_MOUSE_INPUT_EVENT &&
4049                         (event.MouseInput.Event != EMIE_MOUSE_MOVED ||
4050                          (event.MouseInput.Event == EMIE_MOUSE_MOVED &&
4051                           event.MouseInput.isRightPressed() &&
4052                           getItemAtPos(m_pointer).i != getItemAtPos(m_old_pointer).i))) {
4053
4054                 // Get selected item and hovered/clicked item (s)
4055
4056                 m_old_tooltip_id = -1;
4057                 updateSelectedItem();
4058                 GUIInventoryList::ItemSpec s = getItemAtPos(m_pointer);
4059
4060                 Inventory *inv_selected = NULL;
4061                 Inventory *inv_s = NULL;
4062                 InventoryList *list_s = NULL;
4063
4064                 if (m_selected_item) {
4065                         inv_selected = m_invmgr->getInventory(m_selected_item->inventoryloc);
4066                         sanity_check(inv_selected);
4067                         sanity_check(inv_selected->getList(m_selected_item->listname) != NULL);
4068                 }
4069
4070                 u32 s_count = 0;
4071
4072                 if (s.isValid())
4073                 do { // breakable
4074                         inv_s = m_invmgr->getInventory(s.inventoryloc);
4075
4076                         if (!inv_s) {
4077                                 errorstream << "InventoryMenu: The selected inventory location "
4078                                                 << "\"" << s.inventoryloc.dump() << "\" doesn't exist"
4079                                                 << std::endl;
4080                                 s.i = -1;  // make it invalid again
4081                                 break;
4082                         }
4083
4084                         list_s = inv_s->getList(s.listname);
4085                         if (list_s == NULL) {
4086                                 verbosestream << "InventoryMenu: The selected inventory list \""
4087                                                 << s.listname << "\" does not exist" << std::endl;
4088                                 s.i = -1;  // make it invalid again
4089                                 break;
4090                         }
4091
4092                         if ((u32)s.i >= list_s->getSize()) {
4093                                 infostream << "InventoryMenu: The selected inventory list \""
4094                                                 << s.listname << "\" is too small (i=" << s.i << ", size="
4095                                                 << list_s->getSize() << ")" << std::endl;
4096                                 s.i = -1;  // make it invalid again
4097                                 break;
4098                         }
4099
4100                         s_count = list_s->getItem(s.i).count;
4101                 } while(0);
4102
4103                 bool identical = m_selected_item && s.isValid() &&
4104                         (inv_selected == inv_s) &&
4105                         (m_selected_item->listname == s.listname) &&
4106                         (m_selected_item->i == s.i);
4107
4108                 ButtonEventType button = BET_LEFT;
4109                 ButtonEventType updown = BET_OTHER;
4110                 switch (event.MouseInput.Event) {
4111                 case EMIE_LMOUSE_PRESSED_DOWN:
4112                         button = BET_LEFT; updown = BET_DOWN;
4113                         break;
4114                 case EMIE_RMOUSE_PRESSED_DOWN:
4115                         button = BET_RIGHT; updown = BET_DOWN;
4116                         break;
4117                 case EMIE_MMOUSE_PRESSED_DOWN:
4118                         button = BET_MIDDLE; updown = BET_DOWN;
4119                         break;
4120                 case EMIE_MOUSE_WHEEL:
4121                         button = (event.MouseInput.Wheel > 0) ?
4122                                 BET_WHEEL_UP : BET_WHEEL_DOWN;
4123                         updown = BET_DOWN;
4124                         break;
4125                 case EMIE_LMOUSE_LEFT_UP:
4126                         button = BET_LEFT; updown = BET_UP;
4127                         break;
4128                 case EMIE_RMOUSE_LEFT_UP:
4129                         button = BET_RIGHT; updown = BET_UP;
4130                         break;
4131                 case EMIE_MMOUSE_LEFT_UP:
4132                         button = BET_MIDDLE; updown = BET_UP;
4133                         break;
4134                 case EMIE_MOUSE_MOVED:
4135                         updown = BET_MOVE;
4136                         break;
4137                 default:
4138                         break;
4139                 }
4140
4141                 // Set this number to a positive value to generate a move action
4142                 // from m_selected_item to s.
4143                 u32 move_amount = 0;
4144
4145                 // Set this number to a positive value to generate a move action
4146                 // from s to the next inventory ring.
4147                 u32 shift_move_amount = 0;
4148
4149                 // Set this number to a positive value to generate a drop action
4150                 // from m_selected_item.
4151                 u32 drop_amount = 0;
4152
4153                 // Set this number to a positive value to generate a craft action at s.
4154                 u32 craft_amount = 0;
4155
4156                 switch (updown) {
4157                 case BET_DOWN:
4158                         // Some mouse button has been pressed
4159
4160                         //infostream << "Mouse button " << button << " pressed at p=("
4161                         //      << event.MouseInput.X << "," << event.MouseInput.Y << ")"
4162                         //      << std::endl;
4163
4164                         m_selected_dragging = false;
4165
4166                         if (s.isValid() && s.listname == "craftpreview") {
4167                                 // Craft preview has been clicked: craft
4168                                 craft_amount = (button == BET_MIDDLE ? 10 : 1);
4169                         } else if (!m_selected_item) {
4170                                 if (s_count && button != BET_WHEEL_UP) {
4171                                         // Non-empty stack has been clicked: select or shift-move it
4172                                         m_selected_item = new GUIInventoryList::ItemSpec(s);
4173
4174                                         u32 count;
4175                                         if (button == BET_RIGHT)
4176                                                 count = (s_count + 1) / 2;
4177                                         else if (button == BET_MIDDLE)
4178                                                 count = MYMIN(s_count, 10);
4179                                         else if (button == BET_WHEEL_DOWN)
4180                                                 count = 1;
4181                                         else  // left
4182                                                 count = s_count;
4183
4184                                         if (!event.MouseInput.Shift) {
4185                                                 // no shift: select item
4186                                                 m_selected_amount = count;
4187                                                 m_selected_dragging = button != BET_WHEEL_DOWN;
4188                                                 m_auto_place = false;
4189                                         } else {
4190                                                 // shift pressed: move item, right click moves 1
4191                                                 shift_move_amount = button == BET_RIGHT ? 1 : count;
4192                                         }
4193                                 }
4194                         } else { // m_selected_item != NULL
4195                                 assert(m_selected_amount >= 1);
4196
4197                                 if (s.isValid()) {
4198                                         // Clicked a slot: move
4199                                         if (button == BET_RIGHT || button == BET_WHEEL_UP)
4200                                                 move_amount = 1;
4201                                         else if (button == BET_MIDDLE)
4202                                                 move_amount = MYMIN(m_selected_amount, 10);
4203                                         else if (button == BET_LEFT)
4204                                                 move_amount = m_selected_amount;
4205                                         // else wheeldown
4206
4207                                         if (identical) {
4208                                                 if (button == BET_WHEEL_DOWN) {
4209                                                         if (m_selected_amount < s_count)
4210                                                                 ++m_selected_amount;
4211                                                 } else {
4212                                                         if (move_amount >= m_selected_amount)
4213                                                                 m_selected_amount = 0;
4214                                                         else
4215                                                                 m_selected_amount -= move_amount;
4216                                                         move_amount = 0;
4217                                                 }
4218                                         }
4219                                 } else if (!getAbsoluteClippingRect().isPointInside(m_pointer)
4220                                                 && button != BET_WHEEL_DOWN) {
4221                                         // Clicked outside of the window: drop
4222                                         if (button == BET_RIGHT || button == BET_WHEEL_UP)
4223                                                 drop_amount = 1;
4224                                         else if (button == BET_MIDDLE)
4225                                                 drop_amount = MYMIN(m_selected_amount, 10);
4226                                         else  // left
4227                                                 drop_amount = m_selected_amount;
4228                                 }
4229                         }
4230                 break;
4231                 case BET_UP:
4232                         // Some mouse button has been released
4233
4234                         //infostream<<"Mouse button "<<button<<" released at p=("
4235                         //      <<p.X<<","<<p.Y<<")"<<std::endl;
4236
4237                         if (m_selected_dragging && m_selected_item) {
4238                                 if (s.isValid()) {
4239                                         if (!identical) {
4240                                                 // Dragged to different slot: move all selected
4241                                                 move_amount = m_selected_amount;
4242                                         }
4243                                 } else if (!getAbsoluteClippingRect().isPointInside(m_pointer)) {
4244                                         // Dragged outside of window: drop all selected
4245                                         drop_amount = m_selected_amount;
4246                                 }
4247                         }
4248
4249                         m_selected_dragging = false;
4250                         // Keep track of whether the mouse button be released
4251                         // One click is drag without dropping. Click + release
4252                         // + click changes to drop item when moved mode
4253                         if (m_selected_item)
4254                                 m_auto_place = true;
4255                 break;
4256                 case BET_MOVE:
4257                         // Mouse has been moved and rmb is down and mouse pointer just
4258                         // entered a new inventory field (checked in the entry-if, this
4259                         // is the only action here that is generated by mouse movement)
4260                         if (m_selected_item && s.isValid() && s.listname != "craftpreview") {
4261                                 // Move 1 item
4262                                 // TODO: middle mouse to move 10 items might be handy
4263                                 if (m_auto_place) {
4264                                         // Only move an item if the destination slot is empty
4265                                         // or contains the same item type as what is going to be
4266                                         // moved
4267                                         InventoryList *list_from = inv_selected->getList(m_selected_item->listname);
4268                                         InventoryList *list_to = list_s;
4269                                         assert(list_from && list_to);
4270                                         ItemStack stack_from = list_from->getItem(m_selected_item->i);
4271                                         ItemStack stack_to = list_to->getItem(s.i);
4272                                         if (stack_to.empty() || stack_to.name == stack_from.name)
4273                                                 move_amount = 1;
4274                                 }
4275                         }
4276                 break;
4277                 default:
4278                         break;
4279                 }
4280
4281                 // Possibly send inventory action to server
4282                 if (move_amount > 0) {
4283                         // Send IAction::Move
4284
4285                         assert(m_selected_item && m_selected_item->isValid());
4286                         assert(s.isValid());
4287
4288                         assert(inv_selected && inv_s);
4289                         InventoryList *list_from = inv_selected->getList(m_selected_item->listname);
4290                         InventoryList *list_to = list_s;
4291                         assert(list_from && list_to);
4292                         ItemStack stack_from = list_from->getItem(m_selected_item->i);
4293                         ItemStack stack_to = list_to->getItem(s.i);
4294
4295                         // Check how many items can be moved
4296                         move_amount = stack_from.count = MYMIN(move_amount, stack_from.count);
4297                         ItemStack leftover = stack_to.addItem(stack_from, m_client->idef());
4298                         bool move = true;
4299                         // If source stack cannot be added to destination stack at all,
4300                         // they are swapped
4301                         if (leftover.count == stack_from.count &&
4302                                         leftover.name == stack_from.name) {
4303
4304                                 if (m_selected_swap.empty()) {
4305                                         m_selected_amount = stack_to.count;
4306                                         m_selected_dragging = false;
4307
4308                                         // WARNING: BLACK MAGIC, BUT IN A REDUCED SET
4309                                         // Skip next validation checks due async inventory calls
4310                                         m_selected_swap = stack_to;
4311                                 } else {
4312                                         move = false;
4313                                 }
4314                         }
4315                         // Source stack goes fully into destination stack
4316                         else if (leftover.empty()) {
4317                                 m_selected_amount -= move_amount;
4318                         }
4319                         // Source stack goes partly into destination stack
4320                         else {
4321                                 move_amount -= leftover.count;
4322                                 m_selected_amount -= move_amount;
4323                         }
4324
4325                         if (move) {
4326                                 infostream << "Handing IAction::Move to manager" << std::endl;
4327                                 IMoveAction *a = new IMoveAction();
4328                                 a->count = move_amount;
4329                                 a->from_inv = m_selected_item->inventoryloc;
4330                                 a->from_list = m_selected_item->listname;
4331                                 a->from_i = m_selected_item->i;
4332                                 a->to_inv = s.inventoryloc;
4333                                 a->to_list = s.listname;
4334                                 a->to_i = s.i;
4335                                 m_invmgr->inventoryAction(a);
4336                         }
4337                 } else if (shift_move_amount > 0) {
4338                         u32 mis = m_inventory_rings.size();
4339                         u32 i = 0;
4340                         for (; i < mis; i++) {
4341                                 const ListRingSpec &sp = m_inventory_rings[i];
4342                                 if (sp.inventoryloc == s.inventoryloc
4343                                                 && sp.listname == s.listname)
4344                                         break;
4345                         }
4346                         do {
4347                                 if (i >= mis) // if not found
4348                                         break;
4349                                 u32 to_inv_ind = (i + 1) % mis;
4350                                 const ListRingSpec &to_inv_sp = m_inventory_rings[to_inv_ind];
4351                                 InventoryList *list_from = list_s;
4352                                 if (!s.isValid())
4353                                         break;
4354                                 Inventory *inv_to = m_invmgr->getInventory(to_inv_sp.inventoryloc);
4355                                 if (!inv_to)
4356                                         break;
4357                                 InventoryList *list_to = inv_to->getList(to_inv_sp.listname);
4358                                 if (!list_to)
4359                                         break;
4360                                 ItemStack stack_from = list_from->getItem(s.i);
4361                                 assert(shift_move_amount <= stack_from.count);
4362
4363                                 infostream << "Handing IAction::Move to manager" << std::endl;
4364                                 IMoveAction *a = new IMoveAction();
4365                                 a->count = shift_move_amount;
4366                                 a->from_inv = s.inventoryloc;
4367                                 a->from_list = s.listname;
4368                                 a->from_i = s.i;
4369                                 a->to_inv = to_inv_sp.inventoryloc;
4370                                 a->to_list = to_inv_sp.listname;
4371                                 a->move_somewhere = true;
4372                                 m_invmgr->inventoryAction(a);
4373                         } while (0);
4374                 } else if (drop_amount > 0) {
4375                         // Send IAction::Drop
4376
4377                         assert(m_selected_item && m_selected_item->isValid());
4378                         assert(inv_selected);
4379                         InventoryList *list_from = inv_selected->getList(m_selected_item->listname);
4380                         assert(list_from);
4381                         ItemStack stack_from = list_from->getItem(m_selected_item->i);
4382
4383                         // Check how many items can be dropped
4384                         drop_amount = stack_from.count = MYMIN(drop_amount, stack_from.count);
4385                         assert(drop_amount > 0 && drop_amount <= m_selected_amount);
4386                         m_selected_amount -= drop_amount;
4387
4388                         infostream << "Handing IAction::Drop to manager" << std::endl;
4389                         IDropAction *a = new IDropAction();
4390                         a->count = drop_amount;
4391                         a->from_inv = m_selected_item->inventoryloc;
4392                         a->from_list = m_selected_item->listname;
4393                         a->from_i = m_selected_item->i;
4394                         m_invmgr->inventoryAction(a);
4395                 } else if (craft_amount > 0) {
4396                         assert(s.isValid());
4397
4398                         // if there are no items selected or the selected item
4399                         // belongs to craftresult list, proceed with crafting
4400                         if (!m_selected_item ||
4401                                         !m_selected_item->isValid() || m_selected_item->listname == "craftresult") {
4402
4403                                 assert(inv_s);
4404
4405                                 // Send IACTION_CRAFT
4406                                 infostream << "Handing IACTION_CRAFT to manager" << std::endl;
4407                                 ICraftAction *a = new ICraftAction();
4408                                 a->count = craft_amount;
4409                                 a->craft_inv = s.inventoryloc;
4410                                 m_invmgr->inventoryAction(a);
4411                         }
4412                 }
4413
4414                 // If m_selected_amount has been decreased to zero, deselect
4415                 if (m_selected_amount == 0) {
4416                         m_selected_swap.clear();
4417                         delete m_selected_item;
4418                         m_selected_item = nullptr;
4419                         m_selected_amount = 0;
4420                         m_selected_dragging = false;
4421                 }
4422                 m_old_pointer = m_pointer;
4423         }
4424
4425         if (event.EventType == EET_GUI_EVENT) {
4426                 if (event.GUIEvent.EventType == gui::EGET_TAB_CHANGED
4427                                 && isVisible()) {
4428                         // find the element that was clicked
4429                         for (GUIFormSpecMenu::FieldSpec &s : m_fields) {
4430                                 if ((s.ftype == f_TabHeader) &&
4431                                                 (s.fid == event.GUIEvent.Caller->getID())) {
4432                                         s.send = true;
4433                                         acceptInput();
4434                                         s.send = false;
4435                                         return true;
4436                                 }
4437                         }
4438                 }
4439                 if (event.GUIEvent.EventType == gui::EGET_ELEMENT_FOCUS_LOST
4440                                 && isVisible()) {
4441                         if (!canTakeFocus(event.GUIEvent.Element)) {
4442                                 infostream<<"GUIFormSpecMenu: Not allowing focus change."
4443                                                 <<std::endl;
4444                                 // Returning true disables focus change
4445                                 return true;
4446                         }
4447                 }
4448                 if ((event.GUIEvent.EventType == gui::EGET_BUTTON_CLICKED) ||
4449                                 (event.GUIEvent.EventType == gui::EGET_CHECKBOX_CHANGED) ||
4450                                 (event.GUIEvent.EventType == gui::EGET_COMBO_BOX_CHANGED) ||
4451                                 (event.GUIEvent.EventType == gui::EGET_SCROLL_BAR_CHANGED)) {
4452                         s32 caller_id = event.GUIEvent.Caller->getID();
4453
4454                         if (caller_id == 257) {
4455                                 if (m_allowclose) {
4456                                         acceptInput(quit_mode_accept);
4457                                         quitMenu();
4458                                 } else {
4459                                         acceptInput();
4460                                         m_text_dst->gotText(L"ExitButton");
4461                                 }
4462                                 // quitMenu deallocates menu
4463                                 return true;
4464                         }
4465
4466                         // find the element that was clicked
4467                         for (GUIFormSpecMenu::FieldSpec &s : m_fields) {
4468                                 // if its a button, set the send field so
4469                                 // lua knows which button was pressed
4470
4471                                 if (caller_id != s.fid)
4472                                         continue;
4473
4474                                 if (s.ftype == f_Button || s.ftype == f_CheckBox) {
4475                                         s.send = true;
4476                                         if (s.is_exit) {
4477                                                 if (m_allowclose) {
4478                                                         acceptInput(quit_mode_accept);
4479                                                         quitMenu();
4480                                                 } else {
4481                                                         m_text_dst->gotText(L"ExitButton");
4482                                                 }
4483                                                 return true;
4484                                         }
4485
4486                                         acceptInput(quit_mode_no);
4487                                         s.send = false;
4488                                         return true;
4489
4490                                 } else if (s.ftype == f_DropDown) {
4491                                         // only send the changed dropdown
4492                                         for (GUIFormSpecMenu::FieldSpec &s2 : m_fields) {
4493                                                 if (s2.ftype == f_DropDown) {
4494                                                         s2.send = false;
4495                                                 }
4496                                         }
4497                                         s.send = true;
4498                                         acceptInput(quit_mode_no);
4499
4500                                         // revert configuration to make sure dropdowns are sent on
4501                                         // regular button click
4502                                         for (GUIFormSpecMenu::FieldSpec &s2 : m_fields) {
4503                                                 if (s2.ftype == f_DropDown) {
4504                                                         s2.send = true;
4505                                                 }
4506                                         }
4507                                         return true;
4508                                 } else if (s.ftype == f_ScrollBar) {
4509                                         s.fdefault = L"Changed";
4510                                         acceptInput(quit_mode_no);
4511                                         s.fdefault = L"";
4512                                 } else if (s.ftype == f_Unknown || s.ftype == f_HyperText) {
4513                                         s.send = true;
4514                                         acceptInput();
4515                                         s.send = false;
4516                                 }
4517                         }
4518                 }
4519
4520                 if (event.GUIEvent.EventType == gui::EGET_SCROLL_BAR_CHANGED) {
4521                         // move scroll_containers
4522                         for (const std::pair<std::string, GUIScrollContainer *> &c : m_scroll_containers)
4523                                 c.second->onScrollEvent(event.GUIEvent.Caller);
4524                 }
4525
4526                 if (event.GUIEvent.EventType == gui::EGET_EDITBOX_ENTER) {
4527                         if (event.GUIEvent.Caller->getID() > 257) {
4528                                 bool close_on_enter = true;
4529                                 for (GUIFormSpecMenu::FieldSpec &s : m_fields) {
4530                                         if (s.ftype == f_Unknown &&
4531                                                         s.fid == event.GUIEvent.Caller->getID()) {
4532                                                 current_field_enter_pending = s.fname;
4533                                                 std::unordered_map<std::string, bool>::const_iterator it =
4534                                                         field_close_on_enter.find(s.fname);
4535                                                 if (it != field_close_on_enter.end())
4536                                                         close_on_enter = (*it).second;
4537
4538                                                 break;
4539                                         }
4540                                 }
4541
4542                                 if (m_allowclose && close_on_enter) {
4543                                         current_keys_pending.key_enter = true;
4544                                         acceptInput(quit_mode_accept);
4545                                         quitMenu();
4546                                 } else {
4547                                         current_keys_pending.key_enter = true;
4548                                         acceptInput();
4549                                 }
4550                                 // quitMenu deallocates menu
4551                                 return true;
4552                         }
4553                 }
4554
4555                 if (event.GUIEvent.EventType == gui::EGET_TABLE_CHANGED) {
4556                         int current_id = event.GUIEvent.Caller->getID();
4557                         if (current_id > 257) {
4558                                 // find the element that was clicked
4559                                 for (GUIFormSpecMenu::FieldSpec &s : m_fields) {
4560                                         // if it's a table, set the send field
4561                                         // so lua knows which table was changed
4562                                         if ((s.ftype == f_Table) && (s.fid == current_id)) {
4563                                                 s.send = true;
4564                                                 acceptInput();
4565                                                 s.send=false;
4566                                         }
4567                                 }
4568                                 return true;
4569                         }
4570                 }
4571         }
4572
4573         return Parent ? Parent->OnEvent(event) : false;
4574 }
4575
4576 /**
4577  * get name of element by element id
4578  * @param id of element
4579  * @return name string or empty string
4580  */
4581 std::string GUIFormSpecMenu::getNameByID(s32 id)
4582 {
4583         for (FieldSpec &spec : m_fields) {
4584                 if (spec.fid == id)
4585                         return spec.fname;
4586         }
4587         return "";
4588 }
4589
4590
4591 const GUIFormSpecMenu::FieldSpec *GUIFormSpecMenu::getSpecByID(s32 id)
4592 {
4593         for (FieldSpec &spec : m_fields) {
4594                 if (spec.fid == id)
4595                         return &spec;
4596         }
4597         return nullptr;
4598 }
4599
4600 /**
4601  * get label of element by id
4602  * @param id of element
4603  * @return label string or empty string
4604  */
4605 std::wstring GUIFormSpecMenu::getLabelByID(s32 id)
4606 {
4607         for (FieldSpec &spec : m_fields) {
4608                 if (spec.fid == id)
4609                         return spec.flabel;
4610         }
4611         return L"";
4612 }
4613
4614 StyleSpec GUIFormSpecMenu::getDefaultStyleForElement(const std::string &type,
4615                 const std::string &name, const std::string &parent_type) {
4616         return getStyleForElement(type, name, parent_type)[StyleSpec::STATE_DEFAULT];
4617 }
4618
4619 std::array<StyleSpec, StyleSpec::NUM_STATES> GUIFormSpecMenu::getStyleForElement(
4620         const std::string &type, const std::string &name, const std::string &parent_type)
4621 {
4622         std::array<StyleSpec, StyleSpec::NUM_STATES> ret;
4623
4624         auto it = theme_by_type.find("*");
4625         if (it != theme_by_type.end()) {
4626                 for (const StyleSpec &spec : it->second)
4627                         ret[(u32)spec.getState()] |= spec;
4628         }
4629
4630         it = theme_by_name.find("*");
4631         if (it != theme_by_name.end()) {
4632                 for (const StyleSpec &spec : it->second)
4633                         ret[(u32)spec.getState()] |= spec;
4634         }
4635
4636         if (!parent_type.empty()) {
4637                 it = theme_by_type.find(parent_type);
4638                 if (it != theme_by_type.end()) {
4639                         for (const StyleSpec &spec : it->second)
4640                                 ret[(u32)spec.getState()] |= spec;
4641                 }
4642         }
4643
4644         it = theme_by_type.find(type);
4645         if (it != theme_by_type.end()) {
4646                 for (const StyleSpec &spec : it->second)
4647                         ret[(u32)spec.getState()] |= spec;
4648         }
4649
4650         it = theme_by_name.find(name);
4651         if (it != theme_by_name.end()) {
4652                 for (const StyleSpec &spec : it->second)
4653                         ret[(u32)spec.getState()] |= spec;
4654         }
4655
4656         return ret;
4657 }