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