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