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