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