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