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