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